Merge branch 'typescript'
@ -1,2 +1,3 @@
|
||||
build/
|
||||
lib/
|
||||
coverage/
|
||||
|
||||
21
.eslintrc
@ -1,21 +0,0 @@
|
||||
{
|
||||
"parser": "babel-eslint",
|
||||
"extends": ["standard", "standard-react"],
|
||||
"rules": {
|
||||
"max-len": [2, 80, 4],
|
||||
"jsx-quotes": ["error", "prefer-double"],
|
||||
"padded-blocks": 0,
|
||||
"import/first": 0,
|
||||
"no-return-assign": 0,
|
||||
"indent": ["error", 2, { "MemberExpression": 0, "SwitchCase": 1, "flatTernaryExpressions": true }],
|
||||
},
|
||||
"globals": {
|
||||
"expect": true,
|
||||
"jest": true,
|
||||
"jasmine": true,
|
||||
"it": true,
|
||||
"beforeEach": true,
|
||||
"afterEach": true,
|
||||
"describe": true
|
||||
}
|
||||
}
|
||||
66
.eslintrc.yaml
Normal file
@ -0,0 +1,66 @@
|
||||
extends:
|
||||
- eslint:recommended
|
||||
- plugin:react/recommended
|
||||
- plugin:@typescript-eslint/eslint-recommended
|
||||
- plugin:@typescript-eslint/recommended
|
||||
plugins:
|
||||
- import
|
||||
settings:
|
||||
react:
|
||||
version: 'detect'
|
||||
rules:
|
||||
max-len:
|
||||
- warn
|
||||
- code: 80
|
||||
ignorePattern: '^import .* from '
|
||||
comma-dangle:
|
||||
- warn
|
||||
- arrays: always-multiline
|
||||
objects: always-multiline
|
||||
imports: always-multiline
|
||||
exports: always-multiline
|
||||
functions: always-multiline
|
||||
|
||||
semi:
|
||||
- warn
|
||||
- never
|
||||
quotes:
|
||||
- warn
|
||||
- single
|
||||
- allowTemplateLiterals: true
|
||||
# interface-name-prefix:
|
||||
'import/no-extraneous-dependencies': off
|
||||
'@typescript-eslint/member-delimiter-style':
|
||||
- warn
|
||||
- multiline:
|
||||
delimiter: none
|
||||
singleline:
|
||||
delimiter: comma
|
||||
'@typescript-eslint/no-unused-vars':
|
||||
- warn
|
||||
- vars: all
|
||||
args: none
|
||||
ignoreRestSiblings: true
|
||||
'@typescript-eslint/explicit-function-return-type': off
|
||||
'@typescript-eslint/no-non-null-assertion': off
|
||||
'@typescript-eslint/no-use-before-define': off
|
||||
'@typescript-eslint/no-empty-interface': off
|
||||
'@typescript-eslint/no-explicit-any':
|
||||
- warn
|
||||
- ignoreRestArgs: true
|
||||
'@typescript-eslint/triple-slash-reference':
|
||||
- warn
|
||||
- path: always
|
||||
overrides:
|
||||
- files:
|
||||
- '*.test.ts'
|
||||
- '*.test.tsx'
|
||||
rules:
|
||||
'@typescript-eslint/no-explicit-any': off
|
||||
- files:
|
||||
- '*.js'
|
||||
rules:
|
||||
'@typescript-eslint/no-var-requires': off
|
||||
env:
|
||||
node: true
|
||||
es6: true
|
||||
2
.gitignore
vendored
@ -8,3 +8,5 @@ node_modules/
|
||||
config.js
|
||||
coverage/
|
||||
config/local.json
|
||||
lib/
|
||||
tsconfig.tsbuildinfo
|
||||
|
||||
@ -2,7 +2,7 @@ stages:
|
||||
- test
|
||||
|
||||
test:
|
||||
image: node:8
|
||||
image: node:12
|
||||
stage: test
|
||||
script:
|
||||
- npm install
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- "8.12.0"
|
||||
- "8"
|
||||
- "12"
|
||||
script: npm run ci
|
||||
notifications:
|
||||
email: false
|
||||
|
||||
@ -1,11 +0,0 @@
|
||||
import EventEmitter from 'events'
|
||||
const Peer = jest.fn().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
|
||||
16
jest.config.js
Normal file
@ -0,0 +1,16 @@
|
||||
module.exports = {
|
||||
roots: [
|
||||
'<rootDir>/src',
|
||||
],
|
||||
transform: {
|
||||
'^.+\\.tsx?$': 'ts-jest',
|
||||
},
|
||||
testRegex: '(/__tests__/.*|\\.(test|spec))\\.tsx?$',
|
||||
moduleFileExtensions: [
|
||||
'ts',
|
||||
'tsx',
|
||||
'js',
|
||||
'jsx',
|
||||
],
|
||||
setupFiles: ['<rootDir>/jest.setup.js'],
|
||||
}
|
||||
@ -1 +0,0 @@
|
||||
import '@babel/polyfill'
|
||||
6672
package-lock.json
generated
138
package.json
@ -3,33 +3,38 @@
|
||||
"version": "2.0.12",
|
||||
"description": "Group peer to peer video calls for anybody.",
|
||||
"repository": "https://github.com/jeremija/peer-calls",
|
||||
"main": "src/index.js",
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/index.d.ts",
|
||||
"bin": {
|
||||
"peercalls": "./src/index.js"
|
||||
"peercalls": "./lib/index.js"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "node src/index.js",
|
||||
"start:server": "nodemon src/index.js --ignore build/ --ignore src/client",
|
||||
"start": "node lib/index.js",
|
||||
"start:server": "nodemon -e ts,tsx --ignore src/client -x ts-node src/index.ts",
|
||||
"start:watch": "chastifol [ npm run js:watch ] [ npm run css:watch ] [ npm run start:server ]",
|
||||
"watch": "",
|
||||
"prepublishOnly": "npm run build",
|
||||
"build": "npm run css && npm run js",
|
||||
"build": "npm run css && npm run ts && npm run js && npm run js:uglify",
|
||||
"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",
|
||||
"js": "browserify -g [ loose-envify purge --NODE_ENV production ] -t babelify ./lib/client/index.js -o ./build/index.prod.js",
|
||||
"js:watch": "watchify -p tsify ./src/client/index.tsx -v -d -o ./build/index.js",
|
||||
"js:uglify": "minify build/index.prod.js -o build/index.js",
|
||||
"css": "node-sass ./src/scss/style.scss -o ./build/",
|
||||
"css:watch": "npm run css && 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"
|
||||
"lint": "eslint --ext ts,tsx .",
|
||||
"lint:fix": "eslint --ext ts,tsx --fix .",
|
||||
"ci": "npm run lint && npm run test:coverage && npm run build",
|
||||
"ts:watch": "tsc -p . --watch --preserveWatchOutput",
|
||||
"ts": "tsc -p .",
|
||||
"clean": "rimraf lib/ tsconfig.tsbuildinfo build/*"
|
||||
},
|
||||
"babel": {
|
||||
"presets": [
|
||||
[
|
||||
"@babel/preset-env",
|
||||
{
|
||||
"forceAllTransforms": true,
|
||||
"targets": {
|
||||
"browsers": [
|
||||
"last 2 versions",
|
||||
@ -38,76 +43,73 @@
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"@babel/preset-react"
|
||||
],
|
||||
"plugins": [
|
||||
"@babel/plugin-proposal-class-properties",
|
||||
"@babel/plugin-proposal-object-rest-spread"
|
||||
]
|
||||
]
|
||||
},
|
||||
"author": "Jerko Steiner",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"bluebird": "^3.3.4",
|
||||
"classnames": "^2.2.5",
|
||||
"config": "^3.0.0",
|
||||
"express": "^4.13.3",
|
||||
"prop-types": "^15.5.10",
|
||||
"pug": "^2.0.0-rc.2",
|
||||
"config": "^3.2.4",
|
||||
"debug": "^4.1.1",
|
||||
"express": "^4.17.1",
|
||||
"pug": "^2.0.4",
|
||||
"socket.io": "^2.2.0",
|
||||
"uuid": "^3.3.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.7.2",
|
||||
"@babel/polyfill": "^7.7.0",
|
||||
"@babel/preset-env": "^7.7.1",
|
||||
"@types/classnames": "^2.2.9",
|
||||
"@types/config": "0.0.36",
|
||||
"@types/debug": "^4.1.5",
|
||||
"@types/express": "^4.17.2",
|
||||
"@types/jest": "^24.0.23",
|
||||
"@types/lodash": "^4.14.147",
|
||||
"@types/node": "^12.12.7",
|
||||
"@types/react": "^16.9.11",
|
||||
"@types/react-dom": "^16.9.4",
|
||||
"@types/react-redux": "^7.1.5",
|
||||
"@types/react-transition-group": "^4.2.3",
|
||||
"@types/redux": "^3.6.0",
|
||||
"@types/redux-logger": "^3.0.7",
|
||||
"@types/simple-peer": "^6.1.6",
|
||||
"@types/socket.io": "^2.1.4",
|
||||
"@types/socket.io-client": "^1.4.32",
|
||||
"@types/supertest": "^2.0.8",
|
||||
"@types/uuid": "^3.4.6",
|
||||
"@typescript-eslint/eslint-plugin": "^2.7.0",
|
||||
"@typescript-eslint/parser": "^2.7.0",
|
||||
"babel-core": "^7.0.0-bridge.0",
|
||||
"babel-minify": "^0.5.1",
|
||||
"babelify": "^10.0.0",
|
||||
"chastifol": "^4.1.0",
|
||||
"classnames": "^2.2.6",
|
||||
"core-js": "^3.4.1",
|
||||
"eslint": "^6.6.0",
|
||||
"eslint-plugin-import": "^2.18.2",
|
||||
"eslint-plugin-react": "^7.16.0",
|
||||
"jest": "^24.9.0",
|
||||
"lodash": "^4.17.15",
|
||||
"loose-envify": "^1.4.0",
|
||||
"node-sass": "^4.13.0",
|
||||
"nodemon": "^1.19.4",
|
||||
"react": "^16.6.3",
|
||||
"react-dom": "^16.6.3",
|
||||
"react-redux": "^6.0.0",
|
||||
"react-transition-group": "^1.2.1",
|
||||
"redux": "^4.0.1",
|
||||
"react-transition-group": "^2.5.1",
|
||||
"redux": "^4.0.4",
|
||||
"redux-logger": "^3.0.6",
|
||||
"redux-promise-middleware": "^5.1.1",
|
||||
"redux-thunk": "^2.2.0",
|
||||
"screenfull": "^3.3.3",
|
||||
"seamless-immutable": "^7.1.2",
|
||||
"rimraf": "^3.0.0",
|
||||
"screenfull": "^5.0.0",
|
||||
"simple-peer": "^9.1.2",
|
||||
"socket.io": "^2.2.0",
|
||||
"socket.io-client": "^2.2.0",
|
||||
"underscore": "^1.8.3",
|
||||
"uuid": "^3.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.5.0",
|
||||
"@babel/plugin-proposal-class-properties": "^7.5.0",
|
||||
"@babel/plugin-proposal-object-rest-spread": "^7.5.1",
|
||||
"@babel/polyfill": "^7.4.4",
|
||||
"@babel/preset-env": "^7.5.0",
|
||||
"@babel/preset-react": "^7.0.0",
|
||||
"babel-core": "^7.0.0-bridge.0",
|
||||
"babel-eslint": "^10.0.1",
|
||||
"babel-jest": "^24.8.0",
|
||||
"babelify": "^10.0.0",
|
||||
"chastifol": "^4.1.0",
|
||||
"eslint": "^5.10.0",
|
||||
"eslint-config-standard": "^12.0.0",
|
||||
"eslint-config-standard-react": "^7.0.2",
|
||||
"eslint-plugin-import": "^2.3.0",
|
||||
"eslint-plugin-node": "^8.0.0",
|
||||
"eslint-plugin-promise": "^4.0.1",
|
||||
"eslint-plugin-react": "^7.0.1",
|
||||
"eslint-plugin-standard": "^4.0.0",
|
||||
"jest-cli": "^24.8.0",
|
||||
"node-sass": "^4.13.0",
|
||||
"nodemon": "^1.18.8",
|
||||
"redux-mock-store": "^1.2.3",
|
||||
"supertest": "^3.0.0",
|
||||
"uglify-js": "^3.4.9",
|
||||
"ts-jest": "^24.1.0",
|
||||
"ts-node": "^8.5.0",
|
||||
"tsify": "^4.0.1",
|
||||
"typescript": "^3.7.2",
|
||||
"watchify": "^3.11.1"
|
||||
},
|
||||
"jest": {
|
||||
"transform": {
|
||||
"^.+\\.[t|j]sx?$": "<rootDir>/node_modules/babel-jest"
|
||||
},
|
||||
"setupFiles": [
|
||||
"<rootDir>/jest.setup.js"
|
||||
],
|
||||
"modulePathIgnorePatterns": [
|
||||
"<rootDir>/node_modules/"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
BIN
res/fonts/icons.eot
Normal file
25
res/fonts/icons.svg
Normal file
@ -0,0 +1,25 @@
|
||||
<?xml version="1.0" standalone="no"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<metadata>Generated by IcoMoon</metadata>
|
||||
<defs>
|
||||
<font id="icomoon" horiz-adv-x="1024">
|
||||
<font-face units-per-em="1024" ascent="870.850439882698" descent="-153.14956011730206" />
|
||||
<missing-glyph horiz-adv-x="1024" />
|
||||
<glyph unicode=" " horiz-adv-x="0" d="" />
|
||||
<glyph unicode="" glyph-name="mic" d="M738.721 376.857h72.070c0-146.143-116.113-266.26-256.25-286.28v-140.137h-84.082v140.137c-140.137 20.020-256.25 140.137-256.25 286.28h72.070c0-128.125 108.106-216.211 226.221-216.211s226.221 88.086 226.221 216.211zM512.5 248.732c-70.068 0-128.125 58.057-128.125 128.125v256.25c0 70.068 58.057 128.125 128.125 128.125s128.125-58.057 128.125-128.125v-256.25c0-70.068-58.057-128.125-128.125-128.125z" />
|
||||
<glyph unicode="" glyph-name="mic_off" d="M182.178 719.192l714.698-714.698-54.053-54.053-178.174 178.174c-32.031-20.020-72.070-32.031-110.108-38.037v-140.137h-84.082v140.137c-140.137 20.020-256.25 140.137-256.25 286.28h72.070c0-128.125 108.106-216.211 226.221-216.211 34.033 0 68.066 8.008 98.096 22.022l-70.068 70.068c-8.008-2.002-18.018-4.004-28.027-4.004-70.068 0-128.125 58.057-128.125 128.125v32.031l-256.25 256.25zM640.626 370.851l-256.25 254.248v8.008c0 70.068 58.057 128.125 128.125 128.125s128.125-58.057 128.125-128.125v-262.256zM810.792 376.857c0-50.049-14.014-98.096-38.037-140.137l-52.051 54.053c12.012 26.025 18.018 54.053 18.018 86.084h72.070z" />
|
||||
<glyph unicode="" glyph-name="videocam" d="M726.71 398.879l170.166 170.166v-468.457l-170.166 170.166v-150.147c0-24.023-20.020-42.041-44.043-42.041h-512.5c-24.023 0-42.041 18.018-42.041 42.041v428.418c0 24.023 18.018 42.041 42.041 42.041h512.5c24.023 0 44.043-18.018 44.043-42.041v-150.147z" />
|
||||
<glyph unicode="" glyph-name="videocam_off" d="M140.137 761.233l756.739-756.739-54.053-54.053-136.133 136.133c-6.006-4.004-16.016-8.008-24.023-8.008h-512.5c-24.023 0-42.041 18.018-42.041 42.041v428.418c0 24.023 18.018 42.041 42.041 42.041h32.031l-116.113 116.113zM896.876 569.045v-456.446l-478.467 478.467h264.258c24.023 0 44.043-18.018 44.043-42.041v-150.147z" />
|
||||
<glyph unicode="" glyph-name="call_end" d="M512.5 462.941c-68.066 0-134.131-10.010-196.192-30.029v-132.129c0-16.016-10.010-34.033-24.023-40.039-42.041-20.020-80.078-46.045-114.111-78.076-8.008-8.008-18.018-12.012-30.029-12.012s-22.022 4.004-30.029 12.012l-106.104 106.104c-8.008 8.008-12.012 18.018-12.012 30.029s4.004 22.022 12.012 30.029c130.127 124.121 306.299 200.196 500.489 200.196s370.362-76.074 500.489-200.196c8.008-8.008 12.012-18.018 12.012-30.029s-4.004-22.022-12.012-30.029l-106.104-106.104c-8.008-8.008-18.018-12.012-30.029-12.012s-22.022 4.004-30.029 12.012c-34.033 32.031-72.070 58.057-114.111 78.076-14.014 6.006-24.023 20.020-24.023 38.037v132.129c-62.061 20.020-128.125 32.031-196.192 32.031z" />
|
||||
<glyph unicode="" glyph-name="arrow_forward" d="M512.5 677.151l342.334-342.334-342.334-342.334-60.059 60.059 238.233 240.235h-520.508v84.082h520.508l-238.233 240.235z" />
|
||||
<glyph unicode="" glyph-name="fullscreen" d="M598.585 633.108h212.207v-212.207h-84.082v128.125h-128.125v84.082zM726.71 120.607v128.125h84.082v-212.207h-212.207v84.082h128.125zM214.209 420.9v212.207h212.207v-84.082h-128.125v-128.125h-84.082zM298.291 248.732v-128.125h128.125v-84.082h-212.207v212.207h84.082z" />
|
||||
<glyph unicode="" glyph-name="fullscreen_exit" d="M682.667 504.982h128.125v-84.082h-212.207v212.207h84.082v-128.125zM598.585 36.525v212.207h212.207v-84.082h-128.125v-128.125h-84.082zM342.334 504.982v128.125h84.082v-212.207h-212.207v84.082h128.125zM214.209 164.65v84.082h212.207v-212.207h-84.082v128.125h-128.125z" />
|
||||
<glyph unicode="" glyph-name="more_vert" d="M512.5 164.65c46.045 0 86.084-40.039 86.084-86.084s-40.039-86.084-86.084-86.084-86.084 40.039-86.084 86.084 40.039 86.084 86.084 86.084zM512.5 420.9c46.045 0 86.084-40.039 86.084-86.084s-40.039-86.084-86.084-86.084-86.084 40.039-86.084 86.084 40.039 86.084 86.084 86.084zM512.5 504.982c-46.045 0-86.084 40.039-86.084 86.084s40.039 86.084 86.084 86.084 86.084-40.039 86.084-86.084-40.039-86.084-86.084-86.084z" />
|
||||
<glyph unicode="" glyph-name="sentiment_satisfied" d="M512.5 164.65c64.063 0 118.115 34.033 148.145 84.082h70.068c-34.033-88.086-118.115-148.145-218.213-148.145s-184.18 60.059-218.213 148.145h70.068c30.029-50.049 84.082-84.082 148.145-84.082zM512.5-7.518c188.184 0 342.334 154.151 342.334 342.334s-154.151 342.334-342.334 342.334-342.334-154.151-342.334-342.334 154.151-342.334 342.334-342.334zM512.5 761.233c236.231 0 426.416-190.186 426.416-426.416s-190.186-426.416-426.416-426.416-426.416 190.186-426.416 426.416 190.186 426.416 426.416 426.416zM298.291 440.92c0 36.035 28.027 64.063 64.063 64.063s64.063-28.027 64.063-64.063-28.027-64.063-64.063-64.063-64.063 28.027-64.063 64.063zM598.585 440.92c0 36.035 28.027 64.063 64.063 64.063s64.063-28.027 64.063-64.063-28.027-64.063-64.063-64.063-64.063 28.027-64.063 64.063z" />
|
||||
<glyph unicode="" glyph-name="face" d="M512.5-7.518c188.184 0 342.334 154.151 342.334 342.334 0 34.033-6.006 66.065-14.014 96.094-30.029-8.008-62.061-10.010-96.094-10.010-144.141 0-270.264 70.068-348.34 180.176-42.041-102.1-124.121-186.182-224.219-230.225-2.002-12.012-2.002-24.023-2.002-36.035 0-188.184 154.151-342.334 342.334-342.334zM512.5 761.233c236.231 0 426.416-190.186 426.416-426.416s-190.186-426.416-426.416-426.416-426.416 190.186-426.416 426.416 190.186 426.416 426.416 426.416zM640.626 344.826c30.029 0 54.053-22.022 54.053-52.051s-24.023-54.053-54.053-54.053-54.053 24.023-54.053 54.053 24.023 52.051 54.053 52.051zM384.375 344.826c30.029 0 54.053-22.022 54.053-52.051s-24.023-54.053-54.053-54.053-54.053 24.023-54.053 54.053 24.023 52.051 54.053 52.051z" />
|
||||
<glyph unicode="" glyph-name="question_answer" d="M726.71 334.816c0-24.023-20.020-42.041-44.043-42.041h-426.416l-170.166-172.168v598.585c0 24.023 18.018 42.041 42.041 42.041h554.542c24.023 0 44.043-18.018 44.043-42.041v-384.375zM896.876 591.066c24.023 0 42.041-18.018 42.041-42.041v-640.626l-170.166 170.166h-470.459c-24.023 0-42.041 18.018-42.041 42.041v86.084h554.542v384.375h86.084z" />
|
||||
<glyph unicode="" glyph-name="room" d="M512.5 356.838c58.057 0 106.104 48.047 106.104 106.104s-48.047 106.104-106.104 106.104-106.104-48.047-106.104-106.104 48.047-106.104 106.104-106.104zM512.5 761.233c166.162 0 298.291-132.129 298.291-298.291 0-224.219-298.291-554.542-298.291-554.542s-298.291 330.323-298.291 554.542c0 166.162 132.129 298.291 298.291 298.291z" />
|
||||
<glyph unicode="" glyph-name="schedule" d="M534.522 549.025v-224.219l192.188-114.111-32.031-54.053-224.219 136.133v256.25h64.063zM512.5-7.518c188.184 0 342.334 154.151 342.334 342.334s-154.151 342.334-342.334 342.334-342.334-154.151-342.334-342.334 154.151-342.334 342.334-342.334zM512.5 761.233c236.231 0 426.416-190.186 426.416-426.416s-190.186-426.416-426.416-426.416-426.416 190.186-426.416 426.416 190.186 426.416 426.416 426.416z" />
|
||||
<glyph unicode="" glyph-name="file-text2" d="M917.806 666.924c-22.212 30.292-53.174 65.7-87.178 99.704s-69.412 64.964-99.704 87.178c-51.574 37.82-76.592 42.194-90.924 42.194h-496c-44.112 0-80-35.888-80-80v-864c0-44.112 35.888-80 80-80h736c44.112 0 80 35.888 80 80v624c0 14.332-4.372 39.35-42.194 90.924zM785.374 721.374c30.7-30.7 54.8-58.398 72.58-81.374h-153.954v153.946c22.984-17.78 50.678-41.878 81.374-72.572zM896-48c0-8.672-7.328-16-16-16h-736c-8.672 0-16 7.328-16 16v864c0 8.672 7.328 16 16 16 0 0 495.956 0.002 496 0v-224c0-17.672 14.326-32 32-32h224v-624zM736 64h-448c-17.672 0-32 14.326-32 32s14.328 32 32 32h448c17.674 0 32-14.326 32-32s-14.326-32-32-32zM736 192h-448c-17.672 0-32 14.326-32 32s14.328 32 32 32h448c17.674 0 32-14.326 32-32s-14.326-32-32-32zM736 320h-448c-17.672 0-32 14.326-32 32s14.328 32 32 32h448c17.674 0 32-14.326 32-32s-14.326-32-32-32z" />
|
||||
</font></defs></svg>
|
||||
|
After Width: | Height: | Size: 7.8 KiB |
BIN
res/fonts/icons.ttf
Normal file
BIN
res/fonts/icons.woff
Normal file
|
Before Width: | Height: | Size: 9.0 KiB After Width: | Height: | Size: 9.0 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 13 KiB |
14
src/__mocks__/simple-peer.ts
Normal file
@ -0,0 +1,14 @@
|
||||
/* eslint-disable */
|
||||
import EventEmitter from 'events'
|
||||
|
||||
const Peer = jest.fn().mockImplementation(() => {
|
||||
const peer = new EventEmitter();
|
||||
(peer as any).destroy = jest.fn();
|
||||
(peer as any).signal = jest.fn();
|
||||
(peer as any).send = jest.fn();
|
||||
(Peer as any).instances.push(peer)
|
||||
return peer
|
||||
});
|
||||
|
||||
(Peer as any).instances = []
|
||||
export default Peer
|
||||
@ -1,3 +0,0 @@
|
||||
import configureStore from 'redux-mock-store'
|
||||
import { middlewares } from '../middlewares.js'
|
||||
export default configureStore(middlewares)({})
|
||||
@ -1,5 +1,3 @@
|
||||
import Promise from 'bluebird'
|
||||
|
||||
export const createObjectURL = jest.fn()
|
||||
.mockImplementation(object => 'blob://' + String(object))
|
||||
export const revokeObjectURL = jest.fn()
|
||||
@ -7,12 +5,12 @@ export const revokeObjectURL = jest.fn()
|
||||
export class MediaStream {
|
||||
getVideoTracks () {
|
||||
return [{
|
||||
enabled: true
|
||||
enabled: true,
|
||||
}]
|
||||
}
|
||||
getAudioTracks () {
|
||||
return [{
|
||||
enabled: true
|
||||
enabled: true,
|
||||
}]
|
||||
}
|
||||
}
|
||||
@ -21,7 +19,9 @@ export function getUserMedia () {
|
||||
? Promise.resolve(getUserMedia.stream)
|
||||
: Promise.reject(new Error('test'))
|
||||
}
|
||||
getUserMedia.fail = shouldFail => getUserMedia.shouldFail = shouldFail
|
||||
getUserMedia.shouldFail = false
|
||||
getUserMedia.fail = (shouldFail: boolean) =>
|
||||
getUserMedia.shouldFail = shouldFail
|
||||
getUserMedia.stream = new MediaStream()
|
||||
|
||||
export const navigator = window.navigator
|
||||
@ -1,50 +0,0 @@
|
||||
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: { facingMode: 'user' }, 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
|
||||
})
|
||||
}
|
||||
@ -1,86 +0,0 @@
|
||||
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', async () => {
|
||||
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'
|
||||
}
|
||||
}])
|
||||
await promise
|
||||
expect(SocketActions.handshake.mock.calls).toEqual([[{
|
||||
socket,
|
||||
roomName: callId,
|
||||
stream: getUserMedia.stream
|
||||
}]])
|
||||
})
|
||||
|
||||
it('calls dispatches disconnect message on disconnect', async () => {
|
||||
|
||||
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'
|
||||
}
|
||||
}])
|
||||
await promise
|
||||
})
|
||||
|
||||
it('dispatches alert when failed to get media stream', async () => {
|
||||
getUserMedia.fail(true)
|
||||
const promise = store.dispatch(CallActions.init())
|
||||
socket.emit('connect')
|
||||
const result = await promise
|
||||
expect(result.value).toBe(null)
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
})
|
||||
105
src/client/actions/CallActions.test.ts
Normal file
@ -0,0 +1,105 @@
|
||||
jest.mock('../socket')
|
||||
jest.mock('../window')
|
||||
jest.mock('./SocketActions')
|
||||
|
||||
import * as CallActions from './CallActions'
|
||||
import * as SocketActions from './SocketActions'
|
||||
import * as constants from '../constants'
|
||||
import socket from '../socket'
|
||||
import { callId, getUserMedia } from '../window'
|
||||
import { bindActionCreators, createStore, AnyAction, combineReducers, applyMiddleware } from 'redux'
|
||||
import reducers from '../reducers'
|
||||
import { middlewares } from '../middlewares'
|
||||
|
||||
jest.useFakeTimers()
|
||||
|
||||
describe('CallActions', () => {
|
||||
|
||||
let callActions: typeof CallActions
|
||||
|
||||
function allActions(state: AnyAction[] = [], action: AnyAction) {
|
||||
return [...state, action]
|
||||
}
|
||||
|
||||
const configureStore = () => createStore(
|
||||
combineReducers({...reducers, allActions }),
|
||||
applyMiddleware(...middlewares),
|
||||
)
|
||||
let store: ReturnType<typeof configureStore>
|
||||
|
||||
beforeEach(() => {
|
||||
store = createStore(
|
||||
combineReducers({ allActions }),
|
||||
applyMiddleware(...middlewares),
|
||||
)
|
||||
callActions = bindActionCreators(CallActions, store.dispatch);
|
||||
(getUserMedia as any).fail(false);
|
||||
(SocketActions.handshake as jest.Mock).mockReturnValue(jest.fn())
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
jest.runAllTimers()
|
||||
socket.removeAllListeners()
|
||||
})
|
||||
|
||||
describe('init', () => {
|
||||
|
||||
it('calls handshake.init when connected & got camera stream', async () => {
|
||||
const promise = callActions.init()
|
||||
socket.emit('connect')
|
||||
await promise
|
||||
expect(store.getState().allActions.slice(1)).toEqual([{
|
||||
type: constants.NOTIFY,
|
||||
payload: {
|
||||
id: jasmine.any(String),
|
||||
message: 'Connected to server socket',
|
||||
type: 'warning',
|
||||
},
|
||||
}, {
|
||||
type: constants.STREAM_ADD,
|
||||
payload: {
|
||||
stream: jasmine.anything(),
|
||||
userId: constants.ME,
|
||||
},
|
||||
}, {
|
||||
type: constants.INIT,
|
||||
}])
|
||||
expect((SocketActions.handshake as jest.Mock).mock.calls).toEqual([[{
|
||||
socket,
|
||||
roomName: callId,
|
||||
stream: (getUserMedia as any).stream,
|
||||
}]])
|
||||
})
|
||||
|
||||
it('calls dispatches disconnect message on disconnect', async () => {
|
||||
const promise = callActions.init()
|
||||
socket.emit('connect')
|
||||
socket.emit('disconnect')
|
||||
expect(store.getState().allActions.slice(1)).toEqual([{
|
||||
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',
|
||||
},
|
||||
}])
|
||||
await promise
|
||||
})
|
||||
|
||||
it('dispatches alert when failed to get media stream', async () => {
|
||||
(getUserMedia as any).fail(true)
|
||||
const promise = callActions.init()
|
||||
socket.emit('connect')
|
||||
await promise
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
})
|
||||
62
src/client/actions/CallActions.ts
Normal file
@ -0,0 +1,62 @@
|
||||
import * as constants from '../constants'
|
||||
import socket from '../socket'
|
||||
import { Dispatch, ThunkResult } from '../store'
|
||||
import { callId, getUserMedia } from '../window'
|
||||
import * as NotifyActions from './NotifyActions'
|
||||
import * as SocketActions from './SocketActions'
|
||||
import * as StreamActions from './StreamActions'
|
||||
|
||||
export interface InitAction {
|
||||
type: 'INIT'
|
||||
payload: Promise<void>
|
||||
}
|
||||
|
||||
interface InitializeAction {
|
||||
type: 'INIT'
|
||||
}
|
||||
|
||||
const initialize = (): InitializeAction => ({
|
||||
type: 'INIT',
|
||||
})
|
||||
|
||||
export const init = (): ThunkResult<Promise<void>> =>
|
||||
async (dispatch, getState) => {
|
||||
const socket = await dispatch(connect())
|
||||
const stream = await dispatch(getCameraStream())
|
||||
|
||||
dispatch(SocketActions.handshake({
|
||||
socket,
|
||||
roomName: callId,
|
||||
stream,
|
||||
}))
|
||||
|
||||
dispatch(initialize())
|
||||
}
|
||||
|
||||
export const connect = () => (dispatch: Dispatch) => {
|
||||
return new Promise<SocketIOClient.Socket>(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 = () => async (dispatch: Dispatch) => {
|
||||
try {
|
||||
const stream = await getUserMedia({
|
||||
video: { facingMode: 'user' },
|
||||
audio: true,
|
||||
})
|
||||
dispatch(StreamActions.addStream({ stream, userId: constants.ME }))
|
||||
return stream
|
||||
} catch (err) {
|
||||
dispatch(NotifyActions.alert('Could not get access to microphone & camera'))
|
||||
return
|
||||
}
|
||||
}
|
||||
@ -1,16 +0,0 @@
|
||||
import * as constants from '../constants.js'
|
||||
|
||||
export const addMessage = ({ userId, message, timestamp, image }) => ({
|
||||
type: constants.MESSAGE_ADD,
|
||||
payload: {
|
||||
userId,
|
||||
message,
|
||||
timestamp,
|
||||
image
|
||||
}
|
||||
})
|
||||
|
||||
export const loadHistory = messages => ({
|
||||
type: constants.MESSAGES_HISTORY,
|
||||
messages
|
||||
})
|
||||
18
src/client/actions/ChatActions.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { MESSAGE_ADD } from '../constants'
|
||||
|
||||
export interface MessageAddAction {
|
||||
type: 'MESSAGE_ADD'
|
||||
payload: Message
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
userId: string
|
||||
message: string
|
||||
timestamp: string
|
||||
image?: string
|
||||
}
|
||||
|
||||
export const addMessage = (message: Message): MessageAddAction => ({
|
||||
type: MESSAGE_ADD,
|
||||
payload: message,
|
||||
})
|
||||
@ -1,68 +0,0 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
133
src/client/actions/NotifyActions.ts
Normal file
@ -0,0 +1,133 @@
|
||||
import uniqueId from 'lodash/uniqueId'
|
||||
import { Dispatch } from 'redux'
|
||||
import * as constants from '../constants'
|
||||
import { ThunkResult } from '../store'
|
||||
|
||||
const TIMEOUT = 5000
|
||||
|
||||
function format (string: string, args: string[]) {
|
||||
string = args
|
||||
.reduce((string, arg, i) => string.replace('{' + i + '}', arg), string)
|
||||
return string
|
||||
}
|
||||
|
||||
export type NotifyType = 'info' | 'warning' | 'error'
|
||||
|
||||
function notify(dispatch: Dispatch, type: NotifyType, args: string[]) {
|
||||
const string = args[0] || ''
|
||||
const message = format(string, Array.prototype.slice.call(args, 1))
|
||||
const id = uniqueId('notification')
|
||||
const payload: Notification = { id, type, message }
|
||||
|
||||
setTimeout(() => {
|
||||
dispatch(dismissNotification(id))
|
||||
}, TIMEOUT)
|
||||
|
||||
return addNotification(payload)
|
||||
}
|
||||
|
||||
export const info = (...args: any[]): ThunkResult<NotificationAddAction> => {
|
||||
return dispatch => dispatch(notify(dispatch, 'info', args))
|
||||
}
|
||||
|
||||
export const warning = (...args: any[]): ThunkResult<NotificationAddAction> => {
|
||||
return dispatch => dispatch(notify(dispatch, 'warning', args))
|
||||
}
|
||||
|
||||
export const error = (...args: any[]): ThunkResult<NotificationAddAction> => {
|
||||
return dispatch => dispatch(notify(dispatch, 'error', args))
|
||||
}
|
||||
|
||||
function addNotification(payload: Notification): NotificationAddAction {
|
||||
return {
|
||||
type: constants.NOTIFY,
|
||||
payload,
|
||||
}
|
||||
}
|
||||
|
||||
function dismissNotification(id: string): NotificationDismissAction {
|
||||
return {
|
||||
type: constants.NOTIFY_DISMISS,
|
||||
payload: { id },
|
||||
}
|
||||
}
|
||||
|
||||
export interface Notification {
|
||||
id: string
|
||||
type: NotifyType
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface NotificationAddAction {
|
||||
type: 'NOTIFY'
|
||||
payload: Notification
|
||||
}
|
||||
|
||||
export interface NotificationDismissAction {
|
||||
type: 'NOTIFY_DISMISS'
|
||||
payload: { id: string }
|
||||
}
|
||||
|
||||
export interface NotificationClearAction {
|
||||
type: 'NOTIFY_CLEAR'
|
||||
}
|
||||
|
||||
export const clear = (): NotificationClearAction => ({
|
||||
type: constants.NOTIFY_CLEAR,
|
||||
})
|
||||
|
||||
export interface Alert {
|
||||
action?: string
|
||||
dismissable: boolean
|
||||
message: string
|
||||
type: NotifyType
|
||||
}
|
||||
|
||||
export interface AlertAddAction {
|
||||
type: 'ALERT'
|
||||
payload: Alert
|
||||
}
|
||||
|
||||
export function alert (message: string, dismissable = false): AlertAddAction {
|
||||
return {
|
||||
type: constants.ALERT,
|
||||
payload: {
|
||||
action: dismissable ? 'Dismiss' : undefined,
|
||||
dismissable: !!dismissable,
|
||||
message,
|
||||
type: 'warning',
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export interface AlertDismissAction {
|
||||
type: 'ALERT_DISMISS'
|
||||
payload: Alert
|
||||
}
|
||||
|
||||
export const dismissAlert = (alert: Alert): AlertDismissAction => {
|
||||
return {
|
||||
type: constants.ALERT_DISMISS,
|
||||
payload: alert,
|
||||
}
|
||||
}
|
||||
|
||||
export interface AlertClearAction {
|
||||
type: 'ALERT_CLEAR'
|
||||
}
|
||||
|
||||
export const clearAlerts = (): AlertClearAction => {
|
||||
return {
|
||||
type: constants.ALERT_CLEAR,
|
||||
}
|
||||
}
|
||||
|
||||
export type AlertActionType =
|
||||
AlertAddAction |
|
||||
AlertDismissAction |
|
||||
AlertClearAction
|
||||
|
||||
export type NotificationActionType =
|
||||
NotificationAddAction |
|
||||
NotificationDismissAction |
|
||||
NotificationClearAction
|
||||
@ -1,132 +0,0 @@
|
||||
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))
|
||||
}
|
||||
@ -1,170 +0,0 @@
|
||||
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"}' ]])
|
||||
})
|
||||
|
||||
})
|
||||
})
|
||||
177
src/client/actions/PeerActions.test.ts
Normal file
@ -0,0 +1,177 @@
|
||||
jest.mock('../window')
|
||||
jest.mock('simple-peer')
|
||||
|
||||
import * as PeerActions from './PeerActions'
|
||||
import Peer from 'simple-peer'
|
||||
import { EventEmitter } from 'events'
|
||||
import { createStore, Store, GetState } from '../store'
|
||||
import { play } from '../window'
|
||||
import { Dispatch } from 'redux'
|
||||
|
||||
describe('PeerActions', () => {
|
||||
function createSocket () {
|
||||
const socket = new EventEmitter() as unknown as SocketIOClient.Socket
|
||||
socket.id = 'user1'
|
||||
return socket
|
||||
}
|
||||
|
||||
let socket: SocketIOClient.Socket
|
||||
let stream: MediaStream
|
||||
let user: { id: string }
|
||||
let store: Store
|
||||
let instances: Peer.Instance[]
|
||||
let dispatch: Dispatch
|
||||
let getState: GetState
|
||||
let PeerMock: jest.Mock<Peer.Instance>
|
||||
|
||||
beforeEach(() => {
|
||||
store = createStore()
|
||||
dispatch = store.dispatch
|
||||
getState = store.getState
|
||||
|
||||
user = { id: 'user2' }
|
||||
socket = createSocket()
|
||||
instances = (Peer as any).instances = [];
|
||||
(Peer as unknown as jest.Mock).mockClear();
|
||||
(play as jest.Mock).mockClear()
|
||||
stream = { stream: true } as unknown as MediaStream
|
||||
PeerMock = Peer as unknown as jest.Mock<Peer.Instance>
|
||||
})
|
||||
|
||||
describe('create', () => {
|
||||
it('creates a new peer', () => {
|
||||
PeerActions.createPeer({ socket, user, initiator: 'user2', stream })(
|
||||
dispatch, getState)
|
||||
|
||||
expect(instances.length).toBe(1)
|
||||
expect(PeerMock.mock.calls.length).toBe(1)
|
||||
expect(PeerMock.mock.calls[0][0].initiator).toBe(false)
|
||||
expect(PeerMock.mock.calls[0][0].stream).toBe(stream)
|
||||
})
|
||||
|
||||
it('sets initiator correctly', () => {
|
||||
PeerActions
|
||||
.createPeer({
|
||||
socket, user, initiator: 'user1', stream,
|
||||
})(dispatch, getState)
|
||||
|
||||
expect(instances.length).toBe(1)
|
||||
expect(PeerMock.mock.calls.length).toBe(1)
|
||||
expect(PeerMock.mock.calls[0][0].initiator).toBe(true)
|
||||
expect(PeerMock.mock.calls[0][0].stream).toBe(stream)
|
||||
})
|
||||
|
||||
it('destroys old peer before creating new one', () => {
|
||||
PeerActions.createPeer({ socket, user, initiator: 'user2', stream })(
|
||||
dispatch, getState)
|
||||
PeerActions.createPeer({ socket, user, initiator: 'user2', stream })(
|
||||
dispatch, getState)
|
||||
|
||||
expect(instances.length).toBe(2)
|
||||
expect(PeerMock.mock.calls.length).toBe(2)
|
||||
expect((instances[0].destroy as jest.Mock).mock.calls.length).toBe(1)
|
||||
expect((instances[1].destroy as jest.Mock).mock.calls.length).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('events', () => {
|
||||
let peer: Peer.Instance
|
||||
|
||||
beforeEach(() => {
|
||||
PeerActions.createPeer({ socket, user, initiator: 'user1', stream })(
|
||||
dispatch, getState)
|
||||
peer = instances[0]
|
||||
})
|
||||
|
||||
describe('connect', () => {
|
||||
beforeEach(() => peer.emit('connect'))
|
||||
|
||||
it('dispatches "play" action', () => {
|
||||
expect((play as jest.Mock).mock.calls.length).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('data', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
(window as any).TextDecoder = class TextDecoder {
|
||||
constructor (readonly encoding: string) {
|
||||
}
|
||||
decode (object: any) {
|
||||
return object.toString(this.encoding)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('decodes a message', () => {
|
||||
const payload = 'test'
|
||||
const object = JSON.stringify({ payload })
|
||||
peer.emit('data', Buffer.from(object, 'utf-8'))
|
||||
const { list } = store.getState().messages
|
||||
expect(list[list.length - 1]).toEqual({
|
||||
userId: 'user2',
|
||||
timestamp: jasmine.any(String),
|
||||
image: undefined,
|
||||
message: 'test',
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('get', () => {
|
||||
it('returns undefined when not found', () => {
|
||||
const { peers } = store.getState()
|
||||
expect(peers[user.id]).not.toBeDefined()
|
||||
})
|
||||
|
||||
it('returns Peer instance when found', () => {
|
||||
PeerActions.createPeer({ socket, user, initiator: 'user2', stream })(
|
||||
dispatch, getState)
|
||||
|
||||
const { peers } = store.getState()
|
||||
expect(peers[user.id]).toBe(instances[0])
|
||||
})
|
||||
})
|
||||
|
||||
describe('destroyPeers', () => {
|
||||
it('destroys all peers and removes them', () => {
|
||||
PeerActions.createPeer({
|
||||
socket, user: { id: 'user2' }, initiator: 'user2', stream,
|
||||
})(dispatch, getState)
|
||||
PeerActions.createPeer({
|
||||
socket, user: { id: 'user3' }, initiator: 'user3', stream,
|
||||
})(dispatch, getState)
|
||||
|
||||
store.dispatch(PeerActions.destroyPeers())
|
||||
|
||||
expect((instances[0].destroy as jest.Mock).mock.calls.length).toEqual(1)
|
||||
expect((instances[1].destroy as jest.Mock).mock.calls.length).toEqual(1)
|
||||
|
||||
const { peers } = store.getState()
|
||||
expect(Object.keys(peers)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('sendMessage', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
PeerActions.createPeer({
|
||||
socket, user: { id: 'user2' }, initiator: 'user2', stream,
|
||||
})(dispatch, getState)
|
||||
PeerActions.createPeer({
|
||||
socket, user: { id: 'user3' }, initiator: 'user3', stream,
|
||||
})(dispatch, getState)
|
||||
})
|
||||
|
||||
it('sends a message to all peers', () => {
|
||||
PeerActions.sendMessage({ payload: 'test', type: 'text' })(
|
||||
dispatch, getState)
|
||||
const { peers } = store.getState()
|
||||
expect((peers['user2'].send as jest.Mock).mock.calls)
|
||||
.toEqual([[ '{"payload":"test","type":"text"}' ]])
|
||||
expect((peers['user3'].send as jest.Mock).mock.calls)
|
||||
.toEqual([[ '{"payload":"test","type":"text"}' ]])
|
||||
})
|
||||
|
||||
})
|
||||
})
|
||||
262
src/client/actions/PeerActions.ts
Normal file
@ -0,0 +1,262 @@
|
||||
import * as ChatActions from '../actions/ChatActions'
|
||||
import * as NotifyActions from '../actions/NotifyActions'
|
||||
import * as StreamActions from '../actions/StreamActions'
|
||||
import * as constants from '../constants'
|
||||
import Peer from 'simple-peer'
|
||||
import forEach from 'lodash/forEach'
|
||||
import _debug from 'debug'
|
||||
import { play, iceServers } from '../window'
|
||||
import { Dispatch, GetState } from '../store'
|
||||
|
||||
const debug = _debug('peercalls')
|
||||
|
||||
export interface Peers {
|
||||
[id: string]: Peer.Instance
|
||||
}
|
||||
|
||||
export interface PeerHandlerOptions {
|
||||
socket: SocketIOClient.Socket
|
||||
user: { id: string }
|
||||
dispatch: Dispatch
|
||||
getState: GetState
|
||||
}
|
||||
|
||||
class PeerHandler {
|
||||
socket: SocketIOClient.Socket
|
||||
user: { id: string }
|
||||
dispatch: Dispatch
|
||||
getState: GetState
|
||||
|
||||
constructor (readonly options: PeerHandlerOptions) {
|
||||
this.socket = options.socket
|
||||
this.user = options.user
|
||||
this.dispatch = options.dispatch
|
||||
this.getState = options.getState
|
||||
}
|
||||
handleError = (err: Error) => {
|
||||
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: unknown) => {
|
||||
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: MediaStream) => {
|
||||
const { user, dispatch } = this
|
||||
debug('peer: %s, stream', user.id)
|
||||
dispatch(StreamActions.addStream({
|
||||
userId: user.id,
|
||||
stream,
|
||||
}))
|
||||
}
|
||||
handleData = (buffer: ArrayBuffer) => {
|
||||
const { dispatch, user } = this
|
||||
const message = JSON.parse(new window.TextDecoder('utf-8').decode(buffer))
|
||||
debug('peer: %s, message: %o', user.id, buffer)
|
||||
switch (message.type) {
|
||||
case 'file':
|
||||
dispatch(ChatActions.addMessage({
|
||||
userId: user.id,
|
||||
message: message.payload.name,
|
||||
timestamp: new Date().toLocaleString(),
|
||||
image: message.payload.data,
|
||||
}))
|
||||
break
|
||||
default:
|
||||
dispatch(ChatActions.addMessage({
|
||||
userId: user.id,
|
||||
message: message.payload,
|
||||
timestamp: new Date().toLocaleString(),
|
||||
image: undefined,
|
||||
}))
|
||||
}
|
||||
}
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
export interface CreatePeerOptions {
|
||||
socket: SocketIOClient.Socket
|
||||
user: { id: string }
|
||||
initiator: string
|
||||
stream?: MediaStream
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 (options: CreatePeerOptions) {
|
||||
const { socket, user, initiator, stream } = options
|
||||
|
||||
return (dispatch: Dispatch, getState: 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 interface AddPeerParams {
|
||||
peer: Peer.Instance
|
||||
userId: string
|
||||
}
|
||||
|
||||
export interface AddPeerAction {
|
||||
type: 'PEER_ADD'
|
||||
payload: AddPeerParams
|
||||
}
|
||||
|
||||
export const addPeer = (payload: AddPeerParams): AddPeerAction => ({
|
||||
type: constants.PEER_ADD,
|
||||
payload,
|
||||
})
|
||||
|
||||
export interface RemovePeerAction {
|
||||
type: 'PEER_REMOVE'
|
||||
payload: { userId: string }
|
||||
}
|
||||
|
||||
export const removePeer = (userId: string): RemovePeerAction => ({
|
||||
type: constants.PEER_REMOVE,
|
||||
payload: { userId },
|
||||
})
|
||||
|
||||
export interface DestroyPeersAction {
|
||||
type: 'PEERS_DESTROY'
|
||||
}
|
||||
|
||||
export const destroyPeers = (): DestroyPeersAction => ({
|
||||
type: constants.PEERS_DESTROY,
|
||||
})
|
||||
|
||||
export type PeerAction =
|
||||
AddPeerAction |
|
||||
RemovePeerAction |
|
||||
DestroyPeersAction
|
||||
|
||||
export interface TextMessage {
|
||||
type: 'text'
|
||||
payload: string
|
||||
}
|
||||
|
||||
export interface Base64File {
|
||||
name: string
|
||||
size: number
|
||||
type: string
|
||||
data: string
|
||||
}
|
||||
|
||||
export interface FileMessage {
|
||||
type: 'file'
|
||||
payload: Base64File
|
||||
}
|
||||
|
||||
export type Message = TextMessage | FileMessage
|
||||
|
||||
export const sendMessage = (message: Message) =>
|
||||
(dispatch: Dispatch, getState: GetState) => {
|
||||
const { peers } = getState()
|
||||
debug('Sending message type: %s to %s peers.',
|
||||
message.type, Object.keys(peers).length)
|
||||
forEach(peers, (peer, userId) => {
|
||||
switch (message.type) {
|
||||
case 'file':
|
||||
dispatch(ChatActions.addMessage({
|
||||
userId: 'You',
|
||||
message: 'Send file: "' +
|
||||
message.payload.name + '" to peer: ' + userId,
|
||||
timestamp: new Date().toLocaleString(),
|
||||
image: message.payload.data,
|
||||
}))
|
||||
break
|
||||
default:
|
||||
dispatch(ChatActions.addMessage({
|
||||
userId: 'You',
|
||||
message: message.payload,
|
||||
timestamp: new Date().toLocaleString(),
|
||||
image: undefined,
|
||||
}))
|
||||
}
|
||||
peer.send(JSON.stringify(message))
|
||||
})
|
||||
}
|
||||
|
||||
export const sendFile = (file: File) =>
|
||||
async (dispatch: Dispatch, getState: GetState) => {
|
||||
const { name, size, type } = file
|
||||
if (!window.FileReader) {
|
||||
dispatch(NotifyActions.error('File API is not supported by your browser'))
|
||||
return
|
||||
}
|
||||
const reader = new window.FileReader()
|
||||
const base64File = await new Promise<Base64File>(resolve => {
|
||||
reader.addEventListener('load', () => {
|
||||
resolve({
|
||||
name,
|
||||
size,
|
||||
type,
|
||||
data: reader.result as string,
|
||||
})
|
||||
})
|
||||
reader.readAsDataURL(file)
|
||||
})
|
||||
|
||||
sendMessage({ payload: base64File, type: 'file' })(dispatch, getState)
|
||||
}
|
||||
@ -1,77 +0,0 @@
|
||||
import * as ChatActions from '../actions/ChatActions.js'
|
||||
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())
|
||||
}
|
||||
handleMessages = (messages) => {
|
||||
const { dispatch } = this
|
||||
debug('socket messages: %o', messages)
|
||||
dispatch(ChatActions.loadHistory(messages))
|
||||
}
|
||||
handleNewMessage = (payload) => {
|
||||
const { dispatch } = this
|
||||
debug('socket message: %o', payload)
|
||||
dispatch(ChatActions.addMessage(payload))
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
socket.on(constants.SOCKET_EVENT_MESSAGES, handler.handleMessages)
|
||||
socket.on(constants.SOCKET_EVENT_NEW_MESSAGE, handler.handleNewMessage)
|
||||
|
||||
debug('socket.id: %s', socket.id)
|
||||
debug('emit ready for room: %s', roomName)
|
||||
dispatch(NotifyActions.info('Ready for connections'))
|
||||
socket.emit('ready', roomName)
|
||||
}
|
||||
}
|
||||
@ -1,98 +1,105 @@
|
||||
jest.mock('simple-peer')
|
||||
jest.mock('../window.js')
|
||||
jest.mock('../window')
|
||||
|
||||
import * as SocketActions from './SocketActions.js'
|
||||
import * as constants from '../constants.js'
|
||||
import * as SocketActions from './SocketActions'
|
||||
import * as constants from '../constants'
|
||||
import Peer from 'simple-peer'
|
||||
import { EventEmitter } from 'events'
|
||||
import { createStore } from '../store.js'
|
||||
import { createStore, Store, GetState } from '../store'
|
||||
import { Dispatch } from 'redux'
|
||||
|
||||
describe('SocketActions', () => {
|
||||
const roomName = 'bla'
|
||||
|
||||
let socket, store
|
||||
let socket: SocketIOClient.Socket
|
||||
let store: Store
|
||||
let dispatch: Dispatch
|
||||
let getState: GetState
|
||||
let instances: Peer.Instance[]
|
||||
beforeEach(() => {
|
||||
socket = new EventEmitter()
|
||||
socket.id = 'a'
|
||||
socket = new EventEmitter() as any;
|
||||
(socket as any).id = 'a'
|
||||
|
||||
store = createStore()
|
||||
getState = store.getState
|
||||
dispatch = store.dispatch
|
||||
|
||||
Peer.instances = []
|
||||
instances = (Peer as any).instances = []
|
||||
})
|
||||
|
||||
describe('handshake', () => {
|
||||
describe('users', () => {
|
||||
beforeEach(() => {
|
||||
store.dispatch(SocketActions.handshake({ socket, roomName }))
|
||||
SocketActions.handshake({ socket, roomName })(dispatch, getState)
|
||||
const payload = {
|
||||
users: [{ id: 'a' }, { id: 'b' }],
|
||||
initiator: 'a'
|
||||
initiator: 'a',
|
||||
}
|
||||
socket.emit('users', payload)
|
||||
expect(Peer.instances.length).toBe(1)
|
||||
expect(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'
|
||||
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)
|
||||
expect(instances.length).toBe(2)
|
||||
expect((instances[0].destroy as jest.Mock).mock.calls.length).toBe(1)
|
||||
expect((instances[1].destroy as jest.Mock).mock.calls.length).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('signal', () => {
|
||||
let data
|
||||
let data: Peer.SignalData
|
||||
beforeEach(() => {
|
||||
data = {}
|
||||
store.dispatch(SocketActions.handshake({ socket, roomName }))
|
||||
data = {} as any
|
||||
SocketActions.handshake({ socket, roomName })(dispatch, getState)
|
||||
socket.emit('users', {
|
||||
initiator: 'a',
|
||||
users: [{ id: 'a' }, { id: 'b' }]
|
||||
users: [{ id: 'a' }, { id: 'b' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('should forward signal to peer', () => {
|
||||
socket.emit('signal', {
|
||||
userId: 'b',
|
||||
data
|
||||
data,
|
||||
})
|
||||
|
||||
expect(Peer.instances.length).toBe(1)
|
||||
expect(Peer.instances[0].signal.mock.calls.length).toBe(1)
|
||||
expect(instances.length).toBe(1)
|
||||
expect((instances[0].signal as jest.Mock).mock.calls.length).toBe(1)
|
||||
})
|
||||
|
||||
it('does nothing if no peer', () => {
|
||||
socket.emit('signal', {
|
||||
userId: 'a',
|
||||
data
|
||||
data,
|
||||
})
|
||||
|
||||
expect(Peer.instances.length).toBe(1)
|
||||
expect(Peer.instances[0].signal.mock.calls.length).toBe(0)
|
||||
expect(instances.length).toBe(1)
|
||||
expect((instances[0].signal as jest.Mock).mock.calls.length).toBe(0)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('peer events', () => {
|
||||
let peer
|
||||
let peer: Peer.Instance
|
||||
beforeEach(() => {
|
||||
let ready = false
|
||||
socket.once('ready', () => { ready = true })
|
||||
|
||||
store.dispatch(SocketActions.handshake({ socket, roomName }))
|
||||
SocketActions.handshake({ socket, roomName })(dispatch, getState)
|
||||
|
||||
socket.emit('users', {
|
||||
initiator: 'a',
|
||||
users: [{ id: 'a' }, { id: 'b' }]
|
||||
users: [{ id: 'a' }, { id: 'b' }],
|
||||
})
|
||||
expect(Peer.instances.length).toBe(1)
|
||||
peer = Peer.instances[0]
|
||||
expect(instances.length).toBe(1)
|
||||
peer = instances[0]
|
||||
|
||||
expect(ready).toBeDefined()
|
||||
})
|
||||
@ -100,15 +107,15 @@ describe('SocketActions', () => {
|
||||
describe('error', () => {
|
||||
it('destroys peer', () => {
|
||||
peer.emit(constants.PEER_EVENT_ERROR, new Error('bla'))
|
||||
expect(peer.destroy.mock.calls.length).toBe(1)
|
||||
expect((peer.destroy as jest.Mock).mock.calls.length).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('signal', () => {
|
||||
it('emits socket signal with user id', done => {
|
||||
let signal = { bla: 'bla' }
|
||||
const signal = { bla: 'bla' }
|
||||
|
||||
socket.once('signal', payload => {
|
||||
socket.once('signal', (payload: SocketActions.SignalOptions) => {
|
||||
expect(payload.userId).toEqual('b')
|
||||
expect(payload.signal).toBe(signal)
|
||||
done()
|
||||
@ -125,9 +132,10 @@ describe('SocketActions', () => {
|
||||
|
||||
expect(store.getState().streams).toEqual({
|
||||
b: {
|
||||
mediaStream: stream,
|
||||
url: jasmine.any(String)
|
||||
}
|
||||
userId: 'b',
|
||||
stream,
|
||||
url: jasmine.any(String),
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
@ -138,9 +146,10 @@ describe('SocketActions', () => {
|
||||
peer.emit(constants.PEER_EVENT_STREAM, stream)
|
||||
expect(store.getState().streams).toEqual({
|
||||
b: {
|
||||
mediaStream: stream,
|
||||
url: jasmine.any(String)
|
||||
}
|
||||
userId: 'b',
|
||||
stream,
|
||||
url: jasmine.any(String),
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
98
src/client/actions/SocketActions.ts
Normal file
@ -0,0 +1,98 @@
|
||||
import * as NotifyActions from '../actions/NotifyActions'
|
||||
import * as PeerActions from '../actions/PeerActions'
|
||||
import * as constants from '../constants'
|
||||
import keyBy from 'lodash/keyBy'
|
||||
import _debug from 'debug'
|
||||
import { SignalData } from 'simple-peer'
|
||||
import { Dispatch, GetState } from '../store'
|
||||
|
||||
const debug = _debug('peercalls')
|
||||
|
||||
export interface SocketHandlerOptions {
|
||||
socket: SocketIOClient.Socket
|
||||
roomName: string
|
||||
stream?: MediaStream
|
||||
dispatch: Dispatch
|
||||
getState: GetState
|
||||
}
|
||||
|
||||
export interface SignalOptions {
|
||||
signal: SignalData
|
||||
userId: string
|
||||
}
|
||||
|
||||
export interface UsersOptions {
|
||||
initiator: string
|
||||
users: Array<{ id: string }>
|
||||
}
|
||||
|
||||
class SocketHandler {
|
||||
socket: SocketIOClient.Socket
|
||||
roomName: string
|
||||
stream?: MediaStream
|
||||
dispatch: Dispatch
|
||||
getState: GetState
|
||||
|
||||
constructor (options: SocketHandlerOptions) {
|
||||
this.socket = options.socket
|
||||
this.roomName = options.roomName
|
||||
this.stream = options.stream
|
||||
this.dispatch = options.dispatch
|
||||
this.getState = options.getState
|
||||
}
|
||||
handleSignal = ({ userId, signal }: SignalOptions) => {
|
||||
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 }: UsersOptions) => {
|
||||
const { socket, stream, dispatch, getState } = this
|
||||
debug('socket users: %o', users)
|
||||
this.dispatch(NotifyActions.info('Connected users: {0}', users.length))
|
||||
const { peers } = this.getState()
|
||||
|
||||
users
|
||||
.filter(user => !peers[user.id] && user.id !== socket.id)
|
||||
.forEach(user => PeerActions.createPeer({
|
||||
socket,
|
||||
user,
|
||||
initiator,
|
||||
stream,
|
||||
})(dispatch, getState))
|
||||
|
||||
const newUsersMap = keyBy(users, 'id')
|
||||
Object.keys(peers)
|
||||
.filter(id => !newUsersMap[id])
|
||||
.forEach(id => peers[id].destroy())
|
||||
}
|
||||
}
|
||||
|
||||
export interface HandshakeOptions {
|
||||
socket: SocketIOClient.Socket
|
||||
roomName: string
|
||||
stream?: MediaStream
|
||||
}
|
||||
|
||||
export function handshake (options: HandshakeOptions) {
|
||||
const { socket, roomName, stream } = options
|
||||
|
||||
return (dispatch: Dispatch, getState: 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)
|
||||
}
|
||||
}
|
||||
@ -1,24 +0,0 @@
|
||||
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 }
|
||||
})
|
||||
61
src/client/actions/StreamActions.ts
Normal file
@ -0,0 +1,61 @@
|
||||
import * as constants from '../constants'
|
||||
|
||||
export interface AddStreamPayload {
|
||||
userId: string
|
||||
stream: MediaStream
|
||||
url?: string
|
||||
}
|
||||
|
||||
export interface AddStreamAction {
|
||||
type: 'PEER_STREAM_ADD'
|
||||
payload: AddStreamPayload
|
||||
}
|
||||
|
||||
export interface RemoveStreamAction {
|
||||
type: 'PEER_STREAM_REMOVE'
|
||||
payload: RemoveStreamPayload
|
||||
}
|
||||
|
||||
export interface RemoveStreamPayload {
|
||||
userId: string
|
||||
}
|
||||
|
||||
export interface SetActiveStreamAction {
|
||||
type: 'ACTIVE_SET'
|
||||
payload: RemoveStreamPayload
|
||||
}
|
||||
|
||||
export interface ToggleActiveStreamAction {
|
||||
type: 'ACTIVE_TOGGLE'
|
||||
payload: UserIdPayload
|
||||
}
|
||||
|
||||
export interface UserIdPayload {
|
||||
userId: string
|
||||
}
|
||||
|
||||
export const addStream = (payload: AddStreamPayload): AddStreamAction => ({
|
||||
type: constants.STREAM_ADD,
|
||||
payload,
|
||||
})
|
||||
|
||||
export const removeStream = (userId: string): RemoveStreamAction => ({
|
||||
type: constants.STREAM_REMOVE,
|
||||
payload: { userId },
|
||||
})
|
||||
|
||||
export const setActive = (userId: string): SetActiveStreamAction => ({
|
||||
type: constants.ACTIVE_SET,
|
||||
payload: { userId },
|
||||
})
|
||||
|
||||
export const toggleActive = (userId: string): ToggleActiveStreamAction => ({
|
||||
type: constants.ACTIVE_TOGGLE,
|
||||
payload: { userId },
|
||||
})
|
||||
|
||||
export type StreamAction =
|
||||
AddStreamAction |
|
||||
RemoveStreamAction |
|
||||
SetActiveStreamAction |
|
||||
ToggleActiveStreamAction
|
||||
59
src/client/async/action.ts
Normal file
@ -0,0 +1,59 @@
|
||||
import { Action } from 'redux'
|
||||
|
||||
export type PendingAction<T extends string, P> = Action<T> & Promise<P> & {
|
||||
status: 'pending'
|
||||
}
|
||||
|
||||
export type ResolvedAction<T extends string, P> = Action<T> & {
|
||||
payload: P
|
||||
status: 'resolved'
|
||||
}
|
||||
|
||||
export type RejectedAction<T extends string> = Action<T> & {
|
||||
payload: Error
|
||||
status: 'rejected'
|
||||
}
|
||||
|
||||
export type AsyncAction<T extends string, P> =
|
||||
PendingAction<T, P> |
|
||||
ResolvedAction<T, P> |
|
||||
RejectedAction<T>
|
||||
|
||||
export type GetAsyncAction<A> =
|
||||
A extends PendingAction<infer T, infer P>
|
||||
? AsyncAction<T, P>
|
||||
: A extends ResolvedAction<infer T, infer P>
|
||||
? AsyncAction<T, P>
|
||||
: never
|
||||
|
||||
export type GetAllActions<T> = {
|
||||
[K in keyof T]: T[K] extends (...args: any[]) => infer R
|
||||
? R
|
||||
: never
|
||||
}[keyof T]
|
||||
|
||||
export type GetAllAsyncActions<T> = GetAsyncAction<GetAllActions<T>>
|
||||
|
||||
function isPromise(value: unknown): value is Promise<unknown> {
|
||||
return value && typeof value === 'object' &&
|
||||
typeof (value as Promise<unknown>).then === 'function'
|
||||
}
|
||||
|
||||
export function isPendingAction(
|
||||
value: unknown,
|
||||
): value is PendingAction<string, unknown> {
|
||||
return isPromise(value) &&
|
||||
typeof (value as unknown as { type: 'string' }).type === 'string'
|
||||
}
|
||||
|
||||
export function makeAction<A extends unknown[], T extends string, P>(
|
||||
type: T,
|
||||
impl: (...args: A) => Promise<P>,
|
||||
): (...args: A) => PendingAction<T, P> {
|
||||
return (...args: A) => {
|
||||
const pendingAction = impl(...args) as PendingAction<T, P>
|
||||
pendingAction.type = type
|
||||
pendingAction.status = 'pending'
|
||||
return pendingAction
|
||||
}
|
||||
}
|
||||
3
src/client/async/index.ts
Normal file
@ -0,0 +1,3 @@
|
||||
export * from './action'
|
||||
export * from './middleware'
|
||||
export * from './reducer'
|
||||
128
src/client/async/middleware.test.ts
Normal file
@ -0,0 +1,128 @@
|
||||
import { GetAllAsyncActions, makeAction } from './action'
|
||||
import { middleware } from './middleware'
|
||||
import { reduce } from './reducer'
|
||||
import { createStore, applyMiddleware, combineReducers } from 'redux'
|
||||
|
||||
describe('middleware', () => {
|
||||
|
||||
interface State {
|
||||
sum: number
|
||||
status: 'pending' | 'resolved' | 'rejected'
|
||||
}
|
||||
|
||||
const defaultState: State = {
|
||||
status: 'resolved',
|
||||
sum: 0,
|
||||
}
|
||||
|
||||
const actions = {
|
||||
add: makeAction('add', async (a: number, b: number) => {
|
||||
return {a, b}
|
||||
}),
|
||||
subtract: makeAction('subtract', async (a: number, b: number) => {
|
||||
return {a, b}
|
||||
}),
|
||||
reject: makeAction('reject', async (a: number, b: number) => {
|
||||
throw new Error('Test reject')
|
||||
}),
|
||||
}
|
||||
|
||||
type Action = GetAllAsyncActions<typeof actions>
|
||||
|
||||
function result(state = defaultState, action: Action): State {
|
||||
switch (action.type) {
|
||||
case 'add':
|
||||
return reduce(
|
||||
state,
|
||||
action,
|
||||
(state, pending) => ({
|
||||
status: pending.status,
|
||||
sum: state.sum,
|
||||
}),
|
||||
(state, resolved) => ({
|
||||
status: resolved.status,
|
||||
sum: resolved.payload.a + resolved.payload.b,
|
||||
}),
|
||||
(state, rejected) => ({status: rejected.status, sum: 0}),
|
||||
)
|
||||
case 'subtract':
|
||||
return reduce(
|
||||
state,
|
||||
action,
|
||||
(state, pending) => ({
|
||||
status: pending.status,
|
||||
sum: state.sum,
|
||||
}),
|
||||
(state, resolved) => ({
|
||||
status: resolved.status,
|
||||
sum: resolved.payload.a - resolved.payload.b,
|
||||
}),
|
||||
(state, rejected) => ({status: rejected.status, sum: 0}),
|
||||
)
|
||||
case 'reject':
|
||||
return reduce(
|
||||
state,
|
||||
action,
|
||||
(state, pending) => ({
|
||||
status: pending.status,
|
||||
sum: state.sum,
|
||||
}),
|
||||
(state, resolved) => ({
|
||||
status: resolved.status,
|
||||
sum: 0,
|
||||
}),
|
||||
(state, rejected) => ({status: rejected.status, sum: 0}),
|
||||
)
|
||||
default:
|
||||
return state
|
||||
}
|
||||
}
|
||||
|
||||
function getStore() {
|
||||
return createStore(
|
||||
combineReducers({ result }),
|
||||
applyMiddleware(middleware),
|
||||
)
|
||||
}
|
||||
|
||||
describe('pending and resolved', () => {
|
||||
it('makes it easy to dispatch async actions for redux', async () => {
|
||||
const store = getStore()
|
||||
await store.dispatch(actions.add(1, 2))
|
||||
expect(store.getState()).toEqual({
|
||||
result: {
|
||||
status: 'resolved',
|
||||
sum: 3,
|
||||
},
|
||||
})
|
||||
await store.dispatch(actions.subtract(1, 2))
|
||||
expect(store.getState()).toEqual({
|
||||
result: {
|
||||
status: 'resolved',
|
||||
sum: -1,
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('rejected', () => {
|
||||
it('handles rejected actions', async () => {
|
||||
const store = getStore()
|
||||
let error!: Error
|
||||
try {
|
||||
await store.dispatch(actions.reject(1, 2))
|
||||
} catch (err) {
|
||||
error = err
|
||||
}
|
||||
expect(error).toBeTruthy()
|
||||
expect(error.message).toBe('Test reject')
|
||||
expect(store.getState()).toEqual({
|
||||
result: {
|
||||
status: 'rejected',
|
||||
sum: 0,
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
})
|
||||
47
src/client/async/middleware.ts
Normal file
@ -0,0 +1,47 @@
|
||||
import { AnyAction, Middleware } from 'redux'
|
||||
import { isPendingAction, ResolvedAction, RejectedAction } from './action'
|
||||
import _debug from 'debug'
|
||||
|
||||
const debug = _debug('peercalls:async')
|
||||
|
||||
export const middleware: Middleware = store => next => (action: AnyAction) => {
|
||||
if (!isPendingAction(action)) {
|
||||
debug('NOT pending %o', action)
|
||||
return next(action)
|
||||
}
|
||||
|
||||
debug('Pending: %s %s', action.type, action.status)
|
||||
|
||||
const promise = action
|
||||
.then(payload => {
|
||||
debug('Resolved: %s resolved', action.type)
|
||||
const resolvedAction: ResolvedAction<string, unknown> = {
|
||||
payload,
|
||||
type: action.type,
|
||||
status: 'resolved',
|
||||
}
|
||||
store.dispatch(resolvedAction)
|
||||
})
|
||||
|
||||
// Propagate this action. Only attach listeners to the promise.
|
||||
debug('Calling next for %s %s', action.type, action.status)
|
||||
next({
|
||||
type: action.type,
|
||||
status: 'pending',
|
||||
})
|
||||
|
||||
const promise2 = promise
|
||||
.catch((err: Error) => {
|
||||
debug('Rejected: %s rejected %s', action.type, err.stack)
|
||||
const rejectedAction: RejectedAction<string> = {
|
||||
payload: err,
|
||||
type: action.type,
|
||||
status: 'rejected',
|
||||
}
|
||||
store.dispatch(rejectedAction)
|
||||
})
|
||||
|
||||
return promise2.then(() => {
|
||||
return action
|
||||
})
|
||||
}
|
||||
18
src/client/async/reducer.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { AsyncAction, PendingAction, ResolvedAction, RejectedAction } from './action'
|
||||
|
||||
export function reduce<State, T extends string, P>(
|
||||
state: State,
|
||||
action: AsyncAction<T, P>,
|
||||
handlePending: (state: State, action: PendingAction<T, P>) => State,
|
||||
handleResolved: (state: State, action: ResolvedAction<T, P>) => State,
|
||||
handleRejected: (state: State, action: RejectedAction<T>) => State,
|
||||
): State {
|
||||
switch (action.status) {
|
||||
case 'pending':
|
||||
return handlePending(state, action)
|
||||
case 'resolved':
|
||||
return handleResolved(state, action)
|
||||
case 'rejected':
|
||||
return handleRejected(state, action)
|
||||
}
|
||||
}
|
||||
@ -1,18 +1,13 @@
|
||||
import React from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
import classnames from 'classnames'
|
||||
import { Alert as AlertType } from '../actions/NotifyActions'
|
||||
|
||||
export const AlertPropType = PropTypes.shape({
|
||||
dismissable: PropTypes.bool,
|
||||
action: PropTypes.string.isRequired,
|
||||
message: PropTypes.string.isRequired
|
||||
})
|
||||
export interface AlertProps {
|
||||
alert: AlertType
|
||||
dismiss: (alert: AlertType) => void
|
||||
}
|
||||
|
||||
export class Alert extends React.PureComponent {
|
||||
static propTypes = {
|
||||
alert: AlertPropType,
|
||||
dismiss: PropTypes.func.isRequired
|
||||
}
|
||||
export class Alert extends React.PureComponent<AlertProps> {
|
||||
dismiss = () => {
|
||||
const { alert, dismiss } = this.props
|
||||
dismiss(alert)
|
||||
@ -34,11 +29,12 @@ export class Alert extends React.PureComponent {
|
||||
}
|
||||
}
|
||||
|
||||
export default class Alerts extends React.PureComponent {
|
||||
static propTypes = {
|
||||
alerts: PropTypes.arrayOf(AlertPropType).isRequired,
|
||||
dismiss: PropTypes.func.isRequired
|
||||
}
|
||||
export interface AlertsProps {
|
||||
alerts: AlertType[]
|
||||
dismiss: (alert: AlertType) => void
|
||||
}
|
||||
|
||||
export default class Alerts extends React.PureComponent<AlertsProps> {
|
||||
render () {
|
||||
const { alerts, dismiss } = this.props
|
||||
return (
|
||||
@ -1,42 +1,50 @@
|
||||
import * as constants from '../constants.js'
|
||||
import Alerts, { AlertPropType } from './Alerts.js'
|
||||
import Chat, { MessagePropTypes } from './Chat.js'
|
||||
import Notifications, { NotificationPropTypes } from './Notifications.js'
|
||||
import PropTypes from 'prop-types'
|
||||
import map from 'lodash/map'
|
||||
import React from 'react'
|
||||
import Toolbar from './Toolbar.js'
|
||||
import Video, { StreamPropType } from './Video.js'
|
||||
import _ from 'underscore'
|
||||
import Peer from 'simple-peer'
|
||||
import { Message } from '../actions/ChatActions'
|
||||
import { Alert, Notification } from '../actions/NotifyActions'
|
||||
import { TextMessage } from '../actions/PeerActions'
|
||||
import { AddStreamPayload } from '../actions/StreamActions'
|
||||
import * as constants from '../constants'
|
||||
import Alerts from './Alerts'
|
||||
import Chat from './Chat'
|
||||
import Notifications from './Notifications'
|
||||
import Toolbar from './Toolbar'
|
||||
import Video from './Video'
|
||||
|
||||
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,
|
||||
messages: PropTypes.arrayOf(MessagePropTypes).isRequired,
|
||||
peers: PropTypes.object.isRequired,
|
||||
sendMessage: PropTypes.func.isRequired,
|
||||
streams: PropTypes.objectOf(StreamPropType).isRequired,
|
||||
toggleActive: PropTypes.func.isRequired
|
||||
}
|
||||
constructor () {
|
||||
super()
|
||||
this.state = {
|
||||
videos: {},
|
||||
chatVisible: false
|
||||
}
|
||||
export interface AppProps {
|
||||
active: string | null
|
||||
alerts: Alert[]
|
||||
dismissAlert: (alert: Alert) => void
|
||||
init: () => void
|
||||
notifications: Record<string, Notification>
|
||||
messages: Message[]
|
||||
messagesCount: number
|
||||
peers: Record<string, Peer.Instance>
|
||||
sendMessage: (message: TextMessage) => void
|
||||
streams: Record<string, AddStreamPayload>
|
||||
onSendFile: (file: File) => void
|
||||
toggleActive: (userId: string) => void
|
||||
}
|
||||
|
||||
export interface AppState {
|
||||
videos: Record<string, unknown>
|
||||
chatVisible: boolean
|
||||
}
|
||||
|
||||
export default class App extends React.PureComponent<AppProps, AppState> {
|
||||
state: AppState = {
|
||||
videos: {},
|
||||
chatVisible: false,
|
||||
}
|
||||
handleShowChat = () => {
|
||||
this.setState({
|
||||
chatVisible: true
|
||||
chatVisible: true,
|
||||
})
|
||||
}
|
||||
handleHideChat = () => {
|
||||
this.setState({
|
||||
chatVisible: false
|
||||
chatVisible: false,
|
||||
})
|
||||
}
|
||||
handleToggleChat = () => {
|
||||
@ -54,12 +62,13 @@ export default class App extends React.PureComponent {
|
||||
alerts,
|
||||
dismissAlert,
|
||||
notifications,
|
||||
notify,
|
||||
messages,
|
||||
messagesCount,
|
||||
onSendFile,
|
||||
peers,
|
||||
sendMessage,
|
||||
toggleActive,
|
||||
streams
|
||||
streams,
|
||||
} = this.props
|
||||
|
||||
const { videos } = this.state
|
||||
@ -68,18 +77,17 @@ export default class App extends React.PureComponent {
|
||||
<div className="app">
|
||||
<Toolbar
|
||||
chatVisible={this.state.chatVisible}
|
||||
messages={messages}
|
||||
messagesCount={messagesCount}
|
||||
onToggleChat={this.handleToggleChat}
|
||||
onSendFile={onSendFile}
|
||||
stream={streams[constants.ME]}
|
||||
/>
|
||||
<Alerts alerts={alerts} dismiss={dismissAlert} />
|
||||
<Notifications notifications={notifications} />
|
||||
<Chat
|
||||
messages={messages}
|
||||
notify={notify}
|
||||
onClose={this.handleHideChat}
|
||||
sendMessage={sendMessage}
|
||||
videos={videos}
|
||||
visible={this.state.chatVisible}
|
||||
/>
|
||||
<div className="videos">
|
||||
@ -93,7 +101,7 @@ export default class App extends React.PureComponent {
|
||||
mirrored
|
||||
/>
|
||||
|
||||
{_.map(peers, (_, userId) => (
|
||||
{map(peers, (_, userId) => (
|
||||
<Video
|
||||
active={userId === active}
|
||||
key={userId}
|
||||
@ -1,31 +1,37 @@
|
||||
import Input from './Input.js'
|
||||
import PropTypes from 'prop-types'
|
||||
import React from 'react'
|
||||
import classnames from 'classnames'
|
||||
import socket from '../socket.js'
|
||||
import React from 'react'
|
||||
import { Message as MessageType } from '../actions/ChatActions'
|
||||
import { TextMessage } from '../actions/PeerActions'
|
||||
import Input from './Input'
|
||||
|
||||
export const MessagePropTypes = PropTypes.shape({
|
||||
userId: PropTypes.string.isRequired,
|
||||
message: PropTypes.string.isRequired,
|
||||
timestamp: PropTypes.string.isRequired,
|
||||
image: PropTypes.string
|
||||
})
|
||||
export interface MessageProps {
|
||||
message: MessageType
|
||||
}
|
||||
|
||||
function Message (props: MessageProps) {
|
||||
const { message } = props
|
||||
return (
|
||||
<p className="message-text">
|
||||
{message.image && (
|
||||
<img src={message.image} width="100%" />
|
||||
)}
|
||||
{message.message}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
export interface ChatProps {
|
||||
visible: boolean
|
||||
messages: MessageType[]
|
||||
onClose: () => void
|
||||
sendMessage: (message: TextMessage) => void
|
||||
}
|
||||
|
||||
export default class Chat extends React.PureComponent<ChatProps> {
|
||||
chatHistoryRef = React.createRef<HTMLDivElement>()
|
||||
|
||||
export default class Chat extends React.PureComponent {
|
||||
static propTypes = {
|
||||
visible: PropTypes.bool.isRequired,
|
||||
messages: PropTypes.arrayOf(MessagePropTypes).isRequired,
|
||||
notify: PropTypes.func.isRequired,
|
||||
onClose: PropTypes.func.isRequired,
|
||||
sendMessage: PropTypes.func.isRequired,
|
||||
videos: PropTypes.object.isRequired
|
||||
}
|
||||
constructor () {
|
||||
super()
|
||||
this.chatHistoryRef = React.createRef()
|
||||
}
|
||||
scrollToBottom = () => {
|
||||
const chatHistoryRef = this.chatHistoryRef.current
|
||||
const chatHistoryRef = this.chatHistoryRef.current!
|
||||
chatHistoryRef.scrollTop = chatHistoryRef.scrollHeight
|
||||
}
|
||||
componentDidMount () {
|
||||
@ -35,10 +41,10 @@ export default class Chat extends React.PureComponent {
|
||||
this.scrollToBottom()
|
||||
}
|
||||
render () {
|
||||
const { messages, videos, notify, sendMessage } = this.props
|
||||
const { messages, sendMessage } = this.props
|
||||
return (
|
||||
<div className={classnames('chat-container', {
|
||||
show: this.props.visible
|
||||
show: this.props.visible,
|
||||
})}>
|
||||
<div className="chat-header">
|
||||
<div className="chat-close" onClick={this.props.onClose}>
|
||||
@ -53,7 +59,7 @@ export default class Chat extends React.PureComponent {
|
||||
{messages.length ? (
|
||||
messages.map((message, i) => (
|
||||
<div key={i}>
|
||||
{message.userId === socket.id ? (
|
||||
{message.userId === 'You' ? (
|
||||
<div className="chat-item chat-item-me">
|
||||
<div className="message">
|
||||
<span className="message-user-name">
|
||||
@ -61,7 +67,7 @@ export default class Chat extends React.PureComponent {
|
||||
</span>
|
||||
<span className="icon icon-schedule" />
|
||||
<time className="message-time">{message.timestamp}</time>
|
||||
<p className="message-text">{message.message}</p>
|
||||
<Message message={message} />
|
||||
</div>
|
||||
{message.image ? (
|
||||
<img className="chat-item-img" src={message.image} />
|
||||
@ -82,7 +88,7 @@ export default class Chat extends React.PureComponent {
|
||||
</span>
|
||||
<span className="icon icon-schedule" />
|
||||
<time className="message-time">{message.timestamp}</time>
|
||||
<p className="message-text">{message.message}</p>
|
||||
<Message message={message} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@ -97,11 +103,7 @@ export default class Chat extends React.PureComponent {
|
||||
|
||||
</div>
|
||||
|
||||
<Input
|
||||
videos={videos}
|
||||
notify={notify}
|
||||
sendMessage={sendMessage}
|
||||
/>
|
||||
<Input sendMessage={sendMessage} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -1,36 +1,39 @@
|
||||
import Input from './Input.js'
|
||||
import Input from './Input'
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom'
|
||||
import TestUtils from 'react-dom/test-utils'
|
||||
import { TextMessage } from '../actions/PeerActions'
|
||||
|
||||
describe('components/Input', () => {
|
||||
|
||||
let component, node, videos, notify, sendMessage
|
||||
function render () {
|
||||
videos = {}
|
||||
notify = jest.fn()
|
||||
let node: Element
|
||||
let sendMessage: jest.Mock<(message: TextMessage) => void>
|
||||
async function render () {
|
||||
sendMessage = jest.fn()
|
||||
component = TestUtils.renderIntoDocument(
|
||||
<Input
|
||||
videos={videos}
|
||||
sendMessage={sendMessage}
|
||||
notify={notify}
|
||||
/>
|
||||
)
|
||||
node = ReactDOM.findDOMNode(component)
|
||||
const div = document.createElement('div')
|
||||
await new Promise<Input>(resolve => {
|
||||
ReactDOM.render(
|
||||
<Input
|
||||
ref={input => resolve(input!)}
|
||||
sendMessage={sendMessage}
|
||||
/>,
|
||||
div,
|
||||
)
|
||||
})
|
||||
node = div.children[0]
|
||||
}
|
||||
let message = 'test message'
|
||||
const message = 'test message'
|
||||
|
||||
beforeEach(() => render())
|
||||
|
||||
describe('send message', () => {
|
||||
|
||||
let input
|
||||
let input: HTMLTextAreaElement
|
||||
beforeEach(() => {
|
||||
sendMessage.mockClear()
|
||||
input = node.querySelector('textarea')
|
||||
input = node.querySelector('textarea')!
|
||||
TestUtils.Simulate.change(input, {
|
||||
target: { value: message }
|
||||
target: { value: message } as any,
|
||||
})
|
||||
expect(input.value).toBe(message)
|
||||
})
|
||||
@ -39,33 +42,32 @@ describe('components/Input', () => {
|
||||
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}` ]])
|
||||
expect(sendMessage.mock.calls)
|
||||
.toEqual([[ { payload: message, type: 'text' } ]])
|
||||
})
|
||||
})
|
||||
|
||||
describe('handleKeyPress', () => {
|
||||
it('sends a message', () => {
|
||||
TestUtils.Simulate.keyPress(input, {
|
||||
key: 'Enter'
|
||||
key: 'Enter',
|
||||
})
|
||||
expect(input.value).toBe('')
|
||||
expect(sendMessage.mock.calls).toEqual([[ message ]])
|
||||
expect(notify.mock.calls).toEqual([[ `You: ${message}` ]])
|
||||
expect(sendMessage.mock.calls)
|
||||
.toEqual([[ { payload: message, type: 'text' } ]])
|
||||
})
|
||||
|
||||
it('does nothing when other key pressed', () => {
|
||||
TestUtils.Simulate.keyPress(input, {
|
||||
key: 'test'
|
||||
key: 'test',
|
||||
})
|
||||
expect(sendMessage.mock.calls.length).toBe(0)
|
||||
expect(notify.mock.calls.length).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('handleSmileClick', () => {
|
||||
it('adds smile to message', () => {
|
||||
const div = node.querySelector('.chat-controls-buttons-smile')
|
||||
const div = node.querySelector('.chat-controls-buttons-smile')!
|
||||
TestUtils.Simulate.click(div)
|
||||
expect(input.value).toBe('test message😑')
|
||||
})
|
||||
@ -1,69 +1,61 @@
|
||||
import PropTypes from 'prop-types'
|
||||
import React from 'react'
|
||||
import socket from '../socket.js'
|
||||
import React, { ReactEventHandler, ChangeEventHandler, KeyboardEventHandler, MouseEventHandler } from 'react'
|
||||
import { TextMessage } from '../actions/PeerActions'
|
||||
|
||||
export default class Input extends React.PureComponent {
|
||||
static propTypes = {
|
||||
videos: PropTypes.object.isRequired,
|
||||
notify: PropTypes.func.isRequired,
|
||||
sendMessage: PropTypes.func.isRequired
|
||||
export interface InputProps {
|
||||
sendMessage: (message: TextMessage) => void
|
||||
}
|
||||
|
||||
export interface InputState {
|
||||
message: string
|
||||
}
|
||||
|
||||
export default class Input extends React.PureComponent<InputProps, InputState> {
|
||||
textArea = React.createRef<HTMLTextAreaElement>()
|
||||
state = {
|
||||
message: '',
|
||||
}
|
||||
constructor () {
|
||||
super()
|
||||
this.state = {
|
||||
message: ''
|
||||
}
|
||||
}
|
||||
handleChange = e => {
|
||||
handleChange: ChangeEventHandler<HTMLTextAreaElement> = event => {
|
||||
this.setState({
|
||||
message: e.target.value
|
||||
message: event.target.value,
|
||||
})
|
||||
}
|
||||
handleSubmit = e => {
|
||||
handleSubmit: ReactEventHandler<HTMLFormElement> = e => {
|
||||
e.preventDefault()
|
||||
this.submit()
|
||||
}
|
||||
handleKeyPress = e => {
|
||||
handleKeyPress: KeyboardEventHandler<HTMLTextAreaElement> = e => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
this.submit()
|
||||
}
|
||||
}
|
||||
handleSmileClick = e => {
|
||||
handleSmileClick: MouseEventHandler<HTMLElement> = event => {
|
||||
this.setState({
|
||||
message: this.textArea.value + e.currentTarget.innerHTML
|
||||
message: this.textArea.current!.value + event.currentTarget.innerHTML,
|
||||
})
|
||||
}
|
||||
submit = () => {
|
||||
const { videos, notify, sendMessage } = this.props
|
||||
const { sendMessage } = this.props
|
||||
const { message } = this.state
|
||||
if (message) {
|
||||
notify('You: ' + message)
|
||||
sendMessage(message)
|
||||
|
||||
const userId = socket.id
|
||||
const timestamp = new Date().toLocaleString('en-US', {
|
||||
hour: 'numeric',
|
||||
minute: 'numeric',
|
||||
hour12: false
|
||||
sendMessage({
|
||||
payload: message,
|
||||
type: 'text',
|
||||
})
|
||||
let image = null
|
||||
// let image = null
|
||||
|
||||
// take snapshoot
|
||||
try {
|
||||
const video = videos[userId]
|
||||
if (video) {
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.height = video.videoHeight
|
||||
canvas.width = video.videoWidth
|
||||
const avatar = canvas.getContext('2d')
|
||||
avatar.drawImage(video, 0, 0, canvas.width, canvas.height)
|
||||
image = canvas.toDataURL()
|
||||
}
|
||||
} catch (e) {}
|
||||
|
||||
const payload = { userId, message, timestamp, image }
|
||||
socket.emit('new_message', payload)
|
||||
// // take snapshoot
|
||||
// try {
|
||||
// const video = videos[userId]
|
||||
// if (video) {
|
||||
// const canvas = document.createElement('canvas')
|
||||
// canvas.height = video.videoHeight
|
||||
// canvas.width = video.videoWidth
|
||||
// const avatar = canvas.getContext('2d')
|
||||
// avatar.drawImage(video, 0, 0, canvas.width, canvas.height)
|
||||
// image = canvas.toDataURL()
|
||||
// }
|
||||
// } catch (e) {}
|
||||
}
|
||||
this.setState({ message: '' })
|
||||
}
|
||||
@ -77,7 +69,7 @@ export default class Input extends React.PureComponent {
|
||||
onKeyPress={this.handleKeyPress}
|
||||
placeholder="Type a message"
|
||||
value={message}
|
||||
ref={node => { this.textArea = node }}
|
||||
ref={this.textArea}
|
||||
/>
|
||||
<div className="chat-controls-buttons">
|
||||
<input type="submit" value="Send"
|
||||
@ -1,41 +0,0 @@
|
||||
import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup'
|
||||
import PropTypes from 'prop-types'
|
||||
import React from 'react'
|
||||
import classnames from 'classnames'
|
||||
|
||||
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>
|
||||
)
|
||||
}
|
||||
}
|
||||
41
src/client/components/Notifications.tsx
Normal file
@ -0,0 +1,41 @@
|
||||
import CSSTransition from 'react-transition-group/CSSTransition'
|
||||
import React from 'react'
|
||||
import classnames from 'classnames'
|
||||
import { Notification } from '../actions/NotifyActions'
|
||||
|
||||
export interface NotificationProps {
|
||||
notifications: Record<string, Notification>
|
||||
max: number
|
||||
}
|
||||
|
||||
const transitionTimeout = {
|
||||
enter: 200,
|
||||
exit: 100,
|
||||
}
|
||||
|
||||
export default class Notifications
|
||||
extends React.PureComponent<NotificationProps> {
|
||||
static defaultProps = {
|
||||
max: 10,
|
||||
}
|
||||
render () {
|
||||
const { notifications, max } = this.props
|
||||
return (
|
||||
<div className="notifications">
|
||||
{Object.keys(notifications).slice(-max).map(id => (
|
||||
<CSSTransition
|
||||
key={id}
|
||||
classNames='fade'
|
||||
timeout={transitionTimeout}
|
||||
>
|
||||
<div
|
||||
className={classnames(notifications[id].type, 'notification')}
|
||||
>
|
||||
{notifications[id].message}
|
||||
</div>
|
||||
</CSSTransition>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -1,92 +0,0 @@
|
||||
import PropTypes from 'prop-types'
|
||||
import React from 'react'
|
||||
import classnames from 'classnames'
|
||||
import screenfull from 'screenfull'
|
||||
import { MessagePropTypes } from './Chat.js'
|
||||
import { StreamPropType } from './Video.js'
|
||||
|
||||
export default class Toolbar extends React.PureComponent {
|
||||
static propTypes = {
|
||||
messages: PropTypes.arrayOf(MessagePropTypes).isRequired,
|
||||
stream: StreamPropType,
|
||||
onToggleChat: PropTypes.func.isRequired,
|
||||
chatVisible: PropTypes.bool.isRequired
|
||||
}
|
||||
handleMicClick = () => {
|
||||
const { stream } = this.props
|
||||
stream.mediaStream.getAudioTracks().forEach(track => {
|
||||
track.enabled = !track.enabled
|
||||
})
|
||||
this.mixButton.classList.toggle('on')
|
||||
}
|
||||
handleCamClick = () => {
|
||||
const { stream } = this.props
|
||||
stream.mediaStream.getVideoTracks().forEach(track => {
|
||||
track.enabled = !track.enabled
|
||||
})
|
||||
this.camButton.classList.toggle('on')
|
||||
}
|
||||
handleFullscreenClick = () => {
|
||||
if (screenfull.enabled) {
|
||||
screenfull.toggle()
|
||||
this.fullscreenButton.classList.toggle('on')
|
||||
}
|
||||
}
|
||||
handleHangoutClick = () => {
|
||||
window.location.href = '/'
|
||||
}
|
||||
render () {
|
||||
const { messages, stream } = this.props
|
||||
|
||||
return (
|
||||
<div className="toolbar active">
|
||||
<div onClick={this.props.onToggleChat}
|
||||
className={classnames('button chat', {
|
||||
on: this.props.chatVisible
|
||||
})}
|
||||
data-blink={this.props.chatVisible && messages.length}
|
||||
title="Chat"
|
||||
>
|
||||
<span className="icon icon-question_answer" />
|
||||
</div>
|
||||
|
||||
{stream && (
|
||||
<div>
|
||||
<div onClick={this.handleMicClick}
|
||||
ref={node => { this.mixButton = node }}
|
||||
className="button mute-audio"
|
||||
title="Mute audio"
|
||||
>
|
||||
<span className="on icon icon-mic_off" />
|
||||
<span className="off icon icon-mic" />
|
||||
</div>
|
||||
<div onClick={this.handleCamClick}
|
||||
ref={node => { this.camButton = node }}
|
||||
className="button mute-video"
|
||||
title="Mute video"
|
||||
>
|
||||
<span className="on icon icon-videocam_off" />
|
||||
<span className="off icon icon-videocam" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div onClick={this.handleFullscreenClick}
|
||||
ref={node => { this.fullscreenButton = node }}
|
||||
className="button fullscreen"
|
||||
title="Enter fullscreen"
|
||||
>
|
||||
<span className="on icon icon-fullscreen_exit" />
|
||||
<span className="off icon icon-fullscreen" />
|
||||
</div>
|
||||
|
||||
<div onClick={this.handleHangoutClick}
|
||||
className="button hangup"
|
||||
title="Hangup"
|
||||
>
|
||||
<span className="icon icon-call_end" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -1,88 +0,0 @@
|
||||
jest.mock('../window.js')
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom'
|
||||
import TestUtils from 'react-dom/test-utils'
|
||||
import Toolbar from './Toolbar.js'
|
||||
import { MediaStream } from '../window.js'
|
||||
|
||||
describe('components/Toolbar', () => {
|
||||
|
||||
class ToolbarWrapper extends React.PureComponent {
|
||||
static propTypes = Toolbar.propTypes
|
||||
constructor () {
|
||||
super()
|
||||
this.state = {}
|
||||
}
|
||||
render () {
|
||||
return <Toolbar
|
||||
chatVisible={this.props.chatVisible}
|
||||
onToggleChat={this.props.onToggleChat}
|
||||
messages={this.props.messages}
|
||||
stream={this.state.stream || this.props.stream}
|
||||
/>
|
||||
}
|
||||
}
|
||||
|
||||
let component, node, mediaStream, url, onToggleChat
|
||||
function render () {
|
||||
mediaStream = new MediaStream()
|
||||
onToggleChat = jest.fn()
|
||||
component = TestUtils.renderIntoDocument(
|
||||
<ToolbarWrapper
|
||||
chatVisible
|
||||
onToggleChat={onToggleChat}
|
||||
messages={[]}
|
||||
stream={{ mediaStream, url }}
|
||||
/>
|
||||
)
|
||||
node = ReactDOM.findDOMNode(component)
|
||||
}
|
||||
|
||||
describe('render', () => {
|
||||
it('should not fail', () => {
|
||||
render()
|
||||
})
|
||||
})
|
||||
|
||||
describe('handleChatClick', () => {
|
||||
it('toggle chat', () => {
|
||||
expect(onToggleChat.mock.calls.length).toBe(0)
|
||||
const button = node.querySelector('.chat')
|
||||
TestUtils.Simulate.click(button)
|
||||
expect(onToggleChat.mock.calls.length).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('handleMicClick', () => {
|
||||
it('toggle mic', () => {
|
||||
const button = node.querySelector('.mute-audio')
|
||||
TestUtils.Simulate.click(button)
|
||||
expect(button.classList.contains('on')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('handleCamClick', () => {
|
||||
it('toggle cam', () => {
|
||||
const button = node.querySelector('.mute-video')
|
||||
TestUtils.Simulate.click(button)
|
||||
expect(button.classList.contains('on')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('handleFullscreenClick', () => {
|
||||
it('toggle fullscreen', () => {
|
||||
const button = node.querySelector('.fullscreen')
|
||||
TestUtils.Simulate.click(button)
|
||||
expect(button.classList.contains('on')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('handleHangoutClick', () => {
|
||||
it('hangout', () => {
|
||||
const button = node.querySelector('.hangup')
|
||||
TestUtils.Simulate.click(button)
|
||||
expect(window.location.href).toBe('http://localhost/')
|
||||
})
|
||||
})
|
||||
|
||||
})
|
||||
125
src/client/components/Toolbar.test.tsx
Normal file
@ -0,0 +1,125 @@
|
||||
jest.mock('../window')
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom'
|
||||
import TestUtils from 'react-dom/test-utils'
|
||||
import Toolbar, { ToolbarProps } from './Toolbar'
|
||||
import { MediaStream } from '../window'
|
||||
import { AddStreamPayload } from '../actions/StreamActions'
|
||||
|
||||
describe('components/Toolbar', () => {
|
||||
|
||||
interface StreamState {
|
||||
stream: AddStreamPayload | null
|
||||
}
|
||||
|
||||
class ToolbarWrapper extends React.PureComponent<ToolbarProps, StreamState> {
|
||||
state = {
|
||||
stream: null,
|
||||
}
|
||||
render () {
|
||||
return <Toolbar
|
||||
chatVisible={this.props.chatVisible}
|
||||
onToggleChat={this.props.onToggleChat}
|
||||
onSendFile={this.props.onSendFile}
|
||||
messagesCount={this.props.messagesCount}
|
||||
stream={this.state.stream || this.props.stream}
|
||||
/>
|
||||
}
|
||||
}
|
||||
|
||||
let node: Element
|
||||
let mediaStream: MediaStream
|
||||
let url: string
|
||||
let onToggleChat: jest.Mock<() => void>
|
||||
let onSendFile: jest.Mock<(file: File) => void>
|
||||
async function render () {
|
||||
mediaStream = new MediaStream()
|
||||
onToggleChat = jest.fn()
|
||||
onSendFile = jest.fn()
|
||||
const div = document.createElement('div')
|
||||
await new Promise<ToolbarWrapper>(resolve => {
|
||||
ReactDOM.render(
|
||||
<ToolbarWrapper
|
||||
ref={instance => resolve(instance!)}
|
||||
chatVisible
|
||||
onToggleChat={onToggleChat}
|
||||
onSendFile={onSendFile}
|
||||
messagesCount={1}
|
||||
stream={{ userId: '', stream: mediaStream, url }}
|
||||
/>,
|
||||
div,
|
||||
)
|
||||
})
|
||||
node = div.children[0]
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await render()
|
||||
})
|
||||
|
||||
describe('handleChatClick', () => {
|
||||
it('toggle chat', () => {
|
||||
expect(onToggleChat.mock.calls.length).toBe(0)
|
||||
const button = node.querySelector('.chat')!
|
||||
TestUtils.Simulate.click(button)
|
||||
expect(onToggleChat.mock.calls.length).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('handleMicClick', () => {
|
||||
it('toggle mic', () => {
|
||||
const button = node.querySelector('.mute-audio')!
|
||||
TestUtils.Simulate.click(button)
|
||||
expect(button.classList.contains('on')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('handleCamClick', () => {
|
||||
it('toggle cam', () => {
|
||||
const button = node.querySelector('.mute-video')!
|
||||
TestUtils.Simulate.click(button)
|
||||
expect(button.classList.contains('on')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('handleFullscreenClick', () => {
|
||||
it('toggle fullscreen', () => {
|
||||
const button = node.querySelector('.fullscreen')!
|
||||
TestUtils.Simulate.click(button)
|
||||
expect(button.classList.contains('on')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('handleHangoutClick', () => {
|
||||
it('hangout', () => {
|
||||
const button = node.querySelector('.hangup')!
|
||||
TestUtils.Simulate.click(button)
|
||||
expect(window.location.href).toBe('http://localhost/')
|
||||
})
|
||||
})
|
||||
|
||||
describe('handleSendFile', () => {
|
||||
it('triggers input dialog', () => {
|
||||
const sendFileButton = node.querySelector('.send-file')!
|
||||
const click = jest.fn()
|
||||
const file = node.querySelector('input[type=file]')!;
|
||||
(file as any).click = click
|
||||
TestUtils.Simulate.click(sendFileButton)
|
||||
expect(click.mock.calls.length).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('handleSelectFiles', () => {
|
||||
it('iterates through files and calls onSendFile for each', () => {
|
||||
const file = node.querySelector('input[type=file]')!
|
||||
const files = [{ name: 'first' }] as any
|
||||
TestUtils.Simulate.change(file, {
|
||||
target: {
|
||||
files,
|
||||
} as any,
|
||||
})
|
||||
expect(onSendFile.mock.calls).toEqual([[ files[0] ]])
|
||||
})
|
||||
})
|
||||
|
||||
})
|
||||
158
src/client/components/Toolbar.tsx
Normal file
@ -0,0 +1,158 @@
|
||||
import classnames from 'classnames'
|
||||
import React from 'react'
|
||||
import screenfull from 'screenfull'
|
||||
import { AddStreamPayload } from '../actions/StreamActions'
|
||||
|
||||
const hidden = {
|
||||
display: 'none',
|
||||
}
|
||||
|
||||
export interface ToolbarProps {
|
||||
messagesCount: number
|
||||
stream: AddStreamPayload
|
||||
onToggleChat: () => void
|
||||
onSendFile: (file: File) => void
|
||||
chatVisible: boolean
|
||||
}
|
||||
|
||||
export interface ToolbarState {
|
||||
readMessages: number
|
||||
camDisabled: boolean
|
||||
micMuted: boolean
|
||||
fullScreenEnabled: boolean
|
||||
}
|
||||
|
||||
export default class Toolbar
|
||||
extends React.PureComponent<ToolbarProps, ToolbarState> {
|
||||
file = React.createRef<HTMLInputElement>()
|
||||
|
||||
constructor(props: ToolbarProps) {
|
||||
super(props)
|
||||
this.state = {
|
||||
readMessages: props.messagesCount,
|
||||
camDisabled: false,
|
||||
micMuted: false,
|
||||
fullScreenEnabled: false,
|
||||
}
|
||||
}
|
||||
|
||||
handleMicClick = () => {
|
||||
const { stream } = this.props
|
||||
stream.stream.getAudioTracks().forEach(track => {
|
||||
track.enabled = !track.enabled
|
||||
})
|
||||
this.setState({
|
||||
...this.state,
|
||||
micMuted: !this.state.micMuted,
|
||||
})
|
||||
}
|
||||
handleCamClick = () => {
|
||||
const { stream } = this.props
|
||||
stream.stream.getVideoTracks().forEach(track => {
|
||||
track.enabled = !track.enabled
|
||||
})
|
||||
this.setState({
|
||||
...this.state,
|
||||
camDisabled: !this.state.camDisabled,
|
||||
})
|
||||
}
|
||||
handleFullscreenClick = () => {
|
||||
if (screenfull.isEnabled) {
|
||||
screenfull.toggle()
|
||||
this.setState({
|
||||
...this.state,
|
||||
fullScreenEnabled: !this.state.fullScreenEnabled,
|
||||
})
|
||||
}
|
||||
}
|
||||
handleHangoutClick = () => {
|
||||
window.location.href = '/'
|
||||
}
|
||||
handleSendFile = () => {
|
||||
this.file.current!.click()
|
||||
}
|
||||
handleSelectFiles = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
Array
|
||||
.from(event.target!.files!)
|
||||
.forEach(file => this.props.onSendFile(file))
|
||||
}
|
||||
handleToggleChat = () => {
|
||||
this.setState({
|
||||
readMessages: this.props.messagesCount,
|
||||
})
|
||||
this.props.onToggleChat()
|
||||
}
|
||||
render () {
|
||||
const { messagesCount, stream } = this.props
|
||||
|
||||
return (
|
||||
<div className="toolbar active">
|
||||
<div onClick={this.handleToggleChat}
|
||||
className={classnames('button chat', {
|
||||
on: this.props.chatVisible,
|
||||
})}
|
||||
data-blink={!this.props.chatVisible &&
|
||||
messagesCount > this.state.readMessages}
|
||||
title="Chat"
|
||||
>
|
||||
<span className="icon icon-question_answer" />
|
||||
</div>
|
||||
<div
|
||||
className="button send-file"
|
||||
onClick={this.handleSendFile}
|
||||
title="Send file"
|
||||
>
|
||||
<input
|
||||
style={hidden}
|
||||
type="file"
|
||||
multiple
|
||||
ref={this.file}
|
||||
onChange={this.handleSelectFiles}
|
||||
/>
|
||||
<span className="icon icon-file-text2" />
|
||||
</div>
|
||||
|
||||
{stream && (
|
||||
<div>
|
||||
<div
|
||||
onClick={this.handleMicClick}
|
||||
className={classnames('button mute-audio', {
|
||||
on: this.state.micMuted,
|
||||
})}
|
||||
title="Mute audio"
|
||||
>
|
||||
<span className="on icon icon-mic_off" />
|
||||
<span className="off icon icon-mic" />
|
||||
</div>
|
||||
<div onClick={this.handleCamClick}
|
||||
className={classnames('button mute-video', {
|
||||
on: this.state.camDisabled,
|
||||
})}
|
||||
title="Mute video"
|
||||
>
|
||||
<span className="on icon icon-videocam_off" />
|
||||
<span className="off icon icon-videocam" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div onClick={this.handleFullscreenClick}
|
||||
className={classnames('button fullscreen', {
|
||||
on: this.state.fullScreenEnabled,
|
||||
})}
|
||||
title="Enter fullscreen"
|
||||
>
|
||||
<span className="on icon icon-fullscreen_exit" />
|
||||
<span className="off icon icon-fullscreen" />
|
||||
</div>
|
||||
|
||||
<div onClick={this.handleHangoutClick}
|
||||
className="button hangup"
|
||||
title="Hangup"
|
||||
>
|
||||
<span className="icon icon-call_end" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -1,69 +0,0 @@
|
||||
import PropTypes from 'prop-types'
|
||||
import React from 'react'
|
||||
import classnames from 'classnames'
|
||||
import { MediaStream } from '../window.js'
|
||||
import socket from '../socket.js'
|
||||
|
||||
export const StreamPropType = PropTypes.shape({
|
||||
mediaStream: PropTypes.instanceOf(MediaStream).isRequired,
|
||||
url: PropTypes.string
|
||||
})
|
||||
|
||||
export default class Video extends React.PureComponent {
|
||||
static propTypes = {
|
||||
videos: PropTypes.object.isRequired,
|
||||
onClick: PropTypes.func,
|
||||
active: PropTypes.bool.isRequired,
|
||||
stream: StreamPropType,
|
||||
userId: PropTypes.string.isRequired,
|
||||
muted: PropTypes.bool.isRequired,
|
||||
mirrored: PropTypes.bool
|
||||
}
|
||||
static defaultProps = {
|
||||
muted: false,
|
||||
mirrored: false
|
||||
}
|
||||
handleClick = e => {
|
||||
const { onClick, userId } = this.props
|
||||
this.play(e)
|
||||
onClick(userId)
|
||||
}
|
||||
play = e => {
|
||||
e.preventDefault()
|
||||
e.target.play()
|
||||
}
|
||||
componentDidMount () {
|
||||
this.componentDidUpdate()
|
||||
}
|
||||
componentDidUpdate () {
|
||||
const { videos, stream } = this.props
|
||||
const { video } = this.refs
|
||||
const mediaStream = stream && stream.mediaStream
|
||||
const url = stream && stream.url
|
||||
if ('srcObject' in video) {
|
||||
if (video.srcObject !== mediaStream) {
|
||||
this.refs.video.srcObject = mediaStream
|
||||
}
|
||||
} else if (video.src !== url) {
|
||||
video.src = url
|
||||
}
|
||||
videos[socket.id] = video
|
||||
}
|
||||
render () {
|
||||
const { active, mirrored, muted } = this.props
|
||||
const className = classnames('video-container', { active, mirrored })
|
||||
return (
|
||||
<div className={className}>
|
||||
<video
|
||||
id={`video-${socket.id}`}
|
||||
autoPlay
|
||||
onClick={this.handleClick}
|
||||
onLoadedMetadata={this.play}
|
||||
playsInline
|
||||
ref="video"
|
||||
muted={muted}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -1,90 +0,0 @@
|
||||
jest.mock('../window.js')
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom'
|
||||
import TestUtils from 'react-dom/test-utils'
|
||||
import Video from './Video.js'
|
||||
import { MediaStream } from '../window.js'
|
||||
|
||||
describe('components/Video', () => {
|
||||
|
||||
class VideoWrapper extends React.PureComponent {
|
||||
static propTypes = Video.propTypes
|
||||
constructor () {
|
||||
super()
|
||||
this.state = {}
|
||||
}
|
||||
render () {
|
||||
return <Video
|
||||
videos={this.props.videos}
|
||||
active={this.props.active}
|
||||
stream={this.state.stream || this.props.stream}
|
||||
onClick={this.props.onClick}
|
||||
userId="test"
|
||||
muted={this.props.muted}
|
||||
mirrored={this.props.mirrored}
|
||||
/>
|
||||
}
|
||||
}
|
||||
|
||||
let component, videos, video, onClick, mediaStream, url, wrapper
|
||||
function render (flags = {}) {
|
||||
videos = {}
|
||||
onClick = jest.fn()
|
||||
mediaStream = new MediaStream()
|
||||
component = TestUtils.renderIntoDocument(
|
||||
<VideoWrapper
|
||||
videos={videos}
|
||||
active={flags.active || false}
|
||||
stream={{ mediaStream, url }}
|
||||
onClick={onClick}
|
||||
userId="test"
|
||||
muted={flags.muted || false}
|
||||
mirrored={flags.mirrored}
|
||||
/>
|
||||
)
|
||||
wrapper = ReactDOM.findDOMNode(component)
|
||||
video = TestUtils.findRenderedComponentWithType(component, Video)
|
||||
}
|
||||
|
||||
describe('render', () => {
|
||||
it('should not fail', () => {
|
||||
render({})
|
||||
})
|
||||
|
||||
it('Mirrored and active propogate to rendered classes', () => {
|
||||
render({ active: true, mirrored: true })
|
||||
expect(wrapper.className).toBe('video-container active mirrored')
|
||||
})
|
||||
})
|
||||
|
||||
describe('componentDidUpdate', () => {
|
||||
describe('src', () => {
|
||||
beforeEach(() => {
|
||||
render()
|
||||
delete video.refs.video.srcObject
|
||||
})
|
||||
it('updates src only when changed', () => {
|
||||
mediaStream = new MediaStream()
|
||||
component.setState({
|
||||
stream: { url: 'test', mediaStream }
|
||||
})
|
||||
expect(video.refs.video.src).toBe('http://localhost/test')
|
||||
component.setState({
|
||||
stream: { url: 'test', mediaStream }
|
||||
})
|
||||
})
|
||||
it('updates srcObject only when changed', () => {
|
||||
video.refs.video.srcObject = null
|
||||
mediaStream = new MediaStream()
|
||||
component.setState({
|
||||
stream: { url: 'test', mediaStream }
|
||||
})
|
||||
expect(video.refs.video.srcObject).toBe(mediaStream)
|
||||
component.setState({
|
||||
stream: { url: 'test', mediaStream }
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
})
|
||||
120
src/client/components/Video.test.tsx
Normal file
@ -0,0 +1,120 @@
|
||||
jest.mock('../window')
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom'
|
||||
import TestUtils from 'react-dom/test-utils'
|
||||
import { AddStreamPayload } from '../actions/StreamActions'
|
||||
import Video, { VideoProps } from './Video'
|
||||
import { MediaStream } from '../window'
|
||||
|
||||
describe('components/Video', () => {
|
||||
|
||||
interface VideoState {
|
||||
stream: null | AddStreamPayload
|
||||
}
|
||||
|
||||
class VideoWrapper extends React.PureComponent<VideoProps, VideoState> {
|
||||
ref = React.createRef<Video>()
|
||||
|
||||
state = {
|
||||
stream: null,
|
||||
}
|
||||
|
||||
render () {
|
||||
return <Video
|
||||
ref={this.ref}
|
||||
videos={this.props.videos}
|
||||
active={this.props.active}
|
||||
stream={this.state.stream || this.props.stream}
|
||||
onClick={this.props.onClick}
|
||||
userId="test"
|
||||
muted={this.props.muted}
|
||||
mirrored={this.props.mirrored}
|
||||
/>
|
||||
}
|
||||
}
|
||||
|
||||
let component: VideoWrapper
|
||||
let videos: Record<string, unknown> = {}
|
||||
let video: Video
|
||||
let onClick: (userId: string) => void
|
||||
let mediaStream: MediaStream
|
||||
let url: string
|
||||
let wrapper: Element
|
||||
|
||||
interface Flags {
|
||||
active: boolean
|
||||
muted: boolean
|
||||
mirrored: boolean
|
||||
}
|
||||
const defaultFlags: Flags = {
|
||||
active: false,
|
||||
muted: false,
|
||||
mirrored: false,
|
||||
}
|
||||
async function render (args?: Partial<Flags>) {
|
||||
const flags: Flags = Object.assign({}, defaultFlags, args)
|
||||
videos = {}
|
||||
onClick = jest.fn()
|
||||
mediaStream = new MediaStream()
|
||||
const div = document.createElement('div')
|
||||
component = await new Promise<VideoWrapper>(resolve => {
|
||||
ReactDOM.render(
|
||||
<VideoWrapper
|
||||
ref={instance => resolve(instance!)}
|
||||
videos={videos}
|
||||
active={flags.active}
|
||||
stream={{ stream: mediaStream, url, userId: 'test' }}
|
||||
onClick={onClick}
|
||||
userId="test"
|
||||
muted={flags.muted}
|
||||
mirrored={flags.mirrored}
|
||||
/>,
|
||||
div,
|
||||
)
|
||||
})
|
||||
video = TestUtils.findRenderedComponentWithType(component, Video)
|
||||
wrapper = div.children[0]
|
||||
}
|
||||
|
||||
describe('render', () => {
|
||||
it('should not fail', async () => {
|
||||
await render()
|
||||
})
|
||||
|
||||
it('Mirrored and active propogate to rendered classes', async () => {
|
||||
await render({ active: true, mirrored: true })
|
||||
expect(wrapper.className).toBe('video-container active mirrored')
|
||||
})
|
||||
})
|
||||
|
||||
describe('componentDidUpdate', () => {
|
||||
describe('src', () => {
|
||||
beforeEach(async () => {
|
||||
await render()
|
||||
delete video.videoRef.current!.srcObject
|
||||
})
|
||||
it('updates src only when changed', () => {
|
||||
mediaStream = new MediaStream()
|
||||
component.setState({
|
||||
stream: { url: 'test', stream: mediaStream, userId: '' },
|
||||
})
|
||||
expect(video.videoRef.current!.src).toBe('http://localhost/test')
|
||||
component.setState({
|
||||
stream: { url: 'test', stream: mediaStream, userId: '' },
|
||||
})
|
||||
})
|
||||
it('updates srcObject only when changed', () => {
|
||||
video.videoRef.current!.srcObject = null
|
||||
mediaStream = new MediaStream()
|
||||
component.setState({
|
||||
stream: { url: 'test', stream: mediaStream, userId: '' },
|
||||
})
|
||||
expect(video.videoRef.current!.srcObject).toBe(mediaStream)
|
||||
component.setState({
|
||||
stream: { url: 'test', stream: mediaStream, userId: '' },
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
})
|
||||
66
src/client/components/Video.tsx
Normal file
@ -0,0 +1,66 @@
|
||||
import React, { ReactEventHandler } from 'react'
|
||||
import classnames from 'classnames'
|
||||
import socket from '../socket'
|
||||
import { AddStreamPayload } from '../actions/StreamActions'
|
||||
|
||||
export interface VideoProps {
|
||||
videos: Record<string, unknown>
|
||||
onClick: (userId: string) => void
|
||||
active: boolean
|
||||
stream?: AddStreamPayload
|
||||
userId: string
|
||||
muted: boolean
|
||||
mirrored: boolean
|
||||
}
|
||||
|
||||
export default class Video extends React.PureComponent<VideoProps> {
|
||||
videoRef = React.createRef<HTMLVideoElement>()
|
||||
|
||||
static defaultProps = {
|
||||
muted: false,
|
||||
mirrored: false,
|
||||
}
|
||||
handleClick: ReactEventHandler<HTMLVideoElement> = e => {
|
||||
const { onClick, userId } = this.props
|
||||
this.play(e)
|
||||
onClick(userId)
|
||||
}
|
||||
play: ReactEventHandler<HTMLVideoElement> = e => {
|
||||
e.preventDefault();
|
||||
(e.target as HTMLVideoElement).play()
|
||||
}
|
||||
componentDidMount () {
|
||||
this.componentDidUpdate()
|
||||
}
|
||||
componentDidUpdate () {
|
||||
const { videos, stream } = this.props
|
||||
const video = this.videoRef.current!
|
||||
const mediaStream = stream && stream.stream || null
|
||||
const url = stream && stream.url
|
||||
if ('srcObject' in video as unknown) {
|
||||
if (video.srcObject !== mediaStream) {
|
||||
video.srcObject = mediaStream
|
||||
}
|
||||
} else if (video.src !== url) {
|
||||
video.src = url || ''
|
||||
}
|
||||
videos[socket.id] = video
|
||||
}
|
||||
render () {
|
||||
const { active, mirrored, muted } = this.props
|
||||
const className = classnames('video-container', { active, mirrored })
|
||||
return (
|
||||
<div className={className}>
|
||||
<video
|
||||
id={`video-${socket.id}`}
|
||||
autoPlay
|
||||
onClick={this.handleClick}
|
||||
onLoadedMetadata={this.play}
|
||||
playsInline
|
||||
ref={this.videoRef}
|
||||
muted={muted}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,3 @@
|
||||
|
||||
export const ACTIVE_SET = 'ACTIVE_SET'
|
||||
export const ACTIVE_TOGGLE = 'ACTIVE_TOGGLE'
|
||||
|
||||
@ -7,9 +6,6 @@ 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_'
|
||||
|
||||
@ -18,7 +14,6 @@ export const NOTIFY_DISMISS = 'NOTIFY_DISMISS'
|
||||
export const NOTIFY_CLEAR = 'NOTIFY_CLEAR'
|
||||
|
||||
export const MESSAGE_ADD = 'MESSAGE_ADD'
|
||||
export const MESSAGES_HISTORY = 'MESSAGES_HISTORY'
|
||||
|
||||
export const PEER_ADD = 'PEER_ADD'
|
||||
export const PEER_REMOVE = 'PEER_REMOVE'
|
||||
@ -33,8 +28,6 @@ export const PEER_EVENT_DATA = 'data'
|
||||
|
||||
export const SOCKET_EVENT_SIGNAL = 'signal'
|
||||
export const SOCKET_EVENT_USERS = 'users'
|
||||
export const SOCKET_EVENT_MESSAGES = 'messages'
|
||||
export const SOCKET_EVENT_NEW_MESSAGE = 'new_message'
|
||||
|
||||
export const STREAM_ADD = 'PEER_STREAM_ADD'
|
||||
export const STREAM_REMOVE = 'PEER_STREAM_REMOVE'
|
||||
@ -1,30 +0,0 @@
|
||||
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,
|
||||
messages: state.messages,
|
||||
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,102 +0,0 @@
|
||||
jest.mock('../actions/CallActions.js')
|
||||
jest.mock('../socket.js')
|
||||
jest.mock('../window.js')
|
||||
|
||||
import * as constants from '../constants.js'
|
||||
import App from './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 { MediaStream } from '../window.js'
|
||||
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()
|
||||
window.HTMLMediaElement.prototype.play = jest.fn()
|
||||
})
|
||||
|
||||
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 = {
|
||||
test: {
|
||||
mediaStream: new MediaStream(),
|
||||
url: '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 }
|
||||
}])
|
||||
})
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
})
|
||||
124
src/client/containers/App.test.tsx
Normal file
@ -0,0 +1,124 @@
|
||||
jest.mock('../actions/CallActions')
|
||||
jest.mock('../socket')
|
||||
jest.mock('../window')
|
||||
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom'
|
||||
import TestUtils from 'react-dom/test-utils'
|
||||
import { Provider } from 'react-redux'
|
||||
import { AnyAction, applyMiddleware, createStore } from 'redux'
|
||||
import { init } from '../actions/CallActions'
|
||||
import { Alert } from '../actions/NotifyActions'
|
||||
import * as constants from '../constants'
|
||||
import reducers from '../reducers'
|
||||
import { middlewares, State, Store } from '../store'
|
||||
import { MediaStream } from '../window'
|
||||
import App from './App'
|
||||
|
||||
describe('App', () => {
|
||||
|
||||
const initAction = { type: 'INIT' }
|
||||
|
||||
let store: Store
|
||||
let state: Partial<State>
|
||||
let dispatchSpy: jest.SpyInstance<AnyAction, AnyAction[]>
|
||||
beforeEach(() => {
|
||||
state = {};
|
||||
(init as jest.Mock).mockReturnValue(initAction)
|
||||
|
||||
window.HTMLMediaElement.prototype.play = jest.fn()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (dispatchSpy) {
|
||||
dispatchSpy.mockReset()
|
||||
dispatchSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
let node: Element
|
||||
async function render () {
|
||||
store = createStore(
|
||||
reducers,
|
||||
state,
|
||||
applyMiddleware(...middlewares),
|
||||
)
|
||||
dispatchSpy = jest.spyOn(store, 'dispatch')
|
||||
const div = document.createElement('div')
|
||||
node = await new Promise<HTMLDivElement>(resolve => {
|
||||
ReactDOM.render(
|
||||
<Provider store={store}>
|
||||
<div ref={div => resolve(div!)}>
|
||||
<App />
|
||||
</div>
|
||||
</Provider>,
|
||||
div,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
describe('render', () => {
|
||||
it('renders without issues', async () => {
|
||||
await render()
|
||||
expect(node).toBeTruthy()
|
||||
expect((init as jest.Mock).mock.calls.length).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('state', () => {
|
||||
let alert: Alert
|
||||
beforeEach(async () => {
|
||||
state.streams = {
|
||||
test: {
|
||||
userId: 'test',
|
||||
stream: new MediaStream(),
|
||||
url: 'blob://',
|
||||
},
|
||||
}
|
||||
state.peers = {
|
||||
test: {} as any,
|
||||
}
|
||||
state.notifications = {
|
||||
'notification1': {
|
||||
id: 'notification1',
|
||||
message: 'test',
|
||||
type: 'warning',
|
||||
},
|
||||
}
|
||||
alert = {
|
||||
dismissable: true,
|
||||
action: 'Dismiss',
|
||||
message: 'test alert',
|
||||
type: 'info',
|
||||
}
|
||||
state.alerts = [alert]
|
||||
await render()
|
||||
})
|
||||
|
||||
describe('alerts', () => {
|
||||
it('can be dismissed', () => {
|
||||
const dismiss = node.querySelector('.action-alert-dismiss')!
|
||||
dispatchSpy.mockReset()
|
||||
TestUtils.Simulate.click(dismiss)
|
||||
expect(dispatchSpy.mock.calls).toEqual([[{
|
||||
type: constants.ALERT_DISMISS,
|
||||
payload: alert,
|
||||
}]])
|
||||
})
|
||||
})
|
||||
|
||||
describe('video', () => {
|
||||
it('can be activated', () => {
|
||||
dispatchSpy.mockReset()
|
||||
const video = node.querySelector('video')!
|
||||
TestUtils.Simulate.click(video)
|
||||
expect(dispatchSpy.mock.calls).toEqual([[{
|
||||
type: constants.ACTIVE_TOGGLE,
|
||||
payload: { userId: constants.ME },
|
||||
}]])
|
||||
})
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
})
|
||||
32
src/client/containers/App.tsx
Normal file
@ -0,0 +1,32 @@
|
||||
import * as CallActions from '../actions/CallActions'
|
||||
import * as NotifyActions from '../actions/NotifyActions'
|
||||
import * as PeerActions from '../actions/PeerActions'
|
||||
import * as StreamActions from '../actions/StreamActions'
|
||||
import App from '../components/App'
|
||||
import { bindActionCreators, Dispatch } from 'redux'
|
||||
import { connect } from 'react-redux'
|
||||
import { State } from '../store'
|
||||
|
||||
function mapStateToProps (state: State) {
|
||||
return {
|
||||
streams: state.streams,
|
||||
peers: state.peers,
|
||||
alerts: state.alerts,
|
||||
notifications: state.notifications,
|
||||
messages: state.messages.list,
|
||||
messagesCount: state.messages.count,
|
||||
active: state.active,
|
||||
}
|
||||
}
|
||||
|
||||
function mapDispatchToProps (dispatch: Dispatch) {
|
||||
return {
|
||||
toggleActive: bindActionCreators(StreamActions.toggleActive, dispatch),
|
||||
sendMessage: bindActionCreators(PeerActions.sendMessage, dispatch),
|
||||
dismissAlert: bindActionCreators(NotifyActions.dismissAlert, dispatch),
|
||||
init: bindActionCreators(CallActions.init, dispatch),
|
||||
onSendFile: bindActionCreators(PeerActions.sendFile, dispatch),
|
||||
}
|
||||
}
|
||||
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(App)
|
||||
@ -1,49 +0,0 @@
|
||||
const iceServers = require('./iceServers.js')
|
||||
|
||||
function noop () {}
|
||||
|
||||
function checkTURNServer (turnConfig, timeout) {
|
||||
console.log('checking turn server', turnConfig)
|
||||
|
||||
return new Promise(function (resolve, reject) {
|
||||
setTimeout(function () {
|
||||
if (promiseResolved) return
|
||||
resolve(false)
|
||||
promiseResolved = true
|
||||
}, timeout || 5000)
|
||||
|
||||
let promiseResolved = false
|
||||
const PeerConnection = window.RTCPeerConnection ||
|
||||
window.mozRTCPeerConnection ||
|
||||
window.webkitRTCPeerConnection
|
||||
|
||||
const pc = new PeerConnection({ iceServers: [turnConfig] })
|
||||
|
||||
// create a bogus data channel
|
||||
pc.createDataChannel('')
|
||||
pc.createOffer(function (sdp) {
|
||||
// sometimes sdp contains the ice candidates...
|
||||
if (sdp.sdp.indexOf('typ relay') > -1) {
|
||||
promiseResolved = true
|
||||
resolve(true)
|
||||
}
|
||||
pc.setLocalDescription(sdp, noop, noop)
|
||||
}, noop)
|
||||
|
||||
pc.onicecandidate = function (ice) {
|
||||
if (promiseResolved ||
|
||||
!ice ||
|
||||
!ice.candidate ||
|
||||
!ice.candidate.candidate ||
|
||||
!(ice.candidate.candidate.indexOf('typ relay') > -1)) {
|
||||
return
|
||||
}
|
||||
promiseResolved = true
|
||||
resolve(true)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
checkTURNServer(iceServers[0], 10000)
|
||||
.then(console.log.bind(console))
|
||||
.catch(console.error.bind(console))
|
||||
48
src/client/debug/index.ts
Normal file
@ -0,0 +1,48 @@
|
||||
import { config, ICEServer } from '../../server/config'
|
||||
|
||||
async function checkTURNServer (turnConfig: ICEServer, timeoutDuration = 5000) {
|
||||
console.log('checking turn server', turnConfig)
|
||||
|
||||
const timeout = new Promise<unknown>((resolve, reject) => {
|
||||
setTimeout(function () {
|
||||
reject(new Error('timed out'))
|
||||
}, timeoutDuration)
|
||||
})
|
||||
|
||||
async function start() {
|
||||
const PeerConnection = window.RTCPeerConnection ||
|
||||
(
|
||||
window as unknown as { mozRTCPeerConnection: RTCPeerConnection }
|
||||
).mozRTCPeerConnection||
|
||||
window.webkitRTCPeerConnection
|
||||
|
||||
const pc = new PeerConnection({ iceServers: [turnConfig] })
|
||||
|
||||
// create a bogus data channel
|
||||
pc.createDataChannel('')
|
||||
const sdp = await pc.createOffer()
|
||||
// sometimes sdp contains the ice candidates...
|
||||
if (sdp.sdp!.indexOf('typ relay') > -1) {
|
||||
return true
|
||||
}
|
||||
pc.setLocalDescription(sdp)
|
||||
|
||||
return new Promise(resolve => {
|
||||
pc.onicecandidate = function (ice) {
|
||||
if (!ice ||
|
||||
!ice.candidate ||
|
||||
!ice.candidate.candidate ||
|
||||
!(ice.candidate.candidate.indexOf('typ relay') > -1)) {
|
||||
return
|
||||
}
|
||||
resolve(true)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return Promise.race([ timeout, start() ])
|
||||
}
|
||||
|
||||
checkTURNServer(config.iceServers[0], 10000)
|
||||
.then(console.log.bind(console))
|
||||
.catch(console.error.bind(console))
|
||||
@ -1,11 +1,11 @@
|
||||
'use strict'
|
||||
import '@babel/polyfill'
|
||||
import App from './containers/App.js'
|
||||
import 'core-js'
|
||||
import App from './containers/App'
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom'
|
||||
import store from './store.js'
|
||||
import store from './store'
|
||||
import { Provider } from 'react-redux'
|
||||
import { play } from './window.js'
|
||||
import { play } from './window'
|
||||
|
||||
const component = (
|
||||
<Provider store={store}>
|
||||
@ -1,10 +0,0 @@
|
||||
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,5 +1,5 @@
|
||||
import logger from 'redux-logger'
|
||||
import { create } from './middlewares.js'
|
||||
import { create } from './middlewares'
|
||||
|
||||
describe('store', () => {
|
||||
|
||||
11
src/client/middlewares.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { Middleware } from 'redux'
|
||||
import logger from 'redux-logger'
|
||||
import thunk from 'redux-thunk'
|
||||
import { middleware as asyncMiddleware } from './async'
|
||||
|
||||
export const middlewares: Middleware[] = [thunk, asyncMiddleware]
|
||||
export const create = (log = false) => {
|
||||
const m = middlewares.slice()
|
||||
log && m.push(logger)
|
||||
return m
|
||||
}
|
||||
@ -1,12 +1,12 @@
|
||||
import * as StreamActions from '../actions/StreamActions.js'
|
||||
import active from './active.js'
|
||||
import * as StreamActions from '../actions/StreamActions'
|
||||
import active from './active'
|
||||
|
||||
describe('reducers/active', () => {
|
||||
|
||||
describe('setActive', () => {
|
||||
it('sets active to userId', () => {
|
||||
const userId = 'test'
|
||||
let state = active()
|
||||
let state = active(null, {type: 'test'} as any)
|
||||
state = active(state, StreamActions.setActive(userId))
|
||||
expect(state).toBe(userId)
|
||||
})
|
||||
@ -15,7 +15,7 @@ describe('reducers/active', () => {
|
||||
describe('toggleActive', () => {
|
||||
it('sets active to userId', () => {
|
||||
const userId = 'test'
|
||||
let state = active()
|
||||
let state = active(null, {type: 'test'} as any)
|
||||
state = active(state, StreamActions.toggleActive(userId))
|
||||
expect(state).toBe(userId)
|
||||
state = active(state, StreamActions.toggleActive(userId))
|
||||
@ -1,6 +1,12 @@
|
||||
import * as constants from '../constants.js'
|
||||
import * as constants from '../constants'
|
||||
import { StreamAction } from '../actions/StreamActions'
|
||||
|
||||
export default function active (state = null, action) {
|
||||
export type ActiveState = null | string
|
||||
|
||||
export default function active (
|
||||
state: ActiveState = null,
|
||||
action: StreamAction,
|
||||
): ActiveState {
|
||||
switch (action && action.type) {
|
||||
case constants.ACTIVE_SET:
|
||||
case constants.STREAM_ADD:
|
||||
@ -1,19 +0,0 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@ -1,38 +1,37 @@
|
||||
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'
|
||||
import * as NotifyActions from '../actions/NotifyActions'
|
||||
import { applyMiddleware, createStore, Store, bindActionCreators } from 'redux'
|
||||
import { create } from '../middlewares'
|
||||
import reducers from './index'
|
||||
import values from 'lodash/values'
|
||||
|
||||
jest.useFakeTimers()
|
||||
|
||||
describe('reducers/alerts', () => {
|
||||
|
||||
let store
|
||||
let store: Store
|
||||
let notifyActions: typeof NotifyActions
|
||||
beforeEach(() => {
|
||||
store = createStore(
|
||||
reducers,
|
||||
applyMiddleware.apply(null, create())
|
||||
applyMiddleware(...create()),
|
||||
)
|
||||
notifyActions = bindActionCreators(NotifyActions, store.dispatch)
|
||||
})
|
||||
|
||||
|
||||
describe('clearAlert', () => {
|
||||
|
||||
const actions = {
|
||||
true: 'Dismiss',
|
||||
false: ''
|
||||
}
|
||||
;[true, false].forEach(dismissable => {
|
||||
[true, false].forEach(dismissable => {
|
||||
beforeEach(() => {
|
||||
store.dispatch(NotifyActions.clearAlerts())
|
||||
notifyActions.clearAlerts()
|
||||
})
|
||||
it('adds alert to store', () => {
|
||||
store.dispatch(NotifyActions.alert('test', dismissable))
|
||||
notifyActions.alert('test', dismissable)
|
||||
expect(store.getState().alerts).toEqual([{
|
||||
action: actions[dismissable],
|
||||
action: dismissable ? 'Dismiss' : undefined,
|
||||
dismissable,
|
||||
message: 'test',
|
||||
type: 'warning'
|
||||
type: 'warning',
|
||||
}])
|
||||
})
|
||||
})
|
||||
@ -51,25 +50,36 @@ describe('reducers/alerts', () => {
|
||||
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({}))
|
||||
store.dispatch(NotifyActions.dismissAlert({
|
||||
action: undefined,
|
||||
dismissable: false,
|
||||
message: 'bla',
|
||||
type: 'error',
|
||||
}))
|
||||
expect(store.getState().alerts.length).toBe(1)
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
;['info', 'warning', 'error'].forEach(type => {
|
||||
const methods: Array<'info' | 'warning' | 'error'> = [
|
||||
'info',
|
||||
'warning',
|
||||
'error',
|
||||
]
|
||||
|
||||
methods.forEach(type => {
|
||||
|
||||
describe(type, () => {
|
||||
|
||||
beforeEach(() => {
|
||||
store.dispatch(NotifyActions[type]('Hi {0}!', 'John'))
|
||||
notifyActions[type]('Hi {0}!', 'John')
|
||||
})
|
||||
|
||||
it('adds a notification', () => {
|
||||
expect(_.values(store.getState().notifications)).toEqual([{
|
||||
expect(values(store.getState().notifications)).toEqual([{
|
||||
id: jasmine.any(String),
|
||||
message: 'Hi John!',
|
||||
type
|
||||
type,
|
||||
}])
|
||||
})
|
||||
|
||||
@ -79,7 +89,7 @@ describe('reducers/alerts', () => {
|
||||
})
|
||||
|
||||
it('does not fail when no arguments', () => {
|
||||
store.dispatch(NotifyActions[type]())
|
||||
notifyActions[type]()
|
||||
})
|
||||
|
||||
})
|
||||
@ -89,9 +99,9 @@ describe('reducers/alerts', () => {
|
||||
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'))
|
||||
notifyActions.info('Hi {0}!', 'John')
|
||||
notifyActions.warning('Hi {0}!', 'John')
|
||||
notifyActions.error('Hi {0}!', 'John')
|
||||
store.dispatch(NotifyActions.clear())
|
||||
expect(store.getState().notifications).toEqual({})
|
||||
})
|
||||
19
src/client/reducers/alerts.ts
Normal file
@ -0,0 +1,19 @@
|
||||
import * as constants from '../constants'
|
||||
import { AlertActionType, Alert } from '../actions/NotifyActions'
|
||||
|
||||
export type AlertState = Alert[]
|
||||
|
||||
const defaultState: AlertState = []
|
||||
|
||||
export default function alerts (state = defaultState, action: AlertActionType) {
|
||||
switch (action.type) {
|
||||
case constants.ALERT:
|
||||
return [...state, action.payload]
|
||||
case constants.ALERT_DISMISS:
|
||||
return state.filter(a => a !== action.payload)
|
||||
case constants.ALERT_CLEAR:
|
||||
return defaultState
|
||||
default:
|
||||
return state
|
||||
}
|
||||
}
|
||||
@ -1,16 +0,0 @@
|
||||
import active from './active.js'
|
||||
import alerts from './alerts.js'
|
||||
import notifications from './notifications.js'
|
||||
import messages from './messages.js'
|
||||
import peers from './peers.js'
|
||||
import streams from './streams.js'
|
||||
import { combineReducers } from 'redux'
|
||||
|
||||
export default combineReducers({
|
||||
active,
|
||||
alerts,
|
||||
notifications,
|
||||
messages,
|
||||
peers,
|
||||
streams
|
||||
})
|
||||
16
src/client/reducers/index.ts
Normal file
@ -0,0 +1,16 @@
|
||||
import active from './active'
|
||||
import alerts from './alerts'
|
||||
import notifications from './notifications'
|
||||
import messages from './messages'
|
||||
import peers from './peers'
|
||||
import streams from './streams'
|
||||
import { combineReducers } from 'redux'
|
||||
|
||||
export default combineReducers({
|
||||
active,
|
||||
alerts,
|
||||
notifications,
|
||||
messages,
|
||||
peers,
|
||||
streams,
|
||||
})
|
||||
@ -1,17 +0,0 @@
|
||||
import * as constants from '../constants.js'
|
||||
import Immutable from 'seamless-immutable'
|
||||
|
||||
const defaultState = Immutable([])
|
||||
|
||||
export default function messages (state = defaultState, action) {
|
||||
switch (action && action.type) {
|
||||
case constants.MESSAGE_ADD:
|
||||
const messages = state.asMutable()
|
||||
messages.push(action.payload)
|
||||
return Immutable(messages)
|
||||
case constants.MESSAGES_HISTORY:
|
||||
return Immutable(action.messages)
|
||||
default:
|
||||
return state
|
||||
}
|
||||
}
|
||||
@ -1,28 +0,0 @@
|
||||
import * as ChatActions from '../actions/ChatActions.js'
|
||||
import messages from './messages.js'
|
||||
|
||||
describe('reducers/messages', () => {
|
||||
|
||||
describe('addMessage', () => {
|
||||
it('add message to chat', () => {
|
||||
const payload = {
|
||||
userId: 'test',
|
||||
message: 'hello',
|
||||
timestamp: new Date(),
|
||||
image: null
|
||||
}
|
||||
let state = messages()
|
||||
state = messages(state, ChatActions.addMessage(payload))
|
||||
expect(state).toEqual([payload])
|
||||
})
|
||||
})
|
||||
|
||||
describe('messageHistory', () => {
|
||||
it('get chat message hisotry', () => {
|
||||
let state = messages()
|
||||
state = messages(state, ChatActions.loadHistory([]))
|
||||
expect(state).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
})
|
||||
19
src/client/reducers/messages.test.ts
Normal file
@ -0,0 +1,19 @@
|
||||
import * as ChatActions from '../actions/ChatActions'
|
||||
import messages from './messages'
|
||||
|
||||
describe('reducers/messages', () => {
|
||||
|
||||
describe('addMessage', () => {
|
||||
it('add message to chat', () => {
|
||||
const payload: ChatActions.Message = {
|
||||
userId: 'test',
|
||||
message: 'hello',
|
||||
timestamp: new Date().toLocaleString(),
|
||||
}
|
||||
let state = messages(undefined, {type: 'test'} as any)
|
||||
state = messages(state, ChatActions.addMessage(payload))
|
||||
expect(state.list).toEqual([payload])
|
||||
})
|
||||
})
|
||||
|
||||
})
|
||||
40
src/client/reducers/messages.ts
Normal file
@ -0,0 +1,40 @@
|
||||
import * as constants from '../constants'
|
||||
import { Message, MessageAddAction } from '../actions/ChatActions'
|
||||
import { NotificationAddAction } from '../actions/NotifyActions'
|
||||
|
||||
export interface MessagesState {
|
||||
list: Message[]
|
||||
count: number
|
||||
}
|
||||
|
||||
const defaultState: MessagesState = {
|
||||
list: [],
|
||||
count: 0,
|
||||
}
|
||||
|
||||
function convertNotificationToMessage(action: NotificationAddAction): Message {
|
||||
return {
|
||||
userId: '[PeerCalls]',
|
||||
message: action.payload.message,
|
||||
timestamp: new Date().toLocaleString(),
|
||||
}
|
||||
}
|
||||
|
||||
export default function messages (
|
||||
state = defaultState, action: MessageAddAction | NotificationAddAction,
|
||||
): MessagesState {
|
||||
switch (action.type) {
|
||||
case constants.NOTIFY:
|
||||
return {
|
||||
...state,
|
||||
list: [...state.list, convertNotificationToMessage(action)],
|
||||
}
|
||||
case constants.MESSAGE_ADD:
|
||||
return {
|
||||
count: state.count + 1,
|
||||
list: [...state.list, action.payload],
|
||||
}
|
||||
default:
|
||||
return state
|
||||
}
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
31
src/client/reducers/notifications.ts
Normal file
@ -0,0 +1,31 @@
|
||||
import * as constants from '../constants'
|
||||
import { Notification, NotificationActionType } from '../actions/NotifyActions'
|
||||
|
||||
export type NotificationState = Record<string, Notification>
|
||||
|
||||
const defaultState: NotificationState = {}
|
||||
|
||||
export default function notifications (
|
||||
state = defaultState,
|
||||
action: NotificationActionType,
|
||||
) {
|
||||
switch (action.type) {
|
||||
case constants.NOTIFY:
|
||||
return {
|
||||
...state,
|
||||
[action.payload.id]: action.payload,
|
||||
}
|
||||
case constants.NOTIFY_DISMISS:
|
||||
return Object
|
||||
.keys(state)
|
||||
.filter(key => key !== action.payload.id)
|
||||
.reduce((obj, key) => {
|
||||
obj[key] = state[key]
|
||||
return obj
|
||||
}, {} as NotificationState)
|
||||
case constants.NOTIFY_CLEAR:
|
||||
return defaultState
|
||||
default:
|
||||
return state
|
||||
}
|
||||
}
|
||||
@ -1,21 +0,0 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
29
src/client/reducers/peers.ts
Normal file
@ -0,0 +1,29 @@
|
||||
import forEach from 'lodash/forEach'
|
||||
import omit from 'lodash/omit'
|
||||
import Peer from 'simple-peer'
|
||||
import { PeerAction } from '../actions/PeerActions'
|
||||
import * as constants from '../constants'
|
||||
|
||||
export type PeersState = Record<string, Peer.Instance>
|
||||
|
||||
const defaultState: PeersState = {}
|
||||
|
||||
export default function peers(
|
||||
state = defaultState,
|
||||
action: PeerAction,
|
||||
): PeersState {
|
||||
switch (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:
|
||||
forEach(state, peer => peer.destroy())
|
||||
return defaultState
|
||||
default:
|
||||
return state
|
||||
}
|
||||
}
|
||||
@ -1,47 +0,0 @@
|
||||
import * as constants from '../constants.js'
|
||||
import _ from 'underscore'
|
||||
import { createObjectURL, revokeObjectURL } from '../window.js'
|
||||
import _debug from 'debug'
|
||||
|
||||
const debug = _debug('peercalls')
|
||||
const defaultState = Object.freeze({})
|
||||
|
||||
function safeCreateObjectURL (stream) {
|
||||
try {
|
||||
return createObjectURL(stream)
|
||||
} catch (err) {
|
||||
debug('Error using createObjectURL: %s', err)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function addStream (state, action) {
|
||||
const { userId, stream } = action.payload
|
||||
return Object.freeze({
|
||||
...state,
|
||||
[userId]: Object.freeze({
|
||||
mediaStream: stream,
|
||||
url: safeCreateObjectURL(stream)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function removeStream (state, action) {
|
||||
const { userId } = action.payload
|
||||
const stream = state[userId]
|
||||
if (stream && stream.url) {
|
||||
revokeObjectURL(stream.url)
|
||||
}
|
||||
return Object.freeze(_.omit(state, [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,25 +1,25 @@
|
||||
jest.mock('../window.js')
|
||||
jest.mock('../window')
|
||||
|
||||
import * as StreamActions from '../actions/StreamActions.js'
|
||||
import reducers from './index.js'
|
||||
import { createObjectURL, MediaStream } from '../window.js'
|
||||
import { applyMiddleware, createStore } from 'redux'
|
||||
import { create } from '../middlewares.js'
|
||||
import * as StreamActions from '../actions/StreamActions'
|
||||
import reducers from './index'
|
||||
import { createObjectURL, MediaStream } from '../window'
|
||||
import { applyMiddleware, createStore, Store } from 'redux'
|
||||
import { create } from '../middlewares'
|
||||
|
||||
describe('reducers/alerts', () => {
|
||||
|
||||
let store, stream, userId
|
||||
let store: Store, stream: MediaStream, userId: string
|
||||
beforeEach(() => {
|
||||
store = createStore(
|
||||
reducers,
|
||||
applyMiddleware.apply(null, create())
|
||||
applyMiddleware(...create()),
|
||||
)
|
||||
userId = 'test id'
|
||||
stream = new MediaStream()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
createObjectURL
|
||||
(createObjectURL as jest.Mock)
|
||||
.mockImplementation(object => 'blob://' + String(object))
|
||||
})
|
||||
|
||||
@ -34,20 +34,22 @@ describe('reducers/alerts', () => {
|
||||
store.dispatch(StreamActions.addStream({ userId, stream }))
|
||||
expect(store.getState().streams).toEqual({
|
||||
[userId]: {
|
||||
mediaStream: stream,
|
||||
url: jasmine.any(String)
|
||||
}
|
||||
userId,
|
||||
stream: stream,
|
||||
url: jasmine.any(String),
|
||||
},
|
||||
})
|
||||
})
|
||||
it('does not fail when createObjectURL fails', () => {
|
||||
createObjectURL
|
||||
(createObjectURL as jest.Mock)
|
||||
.mockImplementation(() => { throw new Error('test') })
|
||||
store.dispatch(StreamActions.addStream({ userId, stream }))
|
||||
expect(store.getState().streams).toEqual({
|
||||
[userId]: {
|
||||
mediaStream: stream,
|
||||
url: null
|
||||
}
|
||||
userId,
|
||||
stream: stream,
|
||||
url: undefined,
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
63
src/client/reducers/streams.ts
Normal file
@ -0,0 +1,63 @@
|
||||
import _debug from 'debug'
|
||||
import omit from 'lodash/omit'
|
||||
import { AddStreamAction, AddStreamPayload, RemoveStreamAction, StreamAction } from '../actions/StreamActions'
|
||||
import { STREAM_ADD, STREAM_REMOVE } from '../constants'
|
||||
import { createObjectURL, revokeObjectURL } from '../window'
|
||||
|
||||
const debug = _debug('peercalls')
|
||||
const defaultState = Object.freeze({})
|
||||
|
||||
function safeCreateObjectURL (stream: MediaStream) {
|
||||
try {
|
||||
return createObjectURL(stream)
|
||||
} catch (err) {
|
||||
debug('Error using createObjectURL: %s', err)
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
export interface StreamsState {
|
||||
[userId: string]: AddStreamPayload
|
||||
}
|
||||
|
||||
function addStream (
|
||||
state: StreamsState, action: AddStreamAction,
|
||||
): StreamsState {
|
||||
const { userId, stream } = action.payload
|
||||
|
||||
const userStream: AddStreamPayload = {
|
||||
userId,
|
||||
stream,
|
||||
url: safeCreateObjectURL(stream),
|
||||
}
|
||||
|
||||
return {
|
||||
...state,
|
||||
[userId]: userStream,
|
||||
}
|
||||
}
|
||||
|
||||
function removeStream (
|
||||
state: StreamsState, action: RemoveStreamAction,
|
||||
): StreamsState {
|
||||
const { userId } = action.payload
|
||||
const stream = state[userId]
|
||||
if (stream && stream.url) {
|
||||
revokeObjectURL(stream.url)
|
||||
}
|
||||
return omit(state, [userId])
|
||||
}
|
||||
|
||||
export default function streams(
|
||||
state = defaultState,
|
||||
action: StreamAction,
|
||||
): StreamsState {
|
||||
switch (action.type) {
|
||||
case STREAM_ADD:
|
||||
return addStream(state, action)
|
||||
case STREAM_REMOVE:
|
||||
return removeStream(state, action)
|
||||
default:
|
||||
return state
|
||||
}
|
||||
}
|
||||
@ -1,3 +0,0 @@
|
||||
import SocketIOClient from 'socket.io-client'
|
||||
import { baseUrl } from './window.js'
|
||||
export default new SocketIOClient('', { path: baseUrl + '/ws' })
|
||||
3
src/client/socket.ts
Normal file
@ -0,0 +1,3 @@
|
||||
import SocketIOClient from 'socket.io-client'
|
||||
import { baseUrl } from './window'
|
||||
export default SocketIOClient('', { path: baseUrl + '/ws' })
|
||||
@ -1,13 +0,0 @@
|
||||
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()
|
||||
24
src/client/store.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import { Action, applyMiddleware, createStore as _createStore, Store as ReduxStore } from 'redux'
|
||||
import { ThunkAction, ThunkDispatch } from 'redux-thunk'
|
||||
import { create } from './middlewares'
|
||||
import reducers from './reducers'
|
||||
|
||||
export const middlewares = create(
|
||||
window.localStorage && window.localStorage.log,
|
||||
)
|
||||
|
||||
export const createStore = () => _createStore(
|
||||
reducers,
|
||||
applyMiddleware(...middlewares),
|
||||
)
|
||||
|
||||
export default createStore()
|
||||
|
||||
export type Store = ReturnType<typeof createStore>
|
||||
|
||||
type TGetState<T> = T extends ReduxStore<infer State> ? State : never
|
||||
export type State = TGetState<Store>
|
||||
export type GetState = () => State
|
||||
|
||||
export type Dispatch = ThunkDispatch<State, undefined, Action>
|
||||
export type ThunkResult<R> = ThunkAction<R, State, undefined, Action>
|
||||
@ -1,13 +1,11 @@
|
||||
import Promise from 'bluebird'
|
||||
|
||||
import {
|
||||
createObjectURL,
|
||||
revokeObjectURL,
|
||||
getUserMedia,
|
||||
navigator,
|
||||
play,
|
||||
valueOf
|
||||
} from './window.js'
|
||||
valueOf,
|
||||
} from './window'
|
||||
|
||||
describe('window', () => {
|
||||
|
||||
@ -18,47 +16,50 @@ describe('window', () => {
|
||||
const constraints = { video: true }
|
||||
|
||||
afterEach(() => {
|
||||
delete navigator.mediaDevices
|
||||
delete (navigator as any).mediaDevices
|
||||
delete navigator.getUserMedia
|
||||
delete navigator.webkitGetUserMedia
|
||||
delete (navigator as any).webkitGetUserMedia
|
||||
})
|
||||
|
||||
it('calls navigator.mediaDevices.getUserMedia', () => {
|
||||
const promise = Promise.resolve(stream)
|
||||
navigator.mediaDevices = {
|
||||
getUserMedia: jest.fn().mockReturnValue(promise)
|
||||
it('calls navigator.mediaDevices.getUserMedia', async () => {
|
||||
const promise = Promise.resolve(stream);
|
||||
(navigator as any).mediaDevices = {
|
||||
getUserMedia: jest.fn().mockReturnValue(promise),
|
||||
}
|
||||
expect(getUserMedia(constraints)).toBe(promise)
|
||||
expect(await getUserMedia(constraints)).toBe(stream)
|
||||
})
|
||||
|
||||
;['getUserMedia', 'webkitGetUserMedia'].forEach((method) => {
|
||||
it(`it calls navigator.${method} as a fallback`, () => {
|
||||
navigator[method] = jest.fn()
|
||||
(navigator as any)[method] = jest.fn()
|
||||
.mockImplementation(
|
||||
(constraints, onSuccess, onError) => onSuccess(stream)
|
||||
(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()
|
||||
})
|
||||
it('throws error when no supported method', async () => {
|
||||
let error: Error
|
||||
try {
|
||||
await getUserMedia(constraints)
|
||||
} catch (err) {
|
||||
error = err
|
||||
}
|
||||
expect(error!).toBeTruthy()
|
||||
expect(error!.message).toBe('Browser unsupported')
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
describe('play', () => {
|
||||
|
||||
let v1, v2
|
||||
let v1: HTMLVideoElement & { play: jest.Mock }
|
||||
let v2: HTMLVideoElement & { play: jest.Mock }
|
||||
beforeEach(() => {
|
||||
v1 = window.document.createElement('video')
|
||||
v2 = window.document.createElement('video')
|
||||
v1 = window.document.createElement('video') as any
|
||||
v2 = window.document.createElement('video') as any
|
||||
window.document.body.appendChild(v1)
|
||||
window.document.body.appendChild(v2)
|
||||
v1.play = jest.fn()
|
||||
@ -96,7 +97,7 @@ describe('window', () => {
|
||||
|
||||
it('calls window.URL.createObjectURL', () => {
|
||||
window.URL.createObjectURL = jest.fn().mockReturnValue('test')
|
||||
expect(createObjectURL()).toBe('test')
|
||||
expect(createObjectURL('bla')).toBe('test')
|
||||
})
|
||||
|
||||
})
|
||||
@ -105,14 +106,14 @@ describe('window', () => {
|
||||
|
||||
it('calls window.URL.revokeObjectURL', () => {
|
||||
window.URL.revokeObjectURL = jest.fn()
|
||||
expect(revokeObjectURL()).toBe(undefined)
|
||||
expect(revokeObjectURL('bla')).toBe(undefined)
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
describe('valueOf', () => {
|
||||
|
||||
let input
|
||||
let input: HTMLInputElement
|
||||
beforeEach(() => {
|
||||
input = window.document.createElement('input')
|
||||
input.setAttribute('id', 'my-main-id')
|
||||
@ -1,27 +1,30 @@
|
||||
import Promise from 'bluebird'
|
||||
import _debug from 'debug'
|
||||
|
||||
const debug = _debug('peercalls')
|
||||
|
||||
export function getUserMedia (constraints) {
|
||||
export async function getUserMedia (constraints: MediaStreamConstraints) {
|
||||
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
|
||||
return navigator.mediaDevices.getUserMedia(constraints)
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const getMedia = navigator.getUserMedia || navigator.webkitGetUserMedia
|
||||
return new Promise<MediaStream>((resolve, reject) => {
|
||||
const getMedia = navigator.getUserMedia ||
|
||||
(navigator as unknown as {
|
||||
webkitGetUserMedia: typeof navigator.getUserMedia
|
||||
}).webkitGetUserMedia
|
||||
if (!getMedia) reject(new Error('Browser unsupported'))
|
||||
getMedia.call(navigator, constraints, resolve, reject)
|
||||
})
|
||||
}
|
||||
|
||||
export const createObjectURL = object => window.URL.createObjectURL(object)
|
||||
export const revokeObjectURL = url => window.URL.revokeObjectURL(url)
|
||||
export const createObjectURL = (object: unknown) =>
|
||||
window.URL.createObjectURL(object)
|
||||
export const revokeObjectURL = (url: string) => window.URL.revokeObjectURL(url)
|
||||
|
||||
export const navigator = window.navigator
|
||||
|
||||
export function play () {
|
||||
let videos = window.document.querySelectorAll('video')
|
||||
const videos = window.document.querySelectorAll('video')
|
||||
Array.prototype.forEach.call(videos, (video, index) => {
|
||||
debug('playing video: %s', index)
|
||||
try {
|
||||
@ -32,13 +35,13 @@ export function play () {
|
||||
})
|
||||
}
|
||||
|
||||
export const valueOf = id => {
|
||||
const el = window.document.getElementById(id)
|
||||
export const valueOf = (id: string) => {
|
||||
const el = window.document.getElementById(id) as HTMLInputElement
|
||||
return el && el.value
|
||||
}
|
||||
|
||||
export const baseUrl = valueOf('baseUrl')
|
||||
export const callId = valueOf('callId')
|
||||
export const iceServers = JSON.parse(valueOf('iceServers'))
|
||||
export const iceServers = JSON.parse(valueOf('iceServers')!)
|
||||
|
||||
export const MediaStream = window.MediaStream
|
||||
@ -1,11 +1,12 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict'
|
||||
if (!process.env.DEBUG) {
|
||||
process.env.DEBUG = 'peercalls'
|
||||
}
|
||||
|
||||
const app = require('./server/app.js')
|
||||
const debug = require('debug')('peercalls')
|
||||
import app from './server/app'
|
||||
import _debug from 'debug'
|
||||
|
||||
const debug = _debug('peercalls')
|
||||
|
||||
const port = process.env.PORT || 3000
|
||||
const server = app.listen(port, () => debug('Listening on: %s', port))
|
||||
@ -1,24 +0,0 @@
|
||||
<?xml version="1.0" standalone="no"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<metadata>Generated by IcoMoon</metadata>
|
||||
<defs>
|
||||
<font id="icons" horiz-adv-x="1024">
|
||||
<font-face units-per-em="1024" ascent="870.4" descent="-153.6" />
|
||||
<missing-glyph horiz-adv-x="1024" />
|
||||
<glyph unicode=" " horiz-adv-x="0" d="" />
|
||||
<glyph unicode="" glyph-name="mic" d="M738 383.333h72c0-146-116-266-256-286v-140h-84v140c-140 20-256 140-256 286h72c0-128 108-216 226-216s226 88 226 216zM512 255.333c-70 0-128 58-128 128v256c0 70 58 128 128 128s128-58 128-128v-256c0-70-58-128-128-128z" />
|
||||
<glyph unicode="" glyph-name="mic_off" d="M182 725.333l714-714-54-54-178 178c-32-20-72-32-110-38v-140h-84v140c-140 20-256 140-256 286h72c0-128 108-216 226-216 34 0 68 8 98 22l-70 70c-8-2-18-4-28-4-70 0-128 58-128 128v32l-256 256zM640 377.333l-256 254v8c0 70 58 128 128 128s128-58 128-128v-262zM810 383.333c0-50-14-98-38-140l-52 54c12 26 18 54 18 86h72z" />
|
||||
<glyph unicode="" glyph-name="videocam" d="M726 405.333l170 170v-468l-170 170v-150c0-24-20-42-44-42h-512c-24 0-42 18-42 42v428c0 24 18 42 42 42h512c24 0 44-18 44-42v-150z" />
|
||||
<glyph unicode="" glyph-name="videocam_off" d="M140 767.333l756-756-54-54-136 136c-6-4-16-8-24-8h-512c-24 0-42 18-42 42v428c0 24 18 42 42 42h32l-116 116zM896 575.333v-456l-478 478h264c24 0 44-18 44-42v-150z" />
|
||||
<glyph unicode="" glyph-name="call_end" d="M512 469.333c-68 0-134-10-196-30v-132c0-16-10-34-24-40-42-20-80-46-114-78-8-8-18-12-30-12s-22 4-30 12l-106 106c-8 8-12 18-12 30s4 22 12 30c130 124 306 200 500 200s370-76 500-200c8-8 12-18 12-30s-4-22-12-30l-106-106c-8-8-18-12-30-12s-22 4-30 12c-34 32-72 58-114 78-14 6-24 20-24 38v132c-62 20-128 32-196 32z" />
|
||||
<glyph unicode="" glyph-name="arrow_forward" d="M512 683.333l342-342-342-342-60 60 238 240h-520v84h520l-238 240z" />
|
||||
<glyph unicode="" glyph-name="fullscreen" d="M598 639.333h212v-212h-84v128h-128v84zM726 127.333v128h84v-212h-212v84h128zM214 427.333v212h212v-84h-128v-128h-84zM298 255.333v-128h128v-84h-212v212h84z" />
|
||||
<glyph unicode="" glyph-name="fullscreen_exit" d="M682 511.333h128v-84h-212v212h84v-128zM598 43.333v212h212v-84h-128v-128h-84zM342 511.333v128h84v-212h-212v84h128zM214 171.333v84h212v-212h-84v128h-128z" />
|
||||
<glyph unicode="" glyph-name="more_vert" d="M512 171.333c46 0 86-40 86-86s-40-86-86-86-86 40-86 86 40 86 86 86zM512 427.333c46 0 86-40 86-86s-40-86-86-86-86 40-86 86 40 86 86 86zM512 511.333c-46 0-86 40-86 86s40 86 86 86 86-40 86-86-40-86-86-86z" />
|
||||
<glyph unicode="" glyph-name="sentiment_satisfied" d="M512 171.333c64 0 118 34 148 84h70c-34-88-118-148-218-148s-184 60-218 148h70c30-50 84-84 148-84zM512-0.667c188 0 342 154 342 342s-154 342-342 342-342-154-342-342 154-342 342-342zM512 767.333c236 0 426-190 426-426s-190-426-426-426-426 190-426 426 190 426 426 426zM298 447.333c0 36 28 64 64 64s64-28 64-64-28-64-64-64-64 28-64 64zM598 447.333c0 36 28 64 64 64s64-28 64-64-28-64-64-64-64 28-64 64z" />
|
||||
<glyph unicode="" glyph-name="face" d="M512-0.667c188 0 342 154 342 342 0 34-6 66-14 96-30-8-62-10-96-10-144 0-270 70-348 180-42-102-124-186-224-230-2-12-2-24-2-36 0-188 154-342 342-342zM512 767.333c236 0 426-190 426-426s-190-426-426-426-426 190-426 426 190 426 426 426zM640 351.333c30 0 54-22 54-52s-24-54-54-54-54 24-54 54 24 52 54 52zM384 351.333c30 0 54-22 54-52s-24-54-54-54-54 24-54 54 24 52 54 52z" />
|
||||
<glyph unicode="" glyph-name="question_answer" d="M726 341.333c0-24-20-42-44-42h-426l-170-172v598c0 24 18 42 42 42h554c24 0 44-18 44-42v-384zM896 597.333c24 0 42-18 42-42v-640l-170 170h-470c-24 0-42 18-42 42v86h554v384h86z" />
|
||||
<glyph unicode="" glyph-name="room" d="M512 363.333c58 0 106 48 106 106s-48 106-106 106-106-48-106-106 48-106 106-106zM512 767.333c166 0 298-132 298-298 0-224-298-554-298-554s-298 330-298 554c0 166 132 298 298 298z" />
|
||||
<glyph unicode="" glyph-name="schedule" d="M534 555.333v-224l192-114-32-54-224 136v256h64zM512-0.667c188 0 342 154 342 342s-154 342-342 342-342-154-342-342 154-342 342-342zM512 767.333c236 0 426-190 426-426s-190-426-426-426-426 190-426 426 190 426 426 426z" />
|
||||
</font></defs></svg>
|
||||
|
Before Width: | Height: | Size: 4.1 KiB |