├── app
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── mipmap-hdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ │ └── ic_launcher.png
│ │ ├── values
│ │ │ ├── dimens.xml
│ │ │ ├── colors.xml
│ │ │ ├── styles.xml
│ │ │ └── strings.xml
│ │ ├── layout
│ │ │ ├── l_item.xml
│ │ │ └── activity_main.xml
│ │ ├── values-w820dp
│ │ │ └── dimens.xml
│ │ ├── menu
│ │ │ └── menu.xml
│ │ └── drawable
│ │ │ └── json.xml
│ │ ├── kotlin
│ │ └── cz
│ │ │ └── sazel
│ │ │ └── android
│ │ │ └── serverlesswebrtcandroid
│ │ │ ├── console
│ │ │ ├── IConsole.kt
│ │ │ └── RecyclerViewConsole.kt
│ │ │ ├── adapters
│ │ │ └── ConsoleAdapter.kt
│ │ │ ├── MainActivity.kt
│ │ │ └── webrtc
│ │ │ └── ServerlessRTCClient.kt
│ │ └── AndroidManifest.xml
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── .github
├── demo.png
├── create_offer.png
└── paste_answer.png
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── LICENSE
├── .circleci
└── config.yml
├── .gitignore
├── README.md
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/.github/demo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wojta/no-server-webrtc-android/HEAD/.github/demo.png
--------------------------------------------------------------------------------
/.github/create_offer.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wojta/no-server-webrtc-android/HEAD/.github/create_offer.png
--------------------------------------------------------------------------------
/.github/paste_answer.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wojta/no-server-webrtc-android/HEAD/.github/paste_answer.png
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wojta/no-server-webrtc-android/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wojta/no-server-webrtc-android/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wojta/no-server-webrtc-android/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wojta/no-server-webrtc-android/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wojta/no-server-webrtc-android/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wojta/no-server-webrtc-android/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
13 | It's technology for real time peer to peer comunication. Especially useful for transfering audio and video - teleconference apps, but can be used for ordinary data as in this example.
14 | WebRTC is supported in recent Chrome browser, Node.js and also on Android/iOS.
15 |
16 | # How it works?
17 | WebRTC requires two data payloads to be transferred between parties, it's called [*SDP*](https://en.wikipedia.org/wiki/Session_Description_Protocol) (sesssion description protocol). One is called *offer* and the second is *answer*.
18 |
19 | You can either create an offer and send it to other party or wait for an offer to be delivered to you.
20 | Usually SDP handshakes are done by special signalling server, but in this case we are not using any, so you'll need to pass SDPs manually by e.g. e-mail.
21 |
22 | If it's running IPv4, it's very unlikely that both parties will have a public IP address or it will be on the same network.
23 | SDP requires that you'll need to pass external IP address there, this is done automatically by process called ICE gathering. It uses two types of external servers - [STUN](https://en.wikipedia.org/wiki/STUN) and [TURN](https://en.wikipedia.org/wiki/Traversal_Using_Relays_around_NAT).
24 | We are using only STUN here, but it should work with TURN as well (and even better).
25 | It can even punch through some NAT mechanisms.
26 |
27 | It uses **libjingle** library, it's a native library for WebRTC that comes with [Chromium](https://www.chromium.org/). There is also JNI wrapper for use in Java. You can compile it by yourself but it's extremely tricky. You can use already build dependency in your `build.gradle`. This helped me a lot:
28 | * http://tech.pristine.io/automated-webrtc-building/
29 | * https://github.com/pristineio/webrtc-build-scripts
30 |
31 | # Usage
32 |
33 |
34 | # Known issues
35 | * There is no renegotiation of connection, it doesn't make much sense without signalling server.
36 | * If you paste offer in the app, answer is created but after while it goes with 'icegathering failed'. You must be fast to pass the answer to the other side. I'm not sure what causes this.
37 |
38 | # License
39 | You can do whatever you want with this code.
40 |
41 |
42 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/cz/sazel/android/serverlesswebrtcandroid/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package cz.sazel.android.serverlesswebrtcandroid
2 |
3 | import android.os.Bundle
4 | import android.view.Menu
5 | import android.view.MenuItem
6 | import android.view.View.GONE
7 | import android.view.View.VISIBLE
8 | import android.widget.Toast
9 | import androidx.appcompat.app.AppCompatActivity
10 | import androidx.core.app.ActivityCompat
11 | import androidx.recyclerview.widget.LinearLayoutManager
12 | import cz.sazel.android.serverlesswebrtcandroid.console.RecyclerViewConsole
13 | import cz.sazel.android.serverlesswebrtcandroid.databinding.ActivityMainBinding
14 | import cz.sazel.android.serverlesswebrtcandroid.webrtc.ServerlessRTCClient
15 | import cz.sazel.android.serverlesswebrtcandroid.webrtc.ServerlessRTCClient.State.*
16 |
17 |
18 | class MainActivity : AppCompatActivity(), ServerlessRTCClient.IStateChangeListener, ActivityCompat.OnRequestPermissionsResultCallback {
19 |
20 |
21 | lateinit var console: RecyclerViewConsole
22 |
23 | lateinit var client: ServerlessRTCClient
24 | var mnuCreateOffer: MenuItem? = null
25 | private lateinit var binding: ActivityMainBinding
26 |
27 | private var retainInstance: Boolean = false
28 |
29 |
30 | override fun onCreate(savedInstanceState: Bundle?) {
31 | super.onCreate(savedInstanceState)
32 | binding = ActivityMainBinding.inflate(layoutInflater)
33 | setContentView(binding.root)
34 | val layoutManager = LinearLayoutManager(this)
35 |
36 | binding.recyclerView.layoutManager = layoutManager
37 | layoutManager.stackFromEnd = true
38 |
39 | binding.apply {
40 | console = RecyclerViewConsole(recyclerView)
41 | console.initialize(savedInstanceState)
42 |
43 |
44 | val retainedClient = lastCustomNonConfigurationInstance as ServerlessRTCClient?
45 | if (retainedClient == null) {
46 | client = ServerlessRTCClient(console, applicationContext, this@MainActivity)
47 | try {
48 | client.init()
49 | } catch (e: Exception) {
50 | Toast.makeText(this@MainActivity, e.message, Toast.LENGTH_LONG).show()
51 | e.printStackTrace()
52 | }
53 | } else {
54 | client = retainedClient
55 | onStateChanged(client.state)
56 | }
57 |
58 | btSubmit.setOnClickListener { sendMessage() }
59 | edEnterArea.setOnEditorActionListener { _, _, _ ->
60 | sendMessage()
61 | true
62 | }
63 | }
64 | }
65 |
66 |
67 | private fun sendMessage() {
68 | binding.apply {
69 | val newText = edEnterArea.text.toString().trim()
70 | when (client.state) {
71 | WAITING_FOR_OFFER -> client.processOffer(newText)
72 | WAITING_FOR_ANSWER -> client.processAnswer(newText)
73 | CHAT_ESTABLISHED -> {
74 | if (newText.isNotBlank()) {
75 | client.sendMessage(newText)
76 | console.printf(">$newText")
77 | }
78 | }
79 | else -> if (newText.isNotBlank()) console.printf(newText)
80 | }
81 | edEnterArea.setText("")
82 | }
83 | }
84 |
85 | override fun onRetainCustomNonConfigurationInstance(): Any? {
86 | retainInstance = true
87 | return client
88 | }
89 |
90 |
91 | override fun onCreateOptionsMenu(menu: Menu?): Boolean {
92 | menuInflater.inflate(R.menu.menu, menu)
93 | mnuCreateOffer = menu?.findItem(R.id.mnuCreateOffer)
94 | return true
95 | }
96 |
97 | override fun onOptionsItemSelected(item: MenuItem?): Boolean {
98 | when (item?.itemId) {
99 | R.id.mnuCreateOffer -> client.makeOffer()
100 | }
101 |
102 | return super.onOptionsItemSelected(item)
103 | }
104 |
105 | override fun onSaveInstanceState(outState: Bundle) {
106 | super.onSaveInstanceState(outState)
107 | console.onSaveInstanceState(outState)
108 | }
109 |
110 |
111 | override fun onStateChanged(state: ServerlessRTCClient.State) {
112 | //it could be in different thread
113 | binding.apply {
114 | runOnUiThread {
115 | edEnterArea.isEnabled = true
116 | progressBar.visibility = GONE
117 | mnuCreateOffer?.isVisible = false
118 | when (state) {
119 | CHAT_ENDED, INITIALIZING -> client.waitForOffer()
120 | WAITING_FOR_OFFER -> {
121 | mnuCreateOffer?.isVisible = true
122 | edEnterArea.hint = getString(R.string.hint_paste_offer)
123 | }
124 | WAITING_FOR_ANSWER -> edEnterArea.hint = getString(R.string.hint_paste_answer)
125 | CHAT_ESTABLISHED -> edEnterArea.hint = getString(R.string.enter_message)
126 | WAITING_TO_CONNECT, CREATING_OFFER, CREATING_ANSWER -> {
127 | progressBar.visibility = VISIBLE
128 | if (BuildConfig.DEBUG) edEnterArea.hint = state.name
129 | edEnterArea.isEnabled = false
130 | }
131 | }
132 | }
133 | }
134 | }
135 |
136 | override fun onDestroy() {
137 | if (!retainInstance)
138 | client.destroy()
139 | super.onDestroy()
140 |
141 | }
142 | }
143 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/cz/sazel/android/serverlesswebrtcandroid/webrtc/ServerlessRTCClient.kt:
--------------------------------------------------------------------------------
1 | package cz.sazel.android.serverlesswebrtcandroid.webrtc
2 |
3 | import android.content.Context
4 | import cz.sazel.android.serverlesswebrtcandroid.console.IConsole
5 | import org.json.JSONException
6 | import org.json.JSONObject
7 | import org.webrtc.*
8 | import java.nio.ByteBuffer
9 | import java.nio.charset.Charset
10 |
11 | /**
12 | * This class handles all around WebRTC peer connections.
13 | */
14 | class ServerlessRTCClient(val console: IConsole, val context: Context, val listener: IStateChangeListener) {
15 |
16 | lateinit var pc: PeerConnection
17 | private var pcInitialized: Boolean = false
18 |
19 | var channel: DataChannel? = null
20 |
21 | /**
22 | * List of servers that will be used to establish the direct connection, STUN/TURN should be supported.
23 | */
24 | val iceServers = arrayListOf(PeerConnection.IceServer("stun:stun.l.google.com:19302"))
25 |
26 | enum class State {
27 | /**
28 | * Initialization in progress.
29 | */
30 | INITIALIZING,
31 | /**
32 | * App is waiting for offer, fill in the offer into the edit text.
33 | */
34 | WAITING_FOR_OFFER,
35 | /**
36 | * App is creating the offer.
37 | */
38 | CREATING_OFFER,
39 | /**
40 | * App is creating answer to offer.
41 | */
42 | CREATING_ANSWER,
43 | /**
44 | * App created the offer and is now waiting for answer
45 | */
46 | WAITING_FOR_ANSWER,
47 | /**
48 | * Waiting for establishing the connection.
49 | */
50 | WAITING_TO_CONNECT,
51 | /**
52 | * Connection was established. You can chat now.
53 | */
54 | CHAT_ESTABLISHED,
55 | /**
56 | * Connection is terminated chat ended.
57 | */
58 | CHAT_ENDED
59 | }
60 |
61 | lateinit var pcf: PeerConnectionFactory
62 | val pcConstraints = object : MediaConstraints() {
63 | init {
64 | optional.add(MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"))
65 | }
66 | }
67 |
68 | var state: State = State.INITIALIZING
69 | private set(value) {
70 | field = value
71 | listener.onStateChanged(value)
72 | }
73 | get
74 |
75 |
76 | interface IStateChangeListener {
77 | /**
78 | * Called when status of client is changed.
79 | */
80 | fun onStateChanged(state: State)
81 | }
82 |
83 | abstract inner class DefaultObserver : PeerConnection.Observer {
84 |
85 | override fun onDataChannel(p0: DataChannel?) {
86 | console.d("data channel ${p0?.label()} established")
87 | }
88 |
89 | override fun onIceConnectionReceivingChange(p0: Boolean) {
90 | console.d("ice connection receiving change:{$p0}")
91 | }
92 |
93 | override fun onIceConnectionChange(p0: PeerConnection.IceConnectionState?) {
94 | console.d("ice connection state change:${p0?.name}")
95 | if (p0 == PeerConnection.IceConnectionState.DISCONNECTED) {
96 | console.d("closing channel")
97 | channel?.close()
98 | }
99 | }
100 |
101 | override fun onIceGatheringChange(p0: PeerConnection.IceGatheringState?) {
102 | console.d("ice gathering state change:${p0?.name}")
103 | }
104 |
105 | override fun onAddStream(p0: MediaStream?) {
106 |
107 | }
108 |
109 | override fun onSignalingChange(p0: PeerConnection.SignalingState?) {
110 | console.d("signaling state change:${p0?.name}")
111 | }
112 |
113 | override fun onRemoveStream(p0: MediaStream?) {
114 |
115 | }
116 |
117 | override fun onRenegotiationNeeded() {
118 | console.d("renegotiation needed")
119 | }
120 | }
121 |
122 | open inner class DefaultSdpObserver : SdpObserver {
123 |
124 | override fun onCreateSuccess(p0: SessionDescription?) {
125 |
126 | }
127 |
128 | override fun onCreateFailure(p0: String?) {
129 | console.e("failed to create offer:$p0")
130 | }
131 |
132 | override fun onSetFailure(p0: String?) {
133 | console.e("set failure:$p0")
134 | }
135 |
136 | override fun onSetSuccess() {
137 | console.i("set success")
138 | }
139 |
140 | }
141 |
142 |
143 | private val UTF_8 = Charset.forName("UTF-8")
144 |
145 | open inner class DefaultDataChannelObserver(val channel: DataChannel) : DataChannel.Observer {
146 |
147 |
148 | //TODO I'm not sure if this would handle really long messages
149 | override fun onMessage(p0: DataChannel.Buffer?) {
150 | val buf = p0?.data
151 | if (buf != null) {
152 | val byteArray = ByteArray(buf.remaining())
153 | buf.get(byteArray)
154 | val received = kotlin.text.String(byteArray, UTF_8)
155 | try {
156 | val message = JSONObject(received).getString(JSON_MESSAGE)
157 | console.bluef(">$message")
158 | } catch (e: JSONException) {
159 | console.redf("Malformed message received")
160 | }
161 |
162 |
163 | }
164 | }
165 |
166 | override fun onBufferedAmountChange(p0: Long) {
167 | console.d("channel buffered amount change:{$p0}")
168 | }
169 |
170 | override fun onStateChange() {
171 | console.d("Channel state changed:${channel.state()?.name}}")
172 | if (channel.state() == DataChannel.State.OPEN) {
173 | state = State.CHAT_ESTABLISHED
174 | console.bluef("Chat established.")
175 | } else {
176 | state = State.CHAT_ENDED
177 | console.redf("Chat ended.")
178 | }
179 | }
180 | }
181 |
182 | private val JSON_TYPE = "type"
183 | private val JSON_MESSAGE = "message"
184 | private val JSON_SDP = "sdp"
185 |
186 | /**
187 | * Converts session description object to JSON object that can be used in other applications.
188 | * This is what is passed between parties to maintain connection. We need to pass the session description to the other side.
189 | * In normal use case we should use some kind of signalling server, but for this demo you can use some other method to pass it there (like e-mail).
190 | */
191 | fun sessionDescriptionToJSON(sessDesc: SessionDescription): JSONObject {
192 | val json = JSONObject()
193 | json.put(JSON_TYPE, sessDesc.type.canonicalForm())
194 | json.put(JSON_SDP, sessDesc.description)
195 | return json
196 | }
197 |
198 |
199 | /**
200 | * Wait for an offer to be entered by user.
201 | */
202 | fun waitForOffer() {
203 | state = State.WAITING_FOR_OFFER
204 | }
205 |
206 |
207 | /**
208 | * Process offer that was entered by user (this is called getOffer() in JavaScript example)
209 | */
210 | fun processOffer(sdpJSON: String) {
211 | try {
212 | val json = JSONObject(sdpJSON)
213 | val type = json.getString(JSON_TYPE)
214 | val sdp = json.getString(JSON_SDP)
215 | state = State.CREATING_ANSWER
216 | if (type != null && sdp != null && type == "offer") {
217 | val offer = SessionDescription(SessionDescription.Type.OFFER, sdp)
218 | pcInitialized = true
219 | pc = pcf.createPeerConnection(iceServers, pcConstraints, object : DefaultObserver() {
220 | override fun onIceCandidatesRemoved(p0: Array