commit
ac85c144bf
1
.gitignore
vendored
1
.gitignore
vendored
@ -17,6 +17,7 @@ Out/
|
||||
*.exe
|
||||
build/
|
||||
logs/
|
||||
java/wcferry/bin/
|
||||
|
||||
*_pb2.py
|
||||
*_pb2_grpc.py
|
||||
|
63
java/README.MD
Normal file
63
java/README.MD
Normal file
@ -0,0 +1,63 @@
|
||||
# WeChatFerry Java 客户端
|
||||
⚠️ **只支持 Windows** ⚠️
|
||||
|
||||
## 快速开始
|
||||
* 下载 [最新发布的版本](https://github.com/lich0821/WeChatFerry/releases/latest),解压,找到 java 客户端。
|
||||
|
||||
* 使用惯用 IDE,打开工程,编译,运行。
|
||||
|
||||
## 从头开始
|
||||
【添加 `wcferry` 依赖】是必须要执行的,工程里不带这几个文件;如果开发新功能,一般需要修改 `wcf.proto`,从而需要重新生成 PB 文件;其他的,一般不需要关注。
|
||||
|
||||
### 添加 `nng` 依赖
|
||||
* 新建一个 `libs` 目录
|
||||
* 参考 [nng-java](https://github.com/voutilad/nng-java),编译 jar 包(`nng-java-1.4.0-SNAPSHOT.jar`)
|
||||
* 添加依赖 `nng-java-1.4.0-SNAPSHOT.jar`
|
||||
```groovy
|
||||
implementation 'net.java.dev.jna:jna:5.6.0'
|
||||
implementation fileTree(dir: 'libs', include: ['*.jar'])
|
||||
```
|
||||
|
||||
#### 编译 / 安装 `mbedtls`
|
||||
* 下载 [Mbed TLS](https://github.com/Mbed-TLS/mbedtls) 代码并解压
|
||||
* 新建 `build` 目录,生成 VS 工程
|
||||
```sh
|
||||
cd build
|
||||
cmake ..
|
||||
```
|
||||
|
||||
* 以管理员身份运行 VS2019,打开 `mbed TLS.sln`,选择 `Release` `x64`,编译即可
|
||||
* [参考](https://github.com/Mbed-TLS/mbedtls)
|
||||
|
||||
#### 编译 / 安装 `nng`
|
||||
* 下载 [nng](https://github.com/nanomsg/nng) 代码并解压
|
||||
* 新建 `build` 目录,生成 VS 工程
|
||||
```sh
|
||||
cmake -DBUILD_SHARED_LIBS=ON -DNNG_ENABLE_TLS=ON -DMBEDTLS_ROOT_DIR="C:\Program Files (x86)\mbed TLS" ..
|
||||
```
|
||||
|
||||
* 打开 `nng.sln`,选择 `Release` `x64`,编译即可
|
||||
* [参考](https://github.com/nanomsg/nng/issues/953)
|
||||
|
||||
### 添加 PB 依赖
|
||||
```groovy
|
||||
implementation 'com.google.protobuf:protobuf-java:3.22.2' // 版本需要和 protoc 一致
|
||||
```
|
||||
|
||||
#### 重新生成 PB 文件
|
||||
参考 [Protocol Buffer Basics: Java](https://protobuf.dev/getting-started/javatutorial/#problem-domain)。
|
||||
* 下载 `protoc` 工具(注意,需要与 `com.google.protobuf:protobuf-java` 一致):
|
||||
这里下载 [protoc-22.2](https://github.com/protocolbuffers/protobuf/releases/download/v22.2/protoc-22.2-win64.zip),解压,并将所在路径加入环境变量(以便随处可用)。
|
||||
|
||||
* 编译 PB 文件
|
||||
```sh
|
||||
cd C:/Projs/WeChatFerry/java/wcferry/src/main/java
|
||||
protoc.exe --java_out=. --proto_path=C:\Projs\WeChatFerry\rpc\proto wcf.proto
|
||||
```
|
||||
|
||||
### 添加 `wcferry` 依赖
|
||||
将 `wcf.exe` 、 `spy.dll` 、 `spy_debug.dll` 添加到 `C:\Projs\WeChatFerry\java\wcferry\src\main\resources\win32-x86-64`。
|
||||
|
||||
### 其他问题
|
||||
### 乱码
|
||||
参考 [这篇文章](https://www.quanxiaoha.com/idea/idea-chinese-garbled-code.html)。
|
25
java/wcferry/build.gradle
Normal file
25
java/wcferry/build.gradle
Normal file
@ -0,0 +1,25 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
}
|
||||
|
||||
group 'org.example'
|
||||
version '1.0-SNAPSHOT'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'org.slf4j:slf4j-api:2.0.7'
|
||||
implementation 'ch.qos.logback:logback-core:1.3.6'
|
||||
implementation 'ch.qos.logback:logback-classic:1.3.6'
|
||||
implementation 'com.google.protobuf:protobuf-java:3.22.2'
|
||||
implementation 'net.java.dev.jna:jna:5.6.0'
|
||||
implementation fileTree(dir: 'libs', include: ['*.jar'])
|
||||
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
|
||||
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
|
||||
}
|
||||
|
||||
test {
|
||||
useJUnitPlatform()
|
||||
}
|
BIN
java/wcferry/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
java/wcferry/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
5
java/wcferry/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
5
java/wcferry/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
234
java/wcferry/gradlew
vendored
Normal file
234
java/wcferry/gradlew
vendored
Normal file
@ -0,0 +1,234 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=${0##*/}
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
89
java/wcferry/gradlew.bat
vendored
Normal file
89
java/wcferry/gradlew.bat
vendored
Normal file
@ -0,0 +1,89 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
BIN
java/wcferry/libs/nng-java-1.4.0-SNAPSHOT.jar
Normal file
BIN
java/wcferry/libs/nng-java-1.4.0-SNAPSHOT.jar
Normal file
Binary file not shown.
2
java/wcferry/settings.gradle
Normal file
2
java/wcferry/settings.gradle
Normal file
@ -0,0 +1,2 @@
|
||||
rootProject.name = 'wcferry'
|
||||
|
366
java/wcferry/src/main/java/com/iamteer/Client.java
Normal file
366
java/wcferry/src/main/java/com/iamteer/Client.java
Normal file
@ -0,0 +1,366 @@
|
||||
package com.iamteer;
|
||||
|
||||
import com.iamteer.Wcf.*;
|
||||
import io.sisu.nng.Socket;
|
||||
import io.sisu.nng.pair.Pair1Socket;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.net.URL;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
|
||||
public class Client {
|
||||
private static final Logger logger = LoggerFactory.getLogger(Client.class);
|
||||
private final int BUFFER_SIZE = 16 * 1024 * 1024; // 16M
|
||||
private Socket cmdSocket = null;
|
||||
private Socket msgSocket = null;
|
||||
private String cmdUrl = "tcp://127.0.0.1:10086";
|
||||
private boolean isReceivingMsg = false;
|
||||
private boolean isLocalHostPort = false;
|
||||
private BlockingQueue<WxMsg> msgQ;
|
||||
private String wcfPath;
|
||||
|
||||
public Client(String hostPort) {
|
||||
cmdUrl = hostPort;
|
||||
connectRPC(cmdUrl);
|
||||
}
|
||||
|
||||
public Client(boolean debug) {
|
||||
try {
|
||||
URL url = this.getClass().getResource("/win32-x86-64/wcf.exe");
|
||||
wcfPath = url.getFile();
|
||||
String[] cmd = new String[3];
|
||||
cmd[0] = wcfPath;
|
||||
cmd[1] = "start";
|
||||
if (debug) {
|
||||
cmd[2] = "debug";
|
||||
} else {
|
||||
cmd[2] = "";
|
||||
}
|
||||
int status = Runtime.getRuntime().exec(cmd).waitFor();
|
||||
if (status != 0) {
|
||||
logger.error("启动 RPC 失败: {}", status);
|
||||
System.exit(-1);
|
||||
}
|
||||
isLocalHostPort = true;
|
||||
connectRPC(cmdUrl);
|
||||
} catch (Exception e) {
|
||||
logger.error("初始化失败: {}", e);
|
||||
System.exit(-1);
|
||||
}
|
||||
}
|
||||
|
||||
private void connectRPC(String url) {
|
||||
try {
|
||||
cmdSocket = new Pair1Socket();
|
||||
cmdSocket.dial(url);
|
||||
logger.info("请点击登录微信");
|
||||
while (!isLogin()) { // 直到登录成功
|
||||
waitMs(1000);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("连接 RPC 失败: ", e);
|
||||
System.exit(-1);
|
||||
}
|
||||
Runtime.getRuntime().addShutdownHook(new Thread() {
|
||||
public void run() {
|
||||
logger.info("关闭...");
|
||||
diableRecvMsg();
|
||||
if (isLocalHostPort) {
|
||||
try {
|
||||
String[] cmd = new String[2];
|
||||
cmd[0] = wcfPath;
|
||||
cmd[1] = "stop";
|
||||
Process process = Runtime.getRuntime().exec(cmd);
|
||||
int status = process.waitFor();
|
||||
if (status != 0) {
|
||||
System.err.println("停止机器人失败: " + status);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Response sendCmd(Request req) {
|
||||
try {
|
||||
ByteBuffer bb = ByteBuffer.wrap(req.toByteArray());
|
||||
cmdSocket.send(bb);
|
||||
ByteBuffer ret = ByteBuffer.allocate(BUFFER_SIZE);
|
||||
long size = cmdSocket.receive(ret, true);
|
||||
return Response.parseFrom(Arrays.copyOfRange(ret.array(), 0, (int) size));
|
||||
} catch (Exception e) {
|
||||
logger.error("命令调用失败: ", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isLogin() {
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_IS_LOGIN_VALUE).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp != null) {
|
||||
return rsp.getStatus() == 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public String getSelfWxid() {
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_GET_SELF_WXID_VALUE).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp != null) {
|
||||
return rsp.getStr();
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
public Map<Integer, String> getMsgTypes() {
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_GET_MSG_TYPES_VALUE).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp != null) {
|
||||
return rsp.getTypes().getTypesMap();
|
||||
}
|
||||
|
||||
return Wcf.MsgTypes.newBuilder().build().getTypesMap();
|
||||
}
|
||||
|
||||
public List<RpcContact> getContacts() {
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_GET_CONTACTS_VALUE).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp != null) {
|
||||
return rsp.getContacts().getContactsList();
|
||||
}
|
||||
|
||||
return Wcf.RpcContacts.newBuilder().build().getContactsList();
|
||||
}
|
||||
|
||||
public List<String> getDbNames() {
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_GET_DB_NAMES_VALUE).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp != null) {
|
||||
return rsp.getDbs().getNamesList();
|
||||
}
|
||||
|
||||
return Wcf.DbNames.newBuilder().build().getNamesList();
|
||||
}
|
||||
|
||||
public Map<String, String> getDbTables(String db) {
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_GET_DB_TABLES_VALUE).setStr(db).build();
|
||||
Response rsp = sendCmd(req);
|
||||
Map<String, String> tables = new HashMap<>();
|
||||
if (rsp != null) {
|
||||
for (DbTable tbl : rsp.getTables().getTablesList()) {
|
||||
tables.put(tbl.getName(), tbl.getSql());
|
||||
}
|
||||
}
|
||||
|
||||
return tables;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param msg: 消息内容(如果是 @ 消息则需要有跟 @ 的人数量相同的 @)
|
||||
* @param receiver: 消息接收人,私聊为 wxid(wxid_xxxxxxxxxxxxxx),群聊为
|
||||
* roomid(xxxxxxxxxx@chatroom)
|
||||
* @param aters: 群聊时要 @ 的人(私聊时为空字符串),多个用逗号分隔。@所有人 用
|
||||
* notify@all(必须是群主或者管理员才有权限)
|
||||
* @return int
|
||||
* @Description 发送文本消息
|
||||
* @author Changhua
|
||||
* @example sendText(" Hello @ 某人1 @ 某人2 ", " xxxxxxxx @ chatroom ",
|
||||
* "wxid_xxxxxxxxxxxxx1,wxid_xxxxxxxxxxxxx2");
|
||||
**/
|
||||
public int sendText(String msg, String receiver, String aters) {
|
||||
Wcf.TextMsg textMsg = Wcf.TextMsg.newBuilder().setMsg(msg).setReceiver(receiver).setAters(aters).build();
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_SEND_TXT_VALUE).setTxt(textMsg).build();
|
||||
logger.debug("sendText: {}", bytesToHex(req.toByteArray()));
|
||||
Response rsp = sendCmd(req);
|
||||
int ret = -1;
|
||||
if (rsp != null) {
|
||||
ret = rsp.getStatus();
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
public int sendImage(String path, String receiver) {
|
||||
Wcf.PathMsg pathMsg = Wcf.PathMsg.newBuilder().setPath(path).setReceiver(receiver).build();
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_SEND_IMG_VALUE).setFile(pathMsg).build();
|
||||
logger.debug("sendImage: {}", bytesToHex(req.toByteArray()));
|
||||
Response rsp = sendCmd(req);
|
||||
int ret = -1;
|
||||
if (rsp != null) {
|
||||
ret = rsp.getStatus();
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
public int sendFile(String path, String receiver) {
|
||||
Wcf.PathMsg pathMsg = Wcf.PathMsg.newBuilder().setPath(path).setReceiver(receiver).build();
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_SEND_FILE_VALUE).setFile(pathMsg).build();
|
||||
logger.debug("sendFile: {}", bytesToHex(req.toByteArray()));
|
||||
Response rsp = sendCmd(req);
|
||||
int ret = -1;
|
||||
if (rsp != null) {
|
||||
ret = rsp.getStatus();
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
public int sendXml(String receiver, String xml, String path, int type) {
|
||||
Wcf.XmlMsg xmlMsg = Wcf.XmlMsg.newBuilder().setContent(xml).setReceiver(receiver).setPath(path).setType(type).build();
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_SEND_XML_VALUE).setXml(xmlMsg).build();
|
||||
logger.debug("sendXml: {}", bytesToHex(req.toByteArray()));
|
||||
Response rsp = sendCmd(req);
|
||||
int ret = -1;
|
||||
if (rsp != null) {
|
||||
ret = rsp.getStatus();
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
public int sendEmotion(String path, String receiver) {
|
||||
Wcf.PathMsg pathMsg = Wcf.PathMsg.newBuilder().setPath(path).setReceiver(receiver).build();
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_SEND_EMOTION_VALUE).setFile(pathMsg).build();
|
||||
logger.debug("sendEmotion: {}", bytesToHex(req.toByteArray()));
|
||||
Response rsp = sendCmd(req);
|
||||
int ret = -1;
|
||||
if (rsp != null) {
|
||||
ret = rsp.getStatus();
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
public boolean getIsReceivingMsg() {
|
||||
return isReceivingMsg;
|
||||
}
|
||||
|
||||
public WxMsg getMsg() {
|
||||
try {
|
||||
return msgQ.take();
|
||||
} catch (Exception e) {
|
||||
// TODO: handle exception
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void listenMsg(String url) {
|
||||
try {
|
||||
msgSocket = new Pair1Socket();
|
||||
msgSocket.dial(url);
|
||||
msgSocket.setReceiveTimeout(2000); // 2 秒超时
|
||||
} catch (Exception e) {
|
||||
logger.error("创建消息 RPC 失败: {}", e);
|
||||
return;
|
||||
}
|
||||
ByteBuffer bb = ByteBuffer.allocate(BUFFER_SIZE);
|
||||
while (isReceivingMsg) {
|
||||
try {
|
||||
long size = msgSocket.receive(bb, true);
|
||||
WxMsg wxMsg = Response.parseFrom(Arrays.copyOfRange(bb.array(), 0, (int) size)).getWxmsg();
|
||||
msgQ.put(wxMsg);
|
||||
} catch (Exception e) {
|
||||
// 多半是超时,忽略吧
|
||||
}
|
||||
}
|
||||
try {
|
||||
msgSocket.close();
|
||||
} catch (Exception e) {
|
||||
logger.error("关闭连接失败: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void enableRecvMsg(int qSize) {
|
||||
if (isReceivingMsg) {
|
||||
return;
|
||||
}
|
||||
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_ENABLE_RECV_TXT_VALUE).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp == null) {
|
||||
logger.error("启动消息接收失败");
|
||||
isReceivingMsg = false;
|
||||
return;
|
||||
}
|
||||
|
||||
isReceivingMsg = true;
|
||||
msgQ = new ArrayBlockingQueue<WxMsg>(qSize);
|
||||
String msgUrl = cmdUrl.replace("10086", "10087");
|
||||
Thread thread = new Thread(new Runnable() {
|
||||
public void run() {
|
||||
listenMsg(msgUrl);
|
||||
}
|
||||
});
|
||||
thread.start();
|
||||
}
|
||||
|
||||
public int diableRecvMsg() {
|
||||
if (!isReceivingMsg) {
|
||||
return 1;
|
||||
}
|
||||
int ret = -1;
|
||||
Request req = new Request.Builder().setFuncValue(Functions.FUNC_DISABLE_RECV_TXT_VALUE).build();
|
||||
Response rsp = sendCmd(req);
|
||||
if (rsp != null) {
|
||||
ret = rsp.getStatus();
|
||||
if (ret == 0) {
|
||||
isReceivingMsg = false;
|
||||
}
|
||||
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
public void waitMs(int ms) {
|
||||
try {
|
||||
Thread.sleep(ms);
|
||||
} catch (InterruptedException ex) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
public void printContacts(List<RpcContact> contacts) {
|
||||
for (RpcContact c : contacts) {
|
||||
int value = c.getGender();
|
||||
String gender;
|
||||
if (value == 1) {
|
||||
gender = "男";
|
||||
} else if (value == 2) {
|
||||
gender = "女";
|
||||
} else {
|
||||
gender = "未知";
|
||||
}
|
||||
|
||||
logger.info("{}, {}, {}, {}, {}, {}, {}", c.getWxid(), c.getName(), c.getCode(), c.getCountry(), c.getProvince(), c.getCity(), gender);
|
||||
}
|
||||
}
|
||||
|
||||
public void printWxMsg(WxMsg msg) {
|
||||
logger.info("{}[{}]:{}:{}:{}\n{}", msg.getSender(), msg.getRoomid(), msg.getId(), msg.getType(), msg.getXml().replace("\n", "").replace("\t", ""), msg.getContent());
|
||||
}
|
||||
|
||||
public String bytesToHex(byte[] bytes) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (byte b : bytes) {
|
||||
sb.append(String.format("%02x", b));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public void keepRunning() {
|
||||
while (true) {
|
||||
waitMs(1000);
|
||||
}
|
||||
}
|
||||
}
|
62
java/wcferry/src/main/java/com/iamteer/Main.java
Normal file
62
java/wcferry/src/main/java/com/iamteer/Main.java
Normal file
@ -0,0 +1,62 @@
|
||||
package com.iamteer;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Main {
|
||||
private static Logger logger = LoggerFactory.getLogger(Main.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
// 连接远程 RPC
|
||||
// final String url = "tcp://192.168.1.104:10086";
|
||||
// Client client = new Client(url);
|
||||
|
||||
// 本地启动 RPC
|
||||
Client client = new Client(true);
|
||||
|
||||
// 是否已登录
|
||||
logger.info("isLogin: {}", client.isLogin());
|
||||
/*
|
||||
// 登录账号 wxid
|
||||
logger.info("wxid: {}", client.getSelfWxid());
|
||||
|
||||
// 消息类型
|
||||
logger.info("message types: {}", client.getMsgTypes());
|
||||
|
||||
// 所有联系人(包括群聊、公众号、好友……)
|
||||
client.printContacts(client.getContacts());
|
||||
|
||||
// 获取数据库
|
||||
logger.info("dbs: {}", client.getDbNames());
|
||||
|
||||
// 获取数据库下的表
|
||||
String db = "MicroMsg.db";
|
||||
logger.info("tables in {}: {}", db, client.getDbTables(db));
|
||||
|
||||
// 发送文本消息,aters 是要 @ 的 wxid,多个用逗号分隔;消息里@的数量要与aters里的数量对应
|
||||
client.sendText("Hello", "filehelper", "");
|
||||
// client.sendText("Hello @某人1 @某人2", "xxxxxxxx@chatroom", "wxid_xxxxxxxxxxxxx1,wxid_xxxxxxxxxxxxx2");
|
||||
|
||||
// 发送图片消息,图片必须要存在
|
||||
client.sendImage("C:\\Projs\\WeChatFerry\\TEQuant.jpeg", "filehelper");
|
||||
|
||||
// 发送文件消息,文件必须要存在
|
||||
client.sendFile("C:\\Projs\\WeChatFerry\\README.MD", "filehelper");
|
||||
|
||||
String xml = "<?xml version=\"1.0\"?><msg><appmsg appid=\"\" sdkver=\"0\"><title>叮当药房,24小时服务,28分钟送药到家!</title><des>叮当快药首家承诺范围内28分钟送药到家!叮当快药核心区域内7*24小时全天候服务,送药上门!叮当快药官网为您提供快捷便利,正品低价,安全放心的购药、送药服务体验。</des><action>view</action><type>33</type><showtype>0</showtype><content /><url>https://mp.weixin.qq.com/mp/waerrpage?appid=wxc2edadc87077fa2a&type=upgrade&upgradetype=3#wechat_redirect</url><dataurl /><lowurl /><lowdataurl /><recorditem /><thumburl /><messageaction /><md5>7f6f49d301ebf47100199b8a4fcf4de4</md5><extinfo /><sourceusername>gh_c2b88a38c424@app</sourceusername><sourcedisplayname>叮当快药 药店送药到家夜间买药</sourcedisplayname><commenturl /><appattach><totallen>0</totallen><attachid /><emoticonmd5></emoticonmd5><fileext>jpg</fileext><filekey>da0e08f5c7259d03da150d5e7ca6d950</filekey><cdnthumburl>3057020100044b30490201000204e4c0232702032f4ef20204a6bace6f02046401f62d042430326337303430352d333734332d343362652d623335322d6233333566623266376334620204012400030201000405004c537600</cdnthumburl><aeskey>0db26456caf243fbd4efb99058a01d66</aeskey><cdnthumbaeskey>0db26456caf243fbd4efb99058a01d66</cdnthumbaeskey><encryver>1</encryver><cdnthumblength>61558</cdnthumblength><cdnthumbheight>100</cdnthumbheight><cdnthumbwidth>100</cdnthumbwidth></appattach><weappinfo><pagepath>pages/index/index.html</pagepath><username>gh_c2b88a38c424@app</username><appid>wxc2edadc87077fa2a</appid><version>197</version><type>2</type><weappiconurl>http://wx.qlogo.cn/mmhead/Q3auHgzwzM4727n0NQ0ZIPQPlfp15m1WLsnrXbo1kLhFGcolgLyc0A/96</weappiconurl><appservicetype>0</appservicetype><shareId>1_wxc2edadc87077fa2a_29177e9a9b918cb9e75964f80bb8f32e_1677849476_0</shareId></weappinfo><websearch /></appmsg><fromusername>wxid_eob5qfcrv4zd22</fromusername><scene>0</scene><appinfo><version>1</version><appname /></appinfo><commenturl /></msg>";
|
||||
client.sendXml("filehelper", xml, "", 0x21);
|
||||
|
||||
// 发送表情消息,gif 必须要存在
|
||||
client.sendEmotion("C:\\Projs\\WeChatFerry\\emo.gif", "filehelper");
|
||||
|
||||
// 接收消息,并调用 printWxMsg 处理
|
||||
client.enableRecvMsg(100);
|
||||
Thread thread = new Thread(new Runnable() {
|
||||
public void run(){while(client.getIsReceivingMsg()){client.printWxMsg(client.getMsg());}}
|
||||
});
|
||||
thread.start();
|
||||
// client.diableRecvMsg(); // 需要停止时调用
|
||||
|
||||
client.keepRunning();*/
|
||||
}
|
||||
}
|
20187
java/wcferry/src/main/java/com/iamteer/Wcf.java
Normal file
20187
java/wcferry/src/main/java/com/iamteer/Wcf.java
Normal file
File diff suppressed because it is too large
Load Diff
15
java/wcferry/src/main/resources/logback.xml
Normal file
15
java/wcferry/src/main/resources/logback.xml
Normal file
@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<!-- appender 的配置表示打印到控制台。 -->
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<!-- encoder 默认配置为 PatternLayoutEncoder -->
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="debug">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
</configuration>
|
BIN
java/wcferry/src/main/resources/win32-x86-64/nng.dll
Normal file
BIN
java/wcferry/src/main/resources/win32-x86-64/nng.dll
Normal file
Binary file not shown.
@ -1,7 +1,7 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package wcf;
|
||||
option java_package = "com.iamteer.wcf";
|
||||
option java_package = "com.iamteer";
|
||||
|
||||
/*
|
||||
service Wcf {
|
||||
|
Loading…
Reference in New Issue
Block a user