├── settings.gradle
├── app
├── libs
│ ├── slf4j-android-1.5.8.jar
│ └── Java-WebSocket-1.5.2.jar
├── src
│ └── main
│ │ ├── res
│ │ ├── mipmap-hdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── values
│ │ │ ├── strings.xml
│ │ │ └── styles.xml
│ │ ├── values-v21
│ │ │ └── styles.xml
│ │ ├── mipmap-anydpi-v26
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ ├── drawable-v24
│ │ │ └── ic_launcher_foreground.xml
│ │ ├── layout
│ │ │ └── main.xml
│ │ └── drawable
│ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ └── com
│ │ │ └── kdt
│ │ │ └── mrpc
│ │ │ ├── RPCCallback.java
│ │ │ ├── RPCService.java
│ │ │ ├── DiscordSocketClient.java
│ │ │ └── MainActivity.java
│ │ └── AndroidManifest.xml
├── proguard-rules.pro
└── build.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .github
└── workflows
│ └── main.yml
├── .gitignore
├── README.md
├── gradlew
└── LICENSE
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/app/libs/slf4j-android-1.5.8.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/khanhduytran0/MRPC/HEAD/app/libs/slf4j-android-1.5.8.jar
--------------------------------------------------------------------------------
/app/libs/Java-WebSocket-1.5.2.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/khanhduytran0/MRPC/HEAD/app/libs/Java-WebSocket-1.5.2.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/khanhduytran0/MRPC/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/khanhduytran0/MRPC/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/khanhduytran0/MRPC/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/khanhduytran0/MRPC/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/khanhduytran0/MRPC/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/khanhduytran0/MRPC/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/khanhduytran0/MRPC/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/khanhduytran0/MRPC/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/khanhduytran0/MRPC/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/khanhduytran0/MRPC/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/khanhduytran0/MRPC/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | MRPC
5 |
6 |
7 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | -keepattributes SourceFile, LineNumberTable
2 | -renamesourcefileattribute SourceFile
3 | -repackageclasses
4 | -ignorewarnings
5 | -dontwarn
6 | -dontnote
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/values-v21/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Sep 12 09:22:55 CEST 2016
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-6.7.1-all.zip
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/java/com/kdt/mrpc/RPCCallback.java:
--------------------------------------------------------------------------------
1 | package com.kdt.mrpc;
2 |
3 | public interface RPCCallback
4 | {
5 | public static final int STATUS_CONNECTED = 1;
6 | public static final int STATUS_CLOSED = 1000;
7 |
8 | public void appendToLog(String line);
9 | public void onStatusChanged(int code, String reason, boolean remote);
10 | }
11 |
--------------------------------------------------------------------------------
/.github/workflows/main.yml:
--------------------------------------------------------------------------------
1 | name: Android CI
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | pull_request:
7 | branches: [ main ]
8 | workflow_dispatch:
9 |
10 | jobs:
11 | build:
12 |
13 | runs-on: ubuntu-latest
14 |
15 | steps:
16 | - uses: actions/checkout@v2
17 | - name: set up JDK 1.8
18 | uses: actions/setup-java@v1
19 | with:
20 | java-version: 1.8
21 |
22 | - name: Grant execute permission for gradlew
23 | run: chmod +x gradlew
24 | - name: Build with Gradle
25 | run: ./gradlew build
26 | - name: Upload APK
27 | uses: actions/upload-artifact@v2
28 | with:
29 | name: app-debug
30 | path: app/build/outputs/apk/debug/app-debug.apk
31 |
32 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 29
5 |
6 |
7 | defaultConfig {
8 | applicationId "com.kdt.mrpc"
9 | minSdkVersion 19
10 | targetSdkVersion 29
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | // https://mvnrepository.com/artifact/com.google.code.gson/gson
24 | implementation 'com.google.code.gson:gson:2.8.5'
25 | // implementation 'tech.gusavila92:java-android-websocket-client:1.2.2'
26 | implementation fileTree(dir: 'libs', include: ['*.jar'])
27 | }
28 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
15 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
30 |
31 |
32 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.aar
4 | *.ap_
5 | *.aab
6 |
7 | # Files for the ART/Dalvik VM
8 | *.dex
9 |
10 | # Java class files
11 | *.class
12 |
13 | # Generated files
14 | bin/
15 | gen/
16 | out/
17 | # Uncomment the following line in case you need and you don't have the release build type files in your app
18 | # release/
19 |
20 | # Gradle files
21 | .gradle/
22 | build/
23 |
24 | # Local configuration file (sdk path, etc)
25 | local.properties
26 |
27 | # Proguard folder generated by Eclipse
28 | proguard/
29 |
30 | # Log Files
31 | *.log
32 |
33 | # Android Studio Navigation editor temp files
34 | .navigation/
35 |
36 | # Android Studio captures folder
37 | captures/
38 |
39 | # IntelliJ
40 | *.iml
41 | .idea/workspace.xml
42 | .idea/tasks.xml
43 | .idea/gradle.xml
44 | .idea/assetWizardSettings.xml
45 | .idea/dictionaries
46 | .idea/libraries
47 | # Android Studio 3 in .gitignore file.
48 | .idea/caches
49 | .idea/modules.xml
50 | # Comment next line if keeping position of elements in Navigation Editor is relevant for you
51 | .idea/navEditor.xml
52 |
53 | # Keystore files
54 | # Uncomment the following lines if you do not want to check your keystore files in.
55 | #*.jks
56 | #*.keystore
57 |
58 | # External native build folder generated in Android Studio 2.2 and later
59 | .externalNativeBuild
60 | .cxx/
61 |
62 | # Google Services (e.g. APIs or Firebase)
63 | # google-services.json
64 |
65 | # Freeline
66 | freeline.py
67 | freeline/
68 | freeline_project_description.json
69 |
70 | # fastlane
71 | fastlane/report.xml
72 | fastlane/Preview.html
73 | fastlane/screenshots
74 | fastlane/test_output
75 | fastlane/readme.md
76 |
77 | # Version control
78 | vcs.xml
79 |
80 | # lint
81 | lint/intermediates/
82 | lint/generated/
83 | lint/outputs/
84 | lint/tmp/
85 | # lint/reports/
86 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # MRPC
2 | Experimental Discord Mobile Rich Presence (Android)
3 |
4 | ## How does it work?
5 | It's pretty simple.
6 | - Connect to the [Discord Gateway](https://discord.com/developers/docs/topics/gateway) as a normal Discord Client.
7 | - Send [Identify](https://discord.com/developers/docs/topics/gateway#identifying) and [Update Presence](https://discord.com/developers/docs/topics/gateway#update-presence).
8 |
9 | ## Custom image support + gif
10 | MRPC now supports setting custom image through 2 links:
11 | - `https://media.discordapp.net` (resolves from `mp:path/to/image`)
12 | - `https://cdn.discordapp.com` (resolves from `../../path/to/image`)
13 |
14 | In late 2021(?), Discord allowed activity to specify media proxy image, which opens a way to set custom image.
15 | However, there is another trick that has not been used before:
16 |
17 | - By default, Discord parses the input as `application_assets` (unless it is set to media proxy with `mp:` prefix)
18 | - Setting the asset object to `test` results in `https://cdn.discordapp.com/app-assets/application-id/test.png`
19 | - It does not verify anything there. This way, we can put `../..` to escape the path, then we can set anything such as an animated emoji right here, finally `#` at the end to exclude `.png`.
20 | - Setting the asset object to `../../emojis/emoji-id.gif#` results in `https://cdn.discordapp.com/app-assets/application-id/../../emojis/emoji-id.gif#.png` which then gets resolved to `https://cdn.discordapp.com/emojis/emoji-id.gif`
21 |
22 | ## Notes
23 | - MRPC parses the image link automatically, so you just need to paste the link and it will work out of the box. You can only use image link from domains listed above.
24 | - Rate limiting is not yet handled.
25 | - This app uses the Discord Gateway instead of OAuth2 API (which I can't even find the documentation for the `activities.write` scope), so this might not be safe. Use this at your own risk.
26 | - Zlib compression is not yet used, due to the current using library doesn't correctly handle it(?).
27 |
28 | ## License
29 | [Apache License 2.0](https://github.com/khanhduytran0/MRPC/blob/main/LICENSE).
30 |
31 | ## Third party libraries and their licenses
32 | - [gson](https://github.com/google/gson): [Apache License 2.0](https://github.com/google/gson/blob/master/LICENSE).
33 | - [Java-WebSocket](https://github.com/TooTallNate/Java-WebSocket): [MIT License](https://github.com/TooTallNate/Java-WebSocket/blob/master/LICENSE).
34 | - [slf4j-android](https://github.com/twwwt/slf4j): [MIT License](https://github.com/twwwt/slf4j/blob/master/LICENSE.txt).
35 |
36 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/main.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
13 |
14 |
19 |
20 |
24 |
25 |
32 |
33 |
40 |
41 |
42 |
43 |
48 |
49 |
54 |
55 |
60 |
61 |
66 |
67 |
72 |
73 |
76 |
77 |
83 |
84 |
85 |
86 |
87 |
88 |
95 |
96 |
97 |
98 |
--------------------------------------------------------------------------------
/app/src/main/java/com/kdt/mrpc/RPCService.java:
--------------------------------------------------------------------------------
1 | package com.kdt.mrpc;
2 |
3 | import android.app.Notification;
4 | import android.app.NotificationChannel;
5 | import android.app.NotificationManager;
6 | import android.app.Service;
7 | import android.content.Intent;
8 | import android.os.Binder;
9 | import android.os.Build;
10 | import android.os.IBinder;
11 | import java.net.URISyntaxException;
12 | import android.util.Log;
13 |
14 | public class RPCService extends Service implements RPCCallback {
15 | private final RPCBinder binder = new RPCBinder();
16 | private Thread wsThread;
17 | private Notification.Builder builder;
18 | private Notification notification;
19 | protected int lastCode = 0;
20 | protected String lastReason = null;
21 | protected RPCCallback callback;
22 | protected DiscordSocketClient webSocketClient;
23 |
24 | @Override
25 | public IBinder onBind(Intent i) {
26 | return binder;
27 | }
28 |
29 | @Override
30 | public void onCreate() {
31 | super.onCreate();
32 | wsThread = new Thread(new Runnable(){
33 | @Override
34 | public void run() {
35 | try {
36 | webSocketClient = new DiscordSocketClient(RPCService.this);
37 | webSocketClient.connect();
38 | } catch (URISyntaxException e) {
39 | // this should never happen
40 | throw new RuntimeException(e);
41 | }
42 | }
43 | });
44 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
45 | NotificationChannel mChannel = new NotificationChannel(
46 | "MRPC",
47 | "MRPC",
48 | NotificationManager.IMPORTANCE_LOW);
49 | getManager().createNotificationChannel(mChannel);
50 |
51 | builder = new Notification.Builder(this, "MRPC");
52 | } else {
53 | builder = new Notification.Builder(this);
54 | }
55 | builder
56 | .setSmallIcon(R.drawable.ic_launcher_background)
57 | .setContentTitle(getString(R.string.app_name))
58 | .setPriority(Notification.PRIORITY_DEFAULT)
59 | .setOngoing(true);
60 | notification = builder.build();
61 | startForeground(1, notification);
62 | }
63 |
64 | @Override
65 | public void onStart(Intent intent, int startId) {
66 | super.onStart(intent, startId);
67 | wsThread.start();
68 | //getManager().notify(1, mNotification);
69 | //startForeground(1, mNotification);
70 | }
71 |
72 | @Override
73 | public void onDestroy() {
74 | super.onDestroy();
75 | if (webSocketClient != null && !webSocketClient.isClosed()) {
76 | webSocketClient.close(RPCCallback.STATUS_CLOSED);
77 | }
78 |
79 | stopForeground(true);
80 |
81 | if (lastCode != 0) {
82 | builder.setOngoing(false);
83 | notification = builder.build();
84 | getManager().notify(1, notification);
85 | }
86 | }
87 |
88 | @Override
89 | public void onStatusChanged(int code, String reason, boolean remote) {
90 | if (callback != null) {
91 | callback.onStatusChanged(code, reason, remote);
92 | return;
93 | }
94 | lastCode = code;
95 | lastReason = reason;
96 | }
97 |
98 | @Override
99 | public void appendToLog(String line) {
100 | if (callback != null) {
101 | callback.appendToLog(line);
102 | }
103 | Log.i(getString(R.string.app_name), line);
104 | }
105 |
106 | private NotificationManager getManager() {
107 | return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
108 | }
109 |
110 | public void setCallback(RPCCallback callback) {
111 | this.callback = callback;
112 | if (callback != null && lastCode != 0) {
113 | callback.onStatusChanged(lastCode, lastReason, false);
114 | }
115 | }
116 |
117 | protected void updateMessage(String s) {
118 | appendToLog(s);
119 | builder.setContentText(s);
120 | notification = builder.build();
121 | getManager().notify(1, notification);
122 | }
123 |
124 | public class RPCBinder extends Binder {
125 | public RPCService getService() {
126 | return RPCService.this;
127 | }
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 |
2 | #!/usr/bin/env bash
3 |
4 | ##############################################################################
5 | ##
6 | ## Gradle start up script for UN*X
7 | ##
8 | ##############################################################################
9 |
10 | # Attempt to set APP_HOME
11 | # Resolve links: $0 may be a link
12 | PRG="$0"
13 | # Need this for relative symlinks.
14 | while [ -h "$PRG" ] ; do
15 | ls=`ls -ld "$PRG"`
16 | link=`expr "$ls" : '.*-> \(.*\)$'`
17 | if expr "$link" : '/.*' > /dev/null; then
18 | PRG="$link"
19 | else
20 | PRG=`dirname "$PRG"`"/$link"
21 | fi
22 | done
23 | SAVED="`pwd`"
24 | cd "`dirname \"$PRG\"`/" >/dev/null
25 | APP_HOME="`pwd -P`"
26 | cd "$SAVED" >/dev/null
27 |
28 | APP_NAME="Gradle"
29 | APP_BASE_NAME=`basename "$0"`
30 |
31 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
32 | DEFAULT_JVM_OPTS=""
33 |
34 | # Use the maximum available, or set MAX_FD != -1 to use that value.
35 | MAX_FD="maximum"
36 |
37 | warn ( ) {
38 | echo "$*"
39 | }
40 |
41 | die ( ) {
42 | echo
43 | echo "$*"
44 | echo
45 | exit 1
46 | }
47 |
48 | # OS specific support (must be 'true' or 'false').
49 | cygwin=false
50 | msys=false
51 | darwin=false
52 | nonstop=false
53 | case "`uname`" in
54 | CYGWIN* )
55 | cygwin=true
56 | ;;
57 | Darwin* )
58 | darwin=true
59 | ;;
60 | MINGW* )
61 | msys=true
62 | ;;
63 | NONSTOP* )
64 | nonstop=true
65 | ;;
66 | esac
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
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 | Please set the JAVA_HOME variable in your environment to match the
87 | location of your Java installation."
88 | fi
89 |
90 | # Increase the maximum file descriptors if we can.
91 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
92 | MAX_FD_LIMIT=`ulimit -H -n`
93 | if [ $? -eq 0 ] ; then
94 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
95 | MAX_FD="$MAX_FD_LIMIT"
96 | fi
97 | ulimit -n $MAX_FD
98 | if [ $? -ne 0 ] ; then
99 | warn "Could not set maximum file descriptor limit: $MAX_FD"
100 | fi
101 | else
102 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
103 | fi
104 | fi
105 |
106 | # For Darwin, add options to specify how the application appears in the dock
107 | if $darwin; then
108 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
109 | fi
110 |
111 | # For Cygwin, switch paths to Windows format before running java
112 | if $cygwin ; then
113 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
114 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
115 | JAVACMD=`cygpath --unix "$JAVACMD"`
116 |
117 | # We build the pattern for arguments to be converted via cygpath
118 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
119 | SEP=""
120 | for dir in $ROOTDIRSRAW ; do
121 | ROOTDIRS="$ROOTDIRS$SEP$dir"
122 | SEP="|"
123 | done
124 | OURCYGPATTERN="(^($ROOTDIRS))"
125 | # Add a user-defined pattern to the cygpath arguments
126 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
127 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
128 | fi
129 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
130 | i=0
131 | for arg in "$@" ; do
132 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
133 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
134 |
135 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
136 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
137 | else
138 | eval `echo args$i`="\"$arg\""
139 | fi
140 | i=$((i+1))
141 | done
142 | case $i in
143 | (0) set -- ;;
144 | (1) set -- "$args0" ;;
145 | (2) set -- "$args0" "$args1" ;;
146 | (3) set -- "$args0" "$args1" "$args2" ;;
147 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
148 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
149 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
150 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
151 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
152 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
153 | esac
154 | fi
155 |
156 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
157 | function splitJvmOpts() {
158 | JVM_OPTS=("$@")
159 | }
160 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
161 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
162 |
163 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
164 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/java/com/kdt/mrpc/DiscordSocketClient.java:
--------------------------------------------------------------------------------
1 | package com.kdt.mrpc;
2 |
3 | import android.util.ArrayMap;
4 | import android.util.Log;
5 | import com.google.gson.reflect.TypeToken;
6 | import java.net.URI;
7 | import java.net.URISyntaxException;
8 | import java.nio.ByteBuffer;
9 | import java.util.List;
10 | import java.util.Map;
11 | import javax.net.ssl.SSLParameters;
12 | import org.java_websocket.client.WebSocketClient;
13 | import org.java_websocket.handshake.ServerHandshake;
14 |
15 | public class DiscordSocketClient extends WebSocketClient
16 | {
17 | protected String authToken;
18 | private final RPCService service;
19 | private int heartbeat_interval, seq;
20 | private final Runnable heartbeatRunnable;
21 | private Thread heartbeatThr;
22 | private String currentStatus;
23 |
24 | public DiscordSocketClient(final RPCService service) throws URISyntaxException {
25 | super(new URI("wss://gateway.discord.gg/?encoding=json&v=9"));
26 | this.service = service;
27 | heartbeatRunnable = new Runnable(){
28 | @Override
29 | public void run() {
30 | try {
31 | service.updateMessage("Heartbeat wait for " + heartbeat_interval);
32 | if (heartbeat_interval < 10000) throw new RuntimeException("invalid");
33 | Thread.sleep(heartbeat_interval);
34 | send(/*encodeString*/("{\"op\":1, \"d\":" + (seq==0?"null":Integer.toString(seq)) + "}"));
35 | service.updateMessage("Heartbeat sent");
36 | } catch (InterruptedException e) {}
37 | }
38 | };
39 | }
40 |
41 | @Override
42 | public void close(int code) {
43 | heartbeatThr.interrupt();
44 | super.close(code);
45 | }
46 |
47 | @Override
48 | public void onOpen(ServerHandshake s) {
49 | service.updateMessage("Connection opened");
50 | }
51 |
52 | private void onMessageDispatch(ArrayMap map) {
53 | Map data;
54 | switch (((String)map.get("t"))) {
55 | case "READY":
56 | data = (Map) ((Map)map.get("d")).get("user");
57 | service.updateMessage("Connected to " + data.get("username") + "#" + data.get("discriminator"));
58 | service.onStatusChanged(RPCCallback.STATUS_CONNECTED, null, true);
59 | break;
60 | case "SESSIONS_REPLACE":
61 | data = (Map) ((List)map.get("d")).get(0);
62 | currentStatus = (String) data.get("status");
63 | service.appendToLog("Status set to " + currentStatus);
64 | break;
65 | }
66 | }
67 |
68 | @Override
69 | public void onMessage(ByteBuffer message) {
70 | // onMessage(decodeString(message.array()));
71 | }
72 |
73 | @Override
74 | public void onMessage(String message) {
75 | //service.mCallback.appendToLog("onTextReceived: " + message);
76 |
77 | ArrayMap map = MainActivity.GSON.fromJson(
78 | message, new TypeToken>() {}.getType()
79 | );
80 |
81 | // obtain sequence number
82 | Object o = map.get("s");
83 | if (o != null) {
84 | seq = ((Double)o).intValue();
85 | }
86 |
87 | int opcode = ((Double)map.get("op")).intValue();
88 | switch (opcode) {
89 | case 0: // Dispatch event
90 | onMessageDispatch(map);
91 | break;
92 | case 10: // Hello
93 | Map data = (Map) map.get("d");
94 | heartbeat_interval = ((Double)data.get("heartbeat_interval")).intValue();
95 | heartbeatThr = new Thread(heartbeatRunnable);
96 | heartbeatThr.start();
97 | sendIdentify();
98 | break;
99 | case 1: // Heartbeat request
100 | if (!heartbeatThr.interrupted()) {
101 | heartbeatThr.interrupt();
102 | }
103 | send(/*encodeString*/("{\"op\":1, \"d\":" + (seq==0?"null":Integer.toString(seq)) + "}"));
104 |
105 | break;
106 | case 11: // Heartbeat ACK
107 | if (!heartbeatThr.interrupted()) {
108 | heartbeatThr.interrupt();
109 | }
110 | heartbeatThr = new Thread(heartbeatRunnable);
111 | heartbeatThr.start();
112 | break;
113 | }
114 | }
115 |
116 | @Override
117 | public void onClose(int code, String reason, boolean remote) {
118 | service.onStatusChanged(code, reason, remote);
119 | service.updateMessage("Connection closed: " + code + ": " + reason);
120 | if (!heartbeatThr.interrupted()) {
121 | heartbeatThr.interrupt();
122 | }
123 | /*
124 | runOnUiThread(new Runnable() {
125 | @Override
126 | public void run() {
127 | buttonConnect.setText("Connect");
128 | buttonSetActivity.setEnabled(false);
129 | }
130 | });
131 | */
132 | throw new RuntimeException("Interrupt");
133 | }
134 |
135 | @Override
136 | public void onError(Exception e) {
137 | if (!e.getMessage().equals("Interrupt") && service.callback != null) {
138 | service.callback.appendToLog(Log.getStackTraceString(e));
139 | }
140 | }
141 |
142 | @Override
143 | protected void onSetSSLParameters(SSLParameters p) {
144 | try {
145 | super.onSetSSLParameters(p);
146 | } catch (Throwable th) {
147 | th.printStackTrace();
148 | }
149 | }
150 |
151 | private void sendIdentify() {
152 | ArrayMap prop = new ArrayMap<>();
153 | prop.put("$os", "linux");
154 | prop.put("$browser", "Discord Android");
155 | prop.put("$device", "unknown");
156 |
157 | ArrayMap data = new ArrayMap<>();
158 | data.put("token", MainActivity.PREF.getString("authToken", null));
159 | data.put("properties", prop);
160 | data.put("compress", false);
161 | data.put("intents", 0);
162 |
163 | ArrayMap arr = new ArrayMap<>();
164 | arr.put("op", 2);
165 | arr.put("d", data);
166 |
167 | send(MainActivity.GSON.toJson(arr));
168 | }
169 |
170 | private String processImageLink(String link) {
171 | if (link.isEmpty()) {
172 | return null;
173 | }
174 | if (link.contains("://")) {
175 | link = link.split("://")[1];
176 | }
177 | if (link.startsWith("media.discordapp.net/")) {
178 | return link.replace("media.discordapp.net/", "mp:");
179 | } else if (link.startsWith("cdn.discordapp.com")) {
180 | // Trick: allow using CDN URL for custom image
181 | // https://cdn.discordapp.com/app-assets/application-id/../../whatever.png_or_gif#.png
182 | // ".." resolves to the parent directory
183 | // "#" at the end to exclude ".png" from the link
184 | // so it becomes
185 | // https://cdn.discordapp.com/whatever.png_or_gif
186 | return link.replace("cdn.discordapp.com/", "../../") + "#";
187 | }
188 | return link;
189 | }
190 |
191 | public void sendPresenceUpdate(String name, String details, String state, String largeImage, String smallImage) {
192 | long current = System.currentTimeMillis();
193 |
194 | ArrayMap presence = new ArrayMap<>();
195 |
196 | if (name.isEmpty()) {
197 | presence.put("activities", new Object[]{});
198 | } else {
199 | ArrayMap activity = new ArrayMap<>();
200 | activity.put("name", name);
201 | if (!state.isEmpty()) {
202 | activity.put("state", state);
203 | }
204 | if (!details.isEmpty()) {
205 | activity.put("details", details);
206 | }
207 | activity.put("type", 0);
208 |
209 | ArrayMap assets = new ArrayMap<>();
210 | assets.put("large_image", processImageLink(largeImage));
211 | assets.put("small_image", processImageLink(smallImage));
212 | activity.put("assets", assets);
213 |
214 | activity.put("application_id", "567994086452363286");
215 | ArrayMap button = new ArrayMap<>();
216 | button.put("label", "Open GitHub");
217 | button.put("url", "https://github.com");
218 | //activity.put("buttons", new Object[]{button});
219 |
220 | ArrayMap timestamps = new ArrayMap<>();
221 | timestamps.put("start", current);
222 |
223 | activity.put("timestamps", timestamps);
224 | presence.put("activities", new Object[]{activity});
225 | }
226 |
227 | presence.put("afk", true);
228 | presence.put("since", current);
229 | presence.put("status", currentStatus);
230 |
231 | ArrayMap arr = new ArrayMap<>();
232 | arr.put("op", 3);
233 | arr.put("d", presence);
234 |
235 | service.appendToLog(MainActivity.GSON.toJson(arr));
236 | send(MainActivity.GSON.toJson(arr));
237 | }
238 | }
239 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/app/src/main/java/com/kdt/mrpc/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.kdt.mrpc;
2 |
3 | import android.app.Activity;
4 | import android.content.ComponentName;
5 | import android.content.Intent;
6 | import android.content.ServiceConnection;
7 | import android.content.SharedPreferences;
8 | import android.os.Build;
9 | import android.os.Bundle;
10 | import android.os.IBinder;
11 | import android.preference.PreferenceManager;
12 | import android.util.Log;
13 | import android.view.View;
14 | import android.webkit.ValueCallback;
15 | import android.webkit.WebView;
16 | import android.webkit.WebViewClient;
17 | import android.widget.Button;
18 | import android.widget.EditText;
19 | import android.widget.ImageButton;
20 | import android.widget.TextView;
21 | import android.widget.Toast;
22 | import com.google.gson.Gson;
23 | import com.google.gson.GsonBuilder;
24 | import java.io.BufferedReader;
25 | import java.io.File;
26 | import java.io.FileReader;
27 | import java.io.FilenameFilter;
28 |
29 | public class MainActivity extends Activity implements ServiceConnection, RPCCallback
30 | {
31 | protected static final Gson GSON = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
32 | protected static SharedPreferences PREF;
33 |
34 | private Intent intent;
35 | private RPCService service;
36 |
37 | private WebView webView;
38 | private TextView textviewLog;
39 | private Button buttonConnect, buttonSetActivity;
40 | private EditText editActivityName, editActivityState,
41 | editActivityDetails, editActivityLargeImage, editActivitySmallImage;
42 |
43 | @Override
44 | protected void onCreate(Bundle savedInstanceState)
45 | {
46 | super.onCreate(savedInstanceState);
47 | setContentView(R.layout.main);
48 |
49 | PREF = PreferenceManager.getDefaultSharedPreferences(this);
50 |
51 | webView = (WebView) findViewById(R.id.mainWebView);
52 | webView.getSettings().setJavaScriptEnabled(true);
53 | webView.getSettings().setAppCacheEnabled(true);
54 | webView.getSettings().setDatabaseEnabled(true);
55 | webView.getSettings().setDomStorageEnabled(true);
56 | webView.setWebViewClient(new WebViewClient() {
57 | @Override
58 | public boolean shouldOverrideUrlLoading(WebView v, String url) {
59 | Log.d("Web", "Attempt to enter " + url);
60 | if (url.endsWith("/app")) {
61 | /*
62 | webView.evaluateJavascript("javascript:window.localStorage.getItem('token');", new ValueCallback() {
63 | @Override
64 | public void onReceiveValue(String s) {
65 | webView.setVisibility(View.GONE);
66 | appendToLog("value = " + s);
67 | }
68 | });
69 | */
70 | webView.stopLoading();
71 | webView.setVisibility(View.GONE);
72 | extractToken();
73 | login(v);
74 |
75 | return false;
76 | }
77 | return super.shouldOverrideUrlLoading(v, url);
78 | }
79 | });
80 |
81 | textviewLog = (TextView) findViewById(R.id.textviewLog);
82 | buttonConnect = (Button) findViewById(R.id.buttonConnect);
83 | buttonSetActivity = (Button) findViewById(R.id.buttonSetActivity);
84 | buttonSetActivity.setEnabled(false);
85 | editActivityName = (EditText) findViewById(R.id.editActivityName);
86 | editActivityState = (EditText) findViewById(R.id.editActivityState);
87 | editActivityDetails = (EditText) findViewById(R.id.editActivityDetails);
88 | editActivityLargeImage = findViewById(R.id.editActivityLargeImage);
89 | editActivitySmallImage = findViewById(R.id.editActivitySmallImage);
90 |
91 | intent = new Intent(this, RPCService.class);
92 | bindService(intent, this, BIND_AUTO_CREATE);
93 | }
94 |
95 | @Override
96 | protected void onDestroy() {
97 | super.onDestroy();
98 | if (service.lastCode < 2) {
99 | unbindService(this);
100 | }
101 | }
102 |
103 | @Override
104 | public void onServiceConnected(ComponentName componentName, IBinder binder) {
105 | service = ((RPCService.RPCBinder)binder).getService();
106 | service.setCallback(this);
107 | if (service.lastCode == RPCCallback.STATUS_CONNECTED) {
108 | appendToLog("Connected to the running service");
109 | }
110 | if (service.lastCode != 0) {
111 | appendToLog("Previous code: " + service.lastCode + ", reason: " + service.lastReason);
112 | }
113 | }
114 |
115 | @Override
116 | public void onServiceDisconnected(ComponentName componentName) {
117 | service.setCallback(null);
118 | service = null;
119 | }
120 |
121 | /*
122 | @Override
123 | protected void onResume() {
124 | super.onResume();
125 | Uri data = getIntent().getData();
126 | if (data != null && wsThr == null) {
127 | if (data.toString().contains("access_token=")) {
128 | accessToken = data.toString().substring(
129 | data.toString().indexOf("access_token=") + 13,
130 | data.toString().indexOf("&expires_in")
131 | );
132 | actualConnect(null);
133 | } else {
134 | actualConnect(data.getQueryParameter("code"));
135 | }
136 | }
137 | }
138 | */
139 |
140 | public void sendPresenceUpdate(View v) {
141 | service.webSocketClient.sendPresenceUpdate(
142 | editActivityName.getText().toString(),
143 | editActivityDetails.getText().toString(),
144 | editActivityState.getText().toString(),
145 | editActivityLargeImage.getText().toString(),
146 | editActivitySmallImage.getText().toString());
147 | }
148 |
149 | @Override
150 | public void appendToLog(final String msg) {
151 | runOnUiThread(new Runnable(){
152 | @Override
153 | public void run() {
154 | textviewLog.append(msg + "\n");
155 | }
156 | });
157 | }
158 |
159 | @Override
160 | public void onStatusChanged(final int code, final String reason, final boolean remote) {
161 | service.lastCode = code;
162 | service.lastReason = reason;
163 | runOnUiThread(new Runnable(){
164 | @Override
165 | public void run() {
166 | buttonConnect.setEnabled(true);
167 | buttonSetActivity.setEnabled(code == RPCCallback.STATUS_CONNECTED);
168 | if (code == RPCCallback.STATUS_CONNECTED) {
169 | buttonConnect.setText("Disconnect");
170 | } else {
171 | disconnect(false);
172 | }
173 | }
174 | });
175 | }
176 |
177 | public void login(View v) {
178 | if (webView.getVisibility() == View.VISIBLE) {
179 | webView.stopLoading();
180 | webView.setVisibility(View.GONE);
181 | return;
182 | }
183 | /*
184 | if (PREF.contains("authToken")) {
185 | appendToLog("Logged in");
186 | connect(null);
187 | return;
188 | }
189 | */
190 | webView.setVisibility(View.VISIBLE);
191 | webView.loadUrl("https://discord.com/login");
192 | }
193 |
194 | public void connect(View v) {
195 | if (v != null && !extractToken()) {
196 | Toast.makeText(this, "Token is not found, opening login page", Toast.LENGTH_SHORT).show();
197 | login(null);
198 | return;
199 | }
200 |
201 | if (buttonConnect.getText().equals("Connect")) {
202 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
203 | startForegroundService(intent);
204 | } else {
205 | startService(intent);
206 | }
207 | buttonConnect.setEnabled(false);
208 | } else {
209 | disconnect(true);
210 | }
211 | }
212 |
213 | public void disconnect(boolean unbind) {
214 | if (unbind) {
215 | unbindService(this);
216 | stopService(intent);
217 | }
218 | buttonConnect.setText("Connect");
219 | buttonSetActivity.setEnabled(false);
220 | }
221 |
222 | public boolean extractToken() {
223 | // ~~extract token in an ugly way :troll:~~
224 | try {
225 | File f = new File(getFilesDir().getParentFile(), "app_webview/Default/Local Storage/leveldb");
226 | File[] fArr = f.listFiles(new FilenameFilter(){
227 | @Override
228 | public boolean accept(File file, String name) {
229 | return name.endsWith(".log");
230 | }
231 | });
232 | if (fArr.length == 0) {
233 | return false;
234 | }
235 | f = fArr[0];
236 | BufferedReader br = new BufferedReader(new FileReader(f));
237 | String line;
238 | while ((line = br.readLine()) != null) {
239 | if (line.contains("token")) {
240 | break;
241 | }
242 | }
243 | line = line.substring(line.indexOf("token") + 5);
244 | line = line.substring(line.indexOf("\"") + 1);
245 | PREF.edit().putString("authToken", line.substring(0, line.indexOf("\""))).commit();
246 | appendToLog("Successfully extracted token");
247 | return true;
248 | } catch (Throwable e) {
249 | appendToLog("Failed to extract token: " + Log.getStackTraceString(e));
250 | return false;
251 | }
252 | }
253 |
254 | /*
255 | public void code2AccessToken(String code) {
256 | try {
257 | HttpURLConnection conn = (HttpURLConnection) new URL("https://discord.com/api/oauth2/token").openConnection();
258 | conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
259 | conn.setDoInput(true);
260 |
261 | ArrayMap prop = new ArrayMap<>();
262 | prop.put("client_id", "591317049637339146");
263 | prop.put("client_secret", "Discord Android");
264 | prop.put("grant_type", "authorization_code");
265 | prop.put("code", code);
266 | prop.put("redirect_url", "https://account.samsung.com/accounts/oauth/callback");
267 |
268 | byte[] arr = gson.toJson(prop).getBytes();
269 |
270 | conn.getOutputStream().write(arr, 0, arr.length);
271 | } catch (Throwable e) {
272 | throw new RuntimeException(e);
273 | }
274 | }
275 |
276 | public String decodeString(byte[] arr) {
277 | Inflater i = new Inflater();
278 | i.setInput(arr, 0, arr.length);
279 | ByteArrayOutputStream bos = new ByteArrayOutputStream(arr.length);
280 | byte[] buf = new byte[1024];
281 | try {
282 | int count = 1;
283 | while (!i.finished() && count > 0) {
284 | count = i.inflate(buf);
285 | appendlnToLog("decode " + count);
286 | bos.write(buf, 0, count);
287 | }
288 | } catch (DataFormatException e) {
289 | throw new RuntimeException(e);
290 | }
291 | i.end();
292 | try {
293 | bos.close();
294 | } catch (IOException e) {
295 | throw new RuntimeException(e);
296 | }
297 | return new String(bos.toByteArray());
298 | }
299 |
300 | public byte[] encodeString(String str) {
301 | byte[] arr = str.getBytes();
302 | Deflater compresser = new Deflater();
303 | compresser.setInput(arr);
304 | compresser.finish();
305 | ByteArrayOutputStream bos = new ByteArrayOutputStream(arr.length);
306 | // Compress the data
307 | byte[] buf = new byte[1024];
308 | while (!compresser.finished()) {
309 | int count = compresser.deflate(buf);
310 | bos.write(buf, 0, count);
311 | }
312 | compresser.end();
313 | try {
314 | bos.close();
315 | } catch (IOException e) {
316 | throw new RuntimeException(e);
317 | }
318 |
319 | return bos.toByteArray();
320 | }
321 | */
322 | }
323 |
--------------------------------------------------------------------------------