diff --git a/NOTICE b/NOTICE new file mode 100644 index 00000000..b7393e6f --- /dev/null +++ b/NOTICE @@ -0,0 +1,13 @@ +(C) Copyright 2016 Kurento (http://kurento.org) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 00000000..454a58f1 --- /dev/null +++ b/README.md @@ -0,0 +1,257 @@ +[![][KurentoImage]][Kurento] + +Copyright © 2013-2016 [Kurento]. Licensed under [LGPL v2.1 License]. + +kurento-room +============ + +Kurento Room is composed by several modules to offer group communications by +means of WebRTC. These modules are: + + * `kurento-room-sdk` - module that provides a management interface for + developers of multimedia conferences (rooms) applications in Java + * `kurento-room-server` - Kurento’s own implementation of a room API, it + provides the WebSockets API for the communications between room clients and + the server. + * `kurento-room-client` - Java library that uses WebSockets and JSON-RPC to + interact with the server-side of the Room API. Can be used to implement the + client-side of a room application. + * `kurento-room-client-js` - Javascript library that acts as wrapper for several + JS APIs (WebRTC, WebSockets, Kurento Utils). Can be used to implement the + client-side of a room application. + * `kurento-room-demo` - demonstration project, contains the client-side + implementation (HTML, Javascript, graphic resources) and embeds the room + server to provide the functionality required for group communications + * `kurento-room-test` - integration and functionality tests for the basic room + server application + * `kurento-room-demo-test` - integration and functionality tests for the demo + application. + +There is extensive documentation on each of these components together with a +tutorial based on the Room demo. This documentation can be easily generated in +HTML format from the [kurento-room-doc](./kurento-room-doc/README.md) project. + +Dependencies +------------ + +These are some of the design and architecture requirements that an application +has to fulfill in order to integrate the Room API: + + * include the SDK module to its dependencies list + * create one of the two `RoomManager` types as a singleton instance by + providing implementations for the following interfaces: + * `RoomEventHandler` + * `KurentoClientProvider` + * develop the client-side of the application for devices that support WebRTC + (*hint:* or use our *client-js* library and take a look at the demo's client + implementation) + * design a room signaling protocol that will be used between the clients and + the server (*hint:* or use the WebSockets API from `kurento-room-server`) + * implement a handler for clients' requests on the server-side, that will + use the `RoomManager` to process these requests (*hint:* JSON-RPC handler + from `kurento-room-server`) + * choose a response and notification mechanism for the communication with the + clients (*hint:* JSON-RPC notification service from `kurento-room-server`) + +About the technology stacks that can or should be used to implement a Rooms +application: + + * WebSockets for the communications between the server and the clients + * Spring and Spring Boot for the easy configuration and integration with some + of Kurento's modules. It also provides a WebSockets library. + +And of course, the main requirement is at least one installation of the Kurento +Media Server, accessible to the room application. + +Running the demo +---------------- + +For a quick initial contact with the framework, we recommend running the demo +application and observing the exchange of Websocket messages between the clients +and the server. + +Currently, the demo is only supported for Ubuntu 14.04 LTS 64bits. + +After cloning the tutorial, it can be executed directly from the terminal by +using Maven's `exec` plugin. To make sure the demo's +build and execution works smoothly, a stable release (or tag) is checked out +before proceeding with the build (prevents missing dependencies, given that in +Kurento *master* is the development branch): + +``` +$ git clone git@github.com:Kurento/kurento-room.git +$ cd kurento-room +$ git checkout 6.1.0 +$ cd kurento-room-demo +$ mvn compile exec:java +``` + +Now open the following URL in a WebRTC-compatible browser and connect to a new +room by providing the desired user and room names: + +``` +http://localhost:8080 +``` + +Configuring the demo +-------------------- + +There are a couple of interesting options or properties that might have to be +modified for the demo to function properly. + +The properties file, **kroomdemo.conf.json**, used in the demo's execution as +described above, is located in the folder `src/main/resources` and its +contents are the following: + + { + "kms": { + "uris": ["ws://localhost:8888/kurento","ws://127.0.0.1:8888/kurento"] + }, + "app": { + "uri": "http://localhost:8080/" + }, + "kurento": { + "client": { + //milliseconds + "requestTimeout": 20000 + } + }, + "demo": { + //mario-wings.png or wizard.png + "hatUrl": "mario-wings.png" + "hatCoords": { + // mario-wings hat + "offsetXPercent": -0.35F, + "offsetYPercent": -1.2F, + "widthPercent": 1.6F, + "heightPercent": 1.6F + + //wizard hat + //"offsetXPercent": -0.2F, + //"offsetYPercent": -1.35F, + //"widthPercent": 1.5F, + //"heightPercent": 1.5F + }, + "loopback" : { + "remote": false, + //matters only when remote is true + "andLocal": false + }, + "authRegex": ".*", + "kmsLimit": 10 + } + } + +These properties can be overwritten on the command-line when starting +the demo server: + +``` +$ mvn compile exec:java -Dkms.uris=[\"ws://192.168.1.99:9001/kurento\"] +``` + +In this example, we've instructed the demo to use a different URI of a running +KMS instance when creating the `KurentoClient` required by the Room API. + +More details on the demo's configuration and execution can be found in the demo's +[README page](./kurento-room-demo/README.md) or in the Room API +[documentation](./kurento-room-doc/README.md) . + +What is Kurento +--------------- + +Kurento is an open source software project providing a platform suitable +for creating modular applications with advanced real-time communication +capabilities. For knowing more about Kurento, please visit the Kurento +project website: http://www.kurento.org. + +Kurento is part of [FIWARE]. For further information on the relationship of +FIWARE and Kurento check the [Kurento FIWARE Catalog Entry] + +Kurento is part of the [NUBOMEDIA] research initiative. + +Documentation +------------- + +The Kurento project provides detailed [documentation] including tutorials, +installation and development guides. A simplified version of the documentation +can be found on [readthedocs.org]. The [Open API specification] a.k.a. Kurento +Protocol is also available on [apiary.io]. + +Source +------ + +Code for other Kurento projects can be found in the [GitHub Kurento Group]. + +News and Website +---------------- + +Check the [Kurento blog] +Follow us on Twitter @[kurentoms]. + +Issue tracker +------------- + +Issues and bug reports should be posted to the [GitHub Kurento bugtracker] + +Licensing and distribution +-------------------------- + +Software associated to Kurento is provided as open source under GNU Library or +"Lesser" General Public License, version 2.1 (LGPL-2.1). Please check the +specific terms and conditions linked to this open source license at +http://opensource.org/licenses/LGPL-2.1. Please note that software derived as a +result of modifying the source code of Kurento software in order to fix a bug +or incorporate enhancements is considered a derivative work of the product. +Software that merely uses or aggregates (i.e. links to) an otherwise unmodified +version of existing software is not considered a derivative work. + +Contribution policy +------------------- + +You can contribute to the Kurento community through bug-reports, bug-fixes, new +code or new documentation. For contributing to the Kurento community, drop a +post to the [Kurento Public Mailing List] providing full information about your +contribution and its value. In your contributions, you must comply with the +following guidelines + +* You must specify the specific contents of your contribution either through a + detailed bug description, through a pull-request or through a patch. +* You must specify the licensing restrictions of the code you contribute. +* For newly created code to be incorporated in the Kurento code-base, you must + accept Kurento to own the code copyright, so that its open source nature is + guaranteed. +* You must justify appropriately the need and value of your contribution. The + Kurento project has no obligations in relation to accepting contributions + from third parties. +* The Kurento project leaders have the right of asking for further + explanations, tests or validations of any code contributed to the community + before it being incorporated into the Kurento code-base. You must be ready to + addressing all these kind of concerns before having your code approved. + +Support +------- + +The Kurento project provides community support through the [Kurento Public +Mailing List] and through [StackOverflow] using the tags *kurento* and +*fiware-kurento*. + +Before asking for support, please read first the [Kurento Netiquette Guidelines] + +[documentation]: http://www.kurento.org/documentation +[FIWARE]: http://www.fiware.org +[GitHub Kurento bugtracker]: https://github.com/Kurento/bugtracker/issues +[GitHub Kurento Group]: https://github.com/kurento +[kurentoms]: http://twitter.com/kurentoms +[Kurento]: http://kurento.org +[Kurento Blog]: http://www.kurento.org/blog +[Kurento FIWARE Catalog Entry]: http://catalogue.fiware.org/enablers/stream-oriented-kurento +[Kurento Netiquette Guidelines]: http://www.kurento.org/blog/kurento-netiquette-guidelines +[Kurento Public Mailing list]: https://groups.google.com/forum/#!forum/kurento +[KurentoImage]: https://secure.gravatar.com/avatar/21a2a12c56b2a91c8918d5779f1778bf?s=120 +[LGPL v2.1 License]: http://www.gnu.org/licenses/lgpl-2.1.html +[NUBOMEDIA]: http://www.nubomedia.eu +[StackOverflow]: http://stackoverflow.com/search?q=kurento +[Read-the-docs]: http://read-the-docs.readthedocs.org/ +[readthedocs.org]: http://kurento.readthedocs.org/ +[Open API specification]: http://kurento.github.io/doc-kurento/ +[apiary.io]: http://docs.streamoriented.apiary.io/ diff --git a/openvidu-client-js/.bowerrc b/openvidu-client-js/.bowerrc new file mode 100644 index 00000000..9e00ce04 --- /dev/null +++ b/openvidu-client-js/.bowerrc @@ -0,0 +1,3 @@ +{ + "directory" : "static/bower_components" +} diff --git a/openvidu-client-js/.classpath b/openvidu-client-js/.classpath new file mode 100644 index 00000000..6d7587a8 --- /dev/null +++ b/openvidu-client-js/.classpath @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/openvidu-client-js/.gitignore b/openvidu-client-js/.gitignore new file mode 100644 index 00000000..b83d2226 --- /dev/null +++ b/openvidu-client-js/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/openvidu-client-js/.project b/openvidu-client-js/.project new file mode 100644 index 00000000..0eaf3933 --- /dev/null +++ b/openvidu-client-js/.project @@ -0,0 +1,23 @@ + + + kurento-room-client-js + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/openvidu-client-js/.settings/org.eclipse.core.resources.prefs b/openvidu-client-js/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 00000000..db326978 --- /dev/null +++ b/openvidu-client-js/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,3 @@ +eclipse.preferences.version=1 +encoding//src/main/resources=UTF-8 +encoding/=UTF-8 diff --git a/openvidu-client-js/.settings/org.eclipse.jdt.core.prefs b/openvidu-client-js/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000..714351ae --- /dev/null +++ b/openvidu-client-js/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,5 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/openvidu-client-js/.settings/org.eclipse.m2e.core.prefs b/openvidu-client-js/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 00000000..f897a7f1 --- /dev/null +++ b/openvidu-client-js/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/openvidu-client-js/README.md b/openvidu-client-js/README.md new file mode 100644 index 00000000..86c12333 --- /dev/null +++ b/openvidu-client-js/README.md @@ -0,0 +1,118 @@ +[![License badge](https://img.shields.io/badge/license-Apache2-orange.svg)](http://www.apache.org/licenses/LICENSE-2.0) +[![Documentation badge](https://readthedocs.org/projects/fiware-orion/badge/?version=latest)](http://doc-kurento-room.readthedocs.org/en/latest/) +[![Docker badge](https://img.shields.io/docker/pulls/fiware/orion.svg)](https://hub.docker.com/r/fiware/stream-oriented-kurento/) +[![Support badge]( https://img.shields.io/badge/support-sof-yellowgreen.svg)](http://stackoverflow.com/questions/tagged/kurento) + +[![][KurentoImage]][Kurento] + +Copyright © 2013-2016 [Kurento]. Licensed under [Apache 2.0 License]. + +kurento-room-client-js +====================== + +Kurento Room Client JS is a Javascript library that can be used to implement +the client-side of group communications applications based on WebRTC. +It uses WebSockets and JSON-RPC to interact with the server-side of the Room API. + +What is Kurento +--------------- + +Kurento is an open source software project providing a platform suitable +for creating modular applications with advanced real-time communication +capabilities. For knowing more about Kurento, please visit the Kurento +project website: http://www.kurento.org. + +Kurento is part of [FIWARE]. For further information on the relationship of +FIWARE and Kurento check the [Kurento FIWARE Catalog Entry] + +Kurento is part of the [NUBOMEDIA] research initiative. + +Documentation +------------- + +The Kurento project provides detailed [documentation] including tutorials, +installation and development guides. A simplified version of the documentation +can be found on [readthedocs.org]. The [Open API specification] a.k.a. Kurento +Protocol is also available on [apiary.io]. + +Source +------ + +Code for other Kurento projects can be found in the [GitHub Kurento Group]. + +News and Website +---------------- + +Check the [Kurento blog] +Follow us on Twitter @[kurentoms]. + +Issue tracker +------------- + +Issues and bug reports should be posted to the [GitHub Kurento bugtracker] + +Licensing and distribution +-------------------------- + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contribution policy +------------------- + +You can contribute to the Kurento community through bug-reports, bug-fixes, new +code or new documentation. For contributing to the Kurento community, drop a +post to the [Kurento Public Mailing List] providing full information about your +contribution and its value. In your contributions, you must comply with the +following guidelines + +* You must specify the specific contents of your contribution either through a + detailed bug description, through a pull-request or through a patch. +* You must specify the licensing restrictions of the code you contribute. +* For newly created code to be incorporated in the Kurento code-base, you must + accept Kurento to own the code copyright, so that its open source nature is + guaranteed. +* You must justify appropriately the need and value of your contribution. The + Kurento project has no obligations in relation to accepting contributions + from third parties. +* The Kurento project leaders have the right of asking for further + explanations, tests or validations of any code contributed to the community + before it being incorporated into the Kurento code-base. You must be ready to + addressing all these kind of concerns before having your code approved. + +Support +------- + +The Kurento project provides community support through the [Kurento Public +Mailing List] and through [StackOverflow] using the tags *kurento* and +*fiware-kurento*. + +Before asking for support, please read first the [Kurento Netiquette Guidelines] + +[documentation]: http://www.kurento.org/documentation +[FIWARE]: http://www.fiware.org +[GitHub Kurento bugtracker]: https://github.com/Kurento/bugtracker/issues +[GitHub Kurento Group]: https://github.com/kurento +[kurentoms]: http://twitter.com/kurentoms +[Kurento]: http://kurento.org +[Kurento Blog]: http://www.kurento.org/blog +[Kurento FIWARE Catalog Entry]: http://catalogue.fiware.org/enablers/stream-oriented-kurento +[Kurento Netiquette Guidelines]: http://www.kurento.org/blog/kurento-netiquette-guidelines +[Kurento Public Mailing list]: https://groups.google.com/forum/#!forum/kurento +[KurentoImage]: https://secure.gravatar.com/avatar/21a2a12c56b2a91c8918d5779f1778bf?s=120 +[Apache 2.0 License]: http://www.apache.org/licenses/LICENSE-2.0 +[NUBOMEDIA]: http://www.nubomedia.eu +[StackOverflow]: http://stackoverflow.com/search?q=kurento +[Read-the-docs]: http://read-the-docs.readthedocs.org/ +[readthedocs.org]: http://kurento.readthedocs.org/ +[Open API specification]: http://kurento.github.io/doc-kurento/ +[apiary.io]: http://docs.streamoriented.apiary.io/ diff --git a/openvidu-client-js/pom.xml b/openvidu-client-js/pom.xml new file mode 100644 index 00000000..6740637a --- /dev/null +++ b/openvidu-client-js/pom.xml @@ -0,0 +1,119 @@ + + 4.0.0 + + + org.openvidu + openvidu + 6.6.1-SNAPSHOT + + + openvidu-client-js + jar + + Kurento Room Client JS + + Kurento Room JS library for the client-side + + http://www.kurento.org/docs/${project.version} + + + + Apache 2.0 + http://www.apache.org/licenses/LICENSE-2.0 + repo + + + + + Kurento + http://www.kurento.org + + + + ${openvidu.scm.url} + scm:git:${openvidu.scm.connection} + scm:git:${openvidu.scm.connection} + develop + + + + + kurento.org + -kurento.org Community + Kurento.org + http://www.kurento.org + + + + + + + org.codehaus.mojo + exec-maven-plugin + + ${start-class} + + + + + + + src/main/resources + false + + + + + + + org.kurento + kurento-utils-js + + + org.kurento + kurento-jsonrpc-js + + + + org.webjars.bower + adapter.js + + + + org.webjars.bower + EventEmitter.js + + + + + + default + + + default + true + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + org.apache.maven.plugins + maven-failsafe-plugin + + true + + + + + + + + diff --git a/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/.bower.json b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/.bower.json new file mode 100644 index 00000000..dfa1b268 --- /dev/null +++ b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/.bower.json @@ -0,0 +1,39 @@ +{ + "name": "webrtc-adapter", + "version": "0.2.3", + "description": "A shim to insulate apps from WebRTC spec changes and prefix differences", + "repository": { + "type": "git", + "url": "https://github.com/webrtc/adapter.git" + }, + "authors": [ + "The WebRTC project authors (http://www.webrtc.org/)" + ], + "main": "adapter.js", + "moduleType": [ + "globals" + ], + "ignore": [ + "test/*" + ], + "keywords": [ + "WebRTC", + "PeerConnection", + "RTCPeerConnection", + "getUserMedia", + "Chrome", + "Chromium", + "Firefox" + ], + "license": "BSD-3-Clause", + "homepage": "https://github.com/webrtc/adapter", + "_release": "0.2.3", + "_resolution": { + "type": "version", + "tag": "v0.2.3", + "commit": "c51190130048443ec853f95d0a89362c4c79931a" + }, + "_source": "git://github.com/webrtc/adapter.git", + "_target": "*", + "_originalSource": "adapter.js" +} \ No newline at end of file diff --git a/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/.gitignore b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/.gitignore new file mode 100644 index 00000000..ef09aa3b --- /dev/null +++ b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/.gitignore @@ -0,0 +1,3 @@ +browsers/ +node_modules/ +*~ diff --git a/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/.jscsrc b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/.jscsrc new file mode 100644 index 00000000..4b5fa835 --- /dev/null +++ b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/.jscsrc @@ -0,0 +1,3 @@ +{ + "preset": "google" +} diff --git a/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/.jshintrc b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/.jshintrc new file mode 100644 index 00000000..6ed7cddc --- /dev/null +++ b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/.jshintrc @@ -0,0 +1,53 @@ +{ + "browser": true, + "camelcase": true, + "curly": true, + "devel": true, + "eqeqeq": true, + "forin": false, + "globalstrict": true, + "quotmark": "single", + "undef": true, + "unused": "strict", + "globals": { + "addExplicitTest": true, + "addTest": true, + "arrayAverage": true, + "arrayMax": true, + "arrayMin": true, + "attachMediaStream": true, + "attachMediaStream": true, + "audioContext": true, + "AudioContext": true, + "Call": true, + "createIceServers": true, + "createIceServer": true, + "createLineChart": true, + "define": true, + "doGetUserMedia": true, + "expectEquals": true, + "getUserMedia": true, + "getUserMedia": true, + "ga": true, + "GumHandler": true, + "MediaStreamTrack": true, + "reattachMediaStream": true, + "report": true, + "reportBug": true, + "reportError": true, + "reportFatal": true, + "reportInfo": true, + "reportSuccess": true, + "RTCIceCandidate": true, + "RTCPeerConnection": true, + "RTCSessionDescription": true, + "setTestProgress": true, + "setTimeoutWithProgressBar": true, + "Ssim": true, + "StatisticsAggregate": true, + "testFinished": true, + "trace": true, + "webrtcDetectedBrowser": true, + "webrtcDetectedVersion": true + } +} diff --git a/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/.travis.yml b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/.travis.yml new file mode 100644 index 00000000..2083d9e7 --- /dev/null +++ b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/.travis.yml @@ -0,0 +1,34 @@ +sudo: false +language: node_js +node_js: +- 0.10 + +env: + matrix: + - BROWSER=chrome BVER=stable + - BROWSER=chrome BVER=beta + - BROWSER=chrome BVER=unstable + - BROWSER=firefox BVER=stable + - BROWSER=firefox BVER=beta + - BROWSER=firefox BVER=unstable + - BROWSER=firefox BVER=esr + +matrix: + fast_finish: true + + allow_failures: + - env: BROWSER=chrome BVER=unstable + - env: BROWSER=firefox BVER=unstable + +before_script: + - ./node_modules/travis-multirunner/setup.sh + - export DISPLAY=:99.0 + - sh -e /etc/init.d/xvfb start + +script: + - node_modules/.bin/grunt + - npm test + +after_failure: + - for file in *.log; do echo $file; echo "======================"; cat $file; done || true + diff --git a/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/CONTRIBUTING.md b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/CONTRIBUTING.md new file mode 100644 index 00000000..c86d36e4 --- /dev/null +++ b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/CONTRIBUTING.md @@ -0,0 +1,15 @@ +WebRTC welcomes patches/pulls for features and bug fixes. + +For contributors external to Google, follow the instructions given in the [Google Individual Contributor License Agreement](https://cla.developers.google.com/about/google-individual). + +In all cases, contributors must sign a contributor license agreement before a contribution can be accepted. Please complete the agreement for an [individual](https://developers.google.com/open-source/cla/individual) or a [corporation](https://developers.google.com/open-source/cla/corporate) as appropriate. + +If you plan to add a significant component or large chunk of code, we recommend you bring this up on the [webrtc-discuss group](https://groups.google.com/forum/#!forum/discuss-webrtc) for a design discussion before writing code. + +If appropriate, write a unit test which demonstrates that your code functions as expected. Tests are the best way to ensure that future contributors do not break your code accidentally. + +To request a change or addition, you must [submit a pull request](https://help.github.com/categories/collaborating/). + +WebRTC developers monitor outstanding pull requests. They may request changes to the pull request before accepting. They will also verify that a CLA has been signed. + +The [Developer's Guide](https://bit.ly/webrtcdevguide) for this repo has more detailed information about code style, structure and validation. diff --git a/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/Gruntfile.js b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/Gruntfile.js new file mode 100644 index 00000000..f0a9a606 --- /dev/null +++ b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/Gruntfile.js @@ -0,0 +1,40 @@ +'use strict'; + +/* For jshint: */ +/* globals module, require */ + +module.exports = function(grunt) { + grunt.initConfig({ + pkg: grunt.file.readJSON('package.json'), + githooks: { + all: { + 'pre-commit': 'jshint jscs' + } + }, + jshint: { + options: { + jshintrc: '.jshintrc' + }, + files: ['adapter.js', 'test/*.js'] + }, + jscs: { + src: ['adapter.js', 'test/*.js'], + options: { + config: '.jscsrc', + 'excludeFiles': [ + ] + } + }, + testling: { + files: 'test/test.js' + } + }); + + grunt.loadNpmTasks('grunt-contrib-jshint'); + grunt.loadNpmTasks('grunt-jscs'); + grunt.loadNpmTasks('grunt-githooks'); + grunt.registerTask('verify-require', 'Verifies the script can be required in a node context', function () { + require('./adapter'); + }); + grunt.registerTask('default', ['jshint', 'jscs', 'verify-require']); +}; diff --git a/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/LICENSE.md b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/LICENSE.md new file mode 100644 index 00000000..c768cfb8 --- /dev/null +++ b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/LICENSE.md @@ -0,0 +1,29 @@ +Copyright (c) 2014, The WebRTC project authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + * Neither the name of Google nor the names of its contributors may + be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/README-w3c-tests.md b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/README-w3c-tests.md new file mode 100644 index 00000000..81e37916 --- /dev/null +++ b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/README-w3c-tests.md @@ -0,0 +1,14 @@ +How to use adapter with W3C tests +--------------------------------- + +If you want to test that the adapter works with the W3C tests, execute +the following (where TESTDIR is the root of the web-platform-tests repo): + +- (cd $TESTDIR; git checkout master; git checkout -b some-unused-branch-name) +- cat adapter.js > $TESTDIR/common/vendor-prefix.js +- Run the tests according to $TESTDIR/README.md + +WebRTC-specific tests are found in "mediacapture-streams" and "webrtc". +With the adapter installed, the tests should run *without* vendor prefixes. + +Note: Not all of the W3C tests are updated to be spec-conformant. diff --git a/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/README.md b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/README.md new file mode 100644 index 00000000..1adbbc1f --- /dev/null +++ b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/README.md @@ -0,0 +1,65 @@ +[![Build Status](https://travis-ci.org/webrtc/adapter.svg)](https://travis-ci.org/webrtc/adapter) + +# WebRTC adapter # +[adapter.js] is a shim to insulate apps from spec changes and prefix differences. In fact, the standards and protocols used for WebRTC implementations are highly stable, and there are only a few prefixed names. For full interop information, see [webrtc.org/web-apis/interop](http://www.webrtc.org/web-apis/interop). + +## Install ## + +#### Bower +```bash +bower install webrtc-adapter +``` + +#### NPM +```bash +npm install webrtc-adapter-test +``` + +## Inclusion on Browser ## + +#### Bower +```html + +``` + +#### NPM +Copy to desired location in your src tree or use a minify/vulcanize tool (node_modules is usually not published with the code). +See [webrtc/samples repo](https://github.com/webrtc/samples/blob/master/package.json) as an example on how you can do this. + +## Development ## +Detailed information on developing in the [webrtc](https://github.com/webrtc) github repo can be found in the [WebRTC GitHub repo developer's guide](https://docs.google.com/document/d/1tn1t6LW2ffzGuYTK3366w1fhTkkzsSvHsBnOHoDfRzY/edit?pli=1#heading=h.e3366rrgmkdk). + +This guide assumes you are running a Debian based Linux distribution (travis-multirunner currently fetches .deb browser packages). + +#### Clone the repo in desired folder +```bash +git clone https://github.com/webrtc/adapter.git +``` + +#### Install npm dependencies +```bash +sudo npm install +``` + +#### Run tests +Runs the tests in test/tests.js using testling. +```bash +npm test +``` + +#### Change browser and channel/version for testing +Chrome stable is currently installed as the default browser for the tests. + +Currently Chrome and Firefox are supported, check [travis-multirunner](https://github.com/DamonOehlman/travis-multirunner/blob/master/) repo for updates around this. +Firefox channels supported are stable, beta and nightly. +Chrome channels supported on Linux are stable, beta and unstable. + +To select a different browser and/or channel version, change environment variables BROWSER and BVER, then you can rerun the tests with the new browser. +```bash +export BROWSER=firefox BVER=nightly +``` + +Alternatively you can also do it without changing environment variables. +```bash +BROWSER=firefox BVER=nightly npm test +``` diff --git a/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/adapter.js b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/adapter.js new file mode 100644 index 00000000..d9d5e708 --- /dev/null +++ b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/adapter.js @@ -0,0 +1,536 @@ +/* + * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. + */ + +/* More information about these options at jshint.com/docs/options */ +/* jshint browser: true, camelcase: true, curly: true, devel: true, + eqeqeq: true, forin: false, globalstrict: true, node: true, + quotmark: single, undef: true, unused: strict */ +/* global mozRTCIceCandidate, mozRTCPeerConnection, Promise, +mozRTCSessionDescription, webkitRTCPeerConnection, MediaStreamTrack */ +/* exported trace,requestUserMedia */ + +'use strict'; + +var getUserMedia = null; +var attachMediaStream = null; +var reattachMediaStream = null; +var webrtcDetectedBrowser = null; +var webrtcDetectedVersion = null; +var webrtcMinimumVersion = null; +var webrtcUtils = { + log: function() { + // suppress console.log output when being included as a module. + if (typeof module !== 'undefined' || + typeof require === 'function' && typeof define === 'function') { + return; + } + console.log.apply(console, arguments); + } +}; + +function trace(text) { + // This function is used for logging. + if (text[text.length - 1] === '\n') { + text = text.substring(0, text.length - 1); + } + if (window.performance) { + var now = (window.performance.now() / 1000).toFixed(3); + webrtcUtils.log(now + ': ' + text); + } else { + webrtcUtils.log(text); + } +} + +if (typeof window === 'object') { + if (window.HTMLMediaElement && + !('srcObject' in window.HTMLMediaElement.prototype)) { + // Shim the srcObject property, once, when HTMLMediaElement is found. + Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', { + get: function() { + // If prefixed srcObject property exists, return it. + // Otherwise use the shimmed property, _srcObject + return 'mozSrcObject' in this ? this.mozSrcObject : this._srcObject; + }, + set: function(stream) { + if ('mozSrcObject' in this) { + this.mozSrcObject = stream; + } else { + // Use _srcObject as a private property for this shim + this._srcObject = stream; + // TODO: revokeObjectUrl(this.src) when !stream to release resources? + this.src = URL.createObjectURL(stream); + } + } + }); + } + // Proxy existing globals + getUserMedia = window.navigator && window.navigator.getUserMedia; +} + +// Attach a media stream to an element. +attachMediaStream = function(element, stream) { + element.srcObject = stream; +}; + +reattachMediaStream = function(to, from) { + to.srcObject = from.srcObject; +}; + +if (typeof window === 'undefined' || !window.navigator) { + webrtcUtils.log('This does not appear to be a browser'); + webrtcDetectedBrowser = 'not a browser'; +} else if (navigator.mozGetUserMedia && window.mozRTCPeerConnection) { + webrtcUtils.log('This appears to be Firefox'); + + webrtcDetectedBrowser = 'firefox'; + + // the detected firefox version. + webrtcDetectedVersion = + parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10); + + // the minimum firefox version still supported by adapter. + webrtcMinimumVersion = 31; + + // The RTCPeerConnection object. + window.RTCPeerConnection = function(pcConfig, pcConstraints) { + if (webrtcDetectedVersion < 38) { + // .urls is not supported in FF < 38. + // create RTCIceServers with a single url. + if (pcConfig && pcConfig.iceServers) { + var newIceServers = []; + for (var i = 0; i < pcConfig.iceServers.length; i++) { + var server = pcConfig.iceServers[i]; + if (server.hasOwnProperty('urls')) { + for (var j = 0; j < server.urls.length; j++) { + var newServer = { + url: server.urls[j] + }; + if (server.urls[j].indexOf('turn') === 0) { + newServer.username = server.username; + newServer.credential = server.credential; + } + newIceServers.push(newServer); + } + } else { + newIceServers.push(pcConfig.iceServers[i]); + } + } + pcConfig.iceServers = newIceServers; + } + } + return new mozRTCPeerConnection(pcConfig, pcConstraints); // jscs:ignore requireCapitalizedConstructors + }; + + // The RTCSessionDescription object. + window.RTCSessionDescription = mozRTCSessionDescription; + + // The RTCIceCandidate object. + window.RTCIceCandidate = mozRTCIceCandidate; + + // getUserMedia constraints shim. + getUserMedia = function(constraints, onSuccess, onError) { + var constraintsToFF37 = function(c) { + if (typeof c !== 'object' || c.require) { + return c; + } + var require = []; + Object.keys(c).forEach(function(key) { + if (key === 'require' || key === 'advanced' || key === 'mediaSource') { + return; + } + var r = c[key] = (typeof c[key] === 'object') ? + c[key] : {ideal: c[key]}; + if (r.min !== undefined || + r.max !== undefined || r.exact !== undefined) { + require.push(key); + } + if (r.exact !== undefined) { + if (typeof r.exact === 'number') { + r.min = r.max = r.exact; + } else { + c[key] = r.exact; + } + delete r.exact; + } + if (r.ideal !== undefined) { + c.advanced = c.advanced || []; + var oc = {}; + if (typeof r.ideal === 'number') { + oc[key] = {min: r.ideal, max: r.ideal}; + } else { + oc[key] = r.ideal; + } + c.advanced.push(oc); + delete r.ideal; + if (!Object.keys(r).length) { + delete c[key]; + } + } + }); + if (require.length) { + c.require = require; + } + return c; + }; + if (webrtcDetectedVersion < 38) { + webrtcUtils.log('spec: ' + JSON.stringify(constraints)); + if (constraints.audio) { + constraints.audio = constraintsToFF37(constraints.audio); + } + if (constraints.video) { + constraints.video = constraintsToFF37(constraints.video); + } + webrtcUtils.log('ff37: ' + JSON.stringify(constraints)); + } + return navigator.mozGetUserMedia(constraints, onSuccess, onError); + }; + + navigator.getUserMedia = getUserMedia; + + // Shim for mediaDevices on older versions. + if (!navigator.mediaDevices) { + navigator.mediaDevices = {getUserMedia: requestUserMedia, + addEventListener: function() { }, + removeEventListener: function() { } + }; + } + navigator.mediaDevices.enumerateDevices = + navigator.mediaDevices.enumerateDevices || function() { + return new Promise(function(resolve) { + var infos = [ + {kind: 'audioinput', deviceId: 'default', label: '', groupId: ''}, + {kind: 'videoinput', deviceId: 'default', label: '', groupId: ''} + ]; + resolve(infos); + }); + }; + + if (webrtcDetectedVersion < 41) { + // Work around http://bugzil.la/1169665 + var orgEnumerateDevices = + navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices); + navigator.mediaDevices.enumerateDevices = function() { + return orgEnumerateDevices().catch(function(e) { + if (e.name === 'NotFoundError') { + return []; + } + throw e; + }); + }; + } +} else if (navigator.webkitGetUserMedia && !!window.chrome) { + webrtcUtils.log('This appears to be Chrome'); + + webrtcDetectedBrowser = 'chrome'; + + // the detected chrome version. + webrtcDetectedVersion = + parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10); + + // the minimum chrome version still supported by adapter. + webrtcMinimumVersion = 38; + + // The RTCPeerConnection object. + window.RTCPeerConnection = function(pcConfig, pcConstraints) { + // Translate iceTransportPolicy to iceTransports, + // see https://code.google.com/p/webrtc/issues/detail?id=4869 + if (pcConfig && pcConfig.iceTransportPolicy) { + pcConfig.iceTransports = pcConfig.iceTransportPolicy; + } + + var pc = new webkitRTCPeerConnection(pcConfig, pcConstraints); // jscs:ignore requireCapitalizedConstructors + var origGetStats = pc.getStats.bind(pc); + pc.getStats = function(selector, successCallback, errorCallback) { // jshint ignore: line + var self = this; + var args = arguments; + + // If selector is a function then we are in the old style stats so just + // pass back the original getStats format to avoid breaking old users. + if (arguments.length > 0 && typeof selector === 'function') { + return origGetStats(selector, successCallback); + } + + var fixChromeStats = function(response) { + var standardReport = {}; + var reports = response.result(); + reports.forEach(function(report) { + var standardStats = { + id: report.id, + timestamp: report.timestamp, + type: report.type + }; + report.names().forEach(function(name) { + standardStats[name] = report.stat(name); + }); + standardReport[standardStats.id] = standardStats; + }); + + return standardReport; + }; + + if (arguments.length >= 2) { + var successCallbackWrapper = function(response) { + args[1](fixChromeStats(response)); + }; + + return origGetStats.apply(this, [successCallbackWrapper, arguments[0]]); + } + + // promise-support + return new Promise(function(resolve, reject) { + if (args.length === 1 && selector === null) { + origGetStats.apply(self, [ + function(response) { + resolve.apply(null, [fixChromeStats(response)]); + }, reject]); + } else { + origGetStats.apply(self, [resolve, reject]); + } + }); + }; + + return pc; + }; + + // add promise support + ['createOffer', 'createAnswer'].forEach(function(method) { + var nativeMethod = webkitRTCPeerConnection.prototype[method]; + webkitRTCPeerConnection.prototype[method] = function() { + var self = this; + if (arguments.length < 1 || (arguments.length === 1 && + typeof(arguments[0]) === 'object')) { + var opts = arguments.length === 1 ? arguments[0] : undefined; + return new Promise(function(resolve, reject) { + nativeMethod.apply(self, [resolve, reject, opts]); + }); + } else { + return nativeMethod.apply(this, arguments); + } + }; + }); + + ['setLocalDescription', 'setRemoteDescription', + 'addIceCandidate'].forEach(function(method) { + var nativeMethod = webkitRTCPeerConnection.prototype[method]; + webkitRTCPeerConnection.prototype[method] = function() { + var args = arguments; + var self = this; + return new Promise(function(resolve, reject) { + nativeMethod.apply(self, [args[0], + function() { + resolve(); + if (args.length >= 2) { + args[1].apply(null, []); + } + }, + function(err) { + reject(err); + if (args.length >= 3) { + args[2].apply(null, [err]); + } + }] + ); + }); + }; + }); + + // getUserMedia constraints shim. + var constraintsToChrome = function(c) { + if (typeof c !== 'object' || c.mandatory || c.optional) { + return c; + } + var cc = {}; + Object.keys(c).forEach(function(key) { + if (key === 'require' || key === 'advanced' || key === 'mediaSource') { + return; + } + var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]}; + if (r.exact !== undefined && typeof r.exact === 'number') { + r.min = r.max = r.exact; + } + var oldname = function(prefix, name) { + if (prefix) { + return prefix + name.charAt(0).toUpperCase() + name.slice(1); + } + return (name === 'deviceId') ? 'sourceId' : name; + }; + if (r.ideal !== undefined) { + cc.optional = cc.optional || []; + var oc = {}; + if (typeof r.ideal === 'number') { + oc[oldname('min', key)] = r.ideal; + cc.optional.push(oc); + oc = {}; + oc[oldname('max', key)] = r.ideal; + cc.optional.push(oc); + } else { + oc[oldname('', key)] = r.ideal; + cc.optional.push(oc); + } + } + if (r.exact !== undefined && typeof r.exact !== 'number') { + cc.mandatory = cc.mandatory || {}; + cc.mandatory[oldname('', key)] = r.exact; + } else { + ['min', 'max'].forEach(function(mix) { + if (r[mix] !== undefined) { + cc.mandatory = cc.mandatory || {}; + cc.mandatory[oldname(mix, key)] = r[mix]; + } + }); + } + }); + if (c.advanced) { + cc.optional = (cc.optional || []).concat(c.advanced); + } + return cc; + }; + + getUserMedia = function(constraints, onSuccess, onError) { + if (constraints.audio) { + constraints.audio = constraintsToChrome(constraints.audio); + } + if (constraints.video) { + constraints.video = constraintsToChrome(constraints.video); + } + webrtcUtils.log('chrome: ' + JSON.stringify(constraints)); + return navigator.webkitGetUserMedia(constraints, onSuccess, onError); + }; + navigator.getUserMedia = getUserMedia; + + if (!navigator.mediaDevices) { + navigator.mediaDevices = {getUserMedia: requestUserMedia, + enumerateDevices: function() { + return new Promise(function(resolve) { + var kinds = {audio: 'audioinput', video: 'videoinput'}; + return MediaStreamTrack.getSources(function(devices) { + resolve(devices.map(function(device) { + return {label: device.label, + kind: kinds[device.kind], + deviceId: device.id, + groupId: ''}; + })); + }); + }); + }}; + } + + // A shim for getUserMedia method on the mediaDevices object. + // TODO(KaptenJansson) remove once implemented in Chrome stable. + if (!navigator.mediaDevices.getUserMedia) { + navigator.mediaDevices.getUserMedia = function(constraints) { + return requestUserMedia(constraints); + }; + } else { + // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia + // function which returns a Promise, it does not accept spec-style + // constraints. + var origGetUserMedia = navigator.mediaDevices.getUserMedia. + bind(navigator.mediaDevices); + navigator.mediaDevices.getUserMedia = function(c) { + webrtcUtils.log('spec: ' + JSON.stringify(c)); // whitespace for alignment + c.audio = constraintsToChrome(c.audio); + c.video = constraintsToChrome(c.video); + webrtcUtils.log('chrome: ' + JSON.stringify(c)); + return origGetUserMedia(c); + }; + } + + // Dummy devicechange event methods. + // TODO(KaptenJansson) remove once implemented in Chrome stable. + if (typeof navigator.mediaDevices.addEventListener === 'undefined') { + navigator.mediaDevices.addEventListener = function() { + webrtcUtils.log('Dummy mediaDevices.addEventListener called.'); + }; + } + if (typeof navigator.mediaDevices.removeEventListener === 'undefined') { + navigator.mediaDevices.removeEventListener = function() { + webrtcUtils.log('Dummy mediaDevices.removeEventListener called.'); + }; + } + + // Attach a media stream to an element. + attachMediaStream = function(element, stream) { + if (webrtcDetectedVersion >= 43) { + element.srcObject = stream; + } else if (typeof element.src !== 'undefined') { + element.src = URL.createObjectURL(stream); + } else { + webrtcUtils.log('Error attaching stream to element.'); + } + }; + reattachMediaStream = function(to, from) { + if (webrtcDetectedVersion >= 43) { + to.srcObject = from.srcObject; + } else { + to.src = from.src; + } + }; + +} else if (navigator.mediaDevices && navigator.userAgent.match( + /Edge\/(\d+).(\d+)$/)) { + webrtcUtils.log('This appears to be Edge'); + webrtcDetectedBrowser = 'edge'; + + webrtcDetectedVersion = + parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10); + + // the minimum version still supported by adapter. + webrtcMinimumVersion = 12; +} else { + webrtcUtils.log('Browser does not appear to be WebRTC-capable'); +} + +// Returns the result of getUserMedia as a Promise. +function requestUserMedia(constraints) { + return new Promise(function(resolve, reject) { + getUserMedia(constraints, resolve, reject); + }); +} + +var webrtcTesting = {}; +Object.defineProperty(webrtcTesting, 'version', { + set: function(version) { + webrtcDetectedVersion = version; + } +}); + +if (typeof module !== 'undefined') { + var RTCPeerConnection; + if (typeof window !== 'undefined') { + RTCPeerConnection = window.RTCPeerConnection; + } + module.exports = { + RTCPeerConnection: RTCPeerConnection, + getUserMedia: getUserMedia, + attachMediaStream: attachMediaStream, + reattachMediaStream: reattachMediaStream, + webrtcDetectedBrowser: webrtcDetectedBrowser, + webrtcDetectedVersion: webrtcDetectedVersion, + webrtcMinimumVersion: webrtcMinimumVersion, + webrtcTesting: webrtcTesting + //requestUserMedia: not exposed on purpose. + //trace: not exposed on purpose. + }; +} else if ((typeof require === 'function') && (typeof define === 'function')) { + // Expose objects and functions when RequireJS is doing the loading. + define([], function() { + return { + RTCPeerConnection: window.RTCPeerConnection, + getUserMedia: getUserMedia, + attachMediaStream: attachMediaStream, + reattachMediaStream: reattachMediaStream, + webrtcDetectedBrowser: webrtcDetectedBrowser, + webrtcDetectedVersion: webrtcDetectedVersion, + webrtcMinimumVersion: webrtcMinimumVersion, + webrtcTesting: webrtcTesting + //requestUserMedia: not exposed on purpose. + //trace: not exposed on purpose. + }; + }); +} diff --git a/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/bower.json b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/bower.json new file mode 100644 index 00000000..06bc2633 --- /dev/null +++ b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/bower.json @@ -0,0 +1,29 @@ +{ + "name": "webrtc-adapter", + "version": "0.2.3", + "description": "A shim to insulate apps from WebRTC spec changes and prefix differences", + "repository": { + "type": "git", + "url": "https://github.com/webrtc/adapter.git" + }, + "authors": [ + "The WebRTC project authors (http://www.webrtc.org/)" + ], + "main": "adapter.js", + "moduleType": [ + "globals" + ], + "ignore": [ + "test/*" + ], + "keywords": [ + "WebRTC", + "PeerConnection", + "RTCPeerConnection", + "getUserMedia", + "Chrome", + "Chromium", + "Firefox" + ], + "license": "BSD-3-Clause" +} diff --git a/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/package.json b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/package.json new file mode 100644 index 00000000..815ac696 --- /dev/null +++ b/openvidu-client-js/src/main/resources/static/bower_components/adapter.js/package.json @@ -0,0 +1,30 @@ +{ + "name": "webrtc-adapter-test", + "version": "0.2.3", + "description": "Hide browser differences in WebRTC APIs (test package name)", + "license": "BSD-3-Clause", + "main": "adapter.js", + "repository": { + "type": "git", + "url": "https://github.com/webrtc/adapter.git" + }, + "scripts": { + "test": "test/run-tests" + }, + "testling": { + "files": "test/test.js" + }, + "devDependencies": { + "browserify": "^10.2.1", + "grunt": "^0.4.5", + "grunt-cli": ">=0.1.9", + "grunt-contrib-jshint": "^0.11.2", + "grunt-contrib-nodeunit": "~0.4.1", + "grunt-contrib-uglify": "^0.9.1", + "grunt-githooks": "^0.3.1", + "grunt-jscs": "^2.0.0", + "tape": "^4.0.0", + "testling": "^1.7.1", + "travis-multirunner": "^2.6.0" + } +} diff --git a/openvidu-client-js/src/main/resources/static/img/spinner.gif b/openvidu-client-js/src/main/resources/static/img/spinner.gif new file mode 100644 index 00000000..c8bffb23 Binary files /dev/null and b/openvidu-client-js/src/main/resources/static/img/spinner.gif differ diff --git a/openvidu-client-js/src/main/resources/static/js/KurentoRoom.js b/openvidu-client-js/src/main/resources/static/js/KurentoRoom.js new file mode 100644 index 00000000..0da89f14 --- /dev/null +++ b/openvidu-client-js/src/main/resources/static/js/KurentoRoom.js @@ -0,0 +1,1090 @@ +/* + * (C) Copyright 2016 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +// Room -------------------------------- + +function jq(myid) { + + return "#" + myid.replace(/(@|:|\.|\[|\]|,)/g, "\\$1"); + +} + +function Room(kurento, options) { + + var that = this; + + that.name = options.room; + + var ee = new EventEmitter(); + var streams = {}; + var participants = {}; + var participantsSpeaking = []; + var connected = false; + var localParticipant; + var subscribeToStreams = options.subscribeToStreams || true; + var updateSpeakerInterval = options.updateSpeakerInterval || 1500; + var thresholdSpeaker = options.thresholdSpeaker || -50; + + setInterval(updateMainSpeaker, updateSpeakerInterval); + + function updateMainSpeaker() { + if (participantsSpeaking.length > 0) { + ee.emitEvent('update-main-speaker', [{ + participantId: participantsSpeaking[participantsSpeaking.length - 1] + }]); + } + } + + this.getLocalParticipant = function () { + return localParticipant; + } + + this.addEventListener = function (eventName, listener) { + ee.addListener(eventName, listener); + } + + this.emitEvent = function (eventName, eventsArray) { + ee.emitEvent(eventName, eventsArray); + } + + this.connect = function () { + var joinParams = { + user: options.user, + room: options.room + }; + if (localParticipant) { + if (Object.keys(localParticipant.getStreams()).some(function (streamId) { + return streams[streamId].isDataChannelEnabled(); + })) { + joinParams.dataChannels = true; + } + } + kurento.sendRequest('joinRoom', joinParams, function (error, response) { + if (error) { + console.warn('Unable to join room', error); + ee.emitEvent('error-room', [{ + error: error + }]); + } else { + + connected = true; + + var exParticipants = response.value; + + var roomEvent = { + participants: [], + streams: [] + } + + var length = exParticipants.length; + for (var i = 0; i < length; i++) { + + var participant = new Participant(kurento, false, that, + exParticipants[i]); + + participants[participant.getID()] = participant; + + roomEvent.participants.push(participant); + + var streams = participant.getStreams(); + for (var key in streams) { + roomEvent.streams.push(streams[key]); + if (subscribeToStreams) { + streams[key].subscribe(); + } + } + } + + ee.emitEvent('room-connected', [roomEvent]); + } + }); + } + + + this.subscribe = function (stream) { + stream.subscribe(); + } + + this.onParticipantPublished = function (options) { + + var participant = new Participant(kurento, false, that, options); + + var pid = participant.getID(); + if (!(pid in participants)) { + console.info("Publisher not found in participants list by its id", pid); + } else { + console.log("Publisher found in participants list by its id", pid); + } + //replacing old participant (this one has streams) + participants[pid] = participant; + + ee.emitEvent('participant-published', [{ + participant: participant + }]); + + var streams = participant.getStreams(); + for (var key in streams) { + var stream = streams[key]; + + if (subscribeToStreams) { + stream.subscribe(); + ee.emitEvent('stream-added', [{ + stream: stream + }]); + } + } + } + + this.onParticipantJoined = function (msg) { + var participant = new Participant(kurento, false, that, msg); + var pid = participant.getID(); + if (!(pid in participants)) { + console.log("New participant to participants list with id", pid); + participants[pid] = participant; + } else { + //use existing so that we don't lose streams info + console.info("Participant already exists in participants list with " + + "the same id, old:", participants[pid], ", joined now:", participant); + participant = participants[pid]; + } + + ee.emitEvent('participant-joined', [{ + participant: participant + }]); + } + + this.onParticipantLeft = function (msg) { + + var participant = participants[msg.name]; + + if (participant !== undefined) { + delete participants[msg.name]; + + ee.emitEvent('participant-left', [{ + participant: participant + }]); + + var streams = participant.getStreams(); + for (var key in streams) { + ee.emitEvent('stream-removed', [{ + stream: streams[key] + }]); + } + + participant.dispose(); + } else { + console.warn("Participant " + msg.name + + " unknown. Participants: " + + JSON.stringify(participants)); + } + }; + + this.onParticipantEvicted = function (msg) { + ee.emitEvent('participant-evicted', [{ + localParticipant: localParticipant + }]); + }; + + this.onNewMessage = function (msg) { + console.log("New message: " + JSON.stringify(msg)); + var room = msg.room; + var user = msg.user; + var message = msg.message; + + if (user !== undefined) { + ee.emitEvent('newMessage', [{ + room: room, + user: user, + message: message + }]); + } else { + console.error("User undefined in new message:", msg); + } + } + + this.recvIceCandidate = function (msg) { + var candidate = { + candidate: msg.candidate, + sdpMid: msg.sdpMid, + sdpMLineIndex: msg.sdpMLineIndex + } + var participant = participants[msg.endpointName]; + if (!participant) { + console.error("Participant not found for endpoint " + + msg.endpointName + ". Ice candidate will be ignored.", + candidate); + return false; + } + var streams = participant.getStreams(); + for (var key in streams) { + var stream = streams[key]; + stream.getWebRtcPeer().addIceCandidate(candidate, function (error) { + if (error) { + console.error("Error adding candidate for " + key + + " stream of endpoint " + msg.endpointName + + ": " + error); + return; + } + }); + } + } + + this.onRoomClosed = function (msg) { + console.log("Room closed: " + JSON.stringify(msg)); + var room = msg.room; + if (room !== undefined) { + ee.emitEvent('room-closed', [{ + room: room + }]); + } else { + console.error("Room undefined in on room closed", msg); + } + } + + this.onLostConnection = function () { + + if (!connected) { + console.warn('Not connected to room, ignoring lost connection notification'); + return false; + } + + console.log('Lost connection in room ' + that.name); + var room = that.name; + if (room !== undefined) { + ee.emitEvent('lost-connection', [{ + room: room + }]); + } else { + console.error('Room undefined when lost connection'); + } + } + + this.onMediaError = function (params) { + console.error("Media error: " + JSON.stringify(params)); + var error = params.error; + if (error) { + ee.emitEvent('error-media', [{ + error: error + }]); + } else { + console.error("Received undefined media error. Params:", params); + } + } + + /* + * forced means the user was evicted, no need to send the 'leaveRoom' request + */ + this.leave = function (forced, jsonRpcClient) { + forced = !!forced; + console.log("Leaving room (forced=" + forced + ")"); + + if (connected && !forced) { + kurento.sendRequest('leaveRoom', function (error, response) { + if (error) { + console.error(error); + } + jsonRpcClient.close(); + }); + } else { + jsonRpcClient.close(); + } + connected = false; + if (participants) { + for (var pid in participants) { + participants[pid].dispose(); + delete participants[pid]; + } + } + } + + this.disconnect = function (stream) { + var participant = stream.getParticipant(); + if (!participant) { + console.error("Stream to disconnect has no participant", stream); + return false; + } + + delete participants[participant.getID()]; + participant.dispose(); + + if (participant === localParticipant) { + console.log("Unpublishing my media (I'm " + participant.getID() + ")"); + delete localParticipant; + kurento.sendRequest('unpublishVideo', function (error, response) { + if (error) { + console.error(error); + } else { + console.info("Media unpublished correctly"); + } + }); + } else { + console.log("Unsubscribing from " + stream.getGlobalID()); + kurento.sendRequest('unsubscribeFromVideo', { + sender: stream.getGlobalID() + }, + function (error, response) { + if (error) { + console.error(error); + } else { + console.info("Unsubscribed correctly from " + stream.getGlobalID()); + } + }); + } + } + + this.getStreams = function () { + return streams; + } + + this.addParticipantSpeaking = function (participantId) { + participantsSpeaking.push(participantId); + } + + this.removeParticipantSpeaking = function (participantId) { + var pos = -1; + for (var i = 0; i < participantsSpeaking.length; i++) { + if (participantsSpeaking[i] == participantId) { + pos = i; + break; + } + } + if (pos != -1) { + participantsSpeaking.splice(pos, 1); + } + } + + localParticipant = new Participant(kurento, true, that, {id: options.user}); + participants[options.user] = localParticipant; +} + +// Participant -------------------------------- + +function Participant(kurento, local, room, options) { + + var that = this; + var id = options.id; + + var streams = {}; + var streamsOpts = []; + + if (options.streams) { + for (var i = 0; i < options.streams.length; i++) { + var streamOpts = { + id: options.streams[i].id, + participant: that, + recvVideo: (options.streams[i].recvVideo == undefined ? true : options.streams[i].recvVideo), + recvAudio: (options.streams[i].recvAudio == undefined ? true : options.streams[i].recvAudio) + } + var stream = new Stream(kurento, false, room, streamOpts); + addStream(stream); + streamsOpts.push(streamOpts); + } + } + console.log("New " + (local ? "local " : "remote ") + "participant " + id + + ", streams opts: ", streamsOpts); + + that.setId = function (newId) { + id = newId; + } + + function addStream(stream) { + streams[stream.getID()] = stream; + room.getStreams()[stream.getID()] = stream; + } + + that.addStream = addStream; + + that.getStreams = function () { + return streams; + } + + that.dispose = function () { + for (var key in streams) { + streams[key].dispose(); + } + } + + that.getID = function () { + return id; + } + + this.sendIceCandidate = function (candidate) { + console.debug((local ? "Local" : "Remote"), "candidate for", + that.getID(), JSON.stringify(candidate)); + kurento.sendRequest("onIceCandidate", { + endpointName: that.getID(), + candidate: candidate.candidate, + sdpMid: candidate.sdpMid, + sdpMLineIndex: candidate.sdpMLineIndex + }, function (error, response) { + if (error) { + console.error("Error sending ICE candidate: " + + JSON.stringify(error)); + } + }); + } +} + +// Stream -------------------------------- + +/* + * options: name: XXX data: true (Maybe this is based on webrtc) audio: true, + * video: true, url: "file:///..." > Player screen: true > Desktop (implicit + * video:true, audio:false) audio: true, video: true > Webcam + * + * stream.hasAudio(); stream.hasVideo(); stream.hasData(); + */ +function Stream(kurento, local, room, options) { + + var that = this; + + that.room = room; + + var ee = new EventEmitter(); + var sdpOffer; + var wrStream; + var wp; + var id; + if (options.id) { + id = options.id; + } else { + id = "webcam"; + } + var video; + + var videoElements = []; + var elements = []; + var participant = options.participant; + + var speechEvent; + + var recvVideo = options.recvVideo; + this.getRecvVideo = function () { + return recvVideo; + } + + var recvAudio = options.recvAudio; + this.getRecvAudio = function () { + return recvAudio; + } + + var showMyRemote = false; + this.subscribeToMyRemote = function () { + showMyRemote = true; + } + this.displayMyRemote = function () { + return showMyRemote; + } + + var localMirrored = false; + this.mirrorLocalStream = function (wr) { + showMyRemote = true; + localMirrored = true; + if (wr) + wrStream = wr; + } + this.isLocalMirrored = function () { + return localMirrored; + } + + var chanId = 0; + + function getChannelName() { + return that.getGlobalID() + '_' + chanId++; + } + + var dataChannel = options.data || false; + this.isDataChannelEnabled = function () { + return dataChannel; + } + + var dataChannelOpened = false; + this.isDataChannelOpened = function () { + return dataChannelOpened; + } + + function onDataChannelOpen(event) { + console.log('Data channel is opened'); + dataChannelOpened = true; + } + + function onDataChannelClosed(event) { + console.log('Data channel is closed'); + dataChannelOpened = false; + } + + this.sendData = function (data) { + if (wp === undefined) { + throw new Error('WebRTC peer has not been created yet'); + } + if (!dataChannelOpened) { + throw new Error('Data channel is not opened'); + } + console.log("Sending through data channel: " + data); + wp.send(data); + } + + this.getWrStream = function () { + return wrStream; + } + + this.getWebRtcPeer = function () { + return wp; + } + + this.addEventListener = function (eventName, listener) { + ee.addListener(eventName, listener); + } + + function showSpinner(spinnerParentId) { + var progress = document.createElement('div'); + progress.id = 'progress-' + that.getGlobalID(); + progress.style.background = "center transparent url('img/spinner.gif') no-repeat"; + document.getElementById(spinnerParentId).appendChild(progress); + } + + function hideSpinner(spinnerId) { + spinnerId = (typeof spinnerId === 'undefined') ? that.getGlobalID() : spinnerId; + $(jq('progress-' + spinnerId)).remove(); + } + + this.playOnlyVideo = function (parentElement, thumbnailId) { + video = document.createElement('video'); + + video.id = 'native-video-' + that.getGlobalID(); + video.autoplay = true; + video.controls = false; + if (wrStream) { + video.src = URL.createObjectURL(wrStream); + $(jq(thumbnailId)).show(); + hideSpinner(); + } else + console.log("No wrStream yet for", that.getGlobalID()); + + videoElements.push({ + thumb: thumbnailId, + video: video + }); + + if (local) { + video.muted = true; + } + + if (typeof parentElement === "string") { + document.getElementById(parentElement).appendChild(video); + } else { + parentElement.appendChild(video); + } + + return video; + } + + this.playThumbnail = function (thumbnailId) { + + var container = document.createElement('div'); + container.className = "participant"; + container.id = that.getGlobalID(); + document.getElementById(thumbnailId).appendChild(container); + + elements.push(container); + + var name = document.createElement('div'); + container.appendChild(name); + var userName = that.getGlobalID().replace('_webcam', ''); + if (userName.length >= 16) { + userName = userName.substring(0, 16) + "..."; + } + name.appendChild(document.createTextNode(userName)); + name.id = "name-" + that.getGlobalID(); + name.className = "name"; + name.title = that.getGlobalID(); + + showSpinner(thumbnailId); + + return that.playOnlyVideo(container, thumbnailId); + } + + this.getID = function () { + return id; + } + + this.getParticipant = function () { + return participant; + } + + this.getGlobalID = function () { + if (participant) { + return participant.getID() + "_" + id; + } else { + return id + "_webcam"; + } + } + + this.init = function () { + participant.addStream(that); + + var constraints = { + audio: true, + video: { + width: { + ideal: 1280 + }, + frameRate: { + ideal: 15 + } + } + }; + + getUserMedia(constraints, function (userStream) { + wrStream = userStream; + ee.emitEvent('access-accepted', null); + }, function (error) { + console.error("Access denied", error); + ee.emitEvent('access-denied', null); + }); + } + + this.publishVideoCallback = function (error, sdpOfferParam, wp) { + if (error) { + return console.error("(publish) SDP offer error: " + + JSON.stringify(error)); + } + console.log("Sending SDP offer to publish as " + + that.getGlobalID(), sdpOfferParam); + kurento.sendRequest("publishVideo", { + sdpOffer: sdpOfferParam, + doLoopback: that.displayMyRemote() || false + }, function (error, response) { + if (error) { + console.error("Error on publishVideo: " + JSON.stringify(error)); + } else { + that.room.emitEvent('stream-published', [{ + stream: that + }]) + that.processSdpAnswer(response.sdpAnswer); + } + }); + } + + this.startVideoCallback = function (error, sdpOfferParam, wp) { + if (error) { + return console.error("(subscribe) SDP offer error: " + + JSON.stringify(error)); + } + console.log("Sending SDP offer to subscribe to " + + that.getGlobalID(), sdpOfferParam); + kurento.sendRequest("receiveVideoFrom", { + sender: that.getGlobalID(), + sdpOffer: sdpOfferParam + }, function (error, response) { + if (error) { + console.error("Error on recvVideoFrom: " + JSON.stringify(error)); + } else { + that.processSdpAnswer(response.sdpAnswer); + } + }); + } + + function initWebRtcPeer(sdpOfferCallback) { + if (local) { + var options = { + videoStream: wrStream, + onicecandidate: participant.sendIceCandidate.bind(participant), + } + if (dataChannel) { + options.dataChannelConfig = { + id: getChannelName(), + onopen: onDataChannelOpen, + onclose: onDataChannelClosed + }; + options.dataChannels = true; + } + if (that.displayMyRemote()) { + wp = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options, function (error) { + if (error) { + return console.error(error); + } + this.generateOffer(sdpOfferCallback.bind(that)); + }); + } else { + wp = new kurentoUtils.WebRtcPeer.WebRtcPeerSendonly(options, function (error) { + if (error) { + return console.error(error); + } + this.generateOffer(sdpOfferCallback.bind(that)); + }); + } + } else { + var offerConstraints = { + mandatory: { + OfferToReceiveVideo: recvVideo, + OfferToReceiveAudio: recvAudio + } + }; + console.log("Constraints of generate SDP offer (subscribing)", + offerConstraints); + var options = { + onicecandidate: participant.sendIceCandidate.bind(participant), + connectionConstraints: offerConstraints + } + wp = new kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly(options, function (error) { + if (error) { + return console.error(error); + } + this.generateOffer(sdpOfferCallback.bind(that)); + }); + } + console.log("Waiting for SDP offer to be generated (" + + (local ? "local" : "remote") + " peer: " + that.getGlobalID() + ")"); + } + + this.publish = function () { + + // FIXME: Throw error when stream is not local + + initWebRtcPeer(that.publishVideoCallback); + + // FIXME: Now we have coupled connecting to a room and adding a + // stream to this room. But in the new API, there are two steps. + // This is the second step. For now, it do nothing. + + } + + this.subscribe = function () { + + // FIXME: In the current implementation all participants are subscribed + // automatically to all other participants. We use this method only to + // negotiate SDP + + initWebRtcPeer(that.startVideoCallback); + } + + this.processSdpAnswer = function (sdpAnswer) { + var answer = new RTCSessionDescription({ + type: 'answer', + sdp: sdpAnswer, + }); + console.log(that.getGlobalID() + ": set peer connection with recvd SDP answer", + sdpAnswer); + var participantId = that.getGlobalID(); + var pc = wp.peerConnection; + pc.setRemoteDescription(answer, function () { + // Avoids to subscribe to your own stream remotely + // except when showMyRemote is true + if (!local || that.displayMyRemote()) { + wrStream = pc.getRemoteStreams()[0]; + console.log("Peer remote stream", wrStream); + if (wrStream != undefined) { + speechEvent = kurentoUtils.WebRtcPeer.hark(wrStream, {threshold: that.room.thresholdSpeaker}); + speechEvent.on('speaking', function () { + that.room.addParticipantSpeaking(participantId); + that.room.emitEvent('stream-speaking', [{ + participantId: participantId + }]); + }); + speechEvent.on('stopped_speaking', function () { + that.room.removeParticipantSpeaking(participantId); + that.room.emitEvent('stream-stopped-speaking', [{ + participantId: participantId + }]); + }); + } + for (i = 0; i < videoElements.length; i++) { + var thumbnailId = videoElements[i].thumb; + var video = videoElements[i].video; + video.src = URL.createObjectURL(wrStream); + video.onplay = function () { + console.log(that.getGlobalID() + ': ' + 'Video playing'); + $(jq(thumbnailId)).show(); + hideSpinner(that.getGlobalID()); + }; + } + that.room.emitEvent('stream-subscribed', [{ + stream: that + }]); + } + }, function (error) { + console.error(that.getGlobalID() + ": Error setting SDP to the peer connection: " + + JSON.stringify(error)); + }); + } + + this.unpublish = function () { + if (wp) { + wp.dispose(); + } else { + if (wrStream) { + wrStream.getAudioTracks().forEach(function (track) { + track.stop && track.stop() + }) + wrStream.getVideoTracks().forEach(function (track) { + track.stop && track.stop() + }) + } + } + + if (speechEvent) { + speechEvent.stop(); + } + + console.log(that.getGlobalID() + ": Stream '" + id + "' unpublished"); + } + + this.dispose = function () { + + function disposeElement(element) { + if (element && element.parentNode) { + element.parentNode.removeChild(element); + } + } + + for (i = 0; i < elements.length; i++) { + disposeElement(elements[i]); + } + + for (i = 0; i < videoElements.length; i++) { + disposeElement(videoElements[i].video); + } + + disposeElement("progress-" + that.getGlobalID()); + + if (wp) { + wp.dispose(); + } else { + if (wrStream) { + wrStream.getAudioTracks().forEach(function (track) { + track.stop && track.stop() + }) + wrStream.getVideoTracks().forEach(function (track) { + track.stop && track.stop() + }) + } + } + + if (speechEvent) { + speechEvent.stop(); + } + + console.log(that.getGlobalID() + ": Stream '" + id + "' disposed"); + } +} + +// KurentoRoom -------------------------------- + +function KurentoRoom(wsUri, callback) { + if (!(this instanceof KurentoRoom)) + return new KurentoRoom(wsUri, callback); + + var that = this; + + var room; + + var userName; + + var jsonRpcClient; + + function initJsonRpcClient() { + + var config = { + heartbeat: 3000, + sendCloseMessage: false, + ws: { + uri: wsUri, + useSockJS: false, + onconnected: connectCallback, + ondisconnect: disconnectCallback, + onreconnecting: reconnectingCallback, + onreconnected: reconnectedCallback + }, + rpc: { + requestTimeout: 15000, + //notifications + participantJoined: onParticipantJoined, + participantPublished: onParticipantPublished, + participantUnpublished: onParticipantLeft, + participantLeft: onParticipantLeft, + participantEvicted: onParticipantEvicted, + sendMessage: onNewMessage, + iceCandidate: iceCandidateEvent, + mediaError: onMediaError, + custonNotification: customNotification + } + }; + + jsonRpcClient = new RpcBuilder.clients.JsonRpcClient(config); + } + + function customNotification(params) { + if (isRoomAvailable()) { + room.emitEvent("custom-message-received", [{params: params}]); + } + } + + function connectCallback(error) { + if (error) { + callback(error); + } else { + callback(null, that); + } + } + + function isRoomAvailable() { + if (room !== undefined && room instanceof Room) { + return true; + º + } else { + console.warn('Room instance not found'); + return false; + } + } + + function disconnectCallback() { + console.log('Websocket connection lost'); + if (isRoomAvailable()) { + room.onLostConnection(); + } else { + alert('Connection error. Please reload page.'); + } + } + + function reconnectingCallback() { + console.log('Websocket connection lost (reconnecting)'); + if (isRoomAvailable()) { + room.onLostConnection(); + } else { + alert('Connection error. Please reload page.'); + } + } + + function reconnectedCallback() { + console.log('Websocket reconnected'); + } + + function onParticipantJoined(params) { + if (isRoomAvailable()) { + room.onParticipantJoined(params); + } + } + + function onParticipantPublished(params) { + if (isRoomAvailable()) { + room.onParticipantPublished(params); + } + } + + function onParticipantLeft(params) { + if (isRoomAvailable()) { + room.onParticipantLeft(params); + } + } + + function onParticipantEvicted(params) { + if (isRoomAvailable()) { + room.onParticipantEvicted(params); + } + } + + function onNewMessage(params) { + if (isRoomAvailable()) { + room.onNewMessage(params); + } + } + + function iceCandidateEvent(params) { + if (isRoomAvailable()) { + room.recvIceCandidate(params); + } + } + + function onRoomClosed(params) { + if (isRoomAvailable()) { + room.onRoomClosed(params); + } + } + + function onMediaError(params) { + if (isRoomAvailable()) { + room.onMediaError(params); + } + } + + var rpcParams; + + this.setRpcParams = function (params) { + rpcParams = params; + } + + this.sendRequest = function (method, params, callback) { + if (params && params instanceof Function) { + callback = params; + params = undefined; + } + params = params || {}; + + if (rpcParams && rpcParams !== "null" && rpcParams !== "undefined") { + for (var index in rpcParams) { + if (rpcParams.hasOwnProperty(index)) { + params[index] = rpcParams[index]; + console.log('RPC param added to request {' + index + ': ' + rpcParams[index] + '}'); + } + } + } + console.log('Sending request: { method:"' + method + '", params: ' + JSON.stringify(params) + ' }'); + jsonRpcClient.send(method, params, callback); + }; + + this.close = function (forced) { + if (isRoomAvailable()) { + room.leave(forced, jsonRpcClient); + } + }; + + this.disconnectParticipant = function (stream) { + if (isRoomAvailable()) { + room.disconnect(stream); + } + } + + this.Stream = function (room, options) { + options.participant = room.getLocalParticipant(); + return new Stream(that, true, room, options); + }; + + this.Room = function (options) { + room = new Room(that, options); + return room; + }; + + //CHAT + this.sendMessage = function (room, user, message) { + this.sendRequest('sendMessage', { + message: message, + userMessage: user, + roomMessage: room + }, function (error, response) { + if (error) { + console.error(error); + } + }); + }; + + this.sendCustomRequest = function (params, callback) { + this.sendRequest('customRequest', params, callback); + }; + + initJsonRpcClient(); + +} diff --git a/openvidu-client/.classpath b/openvidu-client/.classpath new file mode 100644 index 00000000..af1430be --- /dev/null +++ b/openvidu-client/.classpath @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/openvidu-client/.gitignore b/openvidu-client/.gitignore new file mode 100644 index 00000000..b83d2226 --- /dev/null +++ b/openvidu-client/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/openvidu-client/.project b/openvidu-client/.project new file mode 100644 index 00000000..3309cf98 --- /dev/null +++ b/openvidu-client/.project @@ -0,0 +1,23 @@ + + + kurento-room-client-openvic + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/openvidu-client/.settings/org.eclipse.core.resources.prefs b/openvidu-client/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 00000000..f9fe3459 --- /dev/null +++ b/openvidu-client/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,4 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/test/java=UTF-8 +encoding/=UTF-8 diff --git a/openvidu-client/.settings/org.eclipse.jdt.core.prefs b/openvidu-client/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000..714351ae --- /dev/null +++ b/openvidu-client/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,5 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/openvidu-client/.settings/org.eclipse.m2e.core.prefs b/openvidu-client/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 00000000..f897a7f1 --- /dev/null +++ b/openvidu-client/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/openvidu-client/README.md b/openvidu-client/README.md new file mode 100644 index 00000000..6dbe34e9 --- /dev/null +++ b/openvidu-client/README.md @@ -0,0 +1,119 @@ +[![License badge](https://img.shields.io/badge/license-Apache2-orange.svg)](http://www.apache.org/licenses/LICENSE-2.0) +[![Documentation badge](https://readthedocs.org/projects/fiware-orion/badge/?version=latest)](http://doc-kurento-room.readthedocs.org/en/latest/) +[![Docker badge](https://img.shields.io/docker/pulls/fiware/orion.svg)](https://hub.docker.com/r/fiware/stream-oriented-kurento/) +[![Support badge]( https://img.shields.io/badge/support-sof-yellowgreen.svg)](http://stackoverflow.com/questions/tagged/kurento) + +[![][KurentoImage]][Kurento] + +Copyright © 2013-2016 [Kurento]. Licensed under [Apache 2.0 License]. + +kurento-room-client +====================== + +Kurento Room Client contains the Java client-side of group +communications applications based on WebRTC. +It uses WebSockets and JSON-RPC to interact with the server-side +of the Room API. + +What is Kurento +--------------- + +Kurento is an open source software project providing a platform suitable +for creating modular applications with advanced real-time communication +capabilities. For knowing more about Kurento, please visit the Kurento +project website: http://www.kurento.org. + +Kurento is part of [FIWARE]. For further information on the relationship of +FIWARE and Kurento check the [Kurento FIWARE Catalog Entry] + +Kurento is part of the [NUBOMEDIA] research initiative. + +Documentation +------------- + +The Kurento project provides detailed [documentation] including tutorials, +installation and development guides. A simplified version of the documentation +can be found on [readthedocs.org]. The [Open API specification] a.k.a. Kurento +Protocol is also available on [apiary.io]. + +Source +------ + +Code for other Kurento projects can be found in the [GitHub Kurento Group]. + +News and Website +---------------- + +Check the [Kurento blog] +Follow us on Twitter @[kurentoms]. + +Issue tracker +------------- + +Issues and bug reports should be posted to the [GitHub Kurento bugtracker] + +Licensing and distribution +-------------------------- + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contribution policy +------------------- + +You can contribute to the Kurento community through bug-reports, bug-fixes, new +code or new documentation. For contributing to the Kurento community, drop a +post to the [Kurento Public Mailing List] providing full information about your +contribution and its value. In your contributions, you must comply with the +following guidelines + +* You must specify the specific contents of your contribution either through a + detailed bug description, through a pull-request or through a patch. +* You must specify the licensing restrictions of the code you contribute. +* For newly created code to be incorporated in the Kurento code-base, you must + accept Kurento to own the code copyright, so that its open source nature is + guaranteed. +* You must justify appropriately the need and value of your contribution. The + Kurento project has no obligations in relation to accepting contributions + from third parties. +* The Kurento project leaders have the right of asking for further + explanations, tests or validations of any code contributed to the community + before it being incorporated into the Kurento code-base. You must be ready to + addressing all these kind of concerns before having your code approved. + +Support +------- + +The Kurento project provides community support through the [Kurento Public +Mailing List] and through [StackOverflow] using the tags *kurento* and +*fiware-kurento*. + +Before asking for support, please read first the [Kurento Netiquette Guidelines] + +[documentation]: http://www.kurento.org/documentation +[FIWARE]: http://www.fiware.org +[GitHub Kurento bugtracker]: https://github.com/Kurento/bugtracker/issues +[GitHub Kurento Group]: https://github.com/kurento +[kurentoms]: http://twitter.com/kurentoms +[Kurento]: http://kurento.org +[Kurento Blog]: http://www.kurento.org/blog +[Kurento FIWARE Catalog Entry]: http://catalogue.fiware.org/enablers/stream-oriented-kurento +[Kurento Netiquette Guidelines]: http://www.kurento.org/blog/kurento-netiquette-guidelines +[Kurento Public Mailing list]: https://groups.google.com/forum/#!forum/kurento +[KurentoImage]: https://secure.gravatar.com/avatar/21a2a12c56b2a91c8918d5779f1778bf?s=120 +[Apache 2.0 License]: http://www.apache.org/licenses/LICENSE-2.0 +[NUBOMEDIA]: http://www.nubomedia.eu +[StackOverflow]: http://stackoverflow.com/search?q=kurento +[Read-the-docs]: http://read-the-docs.readthedocs.org/ +[readthedocs.org]: http://kurento.readthedocs.org/ +[Open API specification]: http://kurento.github.io/doc-kurento/ +[apiary.io]: http://docs.streamoriented.apiary.io/ diff --git a/openvidu-client/pom.xml b/openvidu-client/pom.xml new file mode 100644 index 00000000..b0ae6de4 --- /dev/null +++ b/openvidu-client/pom.xml @@ -0,0 +1,104 @@ + + 4.0.0 + + + org.openvidu + openvidu + 6.6.1-SNAPSHOT + + + openvidu-client + jar + + Kurento Room Client + + Kurento Room library for the client-side of Kurento Room Server + + http://www.kurento.org/docs/${project.version} + + + + Apache 2.0 + http://www.apache.org/licenses/LICENSE-2.0 + repo + + + + + Kurento + http://www.kurento.org + + + + ${openvidu.scm.url} + scm:git:${openvidu.scm.connection} + scm:git:${openvidu.scm.connection} + develop + + + + + kurento.org + -kurento.org Community + Kurento.org + http://www.kurento.org + + + + + + org.kurento + kurento-jsonrpc-client + + + + org.kurento + kurento-jsonrpc-client-jetty + + + junit + junit + test + + + org.mockito + mockito-core + test + + + + + + default + + + default + true + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + org.apache.maven.plugins + maven-failsafe-plugin + + true + + + + + + + + diff --git a/openvidu-client/src/main/java/org/openvidu/client/OpenViduClient.java b/openvidu-client/src/main/java/org/openvidu/client/OpenViduClient.java new file mode 100644 index 00000000..1bae6db6 --- /dev/null +++ b/openvidu-client/src/main/java/org/openvidu/client/OpenViduClient.java @@ -0,0 +1,222 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.client; + +import static org.openvidu.client.internal.ProtocolElements.CUSTOMREQUEST_METHOD; +import static org.openvidu.client.internal.ProtocolElements.JOINROOM_DATACHANNELS_PARAM; +import static org.openvidu.client.internal.ProtocolElements.JOINROOM_METHOD; +import static org.openvidu.client.internal.ProtocolElements.JOINROOM_PEERID_PARAM; +import static org.openvidu.client.internal.ProtocolElements.JOINROOM_PEERSTREAMID_PARAM; +import static org.openvidu.client.internal.ProtocolElements.JOINROOM_PEERSTREAMS_PARAM; +import static org.openvidu.client.internal.ProtocolElements.JOINROOM_ROOM_PARAM; +import static org.openvidu.client.internal.ProtocolElements.JOINROOM_USER_PARAM; +import static org.openvidu.client.internal.ProtocolElements.LEAVEROOM_METHOD; +import static org.openvidu.client.internal.ProtocolElements.ONICECANDIDATE_CANDIDATE_PARAM; +import static org.openvidu.client.internal.ProtocolElements.ONICECANDIDATE_EPNAME_PARAM; +import static org.openvidu.client.internal.ProtocolElements.ONICECANDIDATE_METHOD; +import static org.openvidu.client.internal.ProtocolElements.ONICECANDIDATE_SDPMIDPARAM; +import static org.openvidu.client.internal.ProtocolElements.ONICECANDIDATE_SDPMLINEINDEX_PARAM; +import static org.openvidu.client.internal.ProtocolElements.PUBLISHVIDEO_DOLOOPBACK_PARAM; +import static org.openvidu.client.internal.ProtocolElements.PUBLISHVIDEO_METHOD; +import static org.openvidu.client.internal.ProtocolElements.PUBLISHVIDEO_SDPANSWER_PARAM; +import static org.openvidu.client.internal.ProtocolElements.PUBLISHVIDEO_SDPOFFER_PARAM; +import static org.openvidu.client.internal.ProtocolElements.RECEIVEVIDEO_METHOD; +import static org.openvidu.client.internal.ProtocolElements.RECEIVEVIDEO_SDPANSWER_PARAM; +import static org.openvidu.client.internal.ProtocolElements.RECEIVEVIDEO_SDPOFFER_PARAM; +import static org.openvidu.client.internal.ProtocolElements.RECEIVEVIDEO_SENDER_PARAM; +import static org.openvidu.client.internal.ProtocolElements.SENDMESSAGE_MESSAGE_PARAM; +import static org.openvidu.client.internal.ProtocolElements.SENDMESSAGE_ROOM_METHOD; +import static org.openvidu.client.internal.ProtocolElements.SENDMESSAGE_ROOM_PARAM; +import static org.openvidu.client.internal.ProtocolElements.SENDMESSAGE_USER_PARAM; +import static org.openvidu.client.internal.ProtocolElements.UNPUBLISHVIDEO_METHOD; +import static org.openvidu.client.internal.ProtocolElements.UNSUBSCRIBEFROMVIDEO_METHOD; +import static org.openvidu.client.internal.ProtocolElements.UNSUBSCRIBEFROMVIDEO_SENDER_PARAM; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.eclipse.jetty.util.ssl.SslContextFactory; +import org.kurento.jsonrpc.client.JsonRpcClient; +import org.kurento.jsonrpc.client.JsonRpcClientWebSocket; +import org.kurento.jsonrpc.client.JsonRpcWSConnectionListener; +import org.openvidu.client.internal.JsonRoomUtils; +import org.openvidu.client.internal.Notification; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +/** + * Java client for the room server. + * + * @author Radu Tom Vlad + */ +public class OpenViduClient { + + private static final Logger log = LoggerFactory.getLogger(OpenViduClient.class); + + private JsonRpcClient client; + private ServerJsonRpcHandler handler; + + public OpenViduClient(String wsUri) { + this(new JsonRpcClientWebSocket(wsUri, new JsonRpcWSConnectionListener() { + + @Override + public void reconnected(boolean sameServer) { + } + + @Override + public void disconnected() { + log.warn("JsonRpcWebsocket connection: Disconnected"); + } + + @Override + public void connectionFailed() { + log.warn("JsonRpcWebsocket connection: Connection failed"); + } + + @Override + public void connected() { + } + + @Override + public void reconnecting() { + log.warn("JsonRpcWebsocket connection: is reconnecting"); + } + }, new SslContextFactory(true))); + } + + public OpenViduClient(JsonRpcClient client) { + this.client = client; + this.handler = new ServerJsonRpcHandler(); + this.client.setServerRequestHandler(this.handler); + } + + public OpenViduClient(JsonRpcClient client, ServerJsonRpcHandler handler) { + this.client = client; + this.handler = handler; + this.client.setServerRequestHandler(this.handler); + } + + public void close() throws IOException { + this.client.close(); + } + + public Map> joinRoom(String roomName, String userName, Boolean dataChannels) + throws IOException { + JsonObject params = new JsonObject(); + params.addProperty(JOINROOM_ROOM_PARAM, roomName); + params.addProperty(JOINROOM_USER_PARAM, userName); + if (dataChannels != null) { + params.addProperty(JOINROOM_DATACHANNELS_PARAM, dataChannels); + } + JsonElement result = client.sendRequest(JOINROOM_METHOD, params); + Map> peers = new HashMap>(); + JsonArray jsonPeers = JsonRoomUtils.getResponseProperty(result, "value", JsonArray.class); + if (jsonPeers.size() > 0) { + Iterator peerIt = jsonPeers.iterator(); + while (peerIt.hasNext()) { + JsonElement peer = peerIt.next(); + String peerId = JsonRoomUtils.getResponseProperty(peer, JOINROOM_PEERID_PARAM, + String.class); + List streams = new ArrayList(); + JsonArray jsonStreams = JsonRoomUtils.getResponseProperty(peer, JOINROOM_PEERSTREAMS_PARAM, + JsonArray.class, true); + if (jsonStreams != null) { + Iterator streamIt = jsonStreams.iterator(); + while (streamIt.hasNext()) { + streams.add(JsonRoomUtils.getResponseProperty(streamIt.next(), + JOINROOM_PEERSTREAMID_PARAM, String.class)); + } + } + peers.put(peerId, streams); + } + } + return peers; + } + + public void leaveRoom() throws IOException { + client.sendRequest(LEAVEROOM_METHOD, new JsonObject()); + } + + public String publishVideo(String sdpOffer, boolean doLoopback) throws IOException { + JsonObject params = new JsonObject(); + params.addProperty(PUBLISHVIDEO_SDPOFFER_PARAM, sdpOffer); + params.addProperty(PUBLISHVIDEO_DOLOOPBACK_PARAM, doLoopback); + JsonElement result = client.sendRequest(PUBLISHVIDEO_METHOD, params); + return JsonRoomUtils.getResponseProperty(result, PUBLISHVIDEO_SDPANSWER_PARAM, String.class); + } + + public void unpublishVideo() throws IOException { + client.sendRequest(UNPUBLISHVIDEO_METHOD, new JsonObject()); + } + + // sender should look like 'username_streamId' + public String receiveVideoFrom(String sender, String sdpOffer) throws IOException { + JsonObject params = new JsonObject(); + params.addProperty(RECEIVEVIDEO_SENDER_PARAM, sender); + params.addProperty(RECEIVEVIDEO_SDPOFFER_PARAM, sdpOffer); + JsonElement result = client.sendRequest(RECEIVEVIDEO_METHOD, params); + return JsonRoomUtils.getResponseProperty(result, RECEIVEVIDEO_SDPANSWER_PARAM, String.class); + } + + // sender should look like 'username_streamId' + public void unsubscribeFromVideo(String sender) throws IOException { + JsonObject params = new JsonObject(); + params.addProperty(UNSUBSCRIBEFROMVIDEO_SENDER_PARAM, sender); + client.sendRequest(UNSUBSCRIBEFROMVIDEO_METHOD, params); + } + + public void onIceCandidate(String endpointName, String candidate, String sdpMid, + int sdpMLineIndex) throws IOException { + JsonObject params = new JsonObject(); + params.addProperty(ONICECANDIDATE_EPNAME_PARAM, endpointName); + params.addProperty(ONICECANDIDATE_CANDIDATE_PARAM, candidate); + params.addProperty(ONICECANDIDATE_SDPMIDPARAM, sdpMid); + params.addProperty(ONICECANDIDATE_SDPMLINEINDEX_PARAM, sdpMLineIndex); + client.sendRequest(ONICECANDIDATE_METHOD, params); + } + + public void sendMessage(String userName, String roomName, String message) throws IOException { + JsonObject params = new JsonObject(); + params.addProperty(SENDMESSAGE_USER_PARAM, userName); + params.addProperty(SENDMESSAGE_ROOM_PARAM, roomName); + params.addProperty(SENDMESSAGE_MESSAGE_PARAM, message); + client.sendRequest(SENDMESSAGE_ROOM_METHOD, params); + } + + public JsonElement customRequest(JsonObject customReqParams) throws IOException { + return client.sendRequest(CUSTOMREQUEST_METHOD, customReqParams); + } + + /** + * Polls the notifications list maintained by this client to obtain new events sent by server. + * This method blocks until there is a notification to return. This is a one-time operation for + * the returned element. + * + * @return a server notification object, null when interrupted while waiting + */ + public Notification getServerNotification() { + return this.handler.getNotification(); + } +} diff --git a/openvidu-client/src/main/java/org/openvidu/client/OpenViduException.java b/openvidu-client/src/main/java/org/openvidu/client/OpenViduException.java new file mode 100644 index 00000000..a8c320bb --- /dev/null +++ b/openvidu-client/src/main/java/org/openvidu/client/OpenViduException.java @@ -0,0 +1,72 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.openvidu.client; + +public class OpenViduException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public static enum Code { + GENERIC_ERROR_CODE(999), + + TRANSPORT_ERROR_CODE(803), TRANSPORT_RESPONSE_ERROR_CODE(802), TRANSPORT_REQUEST_ERROR_CODE( + 801), + + MEDIA_MUTE_ERROR_CODE(307), MEDIA_NOT_A_WEB_ENDPOINT_ERROR_CODE( + 306), MEDIA_RTP_ENDPOINT_ERROR_CODE(305), MEDIA_WEBRTC_ENDPOINT_ERROR_CODE( + 304), MEDIA_ENDPOINT_ERROR_CODE( + 303), MEDIA_SDP_ERROR_CODE(302), MEDIA_GENERIC_ERROR_CODE(301), + + ROOM_CANNOT_BE_CREATED_ERROR_CODE(204), ROOM_CLOSED_ERROR_CODE(203), ROOM_NOT_FOUND_ERROR_CODE( + 202), ROOM_GENERIC_ERROR_CODE(201), + + USER_NOT_STREAMING_ERROR_CODE(105), EXISTING_USER_IN_ROOM_ERROR_CODE( + 104), USER_CLOSED_ERROR_CODE( + 103), USER_NOT_FOUND_ERROR_CODE(102), USER_GENERIC_ERROR_CODE(101); + + private int value; + + private Code(int value) { + this.value = value; + } + + public int getValue() { + return this.value; + } + } + + private Code code = Code.GENERIC_ERROR_CODE; + + public OpenViduException(Code code, String message) { + super(message); + this.code = code; + } + + public Code getCode() { + return code; + } + + public int getCodeValue() { + return code.getValue(); + } + + @Override + public String toString() { + return "Code: " + getCodeValue() + " " + super.toString(); + } + +} diff --git a/openvidu-client/src/main/java/org/openvidu/client/ServerJsonRpcHandler.java b/openvidu-client/src/main/java/org/openvidu/client/ServerJsonRpcHandler.java new file mode 100644 index 00000000..2078f47e --- /dev/null +++ b/openvidu-client/src/main/java/org/openvidu/client/ServerJsonRpcHandler.java @@ -0,0 +1,221 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.client; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; + +import org.kurento.jsonrpc.DefaultJsonRpcHandler; +import org.kurento.jsonrpc.Transaction; +import org.kurento.jsonrpc.message.Request; +import org.openvidu.client.internal.IceCandidate; +import org.openvidu.client.internal.IceCandidateInfo; +import org.openvidu.client.internal.JsonRoomUtils; +import org.openvidu.client.internal.MediaErrorInfo; +import org.openvidu.client.internal.Notification; +import org.openvidu.client.internal.ParticipantEvictedInfo; +import org.openvidu.client.internal.ParticipantJoinedInfo; +import org.openvidu.client.internal.ParticipantLeftInfo; +import org.openvidu.client.internal.ParticipantPublishedInfo; +import org.openvidu.client.internal.ParticipantUnpublishedInfo; +import org.openvidu.client.internal.ProtocolElements; +import org.openvidu.client.internal.RoomClosedInfo; +import org.openvidu.client.internal.SendMessageInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +/** + * Service that handles server JSON-RPC events. + * + * @author Radu Tom Vlad + */ +public class ServerJsonRpcHandler extends DefaultJsonRpcHandler { + + private static final Logger log = LoggerFactory.getLogger(ServerJsonRpcHandler.class); + + private BlockingQueue notifications = new ArrayBlockingQueue(100); + + @Override + public void handleRequest(Transaction transaction, Request request) throws Exception { + Notification notif = null; + try { + switch (request.getMethod()) { + case ProtocolElements.ICECANDIDATE_METHOD: + notif = iceCandidate(transaction, request); + break; + case ProtocolElements.MEDIAERROR_METHOD: + notif = mediaError(transaction, request); + break; + case ProtocolElements.PARTICIPANTJOINED_METHOD: + notif = participantJoined(transaction, request); + break; + case ProtocolElements.PARTICIPANTLEFT_METHOD: + notif = participantLeft(transaction, request); + break; + case ProtocolElements.PARTICIPANTEVICTED_METHOD: + notif = participantEvicted(transaction, request); + break; + case ProtocolElements.PARTICIPANTPUBLISHED_METHOD: + notif = participantPublished(transaction, request); + break; + case ProtocolElements.PARTICIPANTUNPUBLISHED_METHOD: + notif = participantUnpublished(transaction, request); + break; + case ProtocolElements.ROOMCLOSED_METHOD: + notif = roomClosed(transaction, request); + break; + case ProtocolElements.PARTICIPANTSENDMESSAGE_METHOD: + notif = participantSendMessage(transaction, request); + break; + default: + throw new Exception("Unrecognized request " + request.getMethod()); + } + } catch (Exception e) { + log.error("Exception processing request {}", request, e); + transaction.sendError(e); + return; + } + if (notif != null) { + try { + notifications.put(notif); + log.debug("Enqueued notification {}", notif); + } catch (InterruptedException e) { + log.warn("Interrupted when enqueuing notification {}", notif, e); + } + } + } + + private Notification participantSendMessage(Transaction transaction, + Request request) { + String room = JsonRoomUtils.getRequestParam(request, + ProtocolElements.PARTICIPANTSENDMESSAGE_ROOM_PARAM, String.class); + String user = JsonRoomUtils.getRequestParam(request, + ProtocolElements.PARTICIPANTSENDMESSAGE_USER_PARAM, String.class); + String message = JsonRoomUtils.getRequestParam(request, + ProtocolElements.PARTICIPANTSENDMESSAGE_MESSAGE_PARAM, String.class); + SendMessageInfo eventInfo = new SendMessageInfo(room, user, message); + log.debug("Recvd send message event {}", eventInfo); + return eventInfo; + } + + private Notification roomClosed(Transaction transaction, Request request) { + String room = JsonRoomUtils.getRequestParam(request, ProtocolElements.ROOMCLOSED_ROOM_PARAM, + String.class); + RoomClosedInfo eventInfo = new RoomClosedInfo(room); + log.debug("Recvd room closed event {}", eventInfo); + return eventInfo; + } + + private Notification participantUnpublished(Transaction transaction, + Request request) { + String name = JsonRoomUtils.getRequestParam(request, + ProtocolElements.PARTICIPANTUNPUBLISHED_NAME_PARAM, String.class); + ParticipantUnpublishedInfo eventInfo = new ParticipantUnpublishedInfo(name); + log.debug("Recvd participant unpublished event {}", eventInfo); + return eventInfo; + } + + private Notification participantPublished(Transaction transaction, Request request) { + String id = JsonRoomUtils.getRequestParam(request, + ProtocolElements.PARTICIPANTPUBLISHED_USER_PARAM, String.class); + JsonArray jsonStreams = JsonRoomUtils.getRequestParam(request, + ProtocolElements.PARTICIPANTPUBLISHED_STREAMS_PARAM, JsonArray.class); + Iterator streamIt = jsonStreams.iterator(); + List streams = new ArrayList(); + while (streamIt.hasNext()) { + streams.add(JsonRoomUtils.getResponseProperty(streamIt.next(), + ProtocolElements.PARTICIPANTPUBLISHED_STREAMID_PARAM, String.class)); + } + ParticipantPublishedInfo eventInfo = new ParticipantPublishedInfo(id, streams); + log.debug("Recvd published event {}", eventInfo); + return eventInfo; + } + + private Notification participantEvicted(Transaction transaction, Request request) { + ParticipantEvictedInfo eventInfo = new ParticipantEvictedInfo(); + log.debug("Recvd participant evicted event {}", eventInfo); + return eventInfo; + } + + private Notification participantLeft(Transaction transaction, Request request) { + String name = JsonRoomUtils.getRequestParam(request, + ProtocolElements.PARTICIPANTLEFT_NAME_PARAM, String.class); + ParticipantLeftInfo eventInfo = new ParticipantLeftInfo(name); + log.debug("Recvd participant left event {}", eventInfo); + return eventInfo; + } + + private Notification participantJoined(Transaction transaction, Request request) { + String id = JsonRoomUtils.getRequestParam(request, + ProtocolElements.PARTICIPANTJOINED_USER_PARAM, String.class); + ParticipantJoinedInfo eventInfo = new ParticipantJoinedInfo(id); + log.debug("Recvd participant joined event {}", eventInfo); + return eventInfo; + } + + private Notification mediaError(Transaction transaction, Request request) { + String description = JsonRoomUtils.getRequestParam(request, + ProtocolElements.MEDIAERROR_ERROR_PARAM, String.class); + MediaErrorInfo eventInfo = new MediaErrorInfo(description); + log.debug("Recvd media error event {}", eventInfo); + return eventInfo; + } + + private Notification iceCandidate(Transaction transaction, Request request) { + + String candidate = JsonRoomUtils.getRequestParam(request, + ProtocolElements.ICECANDIDATE_CANDIDATE_PARAM, String.class); + String sdpMid = JsonRoomUtils.getRequestParam(request, + ProtocolElements.ICECANDIDATE_SDPMID_PARAM, String.class); + int sdpMLineIndex = JsonRoomUtils.getRequestParam(request, + ProtocolElements.ICECANDIDATE_SDPMLINEINDEX_PARAM, Integer.class); + + IceCandidate iceCandidate = new IceCandidate(candidate, sdpMid, sdpMLineIndex); + + String endpoint = JsonRoomUtils.getRequestParam(request, + ProtocolElements.ICECANDIDATE_EPNAME_PARAM, String.class); + + IceCandidateInfo eventInfo = new IceCandidateInfo(iceCandidate, endpoint); + log.debug("Recvd ICE candidate event {}", eventInfo); + + return eventInfo; + } + + /** + * Blocks until an element is available and then returns it by removing it from the queue. + * + * @return a {@link Notification} from the queue, null when interrupted + * @see BlockingQueue#take() + */ + public Notification getNotification() { + try { + Notification notif = notifications.take(); + log.debug("Dequeued notification {}", notif); + return notif; + } catch (InterruptedException e) { + log.info("Interrupted while polling notifications' queue"); + return null; + } + } +} diff --git a/openvidu-client/src/main/java/org/openvidu/client/internal/IceCandidate.java b/openvidu-client/src/main/java/org/openvidu/client/internal/IceCandidate.java new file mode 100644 index 00000000..40508018 --- /dev/null +++ b/openvidu-client/src/main/java/org/openvidu/client/internal/IceCandidate.java @@ -0,0 +1,33 @@ +package org.openvidu.client.internal; + +public class IceCandidate { + + private String candidate; + private String sdpMid; + private int sdpMLineIndex; + + public IceCandidate(String candidate, String sdpMid, int sdpMLineIndex) { + super(); + this.candidate = candidate; + this.sdpMid = sdpMid; + this.sdpMLineIndex = sdpMLineIndex; + } + + public String getCandidate() { + return candidate; + } + + public String getSdpMid() { + return sdpMid; + } + + public int getSdpMLineIndex() { + return sdpMLineIndex; + } + + @Override + public String toString() { + return "IceCandidate [candidate=" + candidate + ", sdpMid=" + sdpMid + ", sdpMLineIndex=" + + sdpMLineIndex + "]"; + } +} diff --git a/openvidu-client/src/main/java/org/openvidu/client/internal/IceCandidateInfo.java b/openvidu-client/src/main/java/org/openvidu/client/internal/IceCandidateInfo.java new file mode 100644 index 00000000..89279f4d --- /dev/null +++ b/openvidu-client/src/main/java/org/openvidu/client/internal/IceCandidateInfo.java @@ -0,0 +1,70 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.client.internal; + +/** + * @see Notification + * + * @author Radu Tom Vlad + */ +public class IceCandidateInfo extends Notification { + + private IceCandidate iceCandidate; + private String endpointName; + + public IceCandidateInfo(IceCandidate iceCandidate, String endpointName) { + super(ProtocolElements.ICECANDIDATE_METHOD); + this.iceCandidate = iceCandidate; + this.endpointName = endpointName; + } + + public IceCandidate getIceCandidate() { + return iceCandidate; + } + + public void setIceCandidate(IceCandidate iceCandidate) { + this.iceCandidate = iceCandidate; + } + + public String getEndpointName() { + return endpointName; + } + + public void setEndpointName(String endpointName) { + this.endpointName = endpointName; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("["); + if (getMethod() != null) { + builder.append("method=").append(getMethod()).append(", "); + } + if (endpointName != null) { + builder.append("endpointName=").append(endpointName).append(", "); + } + if (iceCandidate != null) { + builder.append("iceCandidate=[sdpMLineIndex= ").append(iceCandidate.getSdpMLineIndex()) + .append(", sdpMid=").append(iceCandidate.getSdpMid()).append(", candidate=") + .append(iceCandidate.getCandidate()).append("]"); + } + builder.append("]"); + return builder.toString(); + } + +} diff --git a/openvidu-client/src/main/java/org/openvidu/client/internal/JsonRoomUtils.java b/openvidu-client/src/main/java/org/openvidu/client/internal/JsonRoomUtils.java new file mode 100644 index 00000000..bcdeb0a4 --- /dev/null +++ b/openvidu-client/src/main/java/org/openvidu/client/internal/JsonRoomUtils.java @@ -0,0 +1,106 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.client.internal; + +import org.kurento.jsonrpc.message.Request; +import org.openvidu.client.OpenViduException; +import org.openvidu.client.OpenViduException.Code; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +/** + * JSON tools for extracting info from request or response elements. + * + * @author Radu Tom Vlad + */ +public class JsonRoomUtils { + + public static T getRequestParam(Request request, String paramName, Class type) { + return getRequestParam(request, paramName, type, false); + } + + public static T getRequestParam(Request request, String paramName, Class type, + boolean allowNull) { + JsonObject params = request.getParams(); + if (params == null) { + if (!allowNull) { + throw new OpenViduException(Code.TRANSPORT_REQUEST_ERROR_CODE, + "Invalid request lacking parameter '" + paramName + "'"); + } else { + return null; + } + } + return getConverted(params.get(paramName), paramName, type, allowNull); + } + + public static T getResponseProperty(JsonElement result, String property, Class type) { + return getResponseProperty(result, property, type, false); + } + + public static T getResponseProperty(JsonElement result, String property, Class type, + boolean allowNull) { + if (!(result instanceof JsonObject)) { + throw new OpenViduException(Code.TRANSPORT_RESPONSE_ERROR_CODE, + "Invalid response format. The response '" + result + "' should be a Json object"); + } + return getConverted(result.getAsJsonObject().get(property), property, type, allowNull); + } + + public static JsonArray getResponseArray(JsonElement result) { + if (!result.isJsonArray()) { + throw new OpenViduException(Code.TRANSPORT_RESPONSE_ERROR_CODE, + "Invalid response format. The response '" + result + "' should be a Json array"); + } + return result.getAsJsonArray(); + } + + @SuppressWarnings("unchecked") + private static T getConverted(JsonElement paramValue, String property, Class type, + boolean allowNull) { + if (paramValue == null) { + if (allowNull) { + return null; + } else { + throw new OpenViduException(Code.TRANSPORT_ERROR_CODE, "Invalid method lacking parameter '" + + property + "'"); + } + } + + if (type == String.class) { + if (paramValue.isJsonPrimitive()) { + return (T) paramValue.getAsString(); + } + } + + if (type == Integer.class) { + if (paramValue.isJsonPrimitive()) { + return (T) Integer.valueOf(paramValue.getAsInt()); + } + } + + if (type == JsonArray.class) { + if (paramValue.isJsonArray()) { + return (T) paramValue.getAsJsonArray(); + } + } + + throw new OpenViduException(Code.TRANSPORT_ERROR_CODE, "Param '" + property + "' with value '" + + paramValue + "' is not a " + type.getName()); + } +} diff --git a/openvidu-client/src/main/java/org/openvidu/client/internal/MediaErrorInfo.java b/openvidu-client/src/main/java/org/openvidu/client/internal/MediaErrorInfo.java new file mode 100644 index 00000000..f5dd5bf9 --- /dev/null +++ b/openvidu-client/src/main/java/org/openvidu/client/internal/MediaErrorInfo.java @@ -0,0 +1,55 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.client.internal; + +/** + * + * @author Radu Tom Vlad + * + * @see Notification + */ +public class MediaErrorInfo extends Notification { + + private String description; + + public MediaErrorInfo(String description) { + super(ProtocolElements.MEDIAERROR_METHOD); + this.description = description; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("["); + if (getMethod() != null) { + builder.append("method=").append(getMethod()).append(", "); + } + if (description != null) { + builder.append("description=").append(description); + } + builder.append("]"); + return builder.toString(); + } +} diff --git a/openvidu-client/src/main/java/org/openvidu/client/internal/Notification.java b/openvidu-client/src/main/java/org/openvidu/client/internal/Notification.java new file mode 100644 index 00000000..67ac77bf --- /dev/null +++ b/openvidu-client/src/main/java/org/openvidu/client/internal/Notification.java @@ -0,0 +1,90 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.client.internal; + +/** + * Wrapper for server events. + * + * @author Radu Tom Vlad + */ +public abstract class Notification { + + public enum Method { + ICECANDIDATE_METHOD(ProtocolElements.ICECANDIDATE_METHOD), MEDIAERROR_METHOD( + ProtocolElements.MEDIAERROR_METHOD), PARTICIPANTJOINED_METHOD( + ProtocolElements.PARTICIPANTJOINED_METHOD), PARTICIPANTLEFT_METHOD( + ProtocolElements.PARTICIPANTLEFT_METHOD), PARTICIPANTEVICTED_METHOD( + ProtocolElements.PARTICIPANTEVICTED_METHOD), PARTICIPANTPUBLISHED_METHOD( + ProtocolElements.PARTICIPANTPUBLISHED_METHOD), PARTICIPANTUNPUBLISHED_METHOD( + ProtocolElements.PARTICIPANTUNPUBLISHED_METHOD), ROOMCLOSED_METHOD( + ProtocolElements.ROOMCLOSED_METHOD), PARTICIPANTSENDMESSAGE_METHOD( + ProtocolElements.PARTICIPANTSENDMESSAGE_METHOD); + + private String methodValue; + + private Method(String val) { + this.methodValue = val; + } + + public String getMethodValue() { + return methodValue; + } + + public static Method getFromValue(String val) { + for (Method m : Method.values()) { + if (m.methodValue.equals(val)) { + return m; + } + } + return null; + } + + @Override + public String toString() { + return getMethodValue().toString(); + } + } + + private Method method; + + public Notification(Method method) { + this.setMethod(method); + } + + public Notification(String methodValue) { + this(Method.getFromValue(methodValue)); + } + + public Method getMethod() { + return method; + } + + public void setMethod(Method method) { + this.method = method; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("["); + if (method != null) { + builder.append("method=").append(method); + } + builder.append("]"); + return builder.toString(); + } +} diff --git a/openvidu-client/src/main/java/org/openvidu/client/internal/ParticipantEvictedInfo.java b/openvidu-client/src/main/java/org/openvidu/client/internal/ParticipantEvictedInfo.java new file mode 100644 index 00000000..fd9251df --- /dev/null +++ b/openvidu-client/src/main/java/org/openvidu/client/internal/ParticipantEvictedInfo.java @@ -0,0 +1,30 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.client.internal; + +/** + * @see Notification + * + * @author Radu Tom Vlad + */ +public class ParticipantEvictedInfo extends Notification { + + public ParticipantEvictedInfo() { + super(ProtocolElements.PARTICIPANTEVICTED_METHOD); + } + +} diff --git a/openvidu-client/src/main/java/org/openvidu/client/internal/ParticipantJoinedInfo.java b/openvidu-client/src/main/java/org/openvidu/client/internal/ParticipantJoinedInfo.java new file mode 100644 index 00000000..500b0b65 --- /dev/null +++ b/openvidu-client/src/main/java/org/openvidu/client/internal/ParticipantJoinedInfo.java @@ -0,0 +1,54 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.client.internal; + +/** + * @see Notification + * + * @author Radu Tom Vlad + */ +public class ParticipantJoinedInfo extends Notification { + + private String id; + + public ParticipantJoinedInfo(String id) { + super(ProtocolElements.PARTICIPANTJOINED_METHOD); + this.id = id; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("["); + if (getMethod() != null) { + builder.append("method=").append(getMethod()).append(", "); + } + if (id != null) { + builder.append("id=").append(id); + } + builder.append("]"); + return builder.toString(); + } +} diff --git a/openvidu-client/src/main/java/org/openvidu/client/internal/ParticipantLeftInfo.java b/openvidu-client/src/main/java/org/openvidu/client/internal/ParticipantLeftInfo.java new file mode 100644 index 00000000..481b0a0a --- /dev/null +++ b/openvidu-client/src/main/java/org/openvidu/client/internal/ParticipantLeftInfo.java @@ -0,0 +1,54 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.client.internal; + +/** + * @see Notification + * + * @author Radu Tom Vlad + */ +public class ParticipantLeftInfo extends Notification { + + private String name; + + public ParticipantLeftInfo(String name) { + super(ProtocolElements.PARTICIPANTLEFT_METHOD); + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("["); + if (getMethod() != null) { + builder.append("method=").append(getMethod()).append(", "); + } + if (name != null) { + builder.append("name=").append(name); + } + builder.append("]"); + return builder.toString(); + } +} diff --git a/openvidu-client/src/main/java/org/openvidu/client/internal/ParticipantPublishedInfo.java b/openvidu-client/src/main/java/org/openvidu/client/internal/ParticipantPublishedInfo.java new file mode 100644 index 00000000..e1aeb714 --- /dev/null +++ b/openvidu-client/src/main/java/org/openvidu/client/internal/ParticipantPublishedInfo.java @@ -0,0 +1,69 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.client.internal; + +import java.util.List; + +/** + * @see Notification + * + * @author Radu Tom Vlad + */ +public class ParticipantPublishedInfo extends Notification { + + private String id; + private List streams; + + public ParticipantPublishedInfo(String id, List streams) { + super(ProtocolElements.PARTICIPANTPUBLISHED_METHOD); + this.id = id; + this.streams = streams; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public List getStreams() { + return streams; + } + + public void setStreams(List streams) { + this.streams = streams; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("["); + if (getMethod() != null) { + builder.append("method=").append(getMethod()).append(", "); + } + if (id != null) { + builder.append("id=").append(id).append(", "); + } + if (streams != null) { + builder.append("streams=").append(streams); + } + builder.append("]"); + return builder.toString(); + } +} diff --git a/openvidu-client/src/main/java/org/openvidu/client/internal/ParticipantUnpublishedInfo.java b/openvidu-client/src/main/java/org/openvidu/client/internal/ParticipantUnpublishedInfo.java new file mode 100644 index 00000000..e379189c --- /dev/null +++ b/openvidu-client/src/main/java/org/openvidu/client/internal/ParticipantUnpublishedInfo.java @@ -0,0 +1,54 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.client.internal; + +/** + * @see Notification + * + * @author Radu Tom Vlad + */ +public class ParticipantUnpublishedInfo extends Notification { + + private String name; + + public ParticipantUnpublishedInfo(String name) { + super(ProtocolElements.PARTICIPANTUNPUBLISHED_METHOD); + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("["); + if (getMethod() != null) { + builder.append("method=").append(getMethod()).append(", "); + } + if (name != null) { + builder.append("name=").append(name); + } + builder.append("]"); + return builder.toString(); + } +} diff --git a/openvidu-client/src/main/java/org/openvidu/client/internal/ProtocolElements.java b/openvidu-client/src/main/java/org/openvidu/client/internal/ProtocolElements.java new file mode 100644 index 00000000..edf6815f --- /dev/null +++ b/openvidu-client/src/main/java/org/openvidu/client/internal/ProtocolElements.java @@ -0,0 +1,102 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.client.internal; + +/** + * This class defines constant values of client-server messages and their parameters. + * + * @author Radu Tom Vlad + */ +public class ProtocolElements { + + // ---------------------------- CLIENT REQUESTS ----------------------- + + public static final String SENDMESSAGE_ROOM_METHOD = "sendMessage"; + public static final String SENDMESSAGE_USER_PARAM = "userMessage"; + public static final String SENDMESSAGE_ROOM_PARAM = "roomMessage"; + public static final String SENDMESSAGE_MESSAGE_PARAM = "message"; + + public static final String LEAVEROOM_METHOD = "leaveRoom"; + + public static final String JOINROOM_METHOD = "joinRoom"; + public static final String JOINROOM_USER_PARAM = "user"; + public static final String JOINROOM_ROOM_PARAM = "room"; + public static final String JOINROOM_DATACHANNELS_PARAM = "dataChannels"; + public static final String JOINROOM_PEERID_PARAM = "id"; + public static final String JOINROOM_PEERSTREAMS_PARAM = "streams"; + public static final String JOINROOM_PEERSTREAMID_PARAM = "id"; + + public static final String PUBLISHVIDEO_METHOD = "publishVideo"; + public static final String PUBLISHVIDEO_SDPOFFER_PARAM = "sdpOffer"; + public static final String PUBLISHVIDEO_DOLOOPBACK_PARAM = "doLoopback"; + public static final String PUBLISHVIDEO_SDPANSWER_PARAM = "sdpAnswer"; + + public static final String UNPUBLISHVIDEO_METHOD = "unpublishVideo"; + + public static final String RECEIVEVIDEO_METHOD = "receiveVideoFrom"; + public static final String RECEIVEVIDEO_SDPOFFER_PARAM = "sdpOffer"; + public static final String RECEIVEVIDEO_SENDER_PARAM = "sender"; + public static final String RECEIVEVIDEO_SDPANSWER_PARAM = "sdpAnswer"; + + public static final String UNSUBSCRIBEFROMVIDEO_METHOD = "unsubscribeFromVideo"; + public static final String UNSUBSCRIBEFROMVIDEO_SENDER_PARAM = "sender"; + + public static final String ONICECANDIDATE_METHOD = "onIceCandidate"; + public static final String ONICECANDIDATE_EPNAME_PARAM = "endpointName"; + public static final String ONICECANDIDATE_CANDIDATE_PARAM = "candidate"; + public static final String ONICECANDIDATE_SDPMIDPARAM = "sdpMid"; + public static final String ONICECANDIDATE_SDPMLINEINDEX_PARAM = "sdpMLineIndex"; + + public static final String CUSTOMREQUEST_METHOD = "customRequest"; + + // ---------------------------- SERVER RESPONSES & EVENTS ----------------- + + public static final String PARTICIPANTJOINED_METHOD = "participantJoined"; + public static final String PARTICIPANTJOINED_USER_PARAM = "id"; + + public static final String PARTICIPANTLEFT_METHOD = "participantLeft"; + public static final String PARTICIPANTLEFT_NAME_PARAM = "name"; + + public static final String PARTICIPANTEVICTED_METHOD = "participantEvicted"; + + public static final String PARTICIPANTPUBLISHED_METHOD = "participantPublished"; + public static final String PARTICIPANTPUBLISHED_USER_PARAM = "id"; + public static final String PARTICIPANTPUBLISHED_STREAMS_PARAM = "streams"; + public static final String PARTICIPANTPUBLISHED_STREAMID_PARAM = "id"; + + public static final String PARTICIPANTUNPUBLISHED_METHOD = "participantUnpublished"; + public static final String PARTICIPANTUNPUBLISHED_NAME_PARAM = "name"; + + public static final String PARTICIPANTSENDMESSAGE_METHOD = "sendMessage"; + public static final String PARTICIPANTSENDMESSAGE_USER_PARAM = "user"; + public static final String PARTICIPANTSENDMESSAGE_ROOM_PARAM = "room"; + public static final String PARTICIPANTSENDMESSAGE_MESSAGE_PARAM = "message"; + + public static final String ROOMCLOSED_METHOD = "roomClosed"; + public static final String ROOMCLOSED_ROOM_PARAM = "room"; + + public static final String MEDIAERROR_METHOD = "mediaError"; + public static final String MEDIAERROR_ERROR_PARAM = "error"; + + public static final String ICECANDIDATE_METHOD = "iceCandidate"; + public static final String ICECANDIDATE_EPNAME_PARAM = "endpointName"; + public static final String ICECANDIDATE_CANDIDATE_PARAM = "candidate"; + public static final String ICECANDIDATE_SDPMID_PARAM = "sdpMid"; + public static final String ICECANDIDATE_SDPMLINEINDEX_PARAM = "sdpMLineIndex"; + + public static final String CUSTOM_NOTIFICATION = "custonNotification"; +} diff --git a/openvidu-client/src/main/java/org/openvidu/client/internal/RoomClosedInfo.java b/openvidu-client/src/main/java/org/openvidu/client/internal/RoomClosedInfo.java new file mode 100644 index 00000000..15f9eef1 --- /dev/null +++ b/openvidu-client/src/main/java/org/openvidu/client/internal/RoomClosedInfo.java @@ -0,0 +1,54 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.client.internal; + +/** + * @see Notification + * + * @author Radu Tom Vlad + */ +public class RoomClosedInfo extends Notification { + + private String room; + + public RoomClosedInfo(String room) { + super(ProtocolElements.ROOMCLOSED_METHOD); + this.room = room; + } + + public String getRoom() { + return room; + } + + public void setRoom(String room) { + this.room = room; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("["); + if (getMethod() != null) { + builder.append("method=").append(getMethod()).append(", "); + } + if (room != null) { + builder.append("room=").append(room); + } + builder.append("]"); + return builder.toString(); + } +} diff --git a/openvidu-client/src/main/java/org/openvidu/client/internal/SendMessageInfo.java b/openvidu-client/src/main/java/org/openvidu/client/internal/SendMessageInfo.java new file mode 100644 index 00000000..f4ea8acd --- /dev/null +++ b/openvidu-client/src/main/java/org/openvidu/client/internal/SendMessageInfo.java @@ -0,0 +1,80 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.client.internal; + +/** + * @see Notification + * + * @author Radu Tom Vlad + */ +public class SendMessageInfo extends Notification { + + private String room; + private String user; + private String message; + + public SendMessageInfo(String room, String user, String message) { + super(ProtocolElements.PARTICIPANTSENDMESSAGE_METHOD); + this.room = room; + this.user = user; + this.message = message; + } + + public String getRoom() { + return room; + } + + public void setRoom(String room) { + this.room = room; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("["); + if (getMethod() != null) { + builder.append("method=").append(getMethod()).append(", "); + } + if (room != null) { + builder.append("room=").append(room).append(", "); + } + if (user != null) { + builder.append("user=").append(user).append(", "); + } + if (message != null) { + builder.append("message=").append(message); + } + builder.append("]"); + return builder.toString(); + } +} diff --git a/openvidu-client/src/test/java/org/openvidu/client/test/OpenViduClientTest.java b/openvidu-client/src/test/java/org/openvidu/client/test/OpenViduClientTest.java new file mode 100644 index 00000000..98300db2 --- /dev/null +++ b/openvidu-client/src/test/java/org/openvidu/client/test/OpenViduClientTest.java @@ -0,0 +1,73 @@ +/* + * (C) Copyright 2016 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openvidu.client.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.openvidu.client.internal.ProtocolElements.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.kurento.jsonrpc.client.JsonRpcClient; +import org.openvidu.client.OpenViduClient; +import org.openvidu.client.ServerJsonRpcHandler; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; + +/** + * Unit tests for the room client protocol. + * + * @author Radu Tom Vlad (rvlad@naevatec.com) + * @since 6.3.1 + */ +public class OpenViduClientTest { + + private OpenViduClient client; + private ServerJsonRpcHandler serverHandler; + private JsonRpcClient jsonRpcClient; + + @Before + public void setup() { + jsonRpcClient = mock(JsonRpcClient.class); + serverHandler = new ServerJsonRpcHandler(); + client = new OpenViduClient(jsonRpcClient, serverHandler); + } + + @Test + public void testRoomJoin() throws IOException { + JsonObject params = new JsonObject(); + params.addProperty(JOINROOM_ROOM_PARAM, "room"); + params.addProperty(JOINROOM_USER_PARAM, "user"); + + JsonObject result = new JsonObject(); + JsonArray value = new JsonArray(); + result.add("value", value); + + Map> joinResult = new HashMap>(); + + when(jsonRpcClient.sendRequest(JOINROOM_METHOD, params)).thenReturn(result); + assertThat(client.joinRoom("room", "user", null), is(joinResult)); + + } +} diff --git a/openvidu-demo/.bowerrc b/openvidu-demo/.bowerrc new file mode 100644 index 00000000..9e00ce04 --- /dev/null +++ b/openvidu-demo/.bowerrc @@ -0,0 +1,3 @@ +{ + "directory" : "static/bower_components" +} diff --git a/openvidu-demo/.classpath b/openvidu-demo/.classpath new file mode 100644 index 00000000..7e4ca5cd --- /dev/null +++ b/openvidu-demo/.classpath @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/openvidu-demo/.gitignore b/openvidu-demo/.gitignore new file mode 100644 index 00000000..b83d2226 --- /dev/null +++ b/openvidu-demo/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/openvidu-demo/.project b/openvidu-demo/.project new file mode 100644 index 00000000..f160dbb4 --- /dev/null +++ b/openvidu-demo/.project @@ -0,0 +1,23 @@ + + + kurento-room-demo + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/openvidu-demo/.settings/org.eclipse.core.resources.prefs b/openvidu-demo/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 00000000..29abf999 --- /dev/null +++ b/openvidu-demo/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,6 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/main/resources=UTF-8 +encoding//src/test/java=UTF-8 +encoding//src/test/resources=UTF-8 +encoding/=UTF-8 diff --git a/openvidu-demo/.settings/org.eclipse.jdt.core.prefs b/openvidu-demo/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000..714351ae --- /dev/null +++ b/openvidu-demo/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,5 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/openvidu-demo/.settings/org.eclipse.m2e.core.prefs b/openvidu-demo/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 00000000..f897a7f1 --- /dev/null +++ b/openvidu-demo/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/openvidu-demo/LICENSE b/openvidu-demo/LICENSE new file mode 100644 index 00000000..7a4a3ea2 --- /dev/null +++ b/openvidu-demo/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/openvidu-demo/NOTICE b/openvidu-demo/NOTICE new file mode 100644 index 00000000..b7393e6f --- /dev/null +++ b/openvidu-demo/NOTICE @@ -0,0 +1,13 @@ +(C) Copyright 2016 Kurento (http://kurento.org) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/openvidu-demo/README.md b/openvidu-demo/README.md new file mode 100644 index 00000000..fecbe5af --- /dev/null +++ b/openvidu-demo/README.md @@ -0,0 +1,125 @@ +[![License badge](https://img.shields.io/badge/license-Apache2-orange.svg)](http://www.apache.org/licenses/LICENSE-2.0) +[![Documentation badge](https://readthedocs.org/projects/fiware-orion/badge/?version=latest)](http://doc-kurento-room.readthedocs.org/en/latest/) +[![Docker badge](https://img.shields.io/docker/pulls/fiware/orion.svg)](https://hub.docker.com/r/fiware/stream-oriented-kurento/) +[![Support badge]( https://img.shields.io/badge/support-sof-yellowgreen.svg)](http://stackoverflow.com/questions/tagged/kurento) + +[![][KurentoImage]][Kurento] + +Copyright © 2013-2016 [Kurento]. Licensed under [Apache 2.0 License]. + +kurento-room-demo +================= + +Kurento Room Demo implements the group communications with WebRTC using +services from Kurento Room Server. + +The client-side implementation of this demo application is an AngularJS module +that uses the KurentoRoom.js library from the room server package. +It also integrates the room server's Spring application for the server-side +of the Room API. This API is made up of the Room SDK and the signaling +component. For client-server communications the API uses JSON-RPC messages +over WebSockets. + + +What is Kurento +--------------- + +Kurento is an open source software project providing a platform suitable +for creating modular applications with advanced real-time communication +capabilities. For knowing more about Kurento, please visit the Kurento +project website: http://www.kurento.org. + +Kurento is part of [FIWARE]. For further information on the relationship of +FIWARE and Kurento check the [Kurento FIWARE Catalog Entry] + +Kurento is part of the [NUBOMEDIA] research initiative. + +Documentation +------------- + +The Kurento project provides detailed [documentation] including tutorials, +installation and development guides. A simplified version of the documentation +can be found on [readthedocs.org]. The [Open API specification] a.k.a. Kurento +Protocol is also available on [apiary.io]. + +Source +------ + +Code for other Kurento projects can be found in the [GitHub Kurento Group]. + +News and Website +---------------- + +Check the [Kurento blog] +Follow us on Twitter @[kurentoms]. + +Issue tracker +------------- + +Issues and bug reports should be posted to the [GitHub Kurento bugtracker] + +Licensing and distribution +-------------------------- + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contribution policy +------------------- + +You can contribute to the Kurento community through bug-reports, bug-fixes, new +code or new documentation. For contributing to the Kurento community, drop a +post to the [Kurento Public Mailing List] providing full information about your +contribution and its value. In your contributions, you must comply with the +following guidelines + +* You must specify the specific contents of your contribution either through a + detailed bug description, through a pull-request or through a patch. +* You must specify the licensing restrictions of the code you contribute. +* For newly created code to be incorporated in the Kurento code-base, you must + accept Kurento to own the code copyright, so that its open source nature is + guaranteed. +* You must justify appropriately the need and value of your contribution. The + Kurento project has no obligations in relation to accepting contributions + from third parties. +* The Kurento project leaders have the right of asking for further + explanations, tests or validations of any code contributed to the community + before it being incorporated into the Kurento code-base. You must be ready to + addressing all these kind of concerns before having your code approved. + +Support +------- + +The Kurento project provides community support through the [Kurento Public +Mailing List] and through [StackOverflow] using the tags *kurento* and +*fiware-kurento*. + +Before asking for support, please read first the [Kurento Netiquette Guidelines] + +[documentation]: http://www.kurento.org/documentation +[FIWARE]: http://www.fiware.org +[GitHub Kurento bugtracker]: https://github.com/Kurento/bugtracker/issues +[GitHub Kurento Group]: https://github.com/kurento +[kurentoms]: http://twitter.com/kurentoms +[Kurento]: http://kurento.org +[Kurento Blog]: http://www.kurento.org/blog +[Kurento FIWARE Catalog Entry]: http://catalogue.fiware.org/enablers/stream-oriented-kurento +[Kurento Netiquette Guidelines]: http://www.kurento.org/blog/kurento-netiquette-guidelines +[Kurento Public Mailing list]: https://groups.google.com/forum/#!forum/kurento +[KurentoImage]: https://secure.gravatar.com/avatar/21a2a12c56b2a91c8918d5779f1778bf?s=120 +[Apache 2.0 License]: http://www.apache.org/licenses/LICENSE-2.0 +[NUBOMEDIA]: http://www.nubomedia.eu +[StackOverflow]: http://stackoverflow.com/search?q=kurento +[Read-the-docs]: http://read-the-docs.readthedocs.org/ +[readthedocs.org]: http://kurento.readthedocs.org/ +[Open API specification]: http://kurento.github.io/doc-kurento/ +[apiary.io]: http://docs.streamoriented.apiary.io/ diff --git a/openvidu-demo/package/README.md b/openvidu-demo/package/README.md new file mode 100644 index 00000000..a0989dc7 --- /dev/null +++ b/openvidu-demo/package/README.md @@ -0,0 +1,35 @@ +[![License badge](https://img.shields.io/badge/license-Apache2-orange.svg)](http://www.apache.org/licenses/LICENSE-2.0) +[![Documentation badge](https://readthedocs.org/projects/fiware-orion/badge/?version=latest)](http://doc-kurento.readthedocs.org/en/latest/) +[![Docker badge](https://img.shields.io/docker/pulls/fiware/orion.svg)](https://hub.docker.com/r/fiware/stream-oriented-kurento/) +[![Support badge]( https://img.shields.io/badge/support-sof-yellowgreen.svg)](http://stackoverflow.com/questions/tagged/kurento) + +${project.name} +====================== + +The ${project.name} implements multimedia group communications with WebRTC using services from +Kurento Room Server. + +There are complete instructions on how to deploy the demo binary: +http://doc-kurento-room.readthedocs.org/en/current/demo_deployment.html + +Installation instructions +------------------------- + +By running `sudo ./bin/install.sh`, the jar file containing the demo will be copied into +_/var/lib/kurento_, and the startup script will be put in _/etc/init.d/${project.artifactId}_. Once +the demo is installed, it can be managed as a regular service with + +``` +sudo service ${project.artifactId} {start|stop|restart} +``` +If you want to change the port, you can do so by editing the file _/etc/kurento/${project.artifactId}.properties_. + +Quick start instructions +------------------------ + +By running `./bin/start.sh` the jar file containing the demo will be started right away, from the +_files/_ folder. + +Press `Control-C` to stop its execution. + +If you want to change the port, you can do so by editing the file _files/${project.artifactId}.properties_. diff --git a/openvidu-demo/package/bin/install.sh b/openvidu-demo/package/bin/install.sh new file mode 100755 index 00000000..be667441 --- /dev/null +++ b/openvidu-demo/package/bin/install.sh @@ -0,0 +1,50 @@ +#!/bin/bash + +# ${project.description} installer for Ubuntu >= 14.04 +if [ `id -u` -ne 0 ]; then + echo "" + echo "Only root can install Kurento" + echo "" + exit 1 +fi + +echo "Installing kurento-room-sfu-demo" + +APP_HOME=$(dirname $(dirname $(readlink -f $0))) +APP_NAME=${project.artifactId} + +useradd -d /var/kurento/ kurento + +SYSTEMD=$(pidof systemd && echo "systemd" || echo "other") + +# Install binaries +mkdir -p /var/lib/kurento +chown kurento /var/lib/kurento +install -o kurento -g root $APP_HOME/lib/$APP_NAME.jar /var/lib/kurento/ +install -o kurento -g root $APP_HOME/config/$APP_NAME.conf /var/lib/kurento/ +install -o kurento -g root $APP_HOME/config/$APP_NAME.properties /var/lib/kurento/ +install -o kurento -g root $APP_HOME/support-files/keystore.jks /var/lib/kurento/ +ln -s /var/lib/kurento/$APP_NAME.jar /etc/init.d/$APP_NAME +chmod 755 /etc/init.d/$APP_NAME + +mkdir -p /etc/kurento/ +install -o kurento -g root $APP_HOME/config/app.conf.json /etc/kurento/$APP_NAME.conf.json +install -o kurento -g root $APP_HOME/support-files/log4j.properties /etc/kurento/$APP_NAME-log4j.properties + +mkdir -p /var/log/kurento +chown kurento /var/log/kurento + + +if [[ "$SYSTEMD" != "other" ]]; then + install -o root -g root $APP_HOME/support-files/systemd.service /etc/systemd/system/$APP_NAME.service + sudo systemctl daemon-reload + # enable at startup + [ -z "$NOENABLE" ] && systemctl enable $APP_NAME || echo "App not enabled" + # start service + [ -z "$NOSTART" ] && systemctl start $APP_NAME || echo "App not started" +else + # enable at startup + [ -z "$NOENABLE" ] && update-rc.d $APP_NAME defaults || echo "App not enabled" + # start service + [ -z "$NOSTART" ] && service $APP_NAME start || echo "App not started" +fi diff --git a/openvidu-demo/package/config/app.conf.json b/openvidu-demo/package/config/app.conf.json new file mode 100644 index 00000000..e7872179 --- /dev/null +++ b/openvidu-demo/package/config/app.conf.json @@ -0,0 +1,50 @@ +{ + "kms": { + "uris": ["ws://localhost:8888/kurento", "ws://127.0.0.1:8888/kurento"] + }, + "app": { + //has to accessible from the KMS in order to load filter imgs + "uri": "https://localhost:8443/" + }, + "kurento": { + "client": { + //milliseconds + "requestTimeout": 20000 + } + }, + "demo": { + //marker or hat + "filterType" : "marker", + + //markerdetector img(s) in order of preference + "markerUrls": { + "0": "kurento-rect-logo.png", + "1": "twi-logo.png" + }, + + //mario-wings.png or wizard.png + "hatUrl": "mario-wings.png", + "hatCoords": { + // mario-wings hat + "offsetXPercent": -0.35F, + "offsetYPercent": -1.2F, + "widthPercent": 1.6F, + "heightPercent": 1.6F + + //wizard hat + //"offsetXPercent": -0.2F, + //"offsetYPercent": -1.35F, + //"widthPercent": 1.5F, + //"heightPercent": 1.5F + }, + "loopback" : { + "remote": true, + //matters only when remote is true + "andLocal": false + }, + "authRegex": ".*", + "kmsLimit": 1000 + }, + "updateSpeakerInterval": 1800, + "thresholdSpeaker": -50 +} diff --git a/openvidu-demo/package/config/application.conf b/openvidu-demo/package/config/application.conf new file mode 100755 index 00000000..aab3f645 --- /dev/null +++ b/openvidu-demo/package/config/application.conf @@ -0,0 +1,4 @@ +APP_NAME=${project.artifactId} +LOG_FOLDER=/var/log/kurento +LOG_FILENAME=boot.log +JAVA_OPTS="-Dspring.config.location=file:/var/lib/kurento/${project.artifactId}.properties -DconfigFilePath=/etc/kurento/${project.artifactId}.conf.json -Dlogging.config=/etc/kurento/${project.artifactId}-log4j.properties -XX:+HeapDumpOnOutOfMemoryError" \ No newline at end of file diff --git a/openvidu-demo/package/config/application.properties b/openvidu-demo/package/config/application.properties new file mode 100644 index 00000000..3996cc67 --- /dev/null +++ b/openvidu-demo/package/config/application.properties @@ -0,0 +1,7 @@ +server.port: 8443 +server.address: 0.0.0.0 +server.ssl.key-store: keystore.jks +server.ssl.key-store-password: kurento +server.ssl.keyStoreType: JKS +server.ssl.keyAlias: kurento-selfsigned +server.context-path: / \ No newline at end of file diff --git a/openvidu-demo/package/support-files/keystore.jks b/openvidu-demo/package/support-files/keystore.jks new file mode 100644 index 00000000..c13f8038 Binary files /dev/null and b/openvidu-demo/package/support-files/keystore.jks differ diff --git a/openvidu-demo/package/support-files/log4j.properties b/openvidu-demo/package/support-files/log4j.properties new file mode 100644 index 00000000..54432425 --- /dev/null +++ b/openvidu-demo/package/support-files/log4j.properties @@ -0,0 +1,17 @@ +log4j.rootLogger=INFO,CONSOLE +log4j.logger.org.kurento=DEBUG + +# Appenders +log4j.threshold=ALL + +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-5p %c [%t] (%F:%L) - %m%n + +log4j.appender.file=org.apache.log4j.RollingFileAppender +log4j.appender.file.File=${application.log.file} +log4j.appender.file.ImmediateFlush=true +log4j.appender.file.MaxFileSize=10MB +log4j.appender.file.MaxBackupIndex=50 +log4j.appender.file.layout=org.apache.log4j.PatternLayout +log4j.appender.file.layout.ConversionPattern=%d{ISO8601} %-5p [%t] %c{2} (%M(%L)) - %m%n \ No newline at end of file diff --git a/openvidu-demo/package/support-files/systemd.service b/openvidu-demo/package/support-files/systemd.service new file mode 100644 index 00000000..6352b11c --- /dev/null +++ b/openvidu-demo/package/support-files/systemd.service @@ -0,0 +1,9 @@ +[Unit] +Description=${project.description} + +[Service] +User=kurento +ExecStart=/var/lib/kurento/${project.artifactId}.jar run + +[Install] +WantedBy=multi-user.target diff --git a/openvidu-demo/pom.xml b/openvidu-demo/pom.xml new file mode 100644 index 00000000..64205024 --- /dev/null +++ b/openvidu-demo/pom.xml @@ -0,0 +1,234 @@ + + 4.0.0 + + + org.openvidu + openvidu + 6.6.1-SNAPSHOT + + openvidu-demo + jar + + Kurento Room Demo + Kurento Room Demo application + http://www.kurento.org/docs/${project.version} + + + + Apache 2.0 + http://www.apache.org/licenses/LICENSE-2.0 + repo + + + + + Kurento + http://www.kurento.org + + + + ${openvidu.scm.url} + scm:git:${openvidu.scm.connection} + scm:git:${openvidu.scm.connection} + develop + + + + + kurento.org + -kurento.org Community + Kurento.org + http://www.kurento.org + + + + + + org.openvidu.room.demo.KurentoRoomDemoApp + + + + + org.openvidu + openvidu-server + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.openvidu + openvidu-client-js + + + org.openvidu + openvidu-test + test + + + org.kurento.module + markerdetector + + + org.springframework.boot + spring-boot-starter-log4j2 + + + + org.webjars + webjars-locator + + + org.webjars.bower + jquery + 2.2.4 + + + org.webjars + jquery-ui + 1.11.4 + + + org.webjars.bower + angular + 1.5.7 + + + org.webjars.bower + angular-route + 1.5.7 + + + org.webjars.bower + angular-fullscreen + 1.0.1 + + + org.webjars.bower + material-design-iconic-font + 1.1.1 + + + org.webjars.bower + lumx + 0.2.50 + + + org.webjars.bower + angular-clipboard + 1.4.2 + + + + + + + + src/main/resources + false + + + src/main/resources + true + + banner.txt + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + ${start-class} + ZIP + true + + + + + repackage + + + + + + + + org.codehaus.mojo + exec-maven-plugin + + ${start-class} + + + + + org.apache.maven.plugins + maven-assembly-plugin + + src/assembly/bin.xml + ${project.artifactId}-${project.version} + false + + + + package + + single + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + package + + + + + + + + + + + + + + default + + true + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + org.apache.maven.plugins + maven-failsafe-plugin + + true + + + + + + + integration + + + diff --git a/openvidu-demo/src/assembly/bin.xml b/openvidu-demo/src/assembly/bin.xml new file mode 100644 index 00000000..7a2b1311 --- /dev/null +++ b/openvidu-demo/src/assembly/bin.xml @@ -0,0 +1,50 @@ + + bin + + zip + + false + + + + target/${project.artifactId}-${project.version}.jar + lib + ${project.artifactId}.jar + + + package/config/application.conf + + config/${project.artifactId}.conf + true + + + package/config/application.properties + + config/${project.artifactId}.properties + true + + + package/support-files/keystore.jks + + support-files/keystore.jks + false + + + + + + package + + + config/application.conf + config/application.properties + support-files/keystore.jks + + true + + + + diff --git a/openvidu-demo/src/main/java/org/openvidu/demo/ClientConfig.java b/openvidu-demo/src/main/java/org/openvidu/demo/ClientConfig.java new file mode 100644 index 00000000..8a0c1cad --- /dev/null +++ b/openvidu-demo/src/main/java/org/openvidu/demo/ClientConfig.java @@ -0,0 +1,55 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.demo; + +class ClientConfig { + private boolean loopbackRemote; + private boolean loopbackAndLocal; + private String filterRequestParam; + + public boolean isLoopbackRemote() { + return loopbackRemote; + } + + public void setLoopbackRemote(boolean loopbackRemote) { + this.loopbackRemote = loopbackRemote; + } + + public boolean isLoopbackAndLocal() { + return loopbackAndLocal; + } + + public void setLoopbackAndLocal(boolean loopbackAndLocal) { + this.loopbackAndLocal = loopbackAndLocal; + } + + public String getFilterRequestParam() { + return filterRequestParam; + } + + public void setFilterRequestParam(String filterRequestParam) { + this.filterRequestParam = filterRequestParam; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Loopback [remote=").append(loopbackRemote).append(", andLocal=") + .append(loopbackAndLocal).append("], filterRequestParam=").append(filterRequestParam); + return builder.toString(); + } +} diff --git a/openvidu-demo/src/main/java/org/openvidu/demo/DemoController.java b/openvidu-demo/src/main/java/org/openvidu/demo/DemoController.java new file mode 100644 index 00000000..b01d652a --- /dev/null +++ b/openvidu-demo/src/main/java/org/openvidu/demo/DemoController.java @@ -0,0 +1,90 @@ +/* + * (C) Copyright 2016 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.openvidu.demo; + +import org.kurento.commons.PropertiesManager; +import org.openvidu.client.OpenViduException; +import org.openvidu.server.core.NotificationRoomManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +/** + * Rest controller for the room demo app. + * + * @author Radu Tom Vlad (rvlad@naevatec.com) + * @since 6.0.0 + */ +@RestController +public class DemoController { + + private static final Logger log = LoggerFactory.getLogger(DemoController.class); + + private final static boolean DEMO_LOOPBACK_REMOTE = PropertiesManager + .getProperty("demo.loopback.remote", false); + private final static boolean DEMO_LOOPBACK_AND_LOCAL = PropertiesManager + .getProperty("demo.loopback.andLocal", false); + + private static ClientConfig config; + + static { + config = new ClientConfig(); + config.setLoopbackRemote(DEMO_LOOPBACK_REMOTE); + config.setLoopbackAndLocal(DEMO_LOOPBACK_AND_LOCAL); + config.setFilterRequestParam( + KmsFilterType.parseType(OpenViduSampleApp.DEMO_FILTER_TYPE).getCustomRequestParam()); + log.info("Set client config: {}", config); + } + + @Autowired + private NotificationRoomManager roomManager; + + @ResponseStatus(value = HttpStatus.NOT_FOUND) + public class ResourceNotFoundException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public ResourceNotFoundException(String msg) { + super(msg); + } + } + + @RequestMapping("/close") + public void closeRoom(@RequestParam("room") String room) { + log.warn("Trying to close the room '{}'", room); + if (!roomManager.getRooms().contains(room)) { + log.warn("Unable to close room '{}', not found.", room); + throw new ResourceNotFoundException("Room '" + room + "' not found"); + } + try { + roomManager.closeRoom(room); + } catch (OpenViduException e) { + log.warn("Error closing room {}", room, e); + throw new ResourceNotFoundException(e.getMessage()); + } + } + + @RequestMapping("/getClientConfig") + public ClientConfig clientConfig() { + log.debug("Sending client config {}", config); + return config; + } +} diff --git a/openvidu-demo/src/main/java/org/openvidu/demo/DemoJsonRpcUserControl.java b/openvidu-demo/src/main/java/org/openvidu/demo/DemoJsonRpcUserControl.java new file mode 100644 index 00000000..820df4c3 --- /dev/null +++ b/openvidu-demo/src/main/java/org/openvidu/demo/DemoJsonRpcUserControl.java @@ -0,0 +1,169 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.demo; + +import java.io.IOException; +import java.util.SortedMap; + +import org.kurento.client.FaceOverlayFilter; +import org.kurento.client.MediaElement; +import org.kurento.jsonrpc.Transaction; +import org.kurento.jsonrpc.message.Request; +import org.openvidu.server.core.NotificationRoomManager; +import org.openvidu.server.core.api.pojo.ParticipantRequest; +import org.openvidu.server.rpc.JsonRpcUserControl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.JsonObject; + +/** + * User control that applies a media filter when publishing video. + * + * @author Radu Tom Vlad (rvlad@naevatec.com) + */ +public class DemoJsonRpcUserControl extends JsonRpcUserControl { + + private static final String SESSION_ATTRIBUTE_FILTER = "customFilter"; + private static final String MARKER_ID = "markerFilterId"; + + private static final Logger log = LoggerFactory.getLogger(DemoJsonRpcUserControl.class); + + private KmsFilterType filterType = KmsFilterType.HAT; + + private String hatUrl; + private float offsetXPercent; + private float offsetYPercent; + private float widthPercent; + private float heightPercent; + + private SortedMap markerUrls; + + public DemoJsonRpcUserControl(NotificationRoomManager roomManager) { + super(roomManager); + } + + public void setFilterType(KmsFilterType type) { + this.filterType = type; + } + + public void setHatUrl(String hatUrl) { + this.hatUrl = hatUrl; + log.info("Hat URL: {}", hatUrl); + } + + public void setMarkerUrls(SortedMap urls) { + this.markerUrls = urls; + log.info("Marker URL: {}", markerUrls); + } + + public void setHatCoords(JsonObject hatCoords) { + if (hatCoords.get("offsetXPercent") != null) { + offsetXPercent = hatCoords.get("offsetXPercent").getAsFloat(); + } + if (hatCoords.get("offsetYPercent") != null) { + offsetYPercent = hatCoords.get("offsetYPercent").getAsFloat(); + } + if (hatCoords.get("widthPercent") != null) { + widthPercent = hatCoords.get("widthPercent").getAsFloat(); + } + if (hatCoords.get("heightPercent") != null) { + heightPercent = hatCoords.get("heightPercent").getAsFloat(); + } + log.info("Hat coords:\n\toffsetXPercent = {}\n\toffsetYPercent = {}" + + "\n\twidthPercent = {}\n\theightPercent = {}", offsetXPercent, offsetYPercent, + widthPercent, heightPercent); + } + + @Override + public void customRequest(Transaction transaction, Request request, + ParticipantRequest participantRequest) { + try { + if (request.getParams() == null + || request.getParams().get(filterType.getCustomRequestParam()) == null) { + throw new RuntimeException( + "Request element '" + filterType.getCustomRequestParam() + "' is missing"); + } + switch (filterType) { + case MARKER: + handleMarkerRequest(transaction, request, participantRequest); + break; + case HAT: + default: + handleHatRequest(transaction, request, participantRequest); + } + } catch (Exception e) { + log.error("Unable to handle custom request", e); + try { + transaction.sendError(e); + } catch (IOException e1) { + log.warn("Unable to send error response", e1); + } + } + } + + private void handleHatRequest(Transaction transaction, Request request, + ParticipantRequest participantRequest) throws IOException { + boolean filterOn = request.getParams().get(filterType.getCustomRequestParam()).getAsBoolean(); + String pid = participantRequest.getParticipantId(); + if (filterOn) { + if (transaction.getSession().getAttributes().containsKey(SESSION_ATTRIBUTE_FILTER)) { + throw new RuntimeException(filterType + " filter already on"); + } + log.info("Applying {} filter to session {}", filterType, pid); + + FaceOverlayFilter filter = + new FaceOverlayFilter.Builder(roomManager.getPipeline(pid)).build(); + filter.setOverlayedImage(this.hatUrl, this.offsetXPercent, this.offsetYPercent, + this.widthPercent, this.heightPercent); + + addFilter(transaction, pid, filter); + } else { + removeFilter(transaction, pid); + } + transaction.sendResponse(new JsonObject()); + } + + private void handleMarkerRequest(final Transaction transaction, Request request, + ParticipantRequest participantRequest) throws IOException { + Integer currentUrlIndex = + request.getParams().get(filterType.getCustomRequestParam()).getAsInt(); + String pid = participantRequest.getParticipantId(); + + roomManager.updateFilter(roomManager.getRoomManager().getRoomName(pid), MARKER_ID); + + JsonObject result = new JsonObject(); + // TODO: Change RPC to remove next index requirement + // result.addProperty(filterType.getCustomRequestParam(), 0); + transaction.sendResponse(result); + } + + private void addFilter(Transaction transaction, String pid, MediaElement filter) { + roomManager.addMediaElement(pid, filter); + transaction.getSession().getAttributes().put(SESSION_ATTRIBUTE_FILTER, filter); + } + + private void removeFilter(Transaction transaction, String pid) { + if (!transaction.getSession().getAttributes().containsKey(SESSION_ATTRIBUTE_FILTER)) { + throw new RuntimeException("This user has no " + filterType + " filter yet"); + } + log.info("Removing {} filter from session {}", filterType, pid); + roomManager.removeMediaElement(pid, + (MediaElement) transaction.getSession().getAttributes().get(SESSION_ATTRIBUTE_FILTER)); + transaction.getSession().getAttributes().remove(SESSION_ATTRIBUTE_FILTER); + } +} diff --git a/openvidu-demo/src/main/java/org/openvidu/demo/DemoNotificationRoomHandler.java b/openvidu-demo/src/main/java/org/openvidu/demo/DemoNotificationRoomHandler.java new file mode 100644 index 00000000..8241a93a --- /dev/null +++ b/openvidu-demo/src/main/java/org/openvidu/demo/DemoNotificationRoomHandler.java @@ -0,0 +1,121 @@ +package org.openvidu.demo; + +import java.util.SortedMap; + +import org.kurento.client.Continuation; +import org.kurento.client.Filter; +import org.kurento.module.markerdetector.ArMarkerdetector; +import org.openvidu.client.internal.ProtocolElements; +import org.openvidu.server.core.api.UserNotificationService; +import org.openvidu.server.core.internal.DefaultNotificationRoomHandler; +import org.openvidu.server.core.internal.Participant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.JsonObject; + +public class DemoNotificationRoomHandler extends DefaultNotificationRoomHandler { + + private static final Logger log = LoggerFactory.getLogger(DemoNotificationRoomHandler.class); + private SortedMap markerUrls; + + private UserNotificationService notifService; + + public DemoNotificationRoomHandler(UserNotificationService notifService) { + super(notifService); + + this.notifService = notifService; + } + + @Override + public void updateFilter(String roomName, Participant participant, String filterId, + String state) { + Integer newState = -1; + + if (state != null) { + newState = Integer.parseInt(state); + } + + String url = markerUrls.get(newState); + + JsonObject notificationParams = new JsonObject(); + notificationParams.addProperty("MarkerFilterState", newState); + + notifService.sendNotification(participant.getId(), ProtocolElements.CUSTOM_NOTIFICATION, + notificationParams); + + ArMarkerdetector newFilter; + Filter filter = participant.getFilterElement(filterId); + + if (filter == null) { + newFilter = new ArMarkerdetector.Builder(participant.getPipeline()).build(); + log.info("New {} filter for participant {}", filterId, participant.getId()); + participant.addFilterElement(filterId, newFilter); + } else { + log.info("Reusing {} filter in participant {}", filterId, participant.getId()); + newFilter = (ArMarkerdetector) filter; + } + + if (url != null) { + newFilter.setOverlayImage(url, new Continuation() { + @Override + public void onSuccess(Void result) throws Exception { + + } + + @Override + public void onError(Throwable cause) throws Exception { + + } + }); + newFilter.setOverlayScale(1.0F, new Continuation() { + @Override + public void onSuccess(Void result) throws Exception { + + } + + @Override + public void onError(Throwable cause) throws Exception { + + } + }); + } else { + newFilter.setOverlayScale(0.0001F, new Continuation() { + @Override + public void onSuccess(Void result) throws Exception { + + } + + @Override + public void onError(Throwable cause) throws Exception { + + } + }); + } + } + + @Override + public String getNextFilterState(String filterId, String oldState) { + Integer currentUrlIndex; + + if (oldState == null) { + currentUrlIndex = -1; + } else { + currentUrlIndex = Integer.parseInt(oldState); + } + + Integer nextIndex = -1; // disable filter + + if (currentUrlIndex < markerUrls.firstKey()) { + nextIndex = markerUrls.firstKey(); // enable filter using first URL + } else if (currentUrlIndex < markerUrls.lastKey()) { + nextIndex = markerUrls.tailMap(currentUrlIndex + 1).firstKey(); + } + + return nextIndex.toString(); + } + + public void setMarkerUrls(SortedMap markerUrls) { + this.markerUrls = markerUrls; + } +} diff --git a/openvidu-demo/src/main/java/org/openvidu/demo/FixedNKmsManager.java b/openvidu-demo/src/main/java/org/openvidu/demo/FixedNKmsManager.java new file mode 100644 index 00000000..aba764b6 --- /dev/null +++ b/openvidu-demo/src/main/java/org/openvidu/demo/FixedNKmsManager.java @@ -0,0 +1,128 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.demo; + +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.kurento.client.KurentoClient; +import org.kurento.jsonrpc.Session; +import org.openvidu.client.OpenViduException; +import org.openvidu.server.core.internal.DefaultKurentoClientSessionInfo; +import org.openvidu.server.kms.Kms; +import org.openvidu.server.kms.KmsManager; +import org.openvidu.server.kms.MaxWebRtcLoadManager; +import org.openvidu.server.rpc.JsonRpcNotificationService; +import org.openvidu.server.rpc.ParticipantSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +/** + * KMS manager for the room demo app. + * + * @author Radu Tom Vlad (rvlad@naevatec.com) + * @since 6.0.0 + */ +public class FixedNKmsManager extends KmsManager { + private static final Logger log = LoggerFactory.getLogger(FixedNKmsManager.class); + + private String authRegex; + private static Pattern authPattern = null; + + @Autowired + private JsonRpcNotificationService notificationService; + + public FixedNKmsManager(List kmsWsUri) { + for (String uri : kmsWsUri) { + this.addKms(new Kms(KurentoClient.create(uri), uri)); + } + } + + public FixedNKmsManager(List kmsWsUri, int kmsLoadLimit) { + for (String uri : kmsWsUri) { + Kms kms = new Kms(KurentoClient.create(uri), uri); + kms.setLoadManager(new MaxWebRtcLoadManager(kmsLoadLimit)); + this.addKms(kms); + } + } + + public synchronized void setAuthRegex(String regex) { + this.authRegex = regex != null ? regex.trim() : null; + if (authRegex != null && !authRegex.isEmpty()) { + authPattern = Pattern.compile(authRegex, Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE); + } + } + + @Override + public synchronized Kms getKms(DefaultKurentoClientSessionInfo sessionInfo) { + String userName = null; + String participantId = sessionInfo.getParticipantId(); + Session session = notificationService.getSession(participantId); + if (session != null) { + Object sessionValue = session.getAttributes().get(ParticipantSession.SESSION_KEY); + if (sessionValue != null) { + ParticipantSession participantSession = (ParticipantSession) sessionValue; + userName = participantSession.getParticipantName(); + } + } + if (userName == null) { + log.warn("Unable to find user name in session {}", participantId); + throw new OpenViduException(OpenViduException.Code.ROOM_CANNOT_BE_CREATED_ERROR_CODE, + "Not enough information"); + } + if (!canCreateRoom(userName)) { + throw new OpenViduException(OpenViduException.Code.ROOM_CANNOT_BE_CREATED_ERROR_CODE, + "User cannot create a new room"); + } + Kms kms = null; + String type = ""; + boolean hq = isUserHQ(userName); + if (hq) { + kms = getLessLoadedKms(); + } else { + kms = getNextLessLoadedKms(); + if (!kms.allowMoreElements()) { + kms = getLessLoadedKms(); + } else { + type = "next "; + } + } + if (!kms.allowMoreElements()) { + log.debug( + "Was trying Kms which has no resources left: highQ={}, " + "{}less loaded KMS, uri={}", + hq, type, kms.getUri()); + throw new OpenViduException(OpenViduException.Code.ROOM_CANNOT_BE_CREATED_ERROR_CODE, + "No resources left to create new room"); + } + log.debug("Offering Kms: highQ={}, {}less loaded KMS, uri={}", hq, type, kms.getUri()); + return kms; + } + + private boolean isUserHQ(String userName) { + return userName.toLowerCase().startsWith("special"); + } + + private boolean canCreateRoom(String userName) { + if (authPattern == null) { + return true; + } + Matcher m = authPattern.matcher(userName); + return m.matches(); + } +} diff --git a/openvidu-demo/src/main/java/org/openvidu/demo/KmsFilterType.java b/openvidu-demo/src/main/java/org/openvidu/demo/KmsFilterType.java new file mode 100644 index 00000000..e4ef2b57 --- /dev/null +++ b/openvidu-demo/src/main/java/org/openvidu/demo/KmsFilterType.java @@ -0,0 +1,51 @@ +/* + * (C) Copyright 2016 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.openvidu.demo; + +/** + * @author Radu Tom Vlad (radutom.vlad@gmail.com) + * @since 6.5.1 + */ +public enum KmsFilterType { + HAT("hat", "hat"), MARKER("marker", "marker"); + + private String typeValue; + private String customRequestParam; + + private KmsFilterType(String val, String customRequestParam) { + this.typeValue = val; + this.customRequestParam = customRequestParam; + } + + public String getCustomRequestParam() { + return customRequestParam; + } + + /** + * @param val + * filter type String value, ignoring case + * @return the filter type, {@link #HAT} if none found + */ + public static KmsFilterType parseType(String val) { + for (KmsFilterType t : KmsFilterType.values()) { + if (t.typeValue.equalsIgnoreCase(val)) { + return t; + } + } + return HAT; + } +} diff --git a/openvidu-demo/src/main/java/org/openvidu/demo/OpenViduSampleApp.java b/openvidu-demo/src/main/java/org/openvidu/demo/OpenViduSampleApp.java new file mode 100644 index 00000000..5a525f3f --- /dev/null +++ b/openvidu-demo/src/main/java/org/openvidu/demo/OpenViduSampleApp.java @@ -0,0 +1,177 @@ +/* + * (C) Copyright 2014 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.demo; + +import java.util.List; +import java.util.Map.Entry; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.kurento.commons.ConfigFileManager; +import org.kurento.commons.PropertiesManager; +import org.kurento.jsonrpc.JsonUtils; +import org.openvidu.server.OpenViduServer; +import org.openvidu.server.core.NotificationRoomManager; +import org.openvidu.server.kms.KmsManager; +import org.openvidu.server.rpc.JsonRpcUserControl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.context.annotation.Bean; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import static org.kurento.commons.PropertiesManager.getPropertyJson; + +/** + * Demo application for Kurento Room, extends the Room Server application class. Uses the Room + * Client JS library for the web client, which is built with AngularJS and lumx. + * + * @author Micael Gallego (micael.gallego@gmail.com) + * @author Radu Tom Vlad (rvlad@naevatec.com) + * @since 5.0.0 + */ +public class OpenViduSampleApp extends OpenViduServer { + + private static final Logger log = LoggerFactory.getLogger(OpenViduSampleApp.class); + + public final static String KROOMDEMO_CFG_FILENAME = "kurento-room-demo.conf.json"; + + private static JsonObject DEFAULT_HAT_COORDS = new JsonObject(); + private static JsonObject DEFAULT_MARKER_URLS = new JsonObject(); + + static { + ConfigFileManager.loadConfigFile(KROOMDEMO_CFG_FILENAME); + DEFAULT_HAT_COORDS.addProperty("offsetXPercent", -0.35F); + DEFAULT_HAT_COORDS.addProperty("offsetYPercent", -1.2F); + DEFAULT_HAT_COORDS.addProperty("widthPercent", 1.6F); + DEFAULT_HAT_COORDS.addProperty("heightPercent", 1.6F); + + DEFAULT_MARKER_URLS.addProperty("0", "kurento-rect-logo.png"); + } + + private static final String IMG_FOLDER = "img/"; + + private final static String DEFAULT_APP_SERVER_URL = + PropertiesManager.getProperty("app.uri", "https://localhost:8443"); + private final static String APP_SERVER_URL = + System.getProperty("app.server.url", DEFAULT_APP_SERVER_URL); + + private final Integer DEMO_KMS_NODE_LIMIT = PropertiesManager.getProperty("demo.kmsLimit", 1000); + private final String DEMO_AUTH_REGEX = PropertiesManager.getProperty("demo.authRegex"); + + public final static String DEMO_FILTER_TYPE = + PropertiesManager.getProperty("demo.filterType", "hat"); + + private final String DEMO_HAT_URL = + PropertiesManager.getProperty("demo.hatUrl", "mario-wings.png"); + private final JsonObject DEMO_HAT_COORDS = PropertiesManager + .getPropertyJson("demo.hatCoords", DEFAULT_HAT_COORDS.toString(), JsonObject.class); + + private final JsonObject DEMO_MARKER_URLS = PropertiesManager + .getPropertyJson("demo.markerUrls", DEFAULT_MARKER_URLS.toString(), JsonObject.class); + + @Override + public KmsManager kmsManager() { + JsonArray kmsUris = getPropertyJson(OpenViduServer.KMSS_URIS_PROPERTY, + OpenViduServer.KMSS_URIS_DEFAULT, JsonArray.class); + List kmsWsUris = JsonUtils.toStringList(kmsUris); + + log.info("Configuring Kurento Room Server to use the following kmss: {}", kmsWsUris); + + FixedNKmsManager fixedKmsManager = new FixedNKmsManager(kmsWsUris, DEMO_KMS_NODE_LIMIT); + fixedKmsManager.setAuthRegex(DEMO_AUTH_REGEX); + log.debug("Authorization regex for new rooms: {}", DEMO_AUTH_REGEX); + return fixedKmsManager; + } + + @Override + public JsonRpcUserControl userControl() { + DemoJsonRpcUserControl uc = new DemoJsonRpcUserControl(roomManager()); + + KmsFilterType type = KmsFilterType.parseType(DEMO_FILTER_TYPE); + log.info("Configuring demo with filter type: {} (parsed is {})", DEMO_FILTER_TYPE, type); + + uc.setFilterType(type); + + switch (type) { + case MARKER: + SortedMap sortedUrls = new TreeMap<>(); + getMarkerUrls(sortedUrls); + uc.setMarkerUrls(sortedUrls); + break; + case HAT: + default: + uc.setHatUrl(getFullUrl(DEMO_HAT_URL)); + uc.setHatCoords(DEMO_HAT_COORDS); + } + + return uc; + } + + @Bean + public NotificationRoomManager roomManager() { + DemoNotificationRoomHandler notificationRoomHandler = + new DemoNotificationRoomHandler(notificationService()); + + KmsFilterType type = KmsFilterType.parseType(DEMO_FILTER_TYPE); + + switch (type) { + case MARKER: + SortedMap sortedUrls = new TreeMap<>(); + getMarkerUrls(sortedUrls); + + notificationRoomHandler.setMarkerUrls(sortedUrls); + break; + default: + } + + return new NotificationRoomManager(notificationRoomHandler, kmsManager()); + } + + private void getMarkerUrls(SortedMap sortedUrls) { + for (Entry entry : DEMO_MARKER_URLS.entrySet()) { + try { + Integer order = Integer.parseInt(entry.getKey()); + if (order < 0) { + throw new Exception("Illegal configuration, marker url index has to be positive"); + } + String url = entry.getValue().getAsString(); + sortedUrls.put(order, getFullUrl(url)); + } catch (Exception e) { + log.warn("Unable to process marker url [{}] from config file {}", entry, + KROOMDEMO_CFG_FILENAME, e); + } + } + } + + private static String getFullUrl(String url) { + if (APP_SERVER_URL.endsWith("/")) { + return APP_SERVER_URL + IMG_FOLDER + url; + } else { + return APP_SERVER_URL + "/" + IMG_FOLDER + url; + } + } + + public static void main(String[] args) throws Exception { + log.info("Using /dev/urandom for secure random generation"); + System.setProperty("java.security.egd", "file:/dev/./urandom"); + SpringApplication.run(OpenViduSampleApp.class, args); + } +} diff --git a/openvidu-demo/src/main/resources/application.properties b/openvidu-demo/src/main/resources/application.properties new file mode 100644 index 00000000..0dcc86e0 --- /dev/null +++ b/openvidu-demo/src/main/resources/application.properties @@ -0,0 +1,7 @@ +server.port: 8443 +server.address: 0.0.0.0 +server.ssl.key-store: classpath:keystore.jks +server.ssl.key-store-password: kurento +server.ssl.keyStoreType: JKS +server.ssl.keyAlias: kurento-selfsigned +server.context-path: / diff --git a/openvidu-demo/src/main/resources/banner.txt b/openvidu-demo/src/main/resources/banner.txt new file mode 100644 index 00000000..dd03e860 --- /dev/null +++ b/openvidu-demo/src/main/resources/banner.txt @@ -0,0 +1,9 @@ + + .------------------------------------. + | | + | | |/ / _ _ _ ___ _ _| |_ ___ | + | | ' < || | '_/ -_) ' \ _/ _ \ | + | |_|\_\_,_|_| \___|_||_\__\___/ | + | | + '------------------------------------' + version ${project.version} diff --git a/openvidu-demo/src/main/resources/keystore.jks b/openvidu-demo/src/main/resources/keystore.jks new file mode 100644 index 00000000..c13f8038 Binary files /dev/null and b/openvidu-demo/src/main/resources/keystore.jks differ diff --git a/openvidu-demo/src/main/resources/kurento-room-demo.conf.json b/openvidu-demo/src/main/resources/kurento-room-demo.conf.json new file mode 100644 index 00000000..d8b34685 --- /dev/null +++ b/openvidu-demo/src/main/resources/kurento-room-demo.conf.json @@ -0,0 +1,49 @@ +{ + "kms": { + "uris": ["ws://localhost:8888/kurento", "ws://127.0.0.1:8888/kurento"] + }, + "app": { + //has to accessible from the KMS in order to load filter imgs + "uri": "https://localhost:8443/" + }, + "kurento": { + "client": { + //milliseconds + "requestTimeout": 20000 + } + }, + "demo": { + //marker or hat + "filterType" : "marker", + + //markerdetector img(s) in order of preference + "markerUrls": { + "0": "kurento-rect-logo.png" + }, + + //mario-wings.png or wizard.png + "hatUrl": "mario-wings.png", + "hatCoords": { + // mario-wings hat + "offsetXPercent": -0.35F, + "offsetYPercent": -1.2F, + "widthPercent": 1.6F, + "heightPercent": 1.6F + + //wizard hat + //"offsetXPercent": -0.2F, + //"offsetYPercent": -1.35F, + //"widthPercent": 1.5F, + //"heightPercent": 1.5F + }, + "loopback" : { + "remote": true, + //matters only when remote is true + "andLocal": false + }, + "authRegex": ".*", + "kmsLimit": 1000 + }, + "updateSpeakerInterval": 1800, + "thresholdSpeaker": -50 +} diff --git a/openvidu-demo/src/main/resources/log4j.properties b/openvidu-demo/src/main/resources/log4j.properties new file mode 100644 index 00000000..86cfa179 --- /dev/null +++ b/openvidu-demo/src/main/resources/log4j.properties @@ -0,0 +1,10 @@ +log4j.rootLogger=WARN,CONSOLE +log4j.logger.org.kurento=INFO +log4j.logger.org.kurento.room=DEBUG + +# Appenders +log4j.threshold=ALL + +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p %c [%t] (%F:%L) - %m%n \ No newline at end of file diff --git a/openvidu-demo/src/main/resources/static/angular/app.js b/openvidu-demo/src/main/resources/static/angular/app.js new file mode 100644 index 00000000..d79e3e47 --- /dev/null +++ b/openvidu-demo/src/main/resources/static/angular/app.js @@ -0,0 +1,35 @@ +var kurento_room = angular.module('kurento_room', ['ngRoute', 'FBAngular', 'lumx', 'angular-clipboard']); + +kurento_room.config(['$routeProvider', function ($routeProvider) { + $routeProvider + .when('/', { + templateUrl: 'angular/login/login.html', + controller: 'loginController' + }) + .when('/login', { + templateUrl: 'angular/login/login.html', + controller: 'loginController' + }) + .when('/rooms/:existingRoomName', { + templateUrl: 'angular/login/login.html', + controller: 'loginController' + }) + .when('/call', { + templateUrl: 'angular/call/call.html', + controller: 'callController', + resolve: { + factory: checkRouting + } + }) + .otherwise('/'); //redirect to login +}]); + +var checkRouting= function ($rootScope, $location) { + if ($rootScope.isParticipant) { + return true; + } else { + console.log('Not a participant, routing to login'); + $location.path($rootScope.contextpath + '/'); + return false; + } +}; \ No newline at end of file diff --git a/openvidu-demo/src/main/resources/static/angular/call/call.html b/openvidu-demo/src/main/resources/static/angular/call/call.html new file mode 100644 index 00000000..e26a5aa7 --- /dev/null +++ b/openvidu-demo/src/main/resources/static/angular/call/call.html @@ -0,0 +1,67 @@ + +
+ +
+ +
+ + + +
+ + + +
{{roomName}}
+
+ + + + + + + + +
+ +
+ + + +
+
+ + + + +
+ +
+
diff --git a/openvidu-demo/src/main/resources/static/angular/call/callController.js b/openvidu-demo/src/main/resources/static/angular/call/callController.js new file mode 100644 index 00000000..497d7741 --- /dev/null +++ b/openvidu-demo/src/main/resources/static/angular/call/callController.js @@ -0,0 +1,194 @@ +/* + * @author Micael Gallego (micael.gallego@gmail.com) + * @author Raquel Díaz González + */ + +kurento_room.controller('callController', function ($scope, $window, ServiceParticipant, ServiceRoom, Fullscreen, LxNotificationService) { + + $scope.roomName = ServiceRoom.getRoomName(); + $scope.userName = ServiceRoom.getUserName(); + $scope.participants = ServiceParticipant.getParticipants(); + $scope.kurento = ServiceRoom.getKurento(); + $scope.filter = ServiceRoom.getFilterRequestParam(); + + $scope.leaveRoom = function () { + + ServiceRoom.closeKurento(); + + ServiceParticipant.removeParticipants(); + + //redirect to login + $window.location.href = '#/login'; + }; + + window.onbeforeunload = function () { + //not necessary if not connected + if (ServiceParticipant.isConnected()) { + ServiceRoom.closeKurento(); + } + }; + + $scope.$on("$locationChangeStart", function () { + console.log("Changed location to: " + document.location); + if (ServiceParticipant.isConnected()) { + ServiceRoom.closeKurento(); + ServiceParticipant.removeParticipants(); + } + }); + + $scope.goFullscreen = function () { + + if (Fullscreen.isEnabled()) + Fullscreen.cancel(); + else + Fullscreen.all(); + + }; + + $scope.disableMainSpeaker = function (value) { + + var element = document.getElementById("buttonMainSpeaker"); + if (element.classList.contains("md-person")) { //on + element.classList.remove("md-person"); + element.classList.add("md-recent-actors"); + ServiceParticipant.enableMainSpeaker(); + } else { //off + element.classList.remove("md-recent-actors"); + element.classList.add("md-person"); + ServiceParticipant.disableMainSpeaker(); + } + } + + $scope.onOffVolume = function () { + var localStream = ServiceRoom.getLocalStream(); + var element = document.getElementById("buttonVolume"); + if (element.classList.contains("md-volume-off")) { //on + element.classList.remove("md-volume-off"); + element.classList.add("md-volume-up"); + localStream.audioEnabled = true; + } else { //off + element.classList.remove("md-volume-up"); + element.classList.add("md-volume-off"); + localStream.audioEnabled = false; + + } + }; + + $scope.onOffVideocam = function () { + var localStream = ServiceRoom.getLocalStream(); + var element = document.getElementById("buttonVideocam"); + if (element.classList.contains("md-videocam-off")) {//on + element.classList.remove("md-videocam-off"); + element.classList.add("md-videocam"); + localStream.videoEnabled = true; + } else {//off + element.classList.remove("md-videocam"); + element.classList.add("md-videocam-off"); + localStream.videoEnabled = false; + } + }; + + $scope.disconnectStream = function () { + var localStream = ServiceRoom.getLocalStream(); + var participant = ServiceParticipant.getMainParticipant(); + if (!localStream || !participant) { + LxNotificationService.alert('Error!', "Not connected yet", 'Ok', function (answer) { + }); + return false; + } + ServiceParticipant.disconnectParticipant(participant); + ServiceRoom.getKurento().disconnectParticipant(participant.getStream()); + } + + //chat + $scope.message; + + $scope.sendMessage = function () { + console.log("Sending message", $scope.message); + var kurento = ServiceRoom.getKurento(); + kurento.sendMessage($scope.roomName, $scope.userName, $scope.message); + $scope.message = ""; + }; + + //open or close chat when click in chat button + $scope.toggleChat = function () { + var selectedEffect = "slide"; + // most effect types need no options passed by default + var options = {direction: "right"}; + if ($("#effect").is(':visible')) { + $("#content").animate({width: '100%'}, 500); + } else { + $("#content").animate({width: '80%'}, 500); + } + // run the effect + $("#effect").toggle(selectedEffect, options, 500); + }; + + var style = { + hat: { + "-1": "btn--indigo md-mood", + "0": "btn--amber md-face-unlock" + }, + marker: { + "-1": "btn--indigo md-grid-off", + "0": "btn--amber md-grid-on", + "1": "btn--red md-grid-on" + } + }; + + $scope.filterIndex = "-1"; //off + $scope.filterState; + $scope.filterStyle; + updateFilterValues(); + + function updateFilterValues() { + $scope.filterState = parseInt($scope.filterIndex) < 0 ? "off" : "on"; + $scope.filterStyle = style[$scope.filter][$scope.filterIndex]; + } + + $scope.applyFilter = function () { + var reqParams = {}; + if ($scope.filter === "marker") { + reqParams[$scope.filter] = parseInt($scope.filterIndex); + } else { + if (parseInt($scope.filterIndex) < 0) { //off -> on + $scope.filterIndex = "0"; + reqParams[$scope.filter] = true; + } else { //on -> off + $scope.filterIndex = "-1"; + reqParams[$scope.filter] = false; + } + } + + ServiceRoom.getKurento().sendCustomRequest(reqParams, function (error, response) { + if (error) { + console.error("Unable to toggle filter, currently " + + $scope.filterState, error); + LxNotificationService.alert('Error!', + "Unable to toggle filter, currently " + $scope.filterState, + 'Ok', function (answer) { + }); + return false; + } else { + if ($scope.filter === "marker") { + return; + } + + updateFilterValues(); + console.log("Toggled filter " + $scope.filterState + " (idx " + + $scope.filterIndex + ")"); + } + }); + }; + + ServiceParticipant.addEventListener("marker-filter-status-changed", function (status) { + console.log("Filter status changed", status); + if ($scope.filter === "marker") { + $scope.filterIndex = status; + updateFilterValues(); + $scope.$apply(); + } + }); +}); + + diff --git a/openvidu-demo/src/main/resources/static/angular/login/login.html b/openvidu-demo/src/main/resources/static/angular/login/login.html new file mode 100644 index 00000000..f10b9a42 --- /dev/null +++ b/openvidu-demo/src/main/resources/static/angular/login/login.html @@ -0,0 +1,74 @@ + +
+
Kurento Room
+ +
+
+ +
+ + + + + Invalid, please use: + a-zA-Z0-9 + +
+ +
+ + + + + Allowed chars: + a-zA-Z0-9 +
+ +
+ + + {{ $selected }} + + + + {{ $choice }} + + +
+ +
+ +
+ +
+
+
+ +
+
+ +
+
+
+
+ +
+
+ +
+
+ + + +
+ +
+ +
+
+ +
+ diff --git a/openvidu-demo/src/main/resources/static/angular/login/loginController.js b/openvidu-demo/src/main/resources/static/angular/login/loginController.js new file mode 100644 index 00000000..dedaa709 --- /dev/null +++ b/openvidu-demo/src/main/resources/static/angular/login/loginController.js @@ -0,0 +1,210 @@ +/* + * @author Micael Gallego (micael.gallego@gmail.com) + * @author Radu Tom Vlad + */ + +kurento_room.controller('loginController', function($scope, $rootScope, $http, + $window, $routeParams, ServiceParticipant, ServiceRoom, LxNotificationService) { + + $scope.existingRoomName = false; + $scope.roomPickerClass = 'grid__col6'; + $scope.roomPickerLabel = 'Room'; + var name = $routeParams["existingRoomName"]; + if (name && name.length > 0) { + $scope.room = { + roomName: name + } + $scope.existingRoomName = true; + $scope.roomPickerClass = 'grid__col'; + $scope.roomPickerLabel = 'Fixed room name'; + } + + $scope.nameValidation = function(name) { + return /^[a-zA-Z0-9]+$/.test(name); + }; + + $rootScope.isParticipant = false; + + var contextpath = (location.pathname == '/') ? '' : location.pathname; + + $rootScope.contextpath = (location.pathname == '/') ? '' : location.pathname; + + var roomsFragment = $rootScope.contextpath.endsWith('/') ? '#/rooms/' : '/#/rooms/'; + + $http.get($rootScope.contextpath + '/getAllRooms').success(function(data, status, headers, config) { + console.log(JSON.stringify(data)); + $scope.listRooms = data; + }).error(function(data, status, headers, config) {}); + + $http.get($rootScope.contextpath + '/getClientConfig').success(function(data, status, headers, config) { + console.log(JSON.stringify(data)); + $scope.clientConfig = data; + }).error(function(data, status, headers, config) {}); + + $http.get($rootScope.contextpath + '/getUpdateSpeakerInterval').success(function(data, status, headers, config) { + $scope.updateSpeakerInterval = data + }).error(function(data, status, headers, config) {}); + + $http.get($rootScope.contextpath + '/getThresholdSpeaker').success(function(data, status, headers, config) { + $scope.thresholdSpeaker = data + }).error(function(data, status, headers, config) {}); + + $scope.register = function(room) { + + if (!room) + ServiceParticipant.showError($window, LxNotificationService, { + error: { + message: "Username and room fields are both required" + } + }, contextpath); + + $scope.userName = room.userName; + $scope.roomName = room.roomName; + + var wsUri = 'wss://' + location.host + $rootScope.contextpath + '/room'; + + //show loopback stream from server + var displayPublished = $scope.clientConfig.loopbackRemote || false; + //also show local stream when display my remote + var mirrorLocal = $scope.clientConfig.loopbackAndLocal || false; + + var kurento = KurentoRoom(wsUri, function(error, kurento) { + + if (error) { + return console.error('Error in KurentoRoom client', error); + } + + //TODO token should be generated by the server or a 3rd-party component + //kurento.setRpcParams({token : "securityToken"}); + + room = kurento.Room({ + room: $scope.roomName, + user: $scope.userName, + updateSpeakerInterval: $scope.updateSpeakerInterval, + thresholdSpeaker: $scope.thresholdSpeaker + }); + + var localStream = kurento.Stream(room, { + audio: true, + video: true, + data: false + }); + + localStream.addEventListener("access-accepted", function() { + room.addEventListener("room-connected", function(roomEvent) { + var streams = roomEvent.streams; + if (displayPublished) { + localStream.subscribeToMyRemote(); + } + localStream.publish(); + ServiceRoom.setLocalStream(localStream.getWebRtcPeer()); + for (var i = 0; i < streams.length; i++) { + ServiceParticipant.addParticipant(streams[i]); + } + }); + + room.addEventListener("stream-published", function(streamEvent) { + ServiceParticipant.addLocalParticipant(localStream); + if (mirrorLocal && localStream.displayMyRemote()) { + var localVideo = kurento.Stream(room, { + video: true, + id: "localStream" + }); + localVideo.mirrorLocalStream(localStream.getWrStream()); + ServiceParticipant.addLocalMirror(localVideo); + } + }); + + room.addEventListener("stream-added", function(streamEvent) { + ServiceParticipant.addParticipant(streamEvent.stream); + }); + + room.addEventListener("stream-removed", function(streamEvent) { + ServiceParticipant.removeParticipantByStream(streamEvent.stream); + }); + + room.addEventListener("newMessage", function(msg) { + ServiceParticipant.showMessage(msg.room, msg.user, msg.message); + }); + + room.addEventListener("error-room", function(error) { + ServiceParticipant.showError($window, LxNotificationService, error, contextpath); + }); + + room.addEventListener("error-media", function(msg) { + ServiceParticipant.alertMediaError($window, LxNotificationService, msg.error, contextPath, function(answer) { + console.warn("Leave room because of error: " + answer); + if (answer) { + kurento.close(true); + } + }); + }); + + room.addEventListener("room-closed", function(msg) { + if (msg.room !== $scope.roomName) { + console.error("Closed room name doesn't match this room's name", + msg.room, $scope.roomName); + } else { + kurento.close(true); + ServiceParticipant.forceClose($window, LxNotificationService, 'Room ' + + msg.room + ' has been forcibly closed from server', contextpath); + } + }); + + room.addEventListener("lost-connection", function(msg) { + kurento.close(true); + ServiceParticipant.forceClose($window, LxNotificationService, + 'Lost connection with room "' + msg.room + + '". Please try reloading the webpage...'); + }, contextpath); + + room.addEventListener("stream-stopped-speaking", function(participantId) { + ServiceParticipant.streamStoppedSpeaking(participantId); + }); + + room.addEventListener("stream-speaking", function(participantId) { + ServiceParticipant.streamSpeaking(participantId); + }); + + room.addEventListener("update-main-speaker", function(participantId) { + ServiceParticipant.updateMainSpeaker(participantId); + }); + + room.addEventListener("custom-message-received", function(data) { + if (data.params.MarkerFilterState !== undefined) { + ServiceParticipant.changeMarkerFilterStatus(data.params.MarkerFilterState); + } + }); + + room.connect(); + }); + + localStream.addEventListener("access-denied", function() { + ServiceParticipant.showError($window, LxNotificationService, { + error: { + message: "Access not granted to camera and microphone" + } + }); + }, contextpath); + localStream.init(); + }); + + //save kurento & roomName & userName in service + ServiceRoom.setKurento(kurento); + ServiceRoom.setRoomName($scope.roomName); + ServiceRoom.setUserName($scope.userName); + ServiceRoom.setFilterRequestParam($scope.clientConfig.filterRequestParam); + + $rootScope.isParticipant = true; + + //redirect to call + $window.location.href = '#/call'; + }; + $scope.clear = function() { + $scope.room = ""; + $scope.updateRoomUrl(); + }; + $scope.updateRoomUrl = function(roomName) { + $scope.roomUrl = (roomName && roomName.length > 0) ? location.protocol + '//' + location.host + $rootScope.contextpath + roomsFragment + roomName : ''; + }; +}); \ No newline at end of file diff --git a/openvidu-demo/src/main/resources/static/angular/services/Participants.js b/openvidu-demo/src/main/resources/static/angular/services/Participants.js new file mode 100644 index 00000000..d4d1e7a0 --- /dev/null +++ b/openvidu-demo/src/main/resources/static/angular/services/Participants.js @@ -0,0 +1,399 @@ +/* + * (C) Copyright 2016 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +function AppParticipant(stream) { + + this.stream = stream; + this.videoElement; + this.thumbnailId; + this.mainVideo; + var that = this; + + this.getStream = function () { + return this.stream; + } + + this.setMain = function () { + that.videoElement.className += " active-video"; + var mainVideosParent = document.getElementById('main-video'); + + if (elementExists(that.mainVideo)) { + $(that.mainVideo).show(); + } else { + that.mainVideo = stream.playOnlyVideo(mainVideosParent, that.thumbnailId); + } + } + + this.removeMain = function () { + $(that.videoElement).removeClass("active-video"); + if (elementExists(that.mainVideo)) { + $(that.mainVideo).hide(); + } else { + console.warn(stream.getGlobalID() + ': no main video element to remove'); + } + } + + this.remove = function () { + if (that.videoElement !== undefined) { + if (that.videoElement.parentNode !== null) { + that.videoElement.parentNode.removeChild(that.videoElement); + } + } + } + + function elementExists(element) { + return element !== undefined && element.id !== undefined && $('#' + element.id).length > 0; + } + + function playVideo() { + + that.thumbnailId = "video-" + stream.getGlobalID(); + + that.videoElement = document.createElement('div'); + that.videoElement.setAttribute("id", that.thumbnailId); + that.videoElement.className = "video"; + + var speakerSpeakingVolumen = document.createElement('div'); + speakerSpeakingVolumen.setAttribute("id", "speaker" + that.thumbnailId); + speakerSpeakingVolumen.className = 'btn--m btn--green btn--fab mdi md-volume-up blinking'; + speakerSpeakingVolumen.style.position = "absolute"; + speakerSpeakingVolumen.style.left = "3%"; + speakerSpeakingVolumen.style.top = "60%"; + speakerSpeakingVolumen.style.zIndex = "100"; + speakerSpeakingVolumen.style.display = "none"; + that.videoElement.appendChild(speakerSpeakingVolumen); + + document.getElementById("participants").appendChild(that.videoElement); + that.stream.playThumbnail(that.thumbnailId); + } + + playVideo(); +} + +function Participants() { + + var mainParticipant; + var localParticipant; + var mirrorParticipant; + var participants = {}; + var roomName; + var that = this; + var connected = true; + var displayingRelogin = false; + var mainSpeaker = true; + + var ee = new EventEmitter(); + + this.isConnected = function () { + return connected; + } + + this.getRoomName = function () { + console.log("room - getRoom " + roomName); + roomName = room.name; + return roomName; + }; + + this.getMainParticipant = function () { + return mainParticipant; + } + + function updateVideoStyle() { + var MAX_WIDTH = 14; + var numParticipants = Object.keys(participants).length; + var maxParticipantsWithMaxWidth = 98 / MAX_WIDTH; + + if (numParticipants > maxParticipantsWithMaxWidth) { + $('.video').css({ + "width": (98 / numParticipants) + "%" + }); + } else { + $('.video').css({ + "width": MAX_WIDTH + "%" + }); + } + }; + + function updateMainParticipant(participant) { + if (!mainParticipant || (mainParticipant != participant)) { + if (mainParticipant) { + mainParticipant.removeMain(); + } + mainParticipant = participant; + mainParticipant.setMain(); + } + } + + this.addLocalParticipant = function (stream) { + localParticipant = that.addParticipant(stream); + mainParticipant = localParticipant; + mainParticipant.setMain(); + }; + + this.addLocalMirror = function (stream) { + mirrorParticipant = that.addParticipant(stream); + }; + + this.addParticipant = function (stream) { + + var participant = new AppParticipant(stream); + participants[stream.getGlobalID()] = participant; + + updateVideoStyle(); + + $(participant.videoElement).click(function (e) { + updateMainParticipant(participant); + }); + + //updateMainParticipant(participant); + + return participant; + }; + + this.removeParticipantByStream = function (stream) { + this.removeParticipant(stream.getGlobalID()); + }; + + this.disconnectParticipant = function (appParticipant) { + this.removeParticipant(appParticipant.getStream().getGlobalID()); + }; + + this.removeParticipant = function (streamId) { + var participant = participants[streamId]; + delete participants[streamId]; + participant.remove(); + + if (mirrorParticipant) { + var otherLocal = null; + if (participant === localParticipant) { + otherLocal = mirrorParticipant; + } + if (participant === mirrorParticipant) { + otherLocal = localParticipant; + } + if (otherLocal) { + console.log("Removed local participant (or mirror) so removing the other local as well"); + delete participants[otherLocal.getStream().getGlobalID()]; + otherLocal.remove(); + } + } + + //setting main + if (mainParticipant && mainParticipant === participant) { + var mainIsLocal = false; + if (localParticipant) { + if (participant !== localParticipant && participant !== mirrorParticipant) { + mainParticipant = localParticipant; + mainIsLocal = true; + } else { + localParticipant = null; + mirrorParticipant = null; + } + } + if (!mainIsLocal) { + var keys = Object.keys(participants); + if (keys.length > 0) { + mainParticipant = participants[keys[0]]; + } else { + mainParticipant = null; + } + } + if (mainParticipant) { + mainParticipant.setMain(); + console.log("Main video from " + mainParticipant.getStream().getGlobalID()); + } else + console.error("No media streams left to display"); + } + + updateVideoStyle(); + }; + + //only called when leaving the room + this.removeParticipants = function () { + connected = false; + for (var index in participants) { + var participant = participants[index]; + participant.remove(); + } + participants = []; + }; + + this.getParticipants = function () { + return participants; + }; + + this.enableMainSpeaker = function () { + mainSpeaker = true; + } + + this.disableMainSpeaker = function () { + mainSpeaker = false; + } + + // Open the chat automatically when a message is received + function autoOpenChat() { + var selectedEffect = "slide"; + var options = {direction: "right"}; + if ($("#effect").is(':hidden')) { + $("#content").animate({width: '80%'}, 500); + $("#effect").toggle(selectedEffect, options, 500); + } + }; + + this.showMessage = function (room, user, message) { + var ul = document.getElementsByClassName("list"); + + var chatDiv = document.getElementById('chatDiv'); + var messages = $("#messages"); + var updateScroll = true; + if (messages.outerHeight() - chatDiv.scrollTop > chatDiv.offsetHeight) { + updateScroll = false; + } + + var vetext = localParticipant.videoElement.textContent || localParticipant.videoElement.innerText; + var localUser = vetext.replace("_webcam", ""); + if (user === localUser) { //me + + var li = document.createElement('li'); + li.className = "list-row list-row--has-primary list-row--has-separator"; + var div1 = document.createElement("div1"); + div1.className = "list-secondary-tile"; + var img = document.createElement("img"); + img.className = "list-primary-tile__img"; + img.setAttribute("src", "http://ui.lumapps.com/images/placeholder/2-square.jpg"); + var div2 = document.createElement('div'); + div2.className = "list-content-tile list-content-tile--two-lines"; + var strong = document.createElement('strong'); + strong.innerHTML = user; + var span = document.createElement('span'); + span.innerHTML = message; + div2.appendChild(strong); + div2.appendChild(span); + div1.appendChild(img); + li.appendChild(div1); + li.appendChild(div2); + ul[0].appendChild(li); + + } else {//others + + var li = document.createElement('li'); + li.className = "list-row list-row--has-primary list-row--has-separator"; + var div1 = document.createElement("div1"); + div1.className = "list-primary-tile"; + var img = document.createElement("img"); + img.className = "list-primary-tile__img"; + img.setAttribute("src", "http://ui.lumapps.com/images/placeholder/1-square.jpg"); + var div2 = document.createElement('div'); + div2.className = "list-content-tile list-content-tile--two-lines"; + var strong = document.createElement('strong'); + strong.innerHTML = user; + var span = document.createElement('span'); + span.innerHTML = message; + div2.appendChild(strong); + div2.appendChild(span); + div1.appendChild(img); + li.appendChild(div1); + li.appendChild(div2); + ul[0].appendChild(li); + autoOpenChat(); + } + + if (updateScroll) { + chatDiv.scrollTop = messages.outerHeight(); + } + }; + + this.showError = function ($window, LxNotificationService, e, contextPath) { + if (displayingRelogin) { + console.warn('Already displaying an alert that leads to relogin'); + return false; + } + displayingRelogin = true; + that.removeParticipants(); + LxNotificationService.alert('Error!', e.error.message, 'Reconnect', function (answer) { + displayingRelogin = false; + relogin($window, contextPath); + }); + }; + + this.forceClose = function ($window, LxNotificationService, msg, contextPath) { + if (displayingRelogin) { + console.warn('Already displaying an alert that leads to relogin'); + return false; + } + displayingRelogin = true; + that.removeParticipants(); + LxNotificationService.alert('Warning!', msg, 'Reload', function (answer) { + displayingRelogin = false; + relogin($window, contextPath); + }); + }; + + this.alertMediaError = function ($window, LxNotificationService, msg, contextPath, callback) { + if (displayingRelogin) { + console.warn('Already displaying an alert that leads to relogin'); + return false; + } + LxNotificationService.confirm('Warning!', 'Server media error: ' + msg + + ". Please reconnect.", {cancel: 'Disagree', ok: 'Agree'}, + function (answer) { + console.log("User agrees upon media error: " + answer); + if (answer) { + that.removeParticipants(); + relogin($window, contextPath); + } + if (typeof callback === "function") { + callback(answer); + } + }); + }; + + function relogin($window, contextPath) { + //TODO call leaveRoom() in kurento + contextPath = contextPath || '/'; + $window.location.href = contextPath; //'#/login'; + } + + this.streamSpeaking = function (participantId) { + if (participants[participantId.participantId] != undefined) + document.getElementById("speaker" + participants[participantId.participantId].thumbnailId).style.display = ''; + } + + this.streamStoppedSpeaking = function (participantId) { + if (participants[participantId.participantId] != undefined) + document.getElementById("speaker" + participants[participantId.participantId].thumbnailId).style.display = "none"; + } + + this.updateMainSpeaker = function (participantId) { + if (participants[participantId.participantId] != undefined) { + if (mainSpeaker) + updateMainParticipant(participants[participantId.participantId]); + } + } + + this.changeMarkerFilterStatus = function (status) { + this.emitEvent("marker-filter-status-changed", [status]); + console.log("New filter status: " + status); + }; + + this.addEventListener = function (eventName, listener) { + ee.addListener(eventName, listener); + }; + + this.emitEvent = function (eventName, eventsArray) { + ee.emitEvent(eventName, eventsArray); + }; +} \ No newline at end of file diff --git a/openvidu-demo/src/main/resources/static/angular/services/serviceParticipant.js b/openvidu-demo/src/main/resources/static/angular/services/serviceParticipant.js new file mode 100644 index 00000000..8545fdbe --- /dev/null +++ b/openvidu-demo/src/main/resources/static/angular/services/serviceParticipant.js @@ -0,0 +1,9 @@ +/* + * @author Raquel Díaz González + */ + +kurento_room.factory('ServiceParticipant', function () { + + return new Participants(); + +}); \ No newline at end of file diff --git a/openvidu-demo/src/main/resources/static/angular/services/serviceRoom.js b/openvidu-demo/src/main/resources/static/angular/services/serviceRoom.js new file mode 100644 index 00000000..a0a6599b --- /dev/null +++ b/openvidu-demo/src/main/resources/static/angular/services/serviceRoom.js @@ -0,0 +1,60 @@ +/* + * @author Raquel Díaz González + */ + +kurento_room.service('ServiceRoom', function () { + + var kurento; + var roomName; + var userName; + var localStream; + var filterRequestParam; + + this.getKurento = function () { + return kurento; + }; + + this.getRoomName = function () { + return roomName; + }; + + this.setKurento = function (value) { + kurento = value; + }; + + this.setRoomName = function (value) { + roomName = value; + }; + + this.getLocalStream = function () { + return localStream; + }; + + this.setLocalStream = function (value) { + localStream = value; + }; + + this.getUserName = function () { + return userName; + }; + + this.setUserName = function (value) { + userName = value; + }; + + this.closeKurento = function () { + if (kurento && kurento instanceof KurentoRoom) { + kurento.close(); + } else { + console.log('KurentoRoom instance is not set'); + } + }; + + this.getFilterRequestParam = function () { + return filterRequestParam; + }; + + this.setFilterRequestParam = function (value) { + filterRequestParam = value; + }; +}); diff --git a/openvidu-demo/src/main/resources/static/css/googleapis-fonts.css b/openvidu-demo/src/main/resources/static/css/googleapis-fonts.css new file mode 100644 index 00000000..fbb4db72 --- /dev/null +++ b/openvidu-demo/src/main/resources/static/css/googleapis-fonts.css @@ -0,0 +1,56 @@ +/* cyrillic-ext */ +@font-face { + font-family: 'Open Sans'; + font-style: normal; + font-weight: 400; + src: local('Open Sans'), local('OpenSans'), url(//fonts.gstatic.com/s/opensans/v13/K88pR3goAWT7BTt32Z01mxJtnKITppOI_IvcXXDNrsc.woff2) format('woff2'); + unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F; +} +/* cyrillic */ +@font-face { + font-family: 'Open Sans'; + font-style: normal; + font-weight: 400; + src: local('Open Sans'), local('OpenSans'), url(//fonts.gstatic.com/s/opensans/v13/RjgO7rYTmqiVp7vzi-Q5URJtnKITppOI_IvcXXDNrsc.woff2) format('woff2'); + unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek-ext */ +@font-face { + font-family: 'Open Sans'; + font-style: normal; + font-weight: 400; + src: local('Open Sans'), local('OpenSans'), url(//fonts.gstatic.com/s/opensans/v13/LWCjsQkB6EMdfHrEVqA1KRJtnKITppOI_IvcXXDNrsc.woff2) format('woff2'); + unicode-range: U+1F00-1FFF; +} +/* greek */ +@font-face { + font-family: 'Open Sans'; + font-style: normal; + font-weight: 400; + src: local('Open Sans'), local('OpenSans'), url(//fonts.gstatic.com/s/opensans/v13/xozscpT2726on7jbcb_pAhJtnKITppOI_IvcXXDNrsc.woff2) format('woff2'); + unicode-range: U+0370-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Open Sans'; + font-style: normal; + font-weight: 400; + src: local('Open Sans'), local('OpenSans'), url(//fonts.gstatic.com/s/opensans/v13/59ZRklaO5bWGqF5A9baEERJtnKITppOI_IvcXXDNrsc.woff2) format('woff2'); + unicode-range: U+0102-0103, U+1EA0-1EF1, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Open Sans'; + font-style: normal; + font-weight: 400; + src: local('Open Sans'), local('OpenSans'), url(//fonts.gstatic.com/s/opensans/v13/u-WUoqrET9fUeobQW7jkRRJtnKITppOI_IvcXXDNrsc.woff2) format('woff2'); + unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Open Sans'; + font-style: normal; + font-weight: 400; + src: local('Open Sans'), local('OpenSans'), url(//fonts.gstatic.com/s/opensans/v13/cJZKeOuBrn4kERxqtaUH3VtXRa8TVwTICgirnJhmVJw.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000; +} \ No newline at end of file diff --git a/openvidu-demo/src/main/resources/static/css/room.css b/openvidu-demo/src/main/resources/static/css/room.css new file mode 100644 index 00000000..3610c213 --- /dev/null +++ b/openvidu-demo/src/main/resources/static/css/room.css @@ -0,0 +1,240 @@ +html, body { + height: 100%; +} + +#buttonActions>button{ + font-size: 1.9rem; +} + +#room{ + height: 100%; +} + +* { + margin: 0px; + padding: 0px; + overflow: hidden +} + +body { + font-family: 'Open Sans', sans-serif; +} + +.roomUrl { + margin: 40px auto 30px; +} + +#main-video { + height: 100%; + width: 100%; + position: absolute; + top: 0; + bottom: 0; + right: 0; + left: 0; +} + +#main-video>video { + height: 100%; + width: 100%; + position: absolute; + top: 0; + bottom: 0; + right: 0; + left: 0; +} + +#main-video video { + object-fit: contain; +} + +video { + width: 100%; +} + +#content { + background-color: black; + position: absolute; + top: 0px; + left: 0px; + right: 70%; + height: 100%; + width: 100%; +} + +#participants { + position: absolute; + bottom: 0px; + right: 0px; + box-sizing: border-box; + width: 100%; + float: right; + margin: 1em; +} + +.name { + position: absolute; + top: 0px; + bottom: 0px; + left: 0px; + z-index: 99; + background-color: transparent; + margin: 0.5em; + text-shadow: 0px 0px 10px #000000; +} + +.active-video { + border: 2px solid white; +} + +.active-audio { + border: 2px solid blue; +} + +.blinking { + + animation-name: blinking; + animation-duration: 2s; + animation-timing-function: linear; + animation-iteration-count: infinite; + + -webkit-animation-name: blinking; + -webkit-animation-duration: 2s; + -webkit-animation-timing-function: linear; + -webkit-animation-iteration-count: infinite; +} + +@-moz-keyframes blinking{ + 0% { opacity: 1.0; } + 50% { opacity: 0.0; } + 100% { opacity: 1.0; } +} + +@-webkit-keyframes blinking { + 0% { opacity: 1.0; } + 50% { opacity: 0.0; } + 100% { opacity: 1.0; } +} + +@keyframes blinking { + 0% { opacity: 1.0; } + 50% { opacity: 0.0; } + 100% { opacity: 1.0; } +} + +.video { + width: 23%; + /* whatever width you want */ + position: relative; + float: right; + display: block; +} + +.video:after { + padding-top: 56.25%; + /* 16:9 ratio */ + display: block; + content: ''; +} + +.video>div { + position: absolute; + top: 0; + bottom: 0; + right: 0; + left: 0; + width: 100%; + /* fill parent */ + background-color: #000000; + /* let's see it! */ + color: white; + display: flex; + justify-content: center; + /* align horizontal */ + align-items: center; +} + +#logo { + position: absolute; + display: inline; + left: 0px; + top: 0px; + margin: 1em; +} + +#room-name { + display: inline; + width: 100%; + position: absolute; + margin: auto; + background-color: transparent; + margin: 0.5em; + text-shadow: 0px 0px 10px #000000; + text-align: center; + color: white; + font-weight: bold; + font-size: 2em; +} + +.join { + position: relative; + margin: auto; + width: 500px; + text-align: center; + vertical-align: middle; +} + +#join-title { + display: inline-flex; + font-size: 1.5em; + font-weight: bold; + color: #555; + padding-left: 70px; + padding-bottom: 35px; + padding-top: 35px; + background-image: url("../img/kurento.png"); + background-repeat: no-repeat; + background-position: left; + margin: auto 0 auto 0; +} + +/*.join p { + margin: 20px 0 0; +} + +.join p:first-child { + margin-top: 0; +} + +.join input[type=text], .join input[type=password] { + width: 278px; +} + +.join p.submit { + text-align: center; +}*/ + +:-moz-placeholder { + color: #c9c9c9 !important; + font-size: 13px; +} + +::-webkit-input-placeholder { + color: #ccc; + font-size: 13px; +} + +/*chat effect*/ + +#effect { + position: relative; + padding: 0.4em; +} + +.card__content { + padding: 16px; +} + +.card__actions { + border-top-width: 0px; +} diff --git a/openvidu-demo/src/main/resources/static/img/kurento-rect-logo.png b/openvidu-demo/src/main/resources/static/img/kurento-rect-logo.png new file mode 100644 index 00000000..8210e88d Binary files /dev/null and b/openvidu-demo/src/main/resources/static/img/kurento-rect-logo.png differ diff --git a/openvidu-demo/src/main/resources/static/img/kurento.png b/openvidu-demo/src/main/resources/static/img/kurento.png new file mode 100644 index 00000000..6f1a4ad3 Binary files /dev/null and b/openvidu-demo/src/main/resources/static/img/kurento.png differ diff --git a/openvidu-demo/src/main/resources/static/img/mario-wings.png b/openvidu-demo/src/main/resources/static/img/mario-wings.png new file mode 100644 index 00000000..cc890036 Binary files /dev/null and b/openvidu-demo/src/main/resources/static/img/mario-wings.png differ diff --git a/openvidu-demo/src/main/resources/static/img/noVideo.png b/openvidu-demo/src/main/resources/static/img/noVideo.png new file mode 100644 index 00000000..12197a7d Binary files /dev/null and b/openvidu-demo/src/main/resources/static/img/noVideo.png differ diff --git a/openvidu-demo/src/main/resources/static/img/wizard.png b/openvidu-demo/src/main/resources/static/img/wizard.png new file mode 100644 index 00000000..4435c1d4 Binary files /dev/null and b/openvidu-demo/src/main/resources/static/img/wizard.png differ diff --git a/openvidu-demo/src/main/resources/static/index.html b/openvidu-demo/src/main/resources/static/index.html new file mode 100644 index 00000000..465c4f60 --- /dev/null +++ b/openvidu-demo/src/main/resources/static/index.html @@ -0,0 +1,53 @@ + + + + +Kurento Room Demo + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + diff --git a/openvidu-demo/src/test/java/org/openvidu/test/demo/AddRemoveUsersDemoTest.java b/openvidu-demo/src/test/java/org/openvidu/test/demo/AddRemoveUsersDemoTest.java new file mode 100644 index 00000000..b3f27925 --- /dev/null +++ b/openvidu-demo/src/test/java/org/openvidu/test/demo/AddRemoveUsersDemoTest.java @@ -0,0 +1,43 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.test.demo; + +import java.lang.invoke.MethodHandles; +import java.util.Collection; + +import org.junit.runners.Parameterized.Parameters; +import org.kurento.test.browser.WebPageType; +import org.openvidu.test.browser.AddRemoveUsers; + +/** + * @see AddRemoveUsers + * @author Radu Tom Vlad (rvlad@naevatec.com) + */ +public class AddRemoveUsersDemoTest extends AddRemoveUsers { + + @Override + public void setupBrowserTest() throws InterruptedException { + webPageType = WebPageType.ROOT; + super.setupBrowserTest(); + } + + @Parameters(name = "{index}: {0}") + public static Collection data() { + return localChromes(MethodHandles.lookup().lookupClass().getSimpleName(), NUM_USERS, + WebPageType.ROOT); + } +} diff --git a/openvidu-demo/src/test/java/org/openvidu/test/demo/AddRemoveUsersNoSinkVerifyDemoTest.java b/openvidu-demo/src/test/java/org/openvidu/test/demo/AddRemoveUsersNoSinkVerifyDemoTest.java new file mode 100644 index 00000000..9b6622de --- /dev/null +++ b/openvidu-demo/src/test/java/org/openvidu/test/demo/AddRemoveUsersNoSinkVerifyDemoTest.java @@ -0,0 +1,43 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.test.demo; + +import java.lang.invoke.MethodHandles; +import java.util.Collection; + +import org.junit.runners.Parameterized.Parameters; +import org.kurento.test.browser.WebPageType; +import org.openvidu.test.browser.AddRemoveUsersNoSinkVerify; + +/** + * @see AddRemoveUsersNoSinkVerify + * @author Radu Tom Vlad (rvlad@naevatec.com) + */ +public class AddRemoveUsersNoSinkVerifyDemoTest extends AddRemoveUsersNoSinkVerify { + + @Override + public void setupBrowserTest() throws InterruptedException { + webPageType = WebPageType.ROOT; + super.setupBrowserTest(); + } + + @Parameters(name = "{index}: {0}") + public static Collection data() { + return localChromes(MethodHandles.lookup().lookupClass().getSimpleName(), NUM_USERS, + WebPageType.ROOT); + } +} diff --git a/openvidu-demo/src/test/java/org/openvidu/test/demo/NUsersEqualLifetimeDemoTest.java b/openvidu-demo/src/test/java/org/openvidu/test/demo/NUsersEqualLifetimeDemoTest.java new file mode 100644 index 00000000..267163c4 --- /dev/null +++ b/openvidu-demo/src/test/java/org/openvidu/test/demo/NUsersEqualLifetimeDemoTest.java @@ -0,0 +1,44 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.test.demo; + +import java.lang.invoke.MethodHandles; +import java.util.Collection; + +import org.junit.runners.Parameterized.Parameters; +import org.kurento.test.browser.WebPageType; +import org.openvidu.test.browser.NUsersEqualLifetime; + +/** + * @see NUsersEqualLifetime + * @author Radu Tom Vlad (rvlad@naevatec.com) + */ +public class NUsersEqualLifetimeDemoTest extends NUsersEqualLifetime { + + @Override + public void setupBrowserTest() throws InterruptedException { + webPageType = WebPageType.ROOT; + super.setupBrowserTest(); + } + + @Parameters(name = "{index}: {0}") + public static Collection data() { + return localChromes(MethodHandles.lookup().lookupClass().getSimpleName(), NUM_USERS, + WebPageType.ROOT); + } + +} diff --git a/openvidu-demo/src/test/java/org/openvidu/test/demo/OneUserQuickReentryDemoTest.java b/openvidu-demo/src/test/java/org/openvidu/test/demo/OneUserQuickReentryDemoTest.java new file mode 100644 index 00000000..173fcc0d --- /dev/null +++ b/openvidu-demo/src/test/java/org/openvidu/test/demo/OneUserQuickReentryDemoTest.java @@ -0,0 +1,43 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.test.demo; + +import java.lang.invoke.MethodHandles; +import java.util.Collection; + +import org.junit.runners.Parameterized.Parameters; +import org.kurento.test.browser.WebPageType; +import org.openvidu.test.browser.OneUserQuickReentry; + +/** + * @see OneUserQuickReentry + * @author Radu Tom Vlad (rvlad@naevatec.com) + */ +public class OneUserQuickReentryDemoTest extends OneUserQuickReentry { + + @Override + public void setupBrowserTest() throws InterruptedException { + webPageType = WebPageType.ROOT; + super.setupBrowserTest(); + } + + @Parameters(name = "{index}: {0}") + public static Collection data() { + return localChromes(MethodHandles.lookup().lookupClass().getSimpleName(), NUM_USERS, + WebPageType.ROOT); + } +} diff --git a/openvidu-demo/src/test/java/org/openvidu/test/demo/SeqAddRemoveUserDemoTest.java b/openvidu-demo/src/test/java/org/openvidu/test/demo/SeqAddRemoveUserDemoTest.java new file mode 100644 index 00000000..dbc290c5 --- /dev/null +++ b/openvidu-demo/src/test/java/org/openvidu/test/demo/SeqAddRemoveUserDemoTest.java @@ -0,0 +1,44 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.test.demo; + +import java.lang.invoke.MethodHandles; +import java.util.Collection; + +import org.junit.runners.Parameterized.Parameters; +import org.kurento.test.browser.WebPageType; +import org.openvidu.test.browser.SeqAddRemoveUser; + +/** + * @see SeqAddRemoveUser + * @author Radu Tom Vlad (rvlad@naevatec.com) + */ +public class SeqAddRemoveUserDemoTest extends SeqAddRemoveUser { + + @Override + public void setupBrowserTest() throws InterruptedException { + webPageType = WebPageType.ROOT; + super.setupBrowserTest(); + } + + @Parameters(name = "{index}: {0}") + public static Collection data() { + return localChromes(MethodHandles.lookup().lookupClass().getSimpleName(), NUM_USERS, + WebPageType.ROOT); + } + +} diff --git a/openvidu-demo/src/test/java/org/openvidu/test/demo/SeqNUsersEqualLifetimeDemoTest.java b/openvidu-demo/src/test/java/org/openvidu/test/demo/SeqNUsersEqualLifetimeDemoTest.java new file mode 100644 index 00000000..fe47c5be --- /dev/null +++ b/openvidu-demo/src/test/java/org/openvidu/test/demo/SeqNUsersEqualLifetimeDemoTest.java @@ -0,0 +1,44 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.test.demo; + +import java.lang.invoke.MethodHandles; +import java.util.Collection; + +import org.junit.runners.Parameterized.Parameters; +import org.kurento.test.browser.WebPageType; +import org.openvidu.test.browser.SeqNUsersEqualLifetime; + +/** + * @see SeqNUsersEqualLifetime + * @author Radu Tom Vlad (rvlad@naevatec.com) + */ +public class SeqNUsersEqualLifetimeDemoTest extends SeqNUsersEqualLifetime { + + @Override + public void setupBrowserTest() throws InterruptedException { + webPageType = WebPageType.ROOT; + super.setupBrowserTest(); + } + + @Parameters(name = "{index}: {0}") + public static Collection data() { + return localChromes(MethodHandles.lookup().lookupClass().getSimpleName(), NUM_USERS, + WebPageType.ROOT); + } + +} diff --git a/openvidu-demo/src/test/java/org/openvidu/test/demo/TwoUsersEqualLifetimeDemoTest.java b/openvidu-demo/src/test/java/org/openvidu/test/demo/TwoUsersEqualLifetimeDemoTest.java new file mode 100644 index 00000000..70424a3e --- /dev/null +++ b/openvidu-demo/src/test/java/org/openvidu/test/demo/TwoUsersEqualLifetimeDemoTest.java @@ -0,0 +1,44 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.test.demo; + +import java.lang.invoke.MethodHandles; +import java.util.Collection; + +import org.junit.runners.Parameterized.Parameters; +import org.kurento.test.browser.WebPageType; +import org.openvidu.test.browser.TwoUsersEqualLifetime; + +/** + * @see TwoUsersEqualLifetime + * @author Radu Tom Vlad (rvlad@naevatec.com) + */ +public class TwoUsersEqualLifetimeDemoTest extends TwoUsersEqualLifetime { + + @Override + public void setupBrowserTest() throws InterruptedException { + webPageType = WebPageType.ROOT; + super.setupBrowserTest(); + } + + @Parameters(name = "{index}: {0}") + public static Collection data() { + return localChromes(MethodHandles.lookup().lookupClass().getSimpleName(), NUM_USERS, + WebPageType.ROOT); + } + +} diff --git a/openvidu-demo/src/test/java/org/openvidu/test/demo/UnpublishMediaDemoTest.java b/openvidu-demo/src/test/java/org/openvidu/test/demo/UnpublishMediaDemoTest.java new file mode 100644 index 00000000..3a8fdd7f --- /dev/null +++ b/openvidu-demo/src/test/java/org/openvidu/test/demo/UnpublishMediaDemoTest.java @@ -0,0 +1,44 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.test.demo; + +import java.lang.invoke.MethodHandles; +import java.util.Collection; + +import org.junit.runners.Parameterized.Parameters; +import org.kurento.test.browser.WebPageType; +import org.openvidu.test.browser.UnpublishMedia; + +/** + * @see UnpublishMedia + * @author Radu Tom Vlad (rvlad@naevatec.com) + */ +public class UnpublishMediaDemoTest extends UnpublishMedia { + + @Override + public void setupBrowserTest() throws InterruptedException { + webPageType = WebPageType.ROOT; + super.setupBrowserTest(); + } + + @Parameters(name = "{index}: {0}") + public static Collection data() { + return localChromes(MethodHandles.lookup().lookupClass().getSimpleName(), NUM_USERS, + WebPageType.ROOT); + } + +} diff --git a/openvidu-demo/src/test/java/org/openvidu/test/demo/UnsubscribeFromMediaDemoTest.java b/openvidu-demo/src/test/java/org/openvidu/test/demo/UnsubscribeFromMediaDemoTest.java new file mode 100644 index 00000000..cfc7776b --- /dev/null +++ b/openvidu-demo/src/test/java/org/openvidu/test/demo/UnsubscribeFromMediaDemoTest.java @@ -0,0 +1,43 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.test.demo; + +import java.lang.invoke.MethodHandles; +import java.util.Collection; + +import org.junit.runners.Parameterized.Parameters; +import org.kurento.test.browser.WebPageType; +import org.openvidu.test.browser.UnsubscribeFromMedia; + +/** + * @see UnsubscribeFromMedia + * @author Radu Tom Vlad (rvlad@naevatec.com) + */ +public class UnsubscribeFromMediaDemoTest extends UnsubscribeFromMedia { + + @Override + public void setupBrowserTest() throws InterruptedException { + webPageType = WebPageType.ROOT; + super.setupBrowserTest(); + } + + @Parameters(name = "{index}: {0}") + public static Collection data() { + return localChromes(MethodHandles.lookup().lookupClass().getSimpleName(), NUM_USERS, + WebPageType.ROOT); + } +} diff --git a/openvidu-demo/src/test/java/org/openvidu/test/demo/WebAppAvailabilityDemoTest.java b/openvidu-demo/src/test/java/org/openvidu/test/demo/WebAppAvailabilityDemoTest.java new file mode 100644 index 00000000..ec005803 --- /dev/null +++ b/openvidu-demo/src/test/java/org/openvidu/test/demo/WebAppAvailabilityDemoTest.java @@ -0,0 +1,43 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openvidu.test.demo; + +import java.lang.invoke.MethodHandles; +import java.util.Collection; + +import org.junit.runners.Parameterized.Parameters; +import org.kurento.test.browser.WebPageType; +import org.openvidu.test.browser.WebAppAvailability; + +/** + * @author Radu Tom Vlad (rvlad@naevatec.com) + * @see WebAppAvailability + */ +public class WebAppAvailabilityDemoTest extends WebAppAvailability { + + @Override + public void setupBrowserTest() throws InterruptedException { + webPageType = WebPageType.ROOT; + super.setupBrowserTest(); + } + + @Parameters(name = "{index}: {0}") + public static Collection data() { + return localChromes(MethodHandles.lookup().lookupClass().getSimpleName(), NUM_USERS, + WebPageType.ROOT); + } +} diff --git a/openvidu-demo/src/test/java/org/openvidu/test/demo/fake/ExtraKmsFakeUsersDemoTest.java b/openvidu-demo/src/test/java/org/openvidu/test/demo/fake/ExtraKmsFakeUsersDemoTest.java new file mode 100644 index 00000000..699426a7 --- /dev/null +++ b/openvidu-demo/src/test/java/org/openvidu/test/demo/fake/ExtraKmsFakeUsersDemoTest.java @@ -0,0 +1,43 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openvidu.test.demo.fake; + +import java.lang.invoke.MethodHandles; +import java.util.Collection; + +import org.junit.runners.Parameterized.Parameters; +import org.kurento.test.browser.WebPageType; +import org.openvidu.test.fake.ExtraKmsFakeUsers; + +/** + * @see ExtraKmsFakeUsers + * @author Radu Tom Vlad (rvlad@naevatec.com) + */ +public class ExtraKmsFakeUsersDemoTest extends ExtraKmsFakeUsers { + + @Override + public void setupBrowserTest() throws InterruptedException { + webPageType = WebPageType.ROOT; + super.setupBrowserTest(); + } + + @Parameters(name = "{index}: {0}") + public static Collection data() { + return localChromes(MethodHandles.lookup().lookupClass().getSimpleName(), NUM_USERS, + WebPageType.ROOT); + } + +} diff --git a/openvidu-demo/src/test/java/org/openvidu/test/demo/fake/MixedUsersDemoTest.java b/openvidu-demo/src/test/java/org/openvidu/test/demo/fake/MixedUsersDemoTest.java new file mode 100644 index 00000000..8af1c636 --- /dev/null +++ b/openvidu-demo/src/test/java/org/openvidu/test/demo/fake/MixedUsersDemoTest.java @@ -0,0 +1,43 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openvidu.test.demo.fake; + +import java.lang.invoke.MethodHandles; +import java.util.Collection; + +import org.junit.runners.Parameterized.Parameters; +import org.kurento.test.browser.WebPageType; +import org.openvidu.test.fake.MixedUsers; + +/** + * @see MixedUsers + * @author Radu Tom Vlad (rvlad@naevatec.com) + */ +public class MixedUsersDemoTest extends MixedUsers { + + @Override + public void setupBrowserTest() throws InterruptedException { + webPageType = WebPageType.ROOT; + super.setupBrowserTest(); + } + + @Parameters(name = "{index}: {0}") + public static Collection data() { + return localChromes(MethodHandles.lookup().lookupClass().getSimpleName(), CHROME_SPINNER_USERS, + WebPageType.ROOT); + } + +} diff --git a/openvidu-demo/src/test/java/org/openvidu/test/demo/fake/ParallelNFakeUsersDemoTest.java b/openvidu-demo/src/test/java/org/openvidu/test/demo/fake/ParallelNFakeUsersDemoTest.java new file mode 100644 index 00000000..505331e2 --- /dev/null +++ b/openvidu-demo/src/test/java/org/openvidu/test/demo/fake/ParallelNFakeUsersDemoTest.java @@ -0,0 +1,42 @@ +/* + * (C) Copyright 2015 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openvidu.test.demo.fake; + +import java.lang.invoke.MethodHandles; +import java.util.Collection; + +import org.junit.runners.Parameterized.Parameters; +import org.kurento.test.browser.WebPageType; +import org.openvidu.test.fake.ParallelNFakeUsers; + +/** + * @see ParallelNFakeUsers + * @author Radu Tom Vlad (rvlad@naevatec.com) + */ +public class ParallelNFakeUsersDemoTest extends ParallelNFakeUsers { + + @Override + public void setupBrowserTest() throws InterruptedException { + webPageType = WebPageType.ROOT; + super.setupBrowserTest(); + } + + @Parameters(name = "{index}: {0}") + public static Collection data() { + return localChromes(MethodHandles.lookup().lookupClass().getSimpleName(), NUM_USERS, + WebPageType.ROOT); + } +} diff --git a/openvidu-demo/src/test/resources/log4j.properties b/openvidu-demo/src/test/resources/log4j.properties new file mode 100644 index 00000000..26299d69 --- /dev/null +++ b/openvidu-demo/src/test/resources/log4j.properties @@ -0,0 +1,22 @@ +log4j.rootLogger=WARN,CONSOLE,file +log4j.logger.org.kurento=INFO +log4j.logger.org.kurento.client.internal=WARN +log4j.logger.org.kurento.room=DEBUG +log4j.logger.io.github.bonigarcia=DEBUG +log4j.logger.org.kurento.commons=DEBUG +log4j.logger.org.kurento.test=DEBUG + +# Appenders +log4j.threshold=ALL + +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p %c [%t] (%F:%L) - %m%n + +log4j.appender.file=org.apache.log4j.RollingFileAppender +log4j.appender.file.File=target/kurento-room-demo-test.log +log4j.appender.file.ImmediateFlush=true +log4j.appender.file.MaxFileSize=10MB +log4j.appender.file.MaxBackupIndex=50 +log4j.appender.file.layout=org.apache.log4j.PatternLayout +log4j.appender.file.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p [%t] %c (%F:%L(%M)) - %m%n diff --git a/openvidu-demo/src/test/resources/test.conf.json b/openvidu-demo/src/test/resources/test.conf.json new file mode 100644 index 00000000..a02fcc75 --- /dev/null +++ b/openvidu-demo/src/test/resources/test.conf.json @@ -0,0 +1,30 @@ +{ + "kurento": { + "client": { + //milliseconds + "requestTimeout": 20000 + }, + "test": { + "fake": { + //"kmsUri": "ws://127.0.0.1:8888/kurento", + "wr": { + //absolute path on the KMS's machine or http resource + //"files": "/tmp", + + //readable by the user that runs KMS (default is nobody:nogroup) + //"filenames": [] + } + }, + "chrome": { + //if not absolute path, is considered relative to user's home + //"files": "/tmp", + + //accessible to the user that runs the test + "filenames": { + "wav": [], + "y4m": ["video/15sec/rgbHD.y4m"] + } + } + } + } +} diff --git a/openvidu-sampleapp-minimal/.classpath b/openvidu-sampleapp-minimal/.classpath new file mode 100644 index 00000000..fae1a2b3 --- /dev/null +++ b/openvidu-sampleapp-minimal/.classpath @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/openvidu-sampleapp-minimal/.gitignore b/openvidu-sampleapp-minimal/.gitignore new file mode 100644 index 00000000..b83d2226 --- /dev/null +++ b/openvidu-sampleapp-minimal/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/openvidu-sampleapp-minimal/.project b/openvidu-sampleapp-minimal/.project new file mode 100644 index 00000000..7a152f8c --- /dev/null +++ b/openvidu-sampleapp-minimal/.project @@ -0,0 +1,23 @@ + + + openvidu-sampleapp-minimal + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/openvidu-sampleapp-minimal/.settings/org.eclipse.core.resources.prefs b/openvidu-sampleapp-minimal/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 00000000..29abf999 --- /dev/null +++ b/openvidu-sampleapp-minimal/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,6 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/main/resources=UTF-8 +encoding//src/test/java=UTF-8 +encoding//src/test/resources=UTF-8 +encoding/=UTF-8 diff --git a/openvidu-sampleapp-minimal/.settings/org.eclipse.jdt.core.prefs b/openvidu-sampleapp-minimal/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000..714351ae --- /dev/null +++ b/openvidu-sampleapp-minimal/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,5 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/openvidu-sampleapp-minimal/.settings/org.eclipse.m2e.core.prefs b/openvidu-sampleapp-minimal/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 00000000..f897a7f1 --- /dev/null +++ b/openvidu-sampleapp-minimal/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/openvidu-sampleapp-minimal/LICENSE b/openvidu-sampleapp-minimal/LICENSE new file mode 100644 index 00000000..7a4a3ea2 --- /dev/null +++ b/openvidu-sampleapp-minimal/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/openvidu-sampleapp-minimal/NOTICE b/openvidu-sampleapp-minimal/NOTICE new file mode 100644 index 00000000..b7393e6f --- /dev/null +++ b/openvidu-sampleapp-minimal/NOTICE @@ -0,0 +1,13 @@ +(C) Copyright 2016 Kurento (http://kurento.org) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/openvidu-sampleapp-minimal/README.md b/openvidu-sampleapp-minimal/README.md new file mode 100644 index 00000000..7e0867c6 --- /dev/null +++ b/openvidu-sampleapp-minimal/README.md @@ -0,0 +1,116 @@ +[![License badge](https://img.shields.io/badge/license-Apache2-orange.svg)](http://www.apache.org/licenses/LICENSE-2.0) +[![Documentation badge](https://readthedocs.org/projects/fiware-orion/badge/?version=latest)](http://doc-kurento-room.readthedocs.org/en/latest/) +[![Docker badge](https://img.shields.io/docker/pulls/fiware/orion.svg)](https://hub.docker.com/r/fiware/stream-oriented-kurento/) +[![Support badge]( https://img.shields.io/badge/support-sof-yellowgreen.svg)](http://stackoverflow.com/questions/tagged/kurento) + +[![][KurentoImage]][Kurento] + +Copyright © 2013-2016 [Kurento]. Licensed under [Apache 2.0 License]. + +kurento-room-basicapp +========== + +This project contains a lighter or more basic Kurento Room demo application. + +What is Kurento +--------------- + +Kurento is an open source software project providing a platform suitable +for creating modular applications with advanced real-time communication +capabilities. For knowing more about Kurento, please visit the Kurento +project website: http://www.kurento.org. + +Kurento is part of [FIWARE]. For further information on the relationship of +FIWARE and Kurento check the [Kurento FIWARE Catalog Entry] + +Kurento is part of the [NUBOMEDIA] research initiative. + +Documentation +------------- + +The Kurento project provides detailed [documentation] including tutorials, +installation and development guides. A simplified version of the documentation +can be found on [readthedocs.org]. The [Open API specification] a.k.a. Kurento +Protocol is also available on [apiary.io]. + +Source +------ + +Code for other Kurento projects can be found in the [GitHub Kurento Group]. + +News and Website +---------------- + +Check the [Kurento blog] +Follow us on Twitter @[kurentoms]. + +Issue tracker +------------- + +Issues and bug reports should be posted to the [GitHub Kurento bugtracker] + +Licensing and distribution +-------------------------- + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Contribution policy +------------------- + +You can contribute to the Kurento community through bug-reports, bug-fixes, new +code or new documentation. For contributing to the Kurento community, drop a +post to the [Kurento Public Mailing List] providing full information about your +contribution and its value. In your contributions, you must comply with the +following guidelines + +* You must specify the specific contents of your contribution either through a + detailed bug description, through a pull-request or through a patch. +* You must specify the licensing restrictions of the code you contribute. +* For newly created code to be incorporated in the Kurento code-base, you must + accept Kurento to own the code copyright, so that its open source nature is + guaranteed. +* You must justify appropriately the need and value of your contribution. The + Kurento project has no obligations in relation to accepting contributions + from third parties. +* The Kurento project leaders have the right of asking for further + explanations, tests or validations of any code contributed to the community + before it being incorporated into the Kurento code-base. You must be ready to + addressing all these kind of concerns before having your code approved. + +Support +------- + +The Kurento project provides community support through the [Kurento Public +Mailing List] and through [StackOverflow] using the tags *kurento* and +*fiware-kurento*. + +Before asking for support, please read first the [Kurento Netiquette Guidelines] + +[documentation]: http://www.kurento.org/documentation +[FIWARE]: http://www.fiware.org +[GitHub Kurento bugtracker]: https://github.com/Kurento/bugtracker/issues +[GitHub Kurento Group]: https://github.com/kurento +[kurentoms]: http://twitter.com/kurentoms +[Kurento]: http://kurento.org +[Kurento Blog]: http://www.kurento.org/blog +[Kurento FIWARE Catalog Entry]: http://catalogue.fiware.org/enablers/stream-oriented-kurento +[Kurento Netiquette Guidelines]: http://www.kurento.org/blog/kurento-netiquette-guidelines +[Kurento Public Mailing list]: https://groups.google.com/forum/#!forum/kurento +[KurentoImage]: https://secure.gravatar.com/avatar/21a2a12c56b2a91c8918d5779f1778bf?s=120 +[Apache 2.0 License]: http://www.apache.org/licenses/LICENSE-2.0 +[NUBOMEDIA]: http://www.nubomedia.eu +[StackOverflow]: http://stackoverflow.com/search?q=kurento +[Read-the-docs]: http://read-the-docs.readthedocs.org/ +[readthedocs.org]: http://kurento.readthedocs.org/ +[Open API specification]: http://kurento.github.io/doc-kurento/ +[apiary.io]: http://docs.streamoriented.apiary.io/ diff --git a/openvidu-sampleapp-minimal/pom.xml b/openvidu-sampleapp-minimal/pom.xml new file mode 100644 index 00000000..71df52f3 --- /dev/null +++ b/openvidu-sampleapp-minimal/pom.xml @@ -0,0 +1,247 @@ + + 4.0.0 + + + org.openvidu + openvidu + 6.6.1-SNAPSHOT + ../ + + openvidu-sampleapp-minimal + jar + + OpenVidu Sample App "Minimal" + + This project contains a minimal sample app using OpenVidu platorm. + + http://www.kurento.org/docs/${project.version} + + + + Apache 2.0 + http://www.apache.org/licenses/LICENSE-2.0 + repo + + + + + Kurento + http://www.kurento.org + + + + ${openvidu.scm.url} + scm:git:${openvidu.scm.connection} + scm:git:${openvidu.scm.connection} + develop + + + + + kurento.org + -kurento.org Community + Kurento.org + http://www.kurento.org + + + + + + org.openvidu.room.basic.KurentoRoomBasicApp + + + + + + src/main/resources + false + + + src/main/resources + true + + banner.txt + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + ${start-class} + ZIP + + + + + repackage + + + + + + org.codehaus.mojo + exec-maven-plugin + + + java + + java + + + + + ${start-class} + + + + org.apache.maven.plugins + maven-assembly-plugin + + src/assembly/bin.xml + ${project.artifactId}-${project.version} + false + + + + package + + single + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + package + + + + + + + + + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.codehaus.mojo + + + exec-maven-plugin + + + [1.0.0,) + + + exec + + + + + + + + + + org.apache.maven.plugins + + + maven-dependency-plugin + + + [2.8,) + + + unpack + + + + + + + + + + + + + + + + + org.openvidu + openvidu-server + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.openvidu + openvidu-client-js + + + org.springframework.boot + spring-boot-starter-log4j2 + + + org.openvidu + openvidu-test + test + + + + + + default + + true + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + org.apache.maven.plugins + maven-failsafe-plugin + + true + + + + + + + integration + + + diff --git a/openvidu-sampleapp-minimal/src/assembly/bin.xml b/openvidu-sampleapp-minimal/src/assembly/bin.xml new file mode 100644 index 00000000..6bb59757 --- /dev/null +++ b/openvidu-sampleapp-minimal/src/assembly/bin.xml @@ -0,0 +1,27 @@ + + bin + + zip + + + + + + target/${project.artifactId}-${project.version}.jar + lib + + kroombasic.jar + + + + + + package + + + + + \ No newline at end of file diff --git a/openvidu-sampleapp-minimal/src/main/java/org/openvidu/sampleapp/minimal/OpenViduSampleApp.java b/openvidu-sampleapp-minimal/src/main/java/org/openvidu/sampleapp/minimal/OpenViduSampleApp.java new file mode 100644 index 00000000..110ee2c6 --- /dev/null +++ b/openvidu-sampleapp-minimal/src/main/java/org/openvidu/sampleapp/minimal/OpenViduSampleApp.java @@ -0,0 +1,42 @@ +/* + * (C) Copyright 2016 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openvidu.sampleapp.minimal; + +import org.kurento.commons.ConfigFileManager; +import org.openvidu.server.OpenViduServer; +import org.springframework.boot.SpringApplication; +import org.springframework.context.annotation.Import; + +/** + * Basic demo application for Kurento Room, uses the Room Server and the Room Client JS libraries. + * + * @author Micael Gallego (micael.gallego@gmail.com) + * @author Radu Tom Vlad (rvlad@naevatec.com) + * @since 5.0.0 + */ +@Import(OpenViduServer.class) +public class OpenViduSampleApp { + + private final static String BASICAPP_CFG_FILENAME = "kroombasic.conf.json"; + + static { + ConfigFileManager.loadConfigFile(BASICAPP_CFG_FILENAME); + } + + public static void main(String[] args) { + SpringApplication.run(OpenViduSampleApp.class, args); + } +} diff --git a/openvidu-sampleapp-minimal/src/main/resources/application.properties b/openvidu-sampleapp-minimal/src/main/resources/application.properties new file mode 100644 index 00000000..be1d5476 --- /dev/null +++ b/openvidu-sampleapp-minimal/src/main/resources/application.properties @@ -0,0 +1,5 @@ +server.port: 8443 +server.ssl.key-store: classpath:keystore.jks +server.ssl.key-store-password: kurento +server.ssl.keyStoreType: JKS +server.ssl.keyAlias: kurento-selfsigned diff --git a/openvidu-sampleapp-minimal/src/main/resources/banner.txt b/openvidu-sampleapp-minimal/src/main/resources/banner.txt new file mode 100644 index 00000000..03e81872 --- /dev/null +++ b/openvidu-sampleapp-minimal/src/main/resources/banner.txt @@ -0,0 +1,10 @@ + +================================================== + ____ _ ___ __ + / __ \____ ___ ____| | / (_)___/ /_ __ + / / / / __ \/ _ \/ __ \ | / / / __ / / / / + / /_/ / /_/ / __/ / / / |/ / / /_/ / /_/ / + \____/ .___/\___/_/ /_/|___/_/\__,_/\__,_/ + /_/ + v${project.version} +================================================== diff --git a/openvidu-sampleapp-minimal/src/main/resources/keystore.jks b/openvidu-sampleapp-minimal/src/main/resources/keystore.jks new file mode 100644 index 00000000..c13f8038 Binary files /dev/null and b/openvidu-sampleapp-minimal/src/main/resources/keystore.jks differ diff --git a/openvidu-sampleapp-minimal/src/main/resources/kroombasic.conf.json b/openvidu-sampleapp-minimal/src/main/resources/kroombasic.conf.json new file mode 100644 index 00000000..675a1958 --- /dev/null +++ b/openvidu-sampleapp-minimal/src/main/resources/kroombasic.conf.json @@ -0,0 +1,13 @@ +{ + "kms": { + "uris": [ + "ws://127.0.0.1:8888/kurento" + ] + }, + "kurento": { + "client": { + //milliseconds + "requestTimeout": 20000 + } + } +} diff --git a/openvidu-sampleapp-minimal/src/main/resources/log4j.properties b/openvidu-sampleapp-minimal/src/main/resources/log4j.properties new file mode 100644 index 00000000..ecbc4db1 --- /dev/null +++ b/openvidu-sampleapp-minimal/src/main/resources/log4j.properties @@ -0,0 +1,21 @@ +log4j.rootLogger=WARN,CONSOLE,file +log4j.logger.org.kurento=WARN +log4j.logger.org.kurento.commons=DEBUG +log4j.logger.org.kurento.room=INFO +log4j.logger.org.kurento.room.test=DEBUG +log4j.logger.io.github.bonigarcia=DEBUG + +# Appenders +log4j.threshold=ALL + +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%d{HH:mm:ss} %-5p %c [%t] (%F:%L) - %m%n + +log4j.appender.file=org.apache.log4j.RollingFileAppender +log4j.appender.file.File=target/kurento-room-test.log +log4j.appender.file.ImmediateFlush=true +log4j.appender.file.MaxFileSize=10MB +log4j.appender.file.MaxBackupIndex=50 +log4j.appender.file.layout=org.apache.log4j.PatternLayout +log4j.appender.file.layout.ConversionPattern=%d{ISO8601} %-5p [%t] %c (%F:%L(%M)) - %m%n diff --git a/openvidu-sampleapp-minimal/src/main/resources/static/index.html b/openvidu-sampleapp-minimal/src/main/resources/static/index.html new file mode 100644 index 00000000..eef0c61a --- /dev/null +++ b/openvidu-sampleapp-minimal/src/main/resources/static/index.html @@ -0,0 +1,50 @@ + + +Room Example + + + + + + + + + + + + + + + + + +
+
+
+

Join a Room

+
+

+ +

+

+ +

+

+ +

+
+
+ +
+
+
+ + diff --git a/openvidu-sampleapp-minimal/src/main/resources/static/js/EventEmitter.js b/openvidu-sampleapp-minimal/src/main/resources/static/js/EventEmitter.js new file mode 100644 index 00000000..7de59ff3 --- /dev/null +++ b/openvidu-sampleapp-minimal/src/main/resources/static/js/EventEmitter.js @@ -0,0 +1,472 @@ +/*! + * EventEmitter v4.2.11 - git.io/ee + * Unlicense - http://unlicense.org/ + * Oliver Caldwell - http://oli.me.uk/ + * @preserve + */ + +;(function () { + 'use strict'; + + /** + * Class for managing events. + * Can be extended to provide event functionality in other classes. + * + * @class EventEmitter Manages event registering and emitting. + */ + function EventEmitter() {} + + // Shortcuts to improve speed and size + var proto = EventEmitter.prototype; + var exports = this; + var originalGlobalValue = exports.EventEmitter; + + /** + * Finds the index of the listener for the event in its storage array. + * + * @param {Function[]} listeners Array of listeners to search through. + * @param {Function} listener Method to look for. + * @return {Number} Index of the specified listener, -1 if not found + * @api private + */ + function indexOfListener(listeners, listener) { + var i = listeners.length; + while (i--) { + if (listeners[i].listener === listener) { + return i; + } + } + + return -1; + } + + /** + * Alias a method while keeping the context correct, to allow for overwriting of target method. + * + * @param {String} name The name of the target method. + * @return {Function} The aliased method + * @api private + */ + function alias(name) { + return function aliasClosure() { + return this[name].apply(this, arguments); + }; + } + + /** + * Returns the listener array for the specified event. + * Will initialise the event object and listener arrays if required. + * Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them. + * Each property in the object response is an array of listener functions. + * + * @param {String|RegExp} evt Name of the event to return the listeners from. + * @return {Function[]|Object} All listener functions for the event. + */ + proto.getListeners = function getListeners(evt) { + var events = this._getEvents(); + var response; + var key; + + // Return a concatenated array of all matching events if + // the selector is a regular expression. + if (evt instanceof RegExp) { + response = {}; + for (key in events) { + if (events.hasOwnProperty(key) && evt.test(key)) { + response[key] = events[key]; + } + } + } + else { + response = events[evt] || (events[evt] = []); + } + + return response; + }; + + /** + * Takes a list of listener objects and flattens it into a list of listener functions. + * + * @param {Object[]} listeners Raw listener objects. + * @return {Function[]} Just the listener functions. + */ + proto.flattenListeners = function flattenListeners(listeners) { + var flatListeners = []; + var i; + + for (i = 0; i < listeners.length; i += 1) { + flatListeners.push(listeners[i].listener); + } + + return flatListeners; + }; + + /** + * Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful. + * + * @param {String|RegExp} evt Name of the event to return the listeners from. + * @return {Object} All listener functions for an event in an object. + */ + proto.getListenersAsObject = function getListenersAsObject(evt) { + var listeners = this.getListeners(evt); + var response; + + if (listeners instanceof Array) { + response = {}; + response[evt] = listeners; + } + + return response || listeners; + }; + + /** + * Adds a listener function to the specified event. + * The listener will not be added if it is a duplicate. + * If the listener returns true then it will be removed after it is called. + * If you pass a regular expression as the event name then the listener will be added to all events that match it. + * + * @param {String|RegExp} evt Name of the event to attach the listener to. + * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.addListener = function addListener(evt, listener) { + var listeners = this.getListenersAsObject(evt); + var listenerIsWrapped = typeof listener === 'object'; + var key; + + for (key in listeners) { + if (listeners.hasOwnProperty(key) && indexOfListener(listeners[key], listener) === -1) { + listeners[key].push(listenerIsWrapped ? listener : { + listener: listener, + once: false + }); + } + } + + return this; + }; + + /** + * Alias of addListener + */ + proto.on = alias('addListener'); + + /** + * Semi-alias of addListener. It will add a listener that will be + * automatically removed after its first execution. + * + * @param {String|RegExp} evt Name of the event to attach the listener to. + * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.addOnceListener = function addOnceListener(evt, listener) { + return this.addListener(evt, { + listener: listener, + once: true + }); + }; + + /** + * Alias of addOnceListener. + */ + proto.once = alias('addOnceListener'); + + /** + * Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad. + * You need to tell it what event names should be matched by a regex. + * + * @param {String} evt Name of the event to create. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.defineEvent = function defineEvent(evt) { + this.getListeners(evt); + return this; + }; + + /** + * Uses defineEvent to define multiple events. + * + * @param {String[]} evts An array of event names to define. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.defineEvents = function defineEvents(evts) { + for (var i = 0; i < evts.length; i += 1) { + this.defineEvent(evts[i]); + } + return this; + }; + + /** + * Removes a listener function from the specified event. + * When passed a regular expression as the event name, it will remove the listener from all events that match it. + * + * @param {String|RegExp} evt Name of the event to remove the listener from. + * @param {Function} listener Method to remove from the event. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.removeListener = function removeListener(evt, listener) { + var listeners = this.getListenersAsObject(evt); + var index; + var key; + + for (key in listeners) { + if (listeners.hasOwnProperty(key)) { + index = indexOfListener(listeners[key], listener); + + if (index !== -1) { + listeners[key].splice(index, 1); + } + } + } + + return this; + }; + + /** + * Alias of removeListener + */ + proto.off = alias('removeListener'); + + /** + * Adds listeners in bulk using the manipulateListeners method. + * If you pass an object as the second argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added. + * You can also pass it a regular expression to add the array of listeners to all events that match it. + * Yeah, this function does quite a bit. That's probably a bad thing. + * + * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once. + * @param {Function[]} [listeners] An optional array of listener functions to add. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.addListeners = function addListeners(evt, listeners) { + // Pass through to manipulateListeners + return this.manipulateListeners(false, evt, listeners); + }; + + /** + * Removes listeners in bulk using the manipulateListeners method. + * If you pass an object as the second argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. + * You can also pass it an event name and an array of listeners to be removed. + * You can also pass it a regular expression to remove the listeners from all events that match it. + * + * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once. + * @param {Function[]} [listeners] An optional array of listener functions to remove. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.removeListeners = function removeListeners(evt, listeners) { + // Pass through to manipulateListeners + return this.manipulateListeners(true, evt, listeners); + }; + + /** + * Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level. + * The first argument will determine if the listeners are removed (true) or added (false). + * If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. + * You can also pass it an event name and an array of listeners to be added/removed. + * You can also pass it a regular expression to manipulate the listeners of all events that match it. + * + * @param {Boolean} remove True if you want to remove listeners, false if you want to add. + * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once. + * @param {Function[]} [listeners] An optional array of listener functions to add/remove. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.manipulateListeners = function manipulateListeners(remove, evt, listeners) { + var i; + var value; + var single = remove ? this.removeListener : this.addListener; + var multiple = remove ? this.removeListeners : this.addListeners; + + // If evt is an object then pass each of its properties to this method + if (typeof evt === 'object' && !(evt instanceof RegExp)) { + for (i in evt) { + if (evt.hasOwnProperty(i) && (value = evt[i])) { + // Pass the single listener straight through to the singular method + if (typeof value === 'function') { + single.call(this, i, value); + } + else { + // Otherwise pass back to the multiple function + multiple.call(this, i, value); + } + } + } + } + else { + // So evt must be a string + // And listeners must be an array of listeners + // Loop over it and pass each one to the multiple method + i = listeners.length; + while (i--) { + single.call(this, evt, listeners[i]); + } + } + + return this; + }; + + /** + * Removes all listeners from a specified event. + * If you do not specify an event then all listeners will be removed. + * That means every event will be emptied. + * You can also pass a regex to remove all events that match it. + * + * @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.removeEvent = function removeEvent(evt) { + var type = typeof evt; + var events = this._getEvents(); + var key; + + // Remove different things depending on the state of evt + if (type === 'string') { + // Remove all listeners for the specified event + delete events[evt]; + } + else if (evt instanceof RegExp) { + // Remove all events matching the regex. + for (key in events) { + if (events.hasOwnProperty(key) && evt.test(key)) { + delete events[key]; + } + } + } + else { + // Remove all listeners in all events + delete this._events; + } + + return this; + }; + + /** + * Alias of removeEvent. + * + * Added to mirror the node API. + */ + proto.removeAllListeners = alias('removeEvent'); + + /** + * Emits an event of your choice. + * When emitted, every listener attached to that event will be executed. + * If you pass the optional argument array then those arguments will be passed to every listener upon execution. + * Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately. + * So they will not arrive within the array on the other side, they will be separate. + * You can also pass a regular expression to emit to all events that match it. + * + * @param {String|RegExp} evt Name of the event to emit and execute listeners for. + * @param {Array} [args] Optional array of arguments to be passed to each listener. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.emitEvent = function emitEvent(evt, args) { + var listeners = this.getListenersAsObject(evt); + var listener; + var i; + var key; + var response; + + for (key in listeners) { + if (listeners.hasOwnProperty(key)) { + i = listeners[key].length; + + while (i--) { + // If the listener returns true then it shall be removed from the event + // The function is executed either with a basic call or an apply if there is an args array + listener = listeners[key][i]; + + if (listener.once === true) { + this.removeListener(evt, listener.listener); + } + + response = listener.listener.apply(this, args || []); + + if (response === this._getOnceReturnValue()) { + this.removeListener(evt, listener.listener); + } + } + } + } + + return this; + }; + + /** + * Alias of emitEvent + */ + proto.trigger = alias('emitEvent'); + + /** + * Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on. + * As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it. + * + * @param {String|RegExp} evt Name of the event to emit and execute listeners for. + * @param {...*} Optional additional arguments to be passed to each listener. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.emit = function emit(evt) { + var args = Array.prototype.slice.call(arguments, 1); + return this.emitEvent(evt, args); + }; + + /** + * Sets the current value to check against when executing listeners. If a + * listeners return value matches the one set here then it will be removed + * after execution. This value defaults to true. + * + * @param {*} value The new value to check for when executing listeners. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.setOnceReturnValue = function setOnceReturnValue(value) { + this._onceReturnValue = value; + return this; + }; + + /** + * Fetches the current value to check against when executing listeners. If + * the listeners return value matches this one then it should be removed + * automatically. It will return true by default. + * + * @return {*|Boolean} The current value to check for or the default, true. + * @api private + */ + proto._getOnceReturnValue = function _getOnceReturnValue() { + if (this.hasOwnProperty('_onceReturnValue')) { + return this._onceReturnValue; + } + else { + return true; + } + }; + + /** + * Fetches the events object and creates one if required. + * + * @return {Object} The events storage object. + * @api private + */ + proto._getEvents = function _getEvents() { + return this._events || (this._events = {}); + }; + + /** + * Reverts the global {@link EventEmitter} to its previous value and returns a reference to this version. + * + * @return {Function} Non conflicting EventEmitter class. + */ + EventEmitter.noConflict = function noConflict() { + exports.EventEmitter = originalGlobalValue; + return EventEmitter; + }; + + // Expose the class either via AMD, CommonJS or the global object + if (typeof define === 'function' && define.amd) { + define(function () { + return EventEmitter; + }); + } + else if (typeof module === 'object' && module.exports){ + module.exports = EventEmitter; + } + else { + exports.EventEmitter = EventEmitter; + } +}.call(this)); \ No newline at end of file diff --git a/openvidu-sampleapp-minimal/src/main/resources/static/js/adapter.js b/openvidu-sampleapp-minimal/src/main/resources/static/js/adapter.js new file mode 100644 index 00000000..d9d5e708 --- /dev/null +++ b/openvidu-sampleapp-minimal/src/main/resources/static/js/adapter.js @@ -0,0 +1,536 @@ +/* + * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. + */ + +/* More information about these options at jshint.com/docs/options */ +/* jshint browser: true, camelcase: true, curly: true, devel: true, + eqeqeq: true, forin: false, globalstrict: true, node: true, + quotmark: single, undef: true, unused: strict */ +/* global mozRTCIceCandidate, mozRTCPeerConnection, Promise, +mozRTCSessionDescription, webkitRTCPeerConnection, MediaStreamTrack */ +/* exported trace,requestUserMedia */ + +'use strict'; + +var getUserMedia = null; +var attachMediaStream = null; +var reattachMediaStream = null; +var webrtcDetectedBrowser = null; +var webrtcDetectedVersion = null; +var webrtcMinimumVersion = null; +var webrtcUtils = { + log: function() { + // suppress console.log output when being included as a module. + if (typeof module !== 'undefined' || + typeof require === 'function' && typeof define === 'function') { + return; + } + console.log.apply(console, arguments); + } +}; + +function trace(text) { + // This function is used for logging. + if (text[text.length - 1] === '\n') { + text = text.substring(0, text.length - 1); + } + if (window.performance) { + var now = (window.performance.now() / 1000).toFixed(3); + webrtcUtils.log(now + ': ' + text); + } else { + webrtcUtils.log(text); + } +} + +if (typeof window === 'object') { + if (window.HTMLMediaElement && + !('srcObject' in window.HTMLMediaElement.prototype)) { + // Shim the srcObject property, once, when HTMLMediaElement is found. + Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', { + get: function() { + // If prefixed srcObject property exists, return it. + // Otherwise use the shimmed property, _srcObject + return 'mozSrcObject' in this ? this.mozSrcObject : this._srcObject; + }, + set: function(stream) { + if ('mozSrcObject' in this) { + this.mozSrcObject = stream; + } else { + // Use _srcObject as a private property for this shim + this._srcObject = stream; + // TODO: revokeObjectUrl(this.src) when !stream to release resources? + this.src = URL.createObjectURL(stream); + } + } + }); + } + // Proxy existing globals + getUserMedia = window.navigator && window.navigator.getUserMedia; +} + +// Attach a media stream to an element. +attachMediaStream = function(element, stream) { + element.srcObject = stream; +}; + +reattachMediaStream = function(to, from) { + to.srcObject = from.srcObject; +}; + +if (typeof window === 'undefined' || !window.navigator) { + webrtcUtils.log('This does not appear to be a browser'); + webrtcDetectedBrowser = 'not a browser'; +} else if (navigator.mozGetUserMedia && window.mozRTCPeerConnection) { + webrtcUtils.log('This appears to be Firefox'); + + webrtcDetectedBrowser = 'firefox'; + + // the detected firefox version. + webrtcDetectedVersion = + parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10); + + // the minimum firefox version still supported by adapter. + webrtcMinimumVersion = 31; + + // The RTCPeerConnection object. + window.RTCPeerConnection = function(pcConfig, pcConstraints) { + if (webrtcDetectedVersion < 38) { + // .urls is not supported in FF < 38. + // create RTCIceServers with a single url. + if (pcConfig && pcConfig.iceServers) { + var newIceServers = []; + for (var i = 0; i < pcConfig.iceServers.length; i++) { + var server = pcConfig.iceServers[i]; + if (server.hasOwnProperty('urls')) { + for (var j = 0; j < server.urls.length; j++) { + var newServer = { + url: server.urls[j] + }; + if (server.urls[j].indexOf('turn') === 0) { + newServer.username = server.username; + newServer.credential = server.credential; + } + newIceServers.push(newServer); + } + } else { + newIceServers.push(pcConfig.iceServers[i]); + } + } + pcConfig.iceServers = newIceServers; + } + } + return new mozRTCPeerConnection(pcConfig, pcConstraints); // jscs:ignore requireCapitalizedConstructors + }; + + // The RTCSessionDescription object. + window.RTCSessionDescription = mozRTCSessionDescription; + + // The RTCIceCandidate object. + window.RTCIceCandidate = mozRTCIceCandidate; + + // getUserMedia constraints shim. + getUserMedia = function(constraints, onSuccess, onError) { + var constraintsToFF37 = function(c) { + if (typeof c !== 'object' || c.require) { + return c; + } + var require = []; + Object.keys(c).forEach(function(key) { + if (key === 'require' || key === 'advanced' || key === 'mediaSource') { + return; + } + var r = c[key] = (typeof c[key] === 'object') ? + c[key] : {ideal: c[key]}; + if (r.min !== undefined || + r.max !== undefined || r.exact !== undefined) { + require.push(key); + } + if (r.exact !== undefined) { + if (typeof r.exact === 'number') { + r.min = r.max = r.exact; + } else { + c[key] = r.exact; + } + delete r.exact; + } + if (r.ideal !== undefined) { + c.advanced = c.advanced || []; + var oc = {}; + if (typeof r.ideal === 'number') { + oc[key] = {min: r.ideal, max: r.ideal}; + } else { + oc[key] = r.ideal; + } + c.advanced.push(oc); + delete r.ideal; + if (!Object.keys(r).length) { + delete c[key]; + } + } + }); + if (require.length) { + c.require = require; + } + return c; + }; + if (webrtcDetectedVersion < 38) { + webrtcUtils.log('spec: ' + JSON.stringify(constraints)); + if (constraints.audio) { + constraints.audio = constraintsToFF37(constraints.audio); + } + if (constraints.video) { + constraints.video = constraintsToFF37(constraints.video); + } + webrtcUtils.log('ff37: ' + JSON.stringify(constraints)); + } + return navigator.mozGetUserMedia(constraints, onSuccess, onError); + }; + + navigator.getUserMedia = getUserMedia; + + // Shim for mediaDevices on older versions. + if (!navigator.mediaDevices) { + navigator.mediaDevices = {getUserMedia: requestUserMedia, + addEventListener: function() { }, + removeEventListener: function() { } + }; + } + navigator.mediaDevices.enumerateDevices = + navigator.mediaDevices.enumerateDevices || function() { + return new Promise(function(resolve) { + var infos = [ + {kind: 'audioinput', deviceId: 'default', label: '', groupId: ''}, + {kind: 'videoinput', deviceId: 'default', label: '', groupId: ''} + ]; + resolve(infos); + }); + }; + + if (webrtcDetectedVersion < 41) { + // Work around http://bugzil.la/1169665 + var orgEnumerateDevices = + navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices); + navigator.mediaDevices.enumerateDevices = function() { + return orgEnumerateDevices().catch(function(e) { + if (e.name === 'NotFoundError') { + return []; + } + throw e; + }); + }; + } +} else if (navigator.webkitGetUserMedia && !!window.chrome) { + webrtcUtils.log('This appears to be Chrome'); + + webrtcDetectedBrowser = 'chrome'; + + // the detected chrome version. + webrtcDetectedVersion = + parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10); + + // the minimum chrome version still supported by adapter. + webrtcMinimumVersion = 38; + + // The RTCPeerConnection object. + window.RTCPeerConnection = function(pcConfig, pcConstraints) { + // Translate iceTransportPolicy to iceTransports, + // see https://code.google.com/p/webrtc/issues/detail?id=4869 + if (pcConfig && pcConfig.iceTransportPolicy) { + pcConfig.iceTransports = pcConfig.iceTransportPolicy; + } + + var pc = new webkitRTCPeerConnection(pcConfig, pcConstraints); // jscs:ignore requireCapitalizedConstructors + var origGetStats = pc.getStats.bind(pc); + pc.getStats = function(selector, successCallback, errorCallback) { // jshint ignore: line + var self = this; + var args = arguments; + + // If selector is a function then we are in the old style stats so just + // pass back the original getStats format to avoid breaking old users. + if (arguments.length > 0 && typeof selector === 'function') { + return origGetStats(selector, successCallback); + } + + var fixChromeStats = function(response) { + var standardReport = {}; + var reports = response.result(); + reports.forEach(function(report) { + var standardStats = { + id: report.id, + timestamp: report.timestamp, + type: report.type + }; + report.names().forEach(function(name) { + standardStats[name] = report.stat(name); + }); + standardReport[standardStats.id] = standardStats; + }); + + return standardReport; + }; + + if (arguments.length >= 2) { + var successCallbackWrapper = function(response) { + args[1](fixChromeStats(response)); + }; + + return origGetStats.apply(this, [successCallbackWrapper, arguments[0]]); + } + + // promise-support + return new Promise(function(resolve, reject) { + if (args.length === 1 && selector === null) { + origGetStats.apply(self, [ + function(response) { + resolve.apply(null, [fixChromeStats(response)]); + }, reject]); + } else { + origGetStats.apply(self, [resolve, reject]); + } + }); + }; + + return pc; + }; + + // add promise support + ['createOffer', 'createAnswer'].forEach(function(method) { + var nativeMethod = webkitRTCPeerConnection.prototype[method]; + webkitRTCPeerConnection.prototype[method] = function() { + var self = this; + if (arguments.length < 1 || (arguments.length === 1 && + typeof(arguments[0]) === 'object')) { + var opts = arguments.length === 1 ? arguments[0] : undefined; + return new Promise(function(resolve, reject) { + nativeMethod.apply(self, [resolve, reject, opts]); + }); + } else { + return nativeMethod.apply(this, arguments); + } + }; + }); + + ['setLocalDescription', 'setRemoteDescription', + 'addIceCandidate'].forEach(function(method) { + var nativeMethod = webkitRTCPeerConnection.prototype[method]; + webkitRTCPeerConnection.prototype[method] = function() { + var args = arguments; + var self = this; + return new Promise(function(resolve, reject) { + nativeMethod.apply(self, [args[0], + function() { + resolve(); + if (args.length >= 2) { + args[1].apply(null, []); + } + }, + function(err) { + reject(err); + if (args.length >= 3) { + args[2].apply(null, [err]); + } + }] + ); + }); + }; + }); + + // getUserMedia constraints shim. + var constraintsToChrome = function(c) { + if (typeof c !== 'object' || c.mandatory || c.optional) { + return c; + } + var cc = {}; + Object.keys(c).forEach(function(key) { + if (key === 'require' || key === 'advanced' || key === 'mediaSource') { + return; + } + var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]}; + if (r.exact !== undefined && typeof r.exact === 'number') { + r.min = r.max = r.exact; + } + var oldname = function(prefix, name) { + if (prefix) { + return prefix + name.charAt(0).toUpperCase() + name.slice(1); + } + return (name === 'deviceId') ? 'sourceId' : name; + }; + if (r.ideal !== undefined) { + cc.optional = cc.optional || []; + var oc = {}; + if (typeof r.ideal === 'number') { + oc[oldname('min', key)] = r.ideal; + cc.optional.push(oc); + oc = {}; + oc[oldname('max', key)] = r.ideal; + cc.optional.push(oc); + } else { + oc[oldname('', key)] = r.ideal; + cc.optional.push(oc); + } + } + if (r.exact !== undefined && typeof r.exact !== 'number') { + cc.mandatory = cc.mandatory || {}; + cc.mandatory[oldname('', key)] = r.exact; + } else { + ['min', 'max'].forEach(function(mix) { + if (r[mix] !== undefined) { + cc.mandatory = cc.mandatory || {}; + cc.mandatory[oldname(mix, key)] = r[mix]; + } + }); + } + }); + if (c.advanced) { + cc.optional = (cc.optional || []).concat(c.advanced); + } + return cc; + }; + + getUserMedia = function(constraints, onSuccess, onError) { + if (constraints.audio) { + constraints.audio = constraintsToChrome(constraints.audio); + } + if (constraints.video) { + constraints.video = constraintsToChrome(constraints.video); + } + webrtcUtils.log('chrome: ' + JSON.stringify(constraints)); + return navigator.webkitGetUserMedia(constraints, onSuccess, onError); + }; + navigator.getUserMedia = getUserMedia; + + if (!navigator.mediaDevices) { + navigator.mediaDevices = {getUserMedia: requestUserMedia, + enumerateDevices: function() { + return new Promise(function(resolve) { + var kinds = {audio: 'audioinput', video: 'videoinput'}; + return MediaStreamTrack.getSources(function(devices) { + resolve(devices.map(function(device) { + return {label: device.label, + kind: kinds[device.kind], + deviceId: device.id, + groupId: ''}; + })); + }); + }); + }}; + } + + // A shim for getUserMedia method on the mediaDevices object. + // TODO(KaptenJansson) remove once implemented in Chrome stable. + if (!navigator.mediaDevices.getUserMedia) { + navigator.mediaDevices.getUserMedia = function(constraints) { + return requestUserMedia(constraints); + }; + } else { + // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia + // function which returns a Promise, it does not accept spec-style + // constraints. + var origGetUserMedia = navigator.mediaDevices.getUserMedia. + bind(navigator.mediaDevices); + navigator.mediaDevices.getUserMedia = function(c) { + webrtcUtils.log('spec: ' + JSON.stringify(c)); // whitespace for alignment + c.audio = constraintsToChrome(c.audio); + c.video = constraintsToChrome(c.video); + webrtcUtils.log('chrome: ' + JSON.stringify(c)); + return origGetUserMedia(c); + }; + } + + // Dummy devicechange event methods. + // TODO(KaptenJansson) remove once implemented in Chrome stable. + if (typeof navigator.mediaDevices.addEventListener === 'undefined') { + navigator.mediaDevices.addEventListener = function() { + webrtcUtils.log('Dummy mediaDevices.addEventListener called.'); + }; + } + if (typeof navigator.mediaDevices.removeEventListener === 'undefined') { + navigator.mediaDevices.removeEventListener = function() { + webrtcUtils.log('Dummy mediaDevices.removeEventListener called.'); + }; + } + + // Attach a media stream to an element. + attachMediaStream = function(element, stream) { + if (webrtcDetectedVersion >= 43) { + element.srcObject = stream; + } else if (typeof element.src !== 'undefined') { + element.src = URL.createObjectURL(stream); + } else { + webrtcUtils.log('Error attaching stream to element.'); + } + }; + reattachMediaStream = function(to, from) { + if (webrtcDetectedVersion >= 43) { + to.srcObject = from.srcObject; + } else { + to.src = from.src; + } + }; + +} else if (navigator.mediaDevices && navigator.userAgent.match( + /Edge\/(\d+).(\d+)$/)) { + webrtcUtils.log('This appears to be Edge'); + webrtcDetectedBrowser = 'edge'; + + webrtcDetectedVersion = + parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10); + + // the minimum version still supported by adapter. + webrtcMinimumVersion = 12; +} else { + webrtcUtils.log('Browser does not appear to be WebRTC-capable'); +} + +// Returns the result of getUserMedia as a Promise. +function requestUserMedia(constraints) { + return new Promise(function(resolve, reject) { + getUserMedia(constraints, resolve, reject); + }); +} + +var webrtcTesting = {}; +Object.defineProperty(webrtcTesting, 'version', { + set: function(version) { + webrtcDetectedVersion = version; + } +}); + +if (typeof module !== 'undefined') { + var RTCPeerConnection; + if (typeof window !== 'undefined') { + RTCPeerConnection = window.RTCPeerConnection; + } + module.exports = { + RTCPeerConnection: RTCPeerConnection, + getUserMedia: getUserMedia, + attachMediaStream: attachMediaStream, + reattachMediaStream: reattachMediaStream, + webrtcDetectedBrowser: webrtcDetectedBrowser, + webrtcDetectedVersion: webrtcDetectedVersion, + webrtcMinimumVersion: webrtcMinimumVersion, + webrtcTesting: webrtcTesting + //requestUserMedia: not exposed on purpose. + //trace: not exposed on purpose. + }; +} else if ((typeof require === 'function') && (typeof define === 'function')) { + // Expose objects and functions when RequireJS is doing the loading. + define([], function() { + return { + RTCPeerConnection: window.RTCPeerConnection, + getUserMedia: getUserMedia, + attachMediaStream: attachMediaStream, + reattachMediaStream: reattachMediaStream, + webrtcDetectedBrowser: webrtcDetectedBrowser, + webrtcDetectedVersion: webrtcDetectedVersion, + webrtcMinimumVersion: webrtcMinimumVersion, + webrtcTesting: webrtcTesting + //requestUserMedia: not exposed on purpose. + //trace: not exposed on purpose. + }; + }); +} diff --git a/openvidu-sampleapp-minimal/src/main/resources/static/js/color.js b/openvidu-sampleapp-minimal/src/main/resources/static/js/color.js new file mode 100644 index 00000000..1c8285e0 --- /dev/null +++ b/openvidu-sampleapp-minimal/src/main/resources/static/js/color.js @@ -0,0 +1,94 @@ +/* + * (C) Copyright 2016 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +var colorMap = {}; +var initTime; +var maxDistance = 60; // Default max distance for color comparison + +window.onload = function() { + initTime = new Date(); +} + +window.requestAnimationFrame = window.requestAnimationFrame + || window.mozRequestAnimationFrame + || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; + +function checkColor(video, canvas, userId) { + + canvas.width = 1; + canvas.height = 1; + var canvasContext = canvas.getContext("2d"); + + video.crossOrigin = 'anonymous'; + + function step() { + var x = 0; + var y = 0; + + try { + canvasContext.drawImage(video, x, y, 1, 1, 0, 0, 1, 1); + } catch (e) { + // NS_ERROR_NOT_AVAILABLE can happen in Firefox due a bug + if (e.name != "NS_ERROR_NOT_AVAILABLE") { + throw e; + } + } + + var color = Array.prototype.slice.apply( + canvasContext.getImageData(0, 0, 1, 1).data).toString(); + + if (colorMap[userId]) { + if (colorChanged(color, colorMap[userId].rgba)) { + var time = new Date() - initTime; + console.info("Detected color change on user " + userId + + " from " + colorMap[userId].rgba + " to " + color + + " at " + time); + + colorMap[userId].rgba = color; + colorMap[userId].time = time; + } + } else { + // First time + var firstEntry = { + rgba : "0,0,0,0", + time : null + }; + colorMap[userId] = firstEntry; + } + + requestAnimationFrame(step); + } + requestAnimationFrame(step); +} + +function colorChanged(expectedColorStr, realColorStr) { + var realColor = realColorStr.split(","); + var expectedColor = expectedColorStr.split(","); + + var realRed = realColor[0]; + var realGreen = realColor[1]; + var realBlue = realColor[2]; + + var expectedRed = expectedColor[0]; + var expectedGreen = expectedColor[1]; + var expectedBlue = expectedColor[2]; + + var distance = Math.sqrt((realRed - expectedRed) * (realRed - expectedRed) + + (realGreen - expectedGreen) * (realGreen - expectedGreen) + + (realBlue - expectedBlue) * (realBlue - expectedBlue)); + + return distance > maxDistance; +} diff --git a/openvidu-sampleapp-minimal/src/main/resources/static/js/console.js b/openvidu-sampleapp-minimal/src/main/resources/static/js/console.js new file mode 100644 index 00000000..c109e251 --- /dev/null +++ b/openvidu-sampleapp-minimal/src/main/resources/static/js/console.js @@ -0,0 +1,93 @@ +/* + * (C) Copyright 2013 Kurento (http://kurento.org/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +/** + * Object that piggy-back the browser console and show their messages on a DIV + * + * Inspired by Node.js ClIM module (https://github.com/epeli/node-clim) + * + * @constructor + * + * @param {String} + * id: id attribute of the DIV tag where to show the messages + * @param console: + * reference to the original browser console + */ +function Console(id, console) { + var div = document.getElementById(id); + + function createMessage(msg, color) { + // Sanitize the input + msg = msg.toString().replace(/a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return!n.isArray(a)&&a-parseFloat(a)>=0},isPlainObject:function(a){return"object"!==n.type(a)||a.nodeType||n.isWindow(a)?!1:a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf")?!1:!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=l.createElement("script"),b.text=a,l.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:k}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="
",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return g.call(b,a)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:l,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=l.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=l,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};A.prototype=n.fn,y=n(l);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(n(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(C[a]||n.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return n.each(a.match(E)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&n.each(arguments,function(a,b){var c;while((c=n.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(H.resolveWith(l,[n]),n.fn.triggerHandler&&(n(l).triggerHandler("ready"),n(l).off("ready"))))}});function I(){l.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),n.ready()}n.ready.promise=function(b){return H||(H=n.Deferred(),"complete"===l.readyState?setTimeout(n.ready):(l.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},n.ready.promise();var J=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};n.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=n.expando+Math.random()}K.uid=1,K.accepts=n.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,n.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(n.isEmptyObject(f))n.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!n.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b) +},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=n.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||n.isArray(c)?d=L.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:n.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthx",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";k.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|pointer|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return l.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof n!==U&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,m,o,p=[d||l],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||l,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+n.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},e||!o.trigger||o.trigger.apply(d,c)!==!1)){if(!e&&!o.noBubble&&!n.isWindow(d)){for(i=o.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||l)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:o.bindType||q,m=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),m&&m.apply(g,c),m=k&&g[k],m&&m.apply&&n.acceptData(g)&&(b.result=m.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!n.acceptData(d)||k&&n.isFunction(d[q])&&!n.isWindow(d)&&(h=d[k],h&&(d[k]=null),n.event.triggered=q,d[q](),n.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>=0:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h]*)\/>/gi,bb=/<([\w:]+)/,cb=/<|&#?\w+;/,db=/<(?:script|style|link)/i,eb=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/^$|\/(?:java|ecma)script/i,gb=/^true\/(.*)/,hb=/^\s*\s*$/g,ib={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ib.optgroup=ib.option,ib.tbody=ib.tfoot=ib.colgroup=ib.caption=ib.thead,ib.th=ib.td;function jb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function kb(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function lb(a){var b=gb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function mb(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function nb(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=n.extend({},h),M.set(b,i))}}function ob(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function pb(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}n.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=ob(h),f=ob(a),d=0,e=f.length;e>d;d++)pb(f[d],g[d]);if(b)if(c)for(f=f||ob(a),g=g||ob(h),d=0,e=f.length;e>d;d++)nb(f[d],g[d]);else nb(a,h);return g=ob(h,"script"),g.length>0&&mb(g,!i&&ob(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,o=a.length;o>m;m++)if(e=a[m],e||0===e)if("object"===n.type(e))n.merge(l,e.nodeType?[e]:e);else if(cb.test(e)){f=f||k.appendChild(b.createElement("div")),g=(bb.exec(e)||["",""])[1].toLowerCase(),h=ib[g]||ib._default,f.innerHTML=h[1]+e.replace(ab,"<$1>")+h[2],j=h[0];while(j--)f=f.lastChild;n.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===n.inArray(e,d))&&(i=n.contains(e.ownerDocument,e),f=ob(k.appendChild(e),"script"),i&&mb(f),c)){j=0;while(e=f[j++])fb.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f=n.event.special,g=0;void 0!==(c=a[g]);g++){if(n.acceptData(c)&&(e=c[L.expando],e&&(b=L.cache[e]))){if(b.events)for(d in b.events)f[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);L.cache[e]&&delete L.cache[e]}delete M.cache[c[M.expando]]}}}),n.fn.extend({text:function(a){return J(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(ob(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&mb(ob(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(ob(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!db.test(a)&&!ib[(bb.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(ab,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(ob(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(ob(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,m=this,o=l-1,p=a[0],q=n.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&eb.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(c=n.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=n.map(ob(c,"script"),kb),g=f.length;l>j;j++)h=c,j!==o&&(h=n.clone(h,!0,!0),g&&n.merge(f,ob(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,n.map(f,lb),j=0;g>j;j++)h=f[j],fb.test(h.type||"")&&!L.access(h,"globalEval")&&n.contains(i,h)&&(h.src?n._evalUrl&&n._evalUrl(h.src):n.globalEval(h.textContent.replace(hb,"")))}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),n(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qb,rb={};function sb(b,c){var d,e=n(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:n.css(e[0],"display");return e.detach(),f}function tb(a){var b=l,c=rb[a];return c||(c=sb(a,b),"none"!==c&&c||(qb=(qb||n("