├── .gitignore ├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src ├── test │ └── java │ │ └── com │ │ └── outstandingboy │ │ └── donationalert │ │ └── DonationAlertAPITest.java └── main │ └── java │ └── com │ └── outstandingboy │ └── donationalert │ ├── util │ └── Gsons.java │ ├── exception │ ├── TokenNotFoundException.java │ └── TwipVersionNotFoundException.java │ ├── platform │ ├── Platform.java │ ├── Toonation.java │ ├── Twip.java │ └── Chzzk.java │ └── entity │ └── Donation.java ├── gradlew.bat ├── README.md └── gradlew /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | .idea 3 | build 4 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'DonationAlertAPI' 2 | 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/outstanding1301/donation-alert-api/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /src/test/java/com/outstandingboy/donationalert/DonationAlertAPITest.java: -------------------------------------------------------------------------------- 1 | package com.outstandingboy.donationalert; 2 | 3 | import org.junit.Test; 4 | 5 | public class DonationAlertAPITest { 6 | @Test 7 | void parseTest() { 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/outstandingboy/donationalert/util/Gsons.java: -------------------------------------------------------------------------------- 1 | package com.outstandingboy.donationalert.util; 2 | 3 | import com.google.gson.Gson; 4 | 5 | public class Gsons { 6 | private static Gson gson = new Gson(); 7 | 8 | public static Gson gson() { 9 | return gson; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/outstandingboy/donationalert/exception/TokenNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.outstandingboy.donationalert.exception; 2 | 3 | import java.io.IOException; 4 | 5 | public class TokenNotFoundException extends IOException { 6 | public TokenNotFoundException(String message) { 7 | super(message); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/outstandingboy/donationalert/exception/TwipVersionNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.outstandingboy.donationalert.exception; 2 | 3 | import java.io.IOException; 4 | 5 | public class TwipVersionNotFoundException extends IOException { 6 | public TwipVersionNotFoundException(String message) { 7 | super(message); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/outstandingboy/donationalert/platform/Platform.java: -------------------------------------------------------------------------------- 1 | package com.outstandingboy.donationalert.platform; 2 | 3 | import com.outstandingboy.donationalert.entity.Donation; 4 | import io.reactivex.disposables.Disposable; 5 | import io.reactivex.functions.Consumer; 6 | import io.reactivex.subjects.Subject; 7 | 8 | public interface Platform { 9 | Disposable subscribeDonation(Consumer onNext); 10 | 11 | Disposable subscribeMessage(Consumer onNext); 12 | 13 | void close(); 14 | 15 | Subject getDonationObservable(); 16 | 17 | Subject getMessageObservable(); 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/outstandingboy/donationalert/entity/Donation.java: -------------------------------------------------------------------------------- 1 | package com.outstandingboy.donationalert.entity; 2 | 3 | public class Donation { 4 | private String id; 5 | private String nickName; 6 | private String comment; 7 | private long amount; 8 | 9 | public String getId() { 10 | return id; 11 | } 12 | 13 | public void setId(String id) { 14 | this.id = id; 15 | } 16 | 17 | public String getNickName() { 18 | return nickName; 19 | } 20 | 21 | public void setNickName(String nickName) { 22 | this.nickName = nickName; 23 | } 24 | 25 | public String getComment() { 26 | if (comment == null) return ""; 27 | if (comment.startsWith("video://") || comment.startsWith("[yt:")) return "[영상 후원]"; 28 | return comment; 29 | } 30 | 31 | public void setComment(String comment) { 32 | this.comment = comment; 33 | } 34 | 35 | public long getAmount() { 36 | return amount; 37 | } 38 | 39 | public void setAmount(long amount) { 40 | this.amount = amount; 41 | } 42 | 43 | @Override 44 | public String toString() { 45 | return "Donation [id=" + id + ", nickName=" + nickName + ", comment=" + comment + ", amount=" + amount + "]"; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /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="-Xmx64m" 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 | # 💸 Donation Alert API 2 | [Twip](http://twip.kr/), [Toonation](https://toon.at/)의 후원 알림(Alertbox)을 받아올 수 있는 RxJava 기반 Java API 3 | 4 | ![so much money](https://media.giphy.com/media/3orif1esInVTdhaNsk/giphy.gif) 5 | 6 | > [outstandingboy/donation-alert-api](https://github.com/outstanding1301/donation-alert-api) 7 | 8 | ---- 9 | 10 | # 🚀 Start 11 | ## Gradle (use [Jitpack](https://jitpack.io/)) 12 | ```gradle 13 | repositories { 14 | ... 15 | maven { url 'https://jitpack.io' } 16 | } 17 | 18 | dependencies { 19 | ... 20 | compile 'com.github.outstanding1301:donation-alert-api:1.0.0' 21 | } 22 | ``` 23 | 24 | ```maven 25 | 26 | ... 27 | 28 | jitpack.io 29 | https://jitpack.io 30 | 31 | ... 32 | 33 | 34 | 35 | ... 36 | com.github.outstanding1301 37 | donation-alert-api 38 | 1.0.0 39 | ... 40 | 41 | ``` 42 | 43 | ## Twip 44 | ```java 45 | // Twip Alertbox URL의 마지막 https://twip.kr/widgets/alertbox/ 부분을 입력하세요. 46 | Twip twip = new Twip("YOUR_TWIP_KEY"); 47 | 48 | // 메시지를 구독합니다. 49 | // 연결 알림, 에러 등의 String 메시지를 처리하는 핸들러를 인자로 사용합니다. 50 | twip.subscribeMessage(s -> System.out.println(s)); 51 | 52 | // 도네이션 알림을 구독합니다. 53 | // Donation 객체를 처리하는 핸들러를 인자로 사용합니다. 54 | twip.subscribeDonation(donation -> { 55 | System.out.println("[Twip] "+donation.getNickName()+"님이 "+donation.getAmount()+"원을 후원했습니다."); 56 | System.out.println("후원 내용: "+donation.getComment()); 57 | }); 58 | ``` 59 | 60 | ## Toonation 61 | ```java 62 | // Toonation Alertbox URL의 마지막 https://toon.at/widget/alertbox/ 부분을 입력하세요. 63 | Toonation toonation = new Toonation("YOUR_TOONATION_KEY"); 64 | 65 | // 메시지를 구독합니다. 66 | // 연결 알림, 에러 등의 String 메시지를 처리하는 핸들러를 인자로 사용합니다. 67 | toonation.subscribeMessage(s -> System.out.println(s)); 68 | 69 | // 도네이션 알림을 구독합니다. 70 | // Donation 객체를 처리하는 핸들러를 인자로 사용합니다. 71 | toonation.subscribeDonation(donation -> { 72 | System.out.println("[Toonation] "+donation.getNickName()+"님이 "+donation.getAmount()+"원을 후원했습니다."); 73 | System.out.println("후원 내용: "+donation.getComment()); 74 | }); 75 | ``` 76 | 77 | # 📃 Docs 78 | 79 | ## Donation 80 | 81 | | 식별자 | 타입 | 설명 | 82 | |:---:|:---:|:---:| 83 | | id | String | 후원자 ID | 84 | | nickname | String | 후원자 닉네임 | 85 | | comment | String | 후원 내용 | 86 | | amount | Integer | 후원 금액 | 87 | 88 |
89 | 90 | ## Platform (Twip, Toonation) 91 | 92 | | 식별자 | 타입 | 설명 | 93 | |:---:|:---:|:---:| 94 | | subscribeDonation(Consumer onNext) | void | 후원 알림 구독 | 95 | | subscribeMessage(Consumer onNext) | void | API 메시지 구독 | 96 | | close() | void | 연결 종료 | 97 | | getDonationObservable() | Subject | 후원 알림 Subject 객체 반환 | 98 | | getMessageObservable() | Subject | API 메시지 Subject 객체 반환 | 99 | 100 | # 💉 Dependencies 101 | ```gradle 102 | implementation 'io.socket:socket.io-client:1.0.0' 103 | implementation 'io.reactivex.rxjava2:rxjava:2.1.16' 104 | implementation 'org.jsoup:jsoup:1.13.1' 105 | implementation 'com.googlecode.json-simple:json-simple:1.1.1' 106 | ``` 107 | -------------------------------------------------------------------------------- /src/main/java/com/outstandingboy/donationalert/platform/Toonation.java: -------------------------------------------------------------------------------- 1 | package com.outstandingboy.donationalert.platform; 2 | 3 | import com.outstandingboy.donationalert.entity.Donation; 4 | import com.outstandingboy.donationalert.exception.TokenNotFoundException; 5 | import io.reactivex.disposables.Disposable; 6 | import io.reactivex.functions.Consumer; 7 | import io.reactivex.subjects.PublishSubject; 8 | import io.reactivex.subjects.Subject; 9 | import okhttp3.*; 10 | import org.json.simple.JSONObject; 11 | import org.json.simple.parser.JSONParser; 12 | import org.json.simple.parser.ParseException; 13 | import org.jsoup.Jsoup; 14 | import org.jsoup.nodes.Document; 15 | import org.jsoup.nodes.Element; 16 | import org.jsoup.select.Elements; 17 | 18 | import java.io.IOException; 19 | import java.util.concurrent.TimeUnit; 20 | import java.util.regex.Matcher; 21 | import java.util.regex.Pattern; 22 | import java.util.stream.Collectors; 23 | 24 | public class Toonation extends WebSocketListener implements Platform { 25 | private String payload; 26 | private WebSocket socket; 27 | private Subject donationObservable; 28 | private Subject messageObservable; 29 | private boolean timeout = false; 30 | 31 | public Toonation(String key) throws IOException { 32 | Document doc = Jsoup.connect("https://toon.at/widget/alertbox/"+key).get(); 33 | Elements scriptElements = doc.getElementsByTag("script"); 34 | String script = scriptElements.stream().filter(e -> !e.hasAttr("src")).map(Element::toString).collect(Collectors.joining()); 35 | 36 | String payload = parsePayload(script); 37 | 38 | if (payload == null) { 39 | throw new TokenNotFoundException("투네이션 페이로드를 찾을 수 없습니다."); 40 | } 41 | 42 | this.payload = payload; 43 | OkHttpClient client = new OkHttpClient.Builder() 44 | .readTimeout(0, TimeUnit.MILLISECONDS) 45 | .build(); 46 | Request request = new Request.Builder() 47 | .url("wss://toon.at:8071/"+payload) 48 | .build(); 49 | 50 | socket = client.newWebSocket(request, this); 51 | client.dispatcher().executorService().shutdown(); 52 | 53 | donationObservable = PublishSubject.create(); 54 | messageObservable = PublishSubject.create(); 55 | } 56 | 57 | private String parsePayload(String script) { 58 | Pattern p = Pattern.compile("\"payload\":\"(.*)\","); 59 | Matcher m = p.matcher(script); 60 | if (m.find()) { 61 | return m.group(1); 62 | } 63 | return null; 64 | } 65 | 66 | @Override 67 | public void onOpen(WebSocket webSocket, Response response) { 68 | if(!timeout) 69 | messageObservable.onNext("투네이션에 연결되었습니다!"); 70 | else{ 71 | timeout = false; 72 | } 73 | } 74 | 75 | @Override 76 | public void onMessage(WebSocket webSocket, String text) { 77 | JSONParser parser = new JSONParser(); 78 | try { 79 | JSONObject json = (JSONObject) parser.parse(text); 80 | Donation donation = getDonation(json); 81 | 82 | if(donation != null) { 83 | donationObservable.onNext(donation); 84 | } 85 | } catch (ParseException e) { 86 | e.printStackTrace(); 87 | } 88 | } 89 | 90 | @Override 91 | public void onClosed(WebSocket webSocket, int code, String reason) { 92 | messageObservable.onNext("투네이션 연결이 종료 되었습니다!"); 93 | } 94 | 95 | @Override 96 | public void onFailure(WebSocket webSocket, Throwable t, Response response) { 97 | timeout = true; 98 | 99 | webSocket.close(1000, null); 100 | 101 | OkHttpClient client = new OkHttpClient.Builder() 102 | .readTimeout(0, TimeUnit.MILLISECONDS) 103 | .build(); 104 | Request request = new Request.Builder() 105 | .url("wss://toon.at:8071/"+payload) 106 | .build(); 107 | 108 | socket = client.newWebSocket(request, this); 109 | } 110 | 111 | private Donation getDonation(JSONObject json) { 112 | try { 113 | if (!json.containsKey("content")) return null; 114 | json = (JSONObject) json.get("content"); 115 | 116 | Donation donation = new Donation(); 117 | donation.setId((String) json.get("account")); 118 | donation.setNickName((String) json.get("name")); 119 | donation.setAmount((long) json.get("amount")); 120 | donation.setComment((String) json.get("message")); 121 | return donation; 122 | } 123 | catch (Exception e){ 124 | return null; 125 | } 126 | } 127 | 128 | public Subject getDonationObservable() { 129 | return donationObservable; 130 | } 131 | 132 | public Subject getMessageObservable() { 133 | return messageObservable; 134 | } 135 | 136 | @Override 137 | public Disposable subscribeDonation(Consumer onNext) { 138 | return donationObservable.subscribe(onNext); 139 | } 140 | 141 | @Override 142 | public Disposable subscribeMessage(Consumer onNext) { 143 | return messageObservable.subscribe(onNext); 144 | } 145 | 146 | public void close() { 147 | donationObservable.onComplete(); 148 | messageObservable.onComplete(); 149 | socket.close(1000, null); 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /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='"-Xmx64m"' 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 | -------------------------------------------------------------------------------- /src/main/java/com/outstandingboy/donationalert/platform/Twip.java: -------------------------------------------------------------------------------- 1 | package com.outstandingboy.donationalert.platform; 2 | 3 | import com.outstandingboy.donationalert.entity.Donation; 4 | import com.outstandingboy.donationalert.exception.TokenNotFoundException; 5 | import com.outstandingboy.donationalert.exception.TwipVersionNotFoundException; 6 | import io.reactivex.disposables.Disposable; 7 | import io.reactivex.functions.Consumer; 8 | import io.reactivex.subjects.PublishSubject; 9 | import io.reactivex.subjects.Subject; 10 | import io.socket.client.IO; 11 | import io.socket.client.Socket; 12 | import org.json.simple.JSONObject; 13 | import org.json.simple.parser.JSONParser; 14 | import org.json.simple.parser.ParseException; 15 | import org.jsoup.Jsoup; 16 | import org.jsoup.nodes.Document; 17 | import org.jsoup.nodes.Element; 18 | import org.jsoup.select.Elements; 19 | 20 | import java.io.IOException; 21 | import java.io.UnsupportedEncodingException; 22 | import java.net.URISyntaxException; 23 | import java.net.URLEncoder; 24 | import java.util.regex.Matcher; 25 | import java.util.regex.Pattern; 26 | import java.util.stream.Collectors; 27 | 28 | public class Twip implements Platform { 29 | private Socket socket = null; 30 | private Subject donationObservable; 31 | private Subject messageObservable; 32 | 33 | public Twip(String key) throws IOException { 34 | Document doc = Jsoup.connect("https://twip.kr/widgets/alertbox/" + key).get(); 35 | Elements scriptElements = doc.getElementsByTag("script"); 36 | String script = scriptElements.stream().filter(e -> !e.hasAttr("src")).map(Element::toString).collect(Collectors.joining()); 37 | 38 | String version = parseVersion(script); 39 | String token = parseToken(script); 40 | 41 | if (version == null) { 42 | throw new TwipVersionNotFoundException("버전을 찾을 수 없습니다."); 43 | } 44 | if (token == null) { 45 | throw new TokenNotFoundException("토큰을 찾을 수 없습니다."); 46 | } 47 | 48 | init(key, version, token); 49 | } 50 | 51 | public Twip(String key, String version, String token) { 52 | init(key, version, token); 53 | } 54 | 55 | private void init(String key, String version, String token) { 56 | String uri = String.format("https://io.mytwip.net?alertbox_key=" + key 57 | + "&version=" + version + "&token=" + encodeURIComponent(token)); 58 | 59 | IO.Options opts = new IO.Options(); 60 | String transports[] = {"websocket", "polling"}; 61 | opts.transports = transports; 62 | opts.reconnection = true; 63 | 64 | try { 65 | socket = IO.socket(uri, opts); 66 | } catch (URISyntaxException e) { 67 | e.printStackTrace(); 68 | } 69 | 70 | socket.on(Socket.EVENT_CONNECT, (args) -> { 71 | messageObservable.onNext("트윕에 연결되었습니다!"); 72 | }) 73 | .on(Socket.EVENT_CONNECT_ERROR, (args) -> { 74 | messageObservable.onNext("연결 오류가 발생했습니다."); 75 | }) 76 | .on("disconnect", (args) -> { 77 | messageObservable.onNext("연결이 종료되었습니다."); 78 | }) 79 | .on("version not match", (args) -> { 80 | messageObservable.onNext("트윕 버전이 일치하지 않습니다."); 81 | }) 82 | .on("not allowed ip", (args) -> { 83 | messageObservable.onNext("허용되지 않은 IP입니다."); 84 | }) 85 | .on("new donate", (args) -> { 86 | JSONParser parser = new JSONParser(); 87 | try { 88 | JSONObject json = (JSONObject) parser.parse(args[0].toString()); 89 | Donation donation = getDonation(json); 90 | 91 | if (donation != null) { 92 | donationObservable.onNext(donation); 93 | } 94 | } catch (ParseException e) { 95 | e.printStackTrace(); 96 | } 97 | }); 98 | socket.connect(); 99 | 100 | donationObservable = PublishSubject.create(); 101 | messageObservable = PublishSubject.create(); 102 | } 103 | 104 | private String parseVersion(String script) { 105 | Pattern p = Pattern.compile("version: '(.*)'"); 106 | Matcher m = p.matcher(script); 107 | if (m.find()) { 108 | return m.group(1); 109 | } 110 | return null; 111 | } 112 | 113 | private String parseToken(String script) { 114 | Pattern p = Pattern.compile("window.__TOKEN__ = '(.*)'"); 115 | Matcher m = p.matcher(script); 116 | if (m.find()) { 117 | return m.group(1); 118 | } 119 | return null; 120 | } 121 | 122 | private Donation getDonation(JSONObject json) { 123 | try { 124 | Donation donation = new Donation(); 125 | donation.setId((String) json.get("watcher_id")); 126 | donation.setNickName((String) json.get("nickname")); 127 | donation.setAmount((long) json.get("amount")); 128 | donation.setComment((String) json.get("comment")); 129 | return donation; 130 | } catch (Exception e) { 131 | return null; 132 | } 133 | } 134 | 135 | public Subject getDonationObservable() { 136 | return donationObservable; 137 | } 138 | 139 | public Subject getMessageObservable() { 140 | return messageObservable; 141 | } 142 | 143 | @Override 144 | public Disposable subscribeDonation(Consumer onNext) { 145 | return donationObservable.subscribe(onNext); 146 | } 147 | 148 | @Override 149 | public Disposable subscribeMessage(Consumer onNext) { 150 | return messageObservable.subscribe(onNext); 151 | } 152 | 153 | public void close() { 154 | donationObservable.onComplete(); 155 | messageObservable.onComplete(); 156 | socket.close(); 157 | } 158 | 159 | public static String encodeURIComponent(String s) { 160 | String result = null; 161 | try { 162 | result = URLEncoder.encode(s, "UTF-8").replaceAll("%", "%%"); 163 | } catch (UnsupportedEncodingException e) { 164 | result = s; 165 | } 166 | return result; 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /src/main/java/com/outstandingboy/donationalert/platform/Chzzk.java: -------------------------------------------------------------------------------- 1 | package com.outstandingboy.donationalert.platform; 2 | 3 | import com.google.gson.JsonObject; 4 | import com.outstandingboy.donationalert.entity.Donation; 5 | import com.outstandingboy.donationalert.util.Gsons; 6 | import io.reactivex.disposables.Disposable; 7 | import io.reactivex.functions.Consumer; 8 | import io.reactivex.subjects.PublishSubject; 9 | import io.reactivex.subjects.Subject; 10 | import okhttp3.*; 11 | 12 | import java.io.IOException; 13 | import java.util.Arrays; 14 | import java.util.HashMap; 15 | import java.util.Map; 16 | import java.util.concurrent.TimeUnit; 17 | 18 | public class Chzzk extends WebSocketListener implements Platform { 19 | private WebSocket socket; 20 | private Subject donationObservable; 21 | private Subject messageObservable; 22 | 23 | private boolean timeout; 24 | private boolean connected; 25 | private final String channelId; 26 | private final String chatChannelId; 27 | private final String accessToken; 28 | private final int wsId; 29 | private final OkHttpClient client; 30 | 31 | public Chzzk(String channelId) { 32 | this.channelId = channelId; 33 | this.wsId = Math.abs(channelId.chars().sum()) % 9 + 1; 34 | this.client = new OkHttpClient.Builder() 35 | .readTimeout(0, TimeUnit.MILLISECONDS) 36 | .addInterceptor(chain -> { 37 | Request original = chain.request(); 38 | Request authorized = original.newBuilder() 39 | .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0") 40 | .build(); 41 | return chain.proceed(authorized); 42 | }) 43 | .build(); 44 | this.chatChannelId = getChatChannelId(); 45 | accessToken = getAccessToken(); 46 | connectToWebSocket(); 47 | donationObservable = PublishSubject.create(); 48 | messageObservable = PublishSubject.create(); 49 | } 50 | 51 | private void connectToWebSocket() { 52 | Request request = new Request.Builder() 53 | .url("wss://kr-ss" + wsId + ".chat.naver.com/chat") 54 | .build(); 55 | socket = client.newWebSocket(request, this); 56 | } 57 | 58 | private String getChatChannelId() { 59 | Request request = new Request.Builder() 60 | .url("https://api.chzzk.naver.com/service/v2/channels/" + channelId + "/live-detail") 61 | .get() 62 | .build(); 63 | try { 64 | Response res = client.newCall(request).execute(); 65 | if (res.isSuccessful()) { 66 | Map map = Gsons.gson().fromJson(res.body().string(), Map.class); 67 | Map content = (Map) map.get("content"); 68 | return content.get("chatChannelId").toString(); 69 | } 70 | throw new RuntimeException("Failed to get Chat Channel ID from " + channelId); 71 | } catch (Exception e) { 72 | throw new RuntimeException(e); 73 | } 74 | } 75 | 76 | private String getAccessToken() { 77 | Request request = new Request.Builder() 78 | .url("https://comm-api.game.naver.com/nng_main/v1/chats/access-token?channelId=" + chatChannelId + "&chatType=STREAMING") 79 | .get() 80 | .build(); 81 | Response res = null; 82 | try { 83 | res = client.newCall(request).execute(); 84 | JsonObject json = Gsons.gson().fromJson(res.body().string(), JsonObject.class); 85 | JsonObject content = json.get("content").getAsJsonObject(); 86 | return content.get("accessToken").getAsString(); 87 | } catch (IOException e) { 88 | throw new RuntimeException(e); 89 | } 90 | } 91 | 92 | @Override 93 | public void onOpen(WebSocket webSocket, Response response) { 94 | if (!connected) { 95 | HashMap map = new HashMap<>(); 96 | HashMap body = new HashMap<>(); 97 | body.put("accTkn", accessToken); 98 | body.put("auth", "READ"); 99 | body.put("uid", null); 100 | map.put("bdy", body); 101 | map.put("cmd", 100); 102 | map.put("tid", 1); 103 | map.put("ver", "2"); 104 | map.put("cid", chatChannelId); 105 | map.put("svcid", "game"); 106 | webSocket.send(Gsons.gson().toJson(map)); 107 | } 108 | } 109 | 110 | @Override 111 | public void onMessage(WebSocket webSocket, String text) { 112 | JsonObject json = Gsons.gson().fromJson(text, JsonObject.class); 113 | int cmd = json.get("cmd").getAsInt(); 114 | if (cmd == 10100) { 115 | messageObservable.onNext("치지직에 연결되었습니다!"); 116 | } else if (cmd == 93102) { 117 | JsonObject bdy = json.get("bdy").getAsJsonArray().get(0).getAsJsonObject(); 118 | Donation donation = new Donation(); 119 | JsonObject profile = Gsons.gson().fromJson(bdy.get("profile").getAsString(), JsonObject.class); 120 | JsonObject extras = Gsons.gson().fromJson(bdy.get("extras").getAsString(), JsonObject.class); 121 | donation.setId(profile.get("userIdHash").getAsString()); 122 | donation.setAmount(extras.get("payAmount").getAsLong()); 123 | donation.setNickName(profile.get("nickname").getAsString()); 124 | donation.setComment(bdy.get("msg").getAsString()); 125 | donationObservable.onNext(donation); 126 | } 127 | } 128 | 129 | @Override 130 | public void onClosed(WebSocket webSocket, int code, String reason) { 131 | messageObservable.onNext("치지직 연결이 종료 되었습니다!"); 132 | } 133 | 134 | @Override 135 | public void onFailure(WebSocket webSocket, Throwable t, Response response) { 136 | timeout = true; 137 | webSocket.close(1000, null); 138 | connectToWebSocket(); 139 | } 140 | 141 | @Override 142 | public Disposable subscribeDonation(Consumer onNext) { 143 | return donationObservable.subscribe(onNext); 144 | } 145 | 146 | @Override 147 | public Disposable subscribeMessage(Consumer onNext) { 148 | return messageObservable.subscribe(onNext); 149 | } 150 | 151 | @Override 152 | public void close() { 153 | donationObservable.onComplete(); 154 | messageObservable.onComplete(); 155 | socket.close(1000, null); 156 | } 157 | 158 | @Override 159 | public Subject getDonationObservable() { 160 | return donationObservable; 161 | } 162 | 163 | @Override 164 | public Subject getMessageObservable() { 165 | return messageObservable; 166 | } 167 | } 168 | --------------------------------------------------------------------------------