├── protoo-client
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ └── values
│ │ │ │ └── strings.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── org
│ │ │ └── protoojs
│ │ │ └── droid
│ │ │ ├── ProtooException.java
│ │ │ ├── Utils.java
│ │ │ ├── transports
│ │ │ └── AbsWebSocketTransport.java
│ │ │ ├── Logger.java
│ │ │ ├── Message.java
│ │ │ └── Peer.java
│ └── androidTest
│ │ └── java
│ │ └── org
│ │ └── protoojs
│ │ └── droid
│ │ └── MessageTest.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .idea
├── google-java-format.xml
├── runConfigurations.xml
└── codeStyles
│ └── Project.xml
├── gradle.properties
├── LICENSE
├── gradlew.bat
├── README.md
├── .travis.yml
├── .gitignore
└── gradlew
/protoo-client/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':protoo-client'
2 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/haiyangwu/protoo-client-android/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/protoo-client/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | protooDroid
3 |
4 |
--------------------------------------------------------------------------------
/protoo-client/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/google-java-format.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Sep 09 15:06:24 CST 2019
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
7 |
--------------------------------------------------------------------------------
/protoo-client/src/main/java/org/protoojs/droid/ProtooException.java:
--------------------------------------------------------------------------------
1 | package org.protoojs.droid;
2 |
3 | public class ProtooException extends Exception {
4 | private long error;
5 | private String errorReason;
6 |
7 | public ProtooException(long error, String errorReason) {
8 | this.error = error;
9 | this.errorReason = errorReason;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/protoo-client/src/main/java/org/protoojs/droid/Utils.java:
--------------------------------------------------------------------------------
1 | package org.protoojs.droid;
2 |
3 | import java.util.Random;
4 |
5 | public class Utils {
6 |
7 | /**
8 | * Generates a random positive integer.
9 | *
10 | * @return a random positive integer
11 | */
12 | public static long generateRandomNumber() {
13 | return (new Random()).nextInt(10000000);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | android.enableJetifier=true
10 | android.useAndroidX=true
11 | org.gradle.jvmargs=-Xmx1536m
12 | # When configured, Gradle will run in incubating parallel mode.
13 | # This option should only be used with decoupled projects. More details, visit
14 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
15 | # org.gradle.parallel=true
16 |
17 |
18 |
--------------------------------------------------------------------------------
/protoo-client/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/protoo-client/src/main/java/org/protoojs/droid/transports/AbsWebSocketTransport.java:
--------------------------------------------------------------------------------
1 | package org.protoojs.droid.transports;
2 |
3 | import org.json.JSONObject;
4 | import org.protoojs.droid.Message;
5 |
6 | public abstract class AbsWebSocketTransport {
7 |
8 | public interface Listener {
9 |
10 | void onOpen();
11 |
12 | /** Connection could not be established in the first place. */
13 | void onFail();
14 |
15 | /** @param message {@link Message} */
16 | void onMessage(Message message);
17 |
18 | /** A previously established connection was lost unexpected. */
19 | void onDisconnected();
20 |
21 | void onClose();
22 | }
23 |
24 | // WebSocket URL.
25 | protected String mUrl;
26 |
27 | public AbsWebSocketTransport(String url) {
28 | this.mUrl = url;
29 | }
30 |
31 | public abstract void connect(Listener listener);
32 |
33 | public abstract String sendMessage(JSONObject message);
34 |
35 | public abstract void close();
36 |
37 | public abstract boolean isClosed();
38 | }
39 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 Haiyang Wu
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/protoo-client/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.novoda.bintray-release'
3 |
4 | android {
5 | compileSdkVersion 29
6 |
7 | defaultConfig {
8 | minSdkVersion 18
9 | targetSdkVersion 29
10 | versionCode 2
11 | versionName "4.0.3"
12 |
13 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
14 | }
15 |
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 |
23 | compileOptions {
24 | sourceCompatibility JavaVersion.VERSION_1_8
25 | targetCompatibility JavaVersion.VERSION_1_8
26 | }
27 |
28 | lintOptions {
29 | warningsAsErrors true
30 | }
31 | }
32 |
33 | dependencies {
34 | implementation fileTree(dir: 'libs', include: ['*.jar'])
35 |
36 | implementation 'androidx.appcompat:appcompat:1.1.0'
37 | testImplementation 'junit:junit:4.12'
38 | androidTestImplementation 'androidx.test.ext:junit:1.1.1'
39 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
40 | }
41 |
42 | publish {
43 | userOrg = 'haiyangwu'
44 | groupId = 'org.protoojs.droid'
45 | artifactId = 'protoo-client'
46 | publishVersion = '4.0.3'
47 | desc = 'Minimalist and extensible Android Client signaling framework for multi-party Real-Time applications'
48 | website = 'https://github.com/haiyangwu/protoo-client-android'
49 | }
--------------------------------------------------------------------------------
/protoo-client/src/androidTest/java/org/protoojs/droid/MessageTest.java:
--------------------------------------------------------------------------------
1 | package org.protoojs.droid;
2 |
3 | import androidx.test.ext.junit.runners.AndroidJUnit4;
4 |
5 | import org.json.JSONObject;
6 | import org.junit.Test;
7 | import org.junit.runner.RunWith;
8 |
9 | import static org.junit.Assert.assertEquals;
10 | import static org.junit.Assert.assertTrue;
11 |
12 | @RunWith(AndroidJUnit4.class)
13 | public class MessageTest {
14 |
15 | private static final String METHOD_TEST = "test";
16 | private static final long ERROR_CODE_TEST = 1;
17 | private static final String ERROR_REASON_TEST = "test error code";
18 |
19 | @Test
20 | public void createRequestResponse() {
21 | // test createRequest and parse request.
22 | JSONObject requestObj = Message.createRequest(METHOD_TEST, null);
23 | Message parsedRequest = Message.parse(requestObj.toString());
24 | assertTrue(parsedRequest instanceof Message.Request);
25 |
26 | Message.Request request = (Message.Request) parsedRequest;
27 | assertEquals(METHOD_TEST, request.getMethod());
28 |
29 | // test createSuccessResponse and parse success response.
30 | JSONObject sucResObj = Message.createSuccessResponse(request, null);
31 | Message parsedSucRes = Message.parse(sucResObj.toString());
32 | assertTrue(parsedSucRes instanceof Message.Response);
33 |
34 | Message.Response sucRes = (Message.Response) parsedSucRes;
35 | assertEquals(request.getId(), sucRes.getId());
36 |
37 | // test createErrorResponse and parse error response.
38 | JSONObject errResObj = Message.createErrorResponse(request, ERROR_CODE_TEST, ERROR_REASON_TEST);
39 | Message parsedErrRes = Message.parse(errResObj.toString());
40 | assertTrue(parsedErrRes instanceof Message.Response);
41 |
42 | Message.Response errRes = (Message.Response) parsedErrRes;
43 | assertEquals(request.getId(), errRes.getId());
44 | assertEquals(ERROR_CODE_TEST, errRes.getErrorCode());
45 | assertEquals(ERROR_REASON_TEST, errRes.getErrorReason());
46 | }
47 |
48 | @Test
49 | public void createNotification() {
50 | JSONObject request = Message.createNotification(METHOD_TEST, null);
51 | Message parsedMessage = Message.parse(request.toString());
52 | assertTrue(parsedMessage instanceof Message.Notification);
53 | assertEquals(METHOD_TEST, ((Message.Notification) parsedMessage).getMethod());
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # protoo-client-android
2 |
3 | [![Bintray][bintray-shield-protoo-client-android]][bintray-protoo-client-android]
4 | [![Build Status][travis-ci-shield-protoo-client-android]][travis-ci-protoo-client-android]
5 | [![Codacy Badge][codacy-grade-shield-protoo-client-android]][codacy-grade-protoo-client-android]
6 |
7 | Minimalist and extensible Android Client signaling framework for multi-party Real-Time applications
8 |
9 | ## Getting Started
10 | ### Setting up the dependency
11 | Include `protoo-client-android` into your project, for example, as a Gradle compile dependency:
12 |
13 | ```groovy
14 | implementation 'org.protoojs.droid:protoo-client:4.0.3'
15 | ```
16 | ### Example
17 |
18 | * implement your own `WebSocketTransport`
19 | ```java
20 | public class WebSocketTransport extends AbsWebSocketTransport {
21 | // ...
22 | }
23 | ```
24 | > `protoo-client-android` just define a base class [`AbsWebSocketTransport`][code-base-websocket-transport]
25 | > which offer opportunity to implement your own `WebSocketTransport`
26 |
27 | * creates a WebSocket connection
28 |
29 | ```java
30 | WebSocketTransport transport = new WebSocketTransport("wss://example.org");
31 | ```
32 |
33 | * create a participant in a remote room
34 |
35 | ```java
36 | private Peer.Listener peerListener =
37 | new Peer.Listener() {
38 | // ...
39 | };
40 | mPeer = new Peer(transport, peerListener);
41 | ```
42 |
43 | * send request or notify
44 |
45 | Once connected to remote server `Peer.Listener#onOpen` will be called, then you can call
46 | `Peer#request` or `Peer#notify` to send message to server.
47 |
48 | ```java
49 | mPeer.request("dummy", ...);
50 | mPeer.notify("dummy", ...);
51 | ```
52 |
53 | ## Author
54 | Haiyang Wu([@haiyangwu](https://github.com/haiyangwu/) at Github)
55 |
56 | ## License
57 | [MIT](./LICENSE)
58 |
59 |
60 |
61 |
62 | [bintray-protoo-client-android]:https://mvnrepository.com/artifact/org.protoojs.droid/protoo-client
63 | [bintray-shield-protoo-client-android]:https://img.shields.io/bintray/v/haiyangwu/maven/protoo-client
64 | [travis-ci-shield-protoo-client-android]:https://travis-ci.org/haiyangwu/protoo-client-android.svg?branch=master
65 | [travis-ci-protoo-client-android]:https://travis-ci.org/haiyangwu/protoo-client-android
66 | [codacy-grade-shield-protoo-client-android]:https://api.codacy.com/project/badge/Grade/bc233c4d62de4fe9aee1ec9e7c406ef4
67 | [codacy-grade-protoo-client-android]:https://app.codacy.com/manual/haiyangwu/protoo-client-android?utm_source=github.com&utm_medium=referral&utm_content=haiyangwu/protoo-client-android&utm_campaign=Badge_Grade_Dashboard
68 | [code-base-websocket-transport]:./protoo-client/src/main/java/org/protoojs/droid/transports/AbsWebSocketTransport.java
69 |
--------------------------------------------------------------------------------
/protoo-client/src/main/java/org/protoojs/droid/Logger.java:
--------------------------------------------------------------------------------
1 | package org.protoojs.droid;
2 |
3 | import android.util.Log;
4 |
5 | import java.io.PrintWriter;
6 | import java.io.StringWriter;
7 |
8 | class Logger {
9 |
10 | private static LogLevel loggableLevel = LogLevel.LOG_WARN;
11 |
12 | public enum LogLevel {
13 | LOG_NONE,
14 | LOG_ERROR,
15 | LOG_WARN,
16 | LOG_DEBUG,
17 | LOG_TRACE,
18 | }
19 |
20 | public static void setLogLevel(LogLevel level) {
21 | if (level == null) {
22 | throw new IllegalArgumentException("Logging level may not be null.");
23 | }
24 | loggableLevel = level;
25 | }
26 |
27 | public static void d(String tag, String message) {
28 | log(LogLevel.LOG_DEBUG, tag, message);
29 | }
30 |
31 | public static void e(String tag, String message) {
32 | log(LogLevel.LOG_ERROR, tag, message);
33 | }
34 |
35 | public static void w(String tag, String message) {
36 | log(LogLevel.LOG_WARN, tag, message);
37 | }
38 |
39 | public static void e(String tag, String message, Throwable e) {
40 | log(LogLevel.LOG_ERROR, tag, message);
41 | log(LogLevel.LOG_ERROR, tag, e.toString());
42 | log(LogLevel.LOG_ERROR, tag, getStackTraceString(e));
43 | }
44 |
45 | public static void w(String tag, String message, Throwable e) {
46 | log(LogLevel.LOG_WARN, tag, message);
47 | log(LogLevel.LOG_WARN, tag, e.toString());
48 | log(LogLevel.LOG_WARN, tag, getStackTraceString(e));
49 | }
50 |
51 | public static void v(String tag, String message) {
52 | log(LogLevel.LOG_TRACE, tag, message);
53 | }
54 |
55 | private static String getStackTraceString(Throwable e) {
56 | if (e == null) {
57 | return "";
58 | }
59 |
60 | StringWriter sw = new StringWriter();
61 | PrintWriter pw = new PrintWriter(sw);
62 | e.printStackTrace(pw);
63 | return sw.toString();
64 | }
65 |
66 | public static void log(LogLevel level, String tag, String message) {
67 | if (tag == null || message == null) {
68 | throw new IllegalArgumentException("Log tag or message may not be null.");
69 | }
70 |
71 | // Filter log messages below logLevel.
72 | if (LogLevel.LOG_NONE.equals(loggableLevel) || level.ordinal() > loggableLevel.ordinal()) {
73 | return;
74 | }
75 |
76 | switch (level) {
77 | case LOG_ERROR:
78 | Log.e(tag, message);
79 | break;
80 | case LOG_WARN:
81 | Log.w(tag, message);
82 | break;
83 | case LOG_DEBUG:
84 | Log.d(tag, message);
85 | break;
86 | case LOG_TRACE:
87 | Log.v(tag, message);
88 | break;
89 | }
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: android
2 |
3 | jdk:
4 | - oraclejdk8
5 |
6 | env:
7 | global:
8 | - ADB_INSTALL_TIMEOUT=8
9 | - ABI=armeabi-v7a
10 | # use google_apis flavor if no default flavor emulator
11 | - EMU_FLAVOR=default
12 | # PATH order is incredibly important. e.g. the 'emulator' script exists in more than one place!
13 | - ANDROID_HOME=/usr/local/android-sdk
14 | - TOOLS=${ANDROID_HOME}/tools
15 | - PATH=${ANDROID_HOME}:${ANDROID_HOME}/emulator:${TOOLS}:${TOOLS}/bin:${ANDROID_HOME}/platform-tools:${PATH}
16 | matrix:
17 | # only runs locally. Create+Start once from AndroidStudio to init sdcard. Then only from command-line w/-engine classic
18 | # - API=15
19 | # - API=16 AUDIO=-no-audio
20 | # - API=17
21 | # API18 has started being flaky
22 | - API=18
23 | # Kernel/emulator mismatch failure probably fixible with -engine classic
24 | # - API=19
25 | # API 20 was Android Wear only
26 | # - API=21 ABI=x86_64
27 | # - API=22 ABI=x86_64
28 | # - API=23 ABI=x86_64
29 | # - API=24 ABI=x86_64
30 | # - API=25 ABI=x86_64
31 | #- API=26 ABI=x86_64 # Fails with unrecognized tests? orchestrator change or something?
32 | - API=27 ABI=x86_64
33 | # Slowness/timing issues / Fails with unresponsive adb command / so unrecognized API for adb
34 | # - API=28 ABI=x86_64
35 | # Fails I think because of perf + timeouts. 10 minute wait not enough, fixable
36 | # - API=Q ABI=x86_64
37 |
38 | # This block currently does not work, but it used to. API=28/Q are probably fixable
39 | # but we don't need allow_failures to be on in master to work through them
40 | #matrix:
41 | # fast_finish: true # We can report success without waiting for these
42 | # allow_failures:
43 | # - API=28 ABI=x86_64
44 | # #- env: API=28 ABI=x86_64 # allowing failure to see how it works flake-wise
45 |
46 | android:
47 | components:
48 | # installing tools to start, then use `sdkmanager` below to get the rest
49 | - tools
50 |
51 | licenses:
52 | - 'android-sdk-preview-license-.+'
53 | - 'android-sdk-license-.+'
54 | - 'google-gdk-license-.+'
55 |
56 | # Emulator Management: Create, Start and Wait
57 | install:
58 | - echo 'count=0' > /home/travis/.android/repositories.cfg # Avoid harmless sdkmanager warning
59 | - echo y | sdkmanager "platform-tools" >/dev/null
60 | - echo y | sdkmanager "tools" >/dev/null # A second time per Travis docs, gets latest versions
61 | - echo y | sdkmanager "build-tools;28.0.3" >/dev/null # Implicit gradle dependency - gradle drives changes
62 | - echo y | sdkmanager "platforms;android-$API" >/dev/null # We need the API of the emulator we will run
63 | - echo y | sdkmanager "platforms;android-28" >/dev/null # We need the API of the current compileSdkVersion from gradle.properties
64 | - echo y | sdkmanager --channel=4 "emulator" # Experiment with canary, specifying 28.0.3 (prior version) did not work
65 | - echo y | sdkmanager "extras;android;m2repository" >/dev/null
66 | - echo y | sdkmanager "system-images;android-$API;$EMU_FLAVOR;$ABI" #>/dev/null # install our emulator
67 | - echo no | avdmanager create avd --force -n test -k "system-images;android-$API;$EMU_FLAVOR;$ABI" -c 10M
68 | - emulator -verbose -avd test -no-accel -no-snapshot -no-window $AUDIO -camera-back none -camera-front none -selinux permissive -qemu -m 2048 &
69 | - android-wait-for-emulator
70 | - adb shell input keyevent 82 &
71 |
72 | script:
73 | - ./gradlew connectedAndroidTest
74 |
75 | before_cache:
76 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
77 |
78 | cache:
79 | directories:
80 | - $HOME/.gradle/caches/
81 | - $HOME/.gradle/wrapper/
82 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | xmlns:android
14 |
15 | ^$
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 | xmlns:.*
25 |
26 | ^$
27 |
28 |
29 | BY_NAME
30 |
31 |
32 |
33 |
34 |
35 |
36 | .*:id
37 |
38 | http://schemas.android.com/apk/res/android
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 | .*:name
48 |
49 | http://schemas.android.com/apk/res/android
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 | name
59 |
60 | ^$
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 | style
70 |
71 | ^$
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 | .*
81 |
82 | ^$
83 |
84 |
85 | BY_NAME
86 |
87 |
88 |
89 |
90 |
91 |
92 | .*
93 |
94 | http://schemas.android.com/apk/res/android
95 |
96 |
97 | ANDROID_ATTRIBUTE_ORDER
98 |
99 |
100 |
101 |
102 |
103 |
104 | .*
105 |
106 | .*
107 |
108 |
109 | BY_NAME
110 |
111 |
112 |
113 |
114 |
115 |
116 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by https://www.gitignore.io/api/macos,android,androidstudio
2 | # Edit at https://www.gitignore.io/?templates=macos,android,androidstudio
3 |
4 | ### Android ###
5 | # Built application files
6 | *.apk
7 | *.ap_
8 | *.aab
9 |
10 | # Files for the ART/Dalvik VM
11 | *.dex
12 |
13 | # Java class files
14 | *.class
15 |
16 | # Generated files
17 | bin/
18 | gen/
19 | out/
20 | release/
21 |
22 | # Gradle files
23 | .gradle/
24 | build/
25 |
26 | # Local configuration file (sdk path, etc)
27 | local.properties
28 |
29 | # Proguard folder generated by Eclipse
30 | proguard/
31 |
32 | # Log Files
33 | *.log
34 |
35 | # Android Studio Navigation editor temp files
36 | .navigation/
37 |
38 | # Android Studio captures folder
39 | captures/
40 |
41 | # IntelliJ
42 | *.iml
43 | .idea/workspace.xml
44 | .idea/tasks.xml
45 | .idea/gradle.xml
46 | .idea/assetWizardSettings.xml
47 | .idea/dictionaries
48 | .idea/libraries
49 | # Android Studio 3 in .gitignore file.
50 | .idea/caches
51 | .idea/modules.xml
52 | # Comment next line if keeping position of elements in Navigation Editor is relevant for you
53 | .idea/navEditor.xml
54 |
55 | # Keystore files
56 | # Uncomment the following lines if you do not want to check your keystore files in.
57 | #*.jks
58 | #*.keystore
59 |
60 | # External native build folder generated in Android Studio 2.2 and later
61 | .externalNativeBuild
62 |
63 | # Google Services (e.g. APIs or Firebase)
64 | # google-services.json
65 |
66 | # Freeline
67 | freeline.py
68 | freeline/
69 | freeline_project_description.json
70 |
71 | # fastlane
72 | fastlane/report.xml
73 | fastlane/Preview.html
74 | fastlane/screenshots
75 | fastlane/test_output
76 | fastlane/readme.md
77 |
78 | # Version control
79 | vcs.xml
80 |
81 | # lint
82 | lint/intermediates/
83 | lint/generated/
84 | lint/outputs/
85 | lint/tmp/
86 | # lint/reports/
87 |
88 | ### Android Patch ###
89 | gen-external-apklibs
90 | output.json
91 |
92 | ### macOS ###
93 | # General
94 | .DS_Store
95 | .AppleDouble
96 | .LSOverride
97 |
98 | # Icon must end with two \r
99 | Icon
100 |
101 | # Thumbnails
102 | ._*
103 |
104 | # Files that might appear in the root of a volume
105 | .DocumentRevisions-V100
106 | .fseventsd
107 | .Spotlight-V100
108 | .TemporaryItems
109 | .Trashes
110 | .VolumeIcon.icns
111 | .com.apple.timemachine.donotpresent
112 |
113 | # Directories potentially created on remote AFP share
114 | .AppleDB
115 | .AppleDesktop
116 | Network Trash Folder
117 | Temporary Items
118 | .apdisk
119 |
120 | ### AndroidStudio ###
121 | # Covers files to be ignored for android development using Android Studio.
122 |
123 | # Built application files
124 |
125 | # Files for the ART/Dalvik VM
126 |
127 | # Java class files
128 |
129 | # Generated files
130 |
131 | # Gradle files
132 | .gradle
133 |
134 | # Signing files
135 | .signing/
136 |
137 | # Local configuration file (sdk path, etc)
138 |
139 | # Proguard folder generated by Eclipse
140 |
141 | # Log Files
142 |
143 | # Android Studio
144 | /*/build/
145 | /*/local.properties
146 | /*/out
147 | /*/*/build
148 | /*/*/production
149 | *.ipr
150 | *~
151 | *.swp
152 |
153 | # Android Patch
154 |
155 | # External native build folder generated in Android Studio 2.2 and later
156 |
157 | # NDK
158 | obj/
159 |
160 | # IntelliJ IDEA
161 | *.iws
162 | /out/
163 |
164 | # User-specific configurations
165 | .idea/caches/
166 | .idea/libraries/
167 | .idea/shelf/
168 | .idea/.name
169 | .idea/compiler.xml
170 | .idea/copyright/profiles_settings.xml
171 | .idea/encodings.xml
172 | .idea/misc.xml
173 | .idea/scopes/scope_settings.xml
174 | .idea/vcs.xml
175 | .idea/jsLibraryMappings.xml
176 | .idea/datasources.xml
177 | .idea/dataSources.ids
178 | .idea/sqlDataSources.xml
179 | .idea/dynamic.xml
180 | .idea/uiDesigner.xml
181 |
182 | # OS-specific files
183 | .DS_Store?
184 | ehthumbs.db
185 | Thumbs.db
186 |
187 | # Legacy Eclipse project files
188 | .classpath
189 | .project
190 | .cproject
191 | .settings/
192 |
193 | # Mobile Tools for Java (J2ME)
194 | .mtj.tmp/
195 |
196 | # Package Files #
197 | *.war
198 | *.ear
199 |
200 | # virtual machine crash logs (Reference: http://www.java.com/en/download/help/error_hotspot.xml)
201 | hs_err_pid*
202 |
203 | ## Plugin-specific files:
204 |
205 | # mpeltonen/sbt-idea plugin
206 | .idea_modules/
207 |
208 | # JIRA plugin
209 | atlassian-ide-plugin.xml
210 |
211 | # Mongo Explorer plugin
212 | .idea/mongoSettings.xml
213 |
214 | # Crashlytics plugin (for Android Studio and IntelliJ)
215 | com_crashlytics_export_strings.xml
216 | crashlytics.properties
217 | crashlytics-build.properties
218 | fabric.properties
219 |
220 | ### AndroidStudio Patch ###
221 |
222 | !/gradle/wrapper/gradle-wrapper.jar
223 |
224 | # End of https://www.gitignore.io/api/macos,android,androidstudio
225 |
226 | .vscode/
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/protoo-client/src/main/java/org/protoojs/droid/Message.java:
--------------------------------------------------------------------------------
1 | package org.protoojs.droid;
2 |
3 | import android.text.TextUtils;
4 |
5 | import androidx.annotation.NonNull;
6 |
7 | import org.json.JSONException;
8 | import org.json.JSONObject;
9 |
10 | public class Message {
11 |
12 | private static final String TAG = "message";
13 |
14 | // message data.
15 | private JSONObject mData;
16 |
17 | public Message() {}
18 |
19 | public Message(JSONObject data) {
20 | mData = data;
21 | }
22 |
23 | public JSONObject getData() {
24 | return mData;
25 | }
26 |
27 | public void setData(JSONObject data) {
28 | mData = data;
29 | }
30 |
31 | public static class Request extends Message {
32 |
33 | private boolean mRequest = true;
34 | private String mMethod;
35 | private long mId;
36 |
37 | public Request(String method, long id, JSONObject data) {
38 | super(data);
39 | mMethod = method;
40 | mId = id;
41 | }
42 |
43 | public boolean isRequest() {
44 | return mRequest;
45 | }
46 |
47 | public void setRequest(boolean request) {
48 | mRequest = request;
49 | }
50 |
51 | public long getId() {
52 | return mId;
53 | }
54 |
55 | public void setId(long id) {
56 | mId = id;
57 | }
58 |
59 | public String getMethod() {
60 | return mMethod;
61 | }
62 |
63 | public void setMethod(String method) {
64 | mMethod = method;
65 | }
66 | }
67 |
68 | public static class Response extends Message {
69 |
70 | private boolean mResponse = true;
71 | private long mId;
72 | private boolean mOK;
73 | private long mErrorCode;
74 | private String mErrorReason;
75 |
76 | public Response(long id, JSONObject data) {
77 | super(data);
78 | mId = id;
79 | mOK = true;
80 | }
81 |
82 | public Response(long id, long errorCode, String errorReason) {
83 | mId = id;
84 | mOK = false;
85 | mErrorCode = errorCode;
86 | mErrorReason = errorReason;
87 | }
88 |
89 | public boolean isResponse() {
90 | return mResponse;
91 | }
92 |
93 | public void setResponse(boolean response) {
94 | mResponse = response;
95 | }
96 |
97 | public long getId() {
98 | return mId;
99 | }
100 |
101 | public void setId(long id) {
102 | mId = id;
103 | }
104 |
105 | public boolean isOK() {
106 | return mOK;
107 | }
108 |
109 | public void setOK(boolean OK) {
110 | mOK = OK;
111 | }
112 |
113 | public long getErrorCode() {
114 | return mErrorCode;
115 | }
116 |
117 | public void setErrorCode(long errorCode) {
118 | mErrorCode = errorCode;
119 | }
120 |
121 | public String getErrorReason() {
122 | return mErrorReason;
123 | }
124 |
125 | public void setErrorReason(String errorReason) {
126 | mErrorReason = errorReason;
127 | }
128 | }
129 |
130 | public static class Notification extends Message {
131 |
132 | private boolean mNotification = true;
133 | private String mMethod;
134 |
135 | public Notification(String method, JSONObject data) {
136 | super(data);
137 | mMethod = method;
138 | }
139 |
140 | public boolean isNotification() {
141 | return mNotification;
142 | }
143 |
144 | public void setNotification(boolean notification) {
145 | mNotification = notification;
146 | }
147 |
148 | public String getMethod() {
149 | return mMethod;
150 | }
151 |
152 | public void setMethod(String method) {
153 | mMethod = method;
154 | }
155 | }
156 |
157 | public static Message parse(String raw) {
158 | Logger.d(TAG, "parse() ");
159 | JSONObject object;
160 | try {
161 | object = new JSONObject(raw);
162 | } catch (JSONException e) {
163 | Logger.e(TAG, String.format("parse() | invalid JSON: %s", e.getMessage()));
164 | return null;
165 | }
166 |
167 | if (object.optBoolean("request")) {
168 | // Request.
169 | String method = object.optString("method");
170 | long id = object.optLong("id");
171 |
172 | if (TextUtils.isEmpty(method)) {
173 | Logger.e(TAG, "parse() | missing/invalid method field. rawData: " + raw);
174 | return null;
175 | }
176 | if (id == 0) {
177 | Logger.e(TAG, "parse() | missing/invalid id field. rawData: " + raw);
178 | return null;
179 | }
180 |
181 | return new Request(method, id, object.optJSONObject("data"));
182 | } else if (object.optBoolean("response")) {
183 | // Response.
184 | long id = object.optLong("id");
185 |
186 | if (id == 0) {
187 | Logger.e(TAG, "parse() | missing/invalid id field. rawData: " + raw);
188 | return null;
189 | }
190 |
191 | if (object.optBoolean("ok")) {
192 | return new Response(id, object.optJSONObject("data"));
193 | } else {
194 | return new Response(id, object.optLong("errorCode"), object.optString("errorReason"));
195 | }
196 | } else if (object.optBoolean("notification")) {
197 | // Notification.
198 | String method = object.optString("method");
199 |
200 | if (TextUtils.isEmpty(method)) {
201 | Logger.e(TAG, "parse() | missing/invalid method field. rawData: " + raw);
202 | return null;
203 | }
204 |
205 | return new Notification(method, object.optJSONObject("data"));
206 | } else {
207 | // Invalid.
208 | Logger.e(TAG, "parse() | missing request/response field. rawData: " + raw);
209 | return null;
210 | }
211 | }
212 |
213 | public static JSONObject createRequest(String method, JSONObject data) {
214 | JSONObject request = new JSONObject();
215 | try {
216 | request.put("request", true);
217 | request.put("method", method);
218 | request.put("id", Utils.generateRandomNumber());
219 | request.put("data", data != null ? data : new JSONObject());
220 | } catch (JSONException e) {
221 | e.printStackTrace();
222 | }
223 | return request;
224 | }
225 |
226 | @NonNull
227 | public static JSONObject createSuccessResponse(@NonNull Request request, JSONObject data) {
228 | JSONObject response = new JSONObject();
229 | try {
230 | response.put("response", true);
231 | response.put("id", request.getId());
232 | response.put("ok", true);
233 | response.put("data", data != null ? data : new JSONObject());
234 | } catch (JSONException e) {
235 | e.printStackTrace();
236 | }
237 | return response;
238 | }
239 |
240 | @NonNull
241 | public static JSONObject createErrorResponse(
242 | @NonNull Request request, long errorCode, String errorReason) {
243 | JSONObject response = new JSONObject();
244 | try {
245 | response.put("response", true);
246 | response.put("id", request.getId());
247 | response.put("ok", false);
248 | response.put("errorCode", errorCode);
249 | response.put("errorReason", errorReason);
250 | } catch (JSONException e) {
251 | e.printStackTrace();
252 | }
253 | return response;
254 | }
255 |
256 | @NonNull
257 | public static JSONObject createNotification(String method, JSONObject data) {
258 | JSONObject notification = new JSONObject();
259 | try {
260 | notification.put("notification", true);
261 | notification.put("method", method);
262 | notification.put("data", data != null ? data : new JSONObject());
263 | } catch (JSONException e) {
264 | e.printStackTrace();
265 | }
266 | return notification;
267 | }
268 | }
269 |
--------------------------------------------------------------------------------
/protoo-client/src/main/java/org/protoojs/droid/Peer.java:
--------------------------------------------------------------------------------
1 | package org.protoojs.droid;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.os.Handler;
5 | import android.os.Looper;
6 | import android.text.TextUtils;
7 |
8 | import androidx.annotation.NonNull;
9 |
10 | import org.json.JSONException;
11 | import org.json.JSONObject;
12 | import org.protoojs.droid.transports.AbsWebSocketTransport;
13 |
14 | import java.util.HashMap;
15 | import java.util.Map;
16 |
17 | public class Peer implements AbsWebSocketTransport.Listener {
18 |
19 | private static final String TAG = "Peer";
20 |
21 | public interface Listener {
22 |
23 | void onOpen();
24 |
25 | void onFail();
26 |
27 | void onRequest(@NonNull Message.Request request, @NonNull ServerRequestHandler handler);
28 |
29 | void onNotification(@NonNull Message.Notification notification);
30 |
31 | void onDisconnected();
32 |
33 | void onClose();
34 | }
35 |
36 | public interface ServerRequestHandler {
37 |
38 | default void accept() {
39 | accept(null);
40 | }
41 |
42 | void accept(String data);
43 |
44 | void reject(long code, String errorReason);
45 | }
46 |
47 | public interface ClientRequestHandler {
48 |
49 | void resolve(String data);
50 |
51 | void reject(long error, String errorReason);
52 | }
53 |
54 | class ClientRequestHandlerProxy implements ClientRequestHandler, Runnable {
55 |
56 | long mRequestId;
57 | String mMethod;
58 | ClientRequestHandler mClientRequestHandler;
59 |
60 | ClientRequestHandlerProxy(
61 | long requestId,
62 | String method,
63 | long timeoutDelayMillis,
64 | ClientRequestHandler clientRequestHandler) {
65 | mRequestId = requestId;
66 | mMethod = method;
67 | mClientRequestHandler = clientRequestHandler;
68 | mTimerCheckHandler.postDelayed(this, timeoutDelayMillis);
69 | }
70 |
71 | @Override
72 | public void run() {
73 | mSends.remove(mRequestId);
74 | // TODO (HaiyangWu): error code redefine. use http timeout
75 | if (mClientRequestHandler != null) {
76 | mClientRequestHandler.reject(408, "request timeout");
77 | }
78 | }
79 |
80 | @Override
81 | public void resolve(String data) {
82 | Logger.d(TAG, "request() " + mMethod + " success, " + data);
83 | if (mClientRequestHandler != null) {
84 | mClientRequestHandler.resolve(data);
85 | }
86 | }
87 |
88 | @Override
89 | public void reject(long error, String errorReason) {
90 | Logger.w(TAG, "request() " + mMethod + " fail, " + error + ", " + errorReason);
91 | if (mClientRequestHandler != null) {
92 | mClientRequestHandler.reject(error, errorReason);
93 | }
94 | }
95 |
96 | void close() {
97 | // stop timeout check.
98 | mTimerCheckHandler.removeCallbacks(this);
99 | }
100 | }
101 |
102 | // Closed flag.
103 | private boolean mClosed = false;
104 | // Transport.
105 | @NonNull private final AbsWebSocketTransport mTransport;
106 | // Listener.
107 | @NonNull private final Listener mListener;
108 | // Handler for timeout check.
109 | @NonNull private final Handler mTimerCheckHandler;
110 | // Connected flag.
111 | private boolean mConnected;
112 | // Custom data object.
113 | private JSONObject mData;
114 | // Map of pending sent request objects indexed by request id.
115 | @SuppressLint("UseSparseArrays")
116 | private Map mSends = new HashMap<>();
117 |
118 | public Peer(@NonNull AbsWebSocketTransport transport, @NonNull Listener listener) {
119 | mTransport = transport;
120 | mListener = listener;
121 | mTimerCheckHandler = new Handler(Looper.getMainLooper());
122 | handleTransport();
123 | }
124 |
125 | public boolean isClosed() {
126 | return mClosed;
127 | }
128 |
129 | public boolean isConnected() {
130 | return mConnected;
131 | }
132 |
133 | public JSONObject getData() {
134 | return mData;
135 | }
136 |
137 | public void close() {
138 | if (mClosed) {
139 | return;
140 | }
141 |
142 | Logger.d(TAG, "close()");
143 | mClosed = true;
144 | mConnected = false;
145 |
146 | // Close Transport.
147 | mTransport.close();
148 |
149 | // Close every pending sent.
150 | for (ClientRequestHandlerProxy proxy : mSends.values()) {
151 | proxy.close();
152 | }
153 | mSends.clear();
154 |
155 | // Emit 'close' event.
156 | mListener.onClose();
157 | }
158 |
159 | public void request(String method, String data, ClientRequestHandler clientRequestHandler) {
160 | try {
161 | request(method, new JSONObject(data), clientRequestHandler);
162 | } catch (JSONException e) {
163 | e.printStackTrace();
164 | }
165 | }
166 |
167 | public void request(
168 | String method, @NonNull JSONObject data, ClientRequestHandler clientRequestHandler) {
169 | JSONObject request = Message.createRequest(method, data);
170 | long requestId = request.optLong("id");
171 | Logger.d(TAG, String.format("request() [method:%s, data:%s]", method, data.toString()));
172 | String payload = mTransport.sendMessage(request);
173 |
174 | long timeout = (long) (1500 * (15 + (0.1 * payload.length())));
175 | mSends.put(
176 | requestId, new ClientRequestHandlerProxy(requestId, method, timeout, clientRequestHandler));
177 | }
178 |
179 | public void notify(String method, String data) {
180 | try {
181 | notify(method, new JSONObject(data));
182 | } catch (JSONException e) {
183 | e.printStackTrace();
184 | }
185 | }
186 |
187 | public void notify(String method, JSONObject data) {
188 | JSONObject notification = Message.createNotification(method, data);
189 | Logger.d(TAG, String.format("notify() [method:%s]", method));
190 | mTransport.sendMessage(notification);
191 | }
192 |
193 | private void handleTransport() {
194 | if (mTransport.isClosed()) {
195 | if (mClosed) {
196 | return;
197 | }
198 |
199 | mConnected = false;
200 | mListener.onClose();
201 | return;
202 | }
203 |
204 | mTransport.connect(this);
205 | }
206 |
207 | private void handleRequest(Message.Request request) {
208 | mListener.onRequest(
209 | request,
210 | new ServerRequestHandler() {
211 | @Override
212 | public void accept(String data) {
213 | try {
214 | JSONObject response;
215 | if (TextUtils.isEmpty(data)) {
216 | response = Message.createSuccessResponse(request, new JSONObject());
217 | } else {
218 | response = Message.createSuccessResponse(request, new JSONObject(data));
219 | }
220 | mTransport.sendMessage(response);
221 | } catch (Exception e) {
222 | e.printStackTrace();
223 | }
224 | }
225 |
226 | @Override
227 | public void reject(long code, String errorReason) {
228 | JSONObject response = Message.createErrorResponse(request, code, errorReason);
229 | try {
230 | mTransport.sendMessage(response);
231 | } catch (Exception e) {
232 | e.printStackTrace();
233 | }
234 | }
235 | });
236 | }
237 |
238 | private void handleResponse(Message.Response response) {
239 | ClientRequestHandlerProxy sent = mSends.remove(response.getId());
240 | if (sent == null) {
241 | Logger.e(
242 | TAG, "received response does not match any sent request [id:" + response.getId() + "]");
243 | return;
244 | }
245 |
246 | sent.close();
247 | if (response.isOK()) {
248 | sent.resolve(response.getData().toString());
249 | } else {
250 | sent.reject(response.getErrorCode(), response.getErrorReason());
251 | }
252 | }
253 |
254 | private void handleNotification(Message.Notification notification) {
255 | mListener.onNotification(notification);
256 | }
257 |
258 | // implement MyWebSocketTransport$Listener
259 | @Override
260 | public void onOpen() {
261 | if (mClosed) {
262 | return;
263 | }
264 | Logger.d(TAG, "onOpen()");
265 | mConnected = true;
266 | mListener.onOpen();
267 | }
268 |
269 | @Override
270 | public void onFail() {
271 | if (mClosed) {
272 | return;
273 | }
274 | Logger.e(TAG, "onFail()");
275 | mConnected = false;
276 | mListener.onFail();
277 | }
278 |
279 | @Override
280 | public void onMessage(Message message) {
281 | if (mClosed) {
282 | return;
283 | }
284 | Logger.d(TAG, "onMessage()");
285 | if (message instanceof Message.Request) {
286 | handleRequest((Message.Request) message);
287 | } else if (message instanceof Message.Response) {
288 | handleResponse((Message.Response) message);
289 | } else if (message instanceof Message.Notification) {
290 | handleNotification((Message.Notification) message);
291 | }
292 | }
293 |
294 | @Override
295 | public void onDisconnected() {
296 | if (mClosed) {
297 | return;
298 | }
299 | Logger.w(TAG, "onDisconnected()");
300 | mConnected = false;
301 | mListener.onDisconnected();
302 | }
303 |
304 | @Override
305 | public void onClose() {
306 | if (mClosed) {
307 | return;
308 | }
309 | Logger.w(TAG, "onClose()");
310 | mClosed = true;
311 | mConnected = false;
312 | mListener.onClose();
313 | }
314 | }
315 |
--------------------------------------------------------------------------------