yunzhi 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. yunzhi-0.2.0/MANIFEST.in +2 -0
  2. yunzhi-0.2.0/PKG-INFO +82 -0
  3. yunzhi-0.2.0/README.md +72 -0
  4. yunzhi-0.2.0/android/AndroidManifest.xml +26 -0
  5. yunzhi-0.2.0/android/build.sh +36 -0
  6. yunzhi-0.2.0/android/res/drawable/ic_yunzhi.xml +7 -0
  7. yunzhi-0.2.0/android/src/io/yunzhi/receiver/AlertDismissReceiver.java +11 -0
  8. yunzhi-0.2.0/android/src/io/yunzhi/receiver/EmergencyActivity.java +109 -0
  9. yunzhi-0.2.0/android/src/io/yunzhi/receiver/Inbox.java +133 -0
  10. yunzhi-0.2.0/android/src/io/yunzhi/receiver/InboxService.java +141 -0
  11. yunzhi-0.2.0/android/src/io/yunzhi/receiver/Link.java +150 -0
  12. yunzhi-0.2.0/android/src/io/yunzhi/receiver/MainActivity.java +422 -0
  13. yunzhi-0.2.0/android/src/io/yunzhi/receiver/ScannerActivity.java +106 -0
  14. yunzhi-0.2.0/android/src/io/yunzhi/receiver/UrgentAlerts.java +74 -0
  15. yunzhi-0.2.0/android/third-party/ZXing-LICENSE.txt +202 -0
  16. yunzhi-0.2.0/android/third-party/ZXing-NOTICE.txt +4 -0
  17. yunzhi-0.2.0/pyproject.toml +21 -0
  18. yunzhi-0.2.0/setup.cfg +4 -0
  19. yunzhi-0.2.0/src/yunzhi/__init__.py +121 -0
  20. yunzhi-0.2.0/src/yunzhi/_agent.py +165 -0
  21. yunzhi-0.2.0/src/yunzhi/_server.py +147 -0
  22. yunzhi-0.2.0/src/yunzhi/_store.py +181 -0
  23. yunzhi-0.2.0/src/yunzhi/data/yunzhi-android.apk +0 -0
  24. yunzhi-0.2.0/src/yunzhi.egg-info/PKG-INFO +82 -0
  25. yunzhi-0.2.0/src/yunzhi.egg-info/SOURCES.txt +28 -0
  26. yunzhi-0.2.0/src/yunzhi.egg-info/dependency_links.txt +1 -0
  27. yunzhi-0.2.0/src/yunzhi.egg-info/entry_points.txt +2 -0
  28. yunzhi-0.2.0/src/yunzhi.egg-info/requires.txt +2 -0
  29. yunzhi-0.2.0/src/yunzhi.egg-info/top_level.txt +1 -0
  30. yunzhi-0.2.0/tests/test_yunzhi.py +172 -0
@@ -0,0 +1,2 @@
1
+ recursive-include android *.java *.xml *.sh *.txt
2
+ include tests/test_yunzhi.py
yunzhi-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,82 @@
1
+ Metadata-Version: 2.4
2
+ Name: yunzhi
3
+ Version: 0.2.0
4
+ Summary: Pair an Android phone over Wi-Fi and send messages and binary files from Python.
5
+ Keywords: android,lan,qr-code,notification
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: cryptography>=42
9
+ Requires-Dist: qrcode>=7.4
10
+
11
+ # 云知 · yunzhi
12
+
13
+ 让 Python 项目通过局域网向安卓手机发送消息、紧急报警和二进制附件。传输使用扫码时验证的 HTTPS。支持 Android 8.0 及以上。
14
+
15
+ ## 下载安装与绑定
16
+
17
+ 本地发布包可用 `pip install ./yunzhi-0.2.0-py3-none-any.whl` 安装。
18
+
19
+ ```bash
20
+ yunzhi-agent apk-qr
21
+ ```
22
+
23
+ 手机与电脑连上同一 Wi-Fi,用手机系统相机扫描这个二维码直接下载 APK。也可以运行 `yunzhi-agent apk`,或调用 `yunzhi.get_apk()`,把导出的 APK 传到手机安装。下载二维码默认 10 分钟后失效。
24
+
25
+ 在每台要绑定的电脑上启动后台投递服务。macOS 可选择登录后自动运行。
26
+
27
+ ```bash
28
+ # 手动启动,Windows、Linux 和 macOS 均可运行
29
+ yunzhi-agent serve --name "家里电脑"
30
+
31
+ # macOS 登录后自动启动,在未运行 serve 时执行
32
+ yunzhi-agent enable --name "家里电脑"
33
+ ```
34
+
35
+ 再打开一个终端,为每台手机分别运行一次 `yunzhi-agent bind`。手机打开云知,选择「扫描项目二维码」。一台电脑最多绑定 32 台手机,一台手机最多绑定 16 台电脑。用 `yunzhi-agent phones` 查看设备 ID,用 `yunzhi-agent revoke 手机ID` 撤销设备。macOS 可运行 `yunzhi-agent disable` 停用登录后启动。
36
+
37
+ 电脑有多个网络接口时,使用 `serve --host 192.168.1.20` 指定电脑的局域网 IPv4。防火墙需允许手机访问打印的 TCP 端口,默认 8789。建议在路由器为电脑保留固定 IP,服务地址或端口变化后需要重新配对。
38
+
39
+ ## 消息与报警
40
+
41
+ ```python
42
+ from pathlib import Path
43
+ import yunzhi
44
+
45
+ # 向这台电脑已绑定的全部手机发送
46
+ yunzhi.send("语音监测检测到愤怒", source="Sound")
47
+
48
+ # 紧急报警,可附带二进制内容,也可用 to="手机ID" 指定接收者
49
+ yunzhi.send_warning("检测到疑似摔倒,请查看老人情况。", source="YOLO")
50
+ yunzhi.send("检测事件附件", Path("event.bin").read_bytes(), source="YOLO")
51
+ ```
52
+
53
+ 已完成配对后,应用和命令行都能投递。后台服务在监测窗口关闭时可继续投递已入队的消息。即使后台服务暂时停止,发送方也可以将新消息写入同一账号的本地队列,等服务恢复后投递。生成实时检测报警仍需要摄像头或麦克风及识别进程继续运行。
54
+
55
+ ```bash
56
+ yunzhi-agent warn "测试紧急报警" --source "桌面测试"
57
+ ```
58
+
59
+ 老人监测仓库的 YOLO 摔倒流程可用 `YUNZHI_FALL_ALERTS=1` 开启报警桥接。先把云知 wheel 安装到 YOLO 的 Python 环境,并在同一桌面账号启动投递服务、配对手机。确认摔倒时,YOLO 会自动发出紧急消息。
60
+
61
+ ### 手机权限
62
+
63
+ 启用云知首页的「紧急报警」,允许系统通知。Android 14 及以上需要时点击「允许锁屏全屏报警」,在系统设置里授予权限。收到紧急消息后,Android 可在锁屏时显示亮屏报警,手机正在使用时可能显示横幅。报警用系统闹钟铃声,最多响 45 秒,可点「停止响铃」。
64
+
65
+ 可在云知里确认将系统闹钟音量设为最大。该操作也会影响其他闹钟。要在「仅允许优先打扰」模式下接收报警,先授予勿扰访问权限,再启用云知的勿扰例外。最终的响铃、振动和全屏行为取决于系统及厂商设置。手机端保持后台接收开启,系统通知栏会显示常驻状态。
66
+
67
+ ## Python 接口
68
+
69
+ | 接口 | 行为 |
70
+ | --- | --- |
71
+ | `bind_scan(timeout=120, *, host=None, port=0, name=None, qr_path=None)` | 生成一个一次性配对二维码,等待扫描后返回手机 ID。用 `qr_path="pairing.svg"` 导出二维码。 |
72
+ | `send(message, file=None, *, source=None, to=None)` | 将普通消息放入持久化队列并返回消息 ID。默认发送给已绑定的全部手机,`to` 支持单个 ID 或 ID 列表。 |
73
+ | `send_warning(message, file=None, *, source=None, to=None)` | 将紧急报警放入优先队列。5 分钟内未收到的报警会过期,避免手机恢复连接后响起过时的警报。 |
74
+ | `get_apk(destination=None)` | 导出内置 APK 并返回绝对路径。可传入现有目录或目标文件路径。 |
75
+
76
+ 正文最多 8 KiB,附件最多 16 MiB。各手机保存消息和附件后分别确认接收。普通消息待投递时间为 7 天。
77
+
78
+ ## 构建
79
+
80
+ 安卓端需要 JDK 17、Android SDK Platform 36、Build Tools 36.0.0 和 [ZXing Core 3.5.4](https://central.sonatype.com/artifact/com.google.zxing/core/3.5.4)。先配置 `ANDROID_SDK_ROOT`、`JAVA_HOME`、`ZXING_JAR`、`YUNZHI_KEYSTORE` 和 `YUNZHI_KEY_PASSWORD_FILE`,再运行 `bash android/build.sh`。签名密钥使用 `yunzhi` 别名。升级安装时使用原签名密钥。
81
+
82
+ APK 构建完成后,用 `python -m build` 生成 Python wheel 和源码包。
yunzhi-0.2.0/README.md ADDED
@@ -0,0 +1,72 @@
1
+ # 云知 · yunzhi
2
+
3
+ 让 Python 项目通过局域网向安卓手机发送消息、紧急报警和二进制附件。传输使用扫码时验证的 HTTPS。支持 Android 8.0 及以上。
4
+
5
+ ## 下载安装与绑定
6
+
7
+ 本地发布包可用 `pip install ./yunzhi-0.2.0-py3-none-any.whl` 安装。
8
+
9
+ ```bash
10
+ yunzhi-agent apk-qr
11
+ ```
12
+
13
+ 手机与电脑连上同一 Wi-Fi,用手机系统相机扫描这个二维码直接下载 APK。也可以运行 `yunzhi-agent apk`,或调用 `yunzhi.get_apk()`,把导出的 APK 传到手机安装。下载二维码默认 10 分钟后失效。
14
+
15
+ 在每台要绑定的电脑上启动后台投递服务。macOS 可选择登录后自动运行。
16
+
17
+ ```bash
18
+ # 手动启动,Windows、Linux 和 macOS 均可运行
19
+ yunzhi-agent serve --name "家里电脑"
20
+
21
+ # macOS 登录后自动启动,在未运行 serve 时执行
22
+ yunzhi-agent enable --name "家里电脑"
23
+ ```
24
+
25
+ 再打开一个终端,为每台手机分别运行一次 `yunzhi-agent bind`。手机打开云知,选择「扫描项目二维码」。一台电脑最多绑定 32 台手机,一台手机最多绑定 16 台电脑。用 `yunzhi-agent phones` 查看设备 ID,用 `yunzhi-agent revoke 手机ID` 撤销设备。macOS 可运行 `yunzhi-agent disable` 停用登录后启动。
26
+
27
+ 电脑有多个网络接口时,使用 `serve --host 192.168.1.20` 指定电脑的局域网 IPv4。防火墙需允许手机访问打印的 TCP 端口,默认 8789。建议在路由器为电脑保留固定 IP,服务地址或端口变化后需要重新配对。
28
+
29
+ ## 消息与报警
30
+
31
+ ```python
32
+ from pathlib import Path
33
+ import yunzhi
34
+
35
+ # 向这台电脑已绑定的全部手机发送
36
+ yunzhi.send("语音监测检测到愤怒", source="Sound")
37
+
38
+ # 紧急报警,可附带二进制内容,也可用 to="手机ID" 指定接收者
39
+ yunzhi.send_warning("检测到疑似摔倒,请查看老人情况。", source="YOLO")
40
+ yunzhi.send("检测事件附件", Path("event.bin").read_bytes(), source="YOLO")
41
+ ```
42
+
43
+ 已完成配对后,应用和命令行都能投递。后台服务在监测窗口关闭时可继续投递已入队的消息。即使后台服务暂时停止,发送方也可以将新消息写入同一账号的本地队列,等服务恢复后投递。生成实时检测报警仍需要摄像头或麦克风及识别进程继续运行。
44
+
45
+ ```bash
46
+ yunzhi-agent warn "测试紧急报警" --source "桌面测试"
47
+ ```
48
+
49
+ 老人监测仓库的 YOLO 摔倒流程可用 `YUNZHI_FALL_ALERTS=1` 开启报警桥接。先把云知 wheel 安装到 YOLO 的 Python 环境,并在同一桌面账号启动投递服务、配对手机。确认摔倒时,YOLO 会自动发出紧急消息。
50
+
51
+ ### 手机权限
52
+
53
+ 启用云知首页的「紧急报警」,允许系统通知。Android 14 及以上需要时点击「允许锁屏全屏报警」,在系统设置里授予权限。收到紧急消息后,Android 可在锁屏时显示亮屏报警,手机正在使用时可能显示横幅。报警用系统闹钟铃声,最多响 45 秒,可点「停止响铃」。
54
+
55
+ 可在云知里确认将系统闹钟音量设为最大。该操作也会影响其他闹钟。要在「仅允许优先打扰」模式下接收报警,先授予勿扰访问权限,再启用云知的勿扰例外。最终的响铃、振动和全屏行为取决于系统及厂商设置。手机端保持后台接收开启,系统通知栏会显示常驻状态。
56
+
57
+ ## Python 接口
58
+
59
+ | 接口 | 行为 |
60
+ | --- | --- |
61
+ | `bind_scan(timeout=120, *, host=None, port=0, name=None, qr_path=None)` | 生成一个一次性配对二维码,等待扫描后返回手机 ID。用 `qr_path="pairing.svg"` 导出二维码。 |
62
+ | `send(message, file=None, *, source=None, to=None)` | 将普通消息放入持久化队列并返回消息 ID。默认发送给已绑定的全部手机,`to` 支持单个 ID 或 ID 列表。 |
63
+ | `send_warning(message, file=None, *, source=None, to=None)` | 将紧急报警放入优先队列。5 分钟内未收到的报警会过期,避免手机恢复连接后响起过时的警报。 |
64
+ | `get_apk(destination=None)` | 导出内置 APK 并返回绝对路径。可传入现有目录或目标文件路径。 |
65
+
66
+ 正文最多 8 KiB,附件最多 16 MiB。各手机保存消息和附件后分别确认接收。普通消息待投递时间为 7 天。
67
+
68
+ ## 构建
69
+
70
+ 安卓端需要 JDK 17、Android SDK Platform 36、Build Tools 36.0.0 和 [ZXing Core 3.5.4](https://central.sonatype.com/artifact/com.google.zxing/core/3.5.4)。先配置 `ANDROID_SDK_ROOT`、`JAVA_HOME`、`ZXING_JAR`、`YUNZHI_KEYSTORE` 和 `YUNZHI_KEY_PASSWORD_FILE`,再运行 `bash android/build.sh`。签名密钥使用 `yunzhi` 别名。升级安装时使用原签名密钥。
71
+
72
+ APK 构建完成后,用 `python -m build` 生成 Python wheel 和源码包。
@@ -0,0 +1,26 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android"
2
+ package="io.yunzhi.receiver" android:versionCode="2" android:versionName="0.2.0">
3
+ <uses-sdk android:minSdkVersion="26" android:targetSdkVersion="36" />
4
+ <uses-feature android:name="android.hardware.camera" android:required="false" />
5
+ <uses-permission android:name="android.permission.INTERNET" />
6
+ <uses-permission android:name="android.permission.CAMERA" />
7
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
8
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
9
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_REMOTE_MESSAGING" />
10
+ <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
11
+ <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
12
+ <uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
13
+ <application android:label="云知" android:icon="@drawable/ic_yunzhi" android:allowBackup="false"
14
+ android:theme="@android:style/Theme.Material.Light.NoActionBar">
15
+ <activity android:name=".MainActivity" android:exported="true">
16
+ <intent-filter>
17
+ <action android:name="android.intent.action.MAIN" />
18
+ <category android:name="android.intent.category.LAUNCHER" />
19
+ </intent-filter>
20
+ </activity>
21
+ <activity android:name=".ScannerActivity" android:exported="false" android:screenOrientation="portrait" />
22
+ <activity android:name=".EmergencyActivity" android:exported="false" android:excludeFromRecents="true" />
23
+ <receiver android:name=".AlertDismissReceiver" android:exported="false" />
24
+ <service android:name=".InboxService" android:exported="false" android:foregroundServiceType="remoteMessaging" />
25
+ </application>
26
+ </manifest>
@@ -0,0 +1,36 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ : "${ANDROID_SDK_ROOT:?Set ANDROID_SDK_ROOT to your Android SDK directory}"
4
+ : "${JAVA_HOME:?Set JAVA_HOME to a JDK 17 directory}"
5
+ : "${ZXING_JAR:?Set ZXING_JAR to ZXing Core 3.5.4 from Maven Central}"
6
+ : "${YUNZHI_KEYSTORE:?Set YUNZHI_KEYSTORE to your APK signing keystore}"
7
+ : "${YUNZHI_KEY_PASSWORD_FILE:?Set YUNZHI_KEY_PASSWORD_FILE to a file containing the keystore password}"
8
+ export PATH="$JAVA_HOME/bin:$PATH"
9
+
10
+ root="$(cd "$(dirname "$0")" && pwd)"
11
+ tools="$ANDROID_SDK_ROOT/build-tools/36.0.0"
12
+ platform="$ANDROID_SDK_ROOT/platforms/android-36/android.jar"
13
+ output="$root/../src/yunzhi/data/yunzhi-android.apk"
14
+ scratch="$(mktemp -d)"
15
+ trap 'rm -rf "$scratch"' EXIT
16
+ mkdir -p "$scratch"/{java,classes,dex,META-INF}
17
+
18
+ "$tools/aapt2" compile --dir "$root/res" -o "$scratch/resources.zip"
19
+ "$tools/aapt2" link -I "$platform" --manifest "$root/AndroidManifest.xml" \
20
+ --java "$scratch/java" -o "$scratch/resources.apk" "$scratch/resources.zip"
21
+ "$JAVA_HOME/bin/javac" --release 8 -encoding UTF-8 \
22
+ -classpath "$platform:$ZXING_JAR" -d "$scratch/classes" \
23
+ "$root"/src/io/yunzhi/receiver/*.java "$scratch/java/io/yunzhi/receiver/R.java"
24
+ "$JAVA_HOME/bin/jar" cf "$scratch/classes.jar" -C "$scratch/classes" .
25
+ "$tools/d8" --min-api 26 --release --lib "$platform" --output "$scratch/dex" \
26
+ "$scratch/classes.jar" "$ZXING_JAR"
27
+ cp "$root"/third-party/*.txt "$scratch/META-INF/"
28
+ cp "$scratch"/dex/classes*.dex "$scratch/"
29
+ (cd "$scratch" && zip -q resources.apk classes*.dex META-INF/ZXing-LICENSE.txt META-INF/ZXing-NOTICE.txt)
30
+ "$tools/zipalign" -f 4 "$scratch/resources.apk" "$scratch/aligned.apk"
31
+ "$tools/apksigner" sign --ks "$YUNZHI_KEYSTORE" --ks-key-alias yunzhi \
32
+ --ks-pass "file:$YUNZHI_KEY_PASSWORD_FILE" --out "$scratch/signed.apk" "$scratch/aligned.apk"
33
+ "$tools/apksigner" verify "$scratch/signed.apk"
34
+ mkdir -p "$(dirname "$output")"
35
+ cp "$scratch/signed.apk" "$output"
36
+ printf '%s\n' "$output"
@@ -0,0 +1,7 @@
1
+ <vector xmlns:android="http://schemas.android.com/apk/res/android"
2
+ android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
3
+ <path android:fillColor="#3D6E5F"
4
+ android:pathData="M2,12A10,10 0,1 0,22 12A10,10 0,1 0,2 12Z"/>
5
+ <path android:strokeColor="#FFFFFF" android:strokeWidth="1.7" android:strokeLineCap="round"
6
+ android:strokeLineJoin="round" android:pathData="M6,12h3l2,-4l2,8l2,-4h3"/>
7
+ </vector>
@@ -0,0 +1,11 @@
1
+ package io.yunzhi.receiver;
2
+
3
+ import android.content.BroadcastReceiver;
4
+ import android.content.Context;
5
+ import android.content.Intent;
6
+
7
+ public final class AlertDismissReceiver extends BroadcastReceiver {
8
+ @Override public void onReceive(Context context, Intent intent) {
9
+ UrgentAlerts.dismiss(context, intent.getStringExtra("messageId"));
10
+ }
11
+ }
@@ -0,0 +1,109 @@
1
+ package io.yunzhi.receiver;
2
+
3
+ import android.app.Activity;
4
+ import android.app.KeyguardManager;
5
+ import android.content.Intent;
6
+ import android.graphics.Color;
7
+ import android.graphics.Typeface;
8
+ import android.os.Build;
9
+ import android.os.Bundle;
10
+ import android.view.Gravity;
11
+ import android.view.WindowManager;
12
+ import android.widget.Button;
13
+ import android.widget.LinearLayout;
14
+ import android.widget.ScrollView;
15
+ import android.widget.TextView;
16
+ import org.json.JSONArray;
17
+ import org.json.JSONObject;
18
+
19
+ public final class EmergencyActivity extends Activity {
20
+ @Override public void onCreate(Bundle state) {
21
+ super.onCreate(state);
22
+ if (Build.VERSION.SDK_INT >= 27) {
23
+ setShowWhenLocked(true);
24
+ setTurnScreenOn(true);
25
+ } else {
26
+ getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
27
+ }
28
+ if (!Inbox.preferences(this).getBoolean(UrgentAlerts.ENABLED, false)) {
29
+ finish();
30
+ return;
31
+ }
32
+ String id = getIntent().getStringExtra("messageId");
33
+ JSONObject item = lookup(id);
34
+ KeyguardManager lock = getSystemService(KeyguardManager.class);
35
+ ScrollView scroll = new ScrollView(this);
36
+ scroll.setFillViewport(true);
37
+ scroll.setBackgroundColor(0xff781d26);
38
+ LinearLayout screen = new LinearLayout(this);
39
+ screen.setOrientation(LinearLayout.VERTICAL);
40
+ screen.setGravity(Gravity.CENTER_VERTICAL);
41
+ screen.setPadding(dp(26), dp(32), dp(26), dp(32));
42
+ scroll.addView(screen);
43
+ if (Build.VERSION.SDK_INT >= 30) {
44
+ screen.setOnApplyWindowInsetsListener((view, insets) -> {
45
+ android.graphics.Insets bars = insets.getInsets(android.view.WindowInsets.Type.systemBars());
46
+ screen.setPadding(dp(26) + bars.left, dp(32) + bars.top, dp(26) + bars.right, dp(32) + bars.bottom);
47
+ return insets;
48
+ });
49
+ }
50
+
51
+ TextView title = label("紧急报警", 38);
52
+ title.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
53
+ screen.addView(title);
54
+ TextView description = label(item == null || lock.isDeviceLocked() ? "请解锁手机查看报警详情。"
55
+ : item.optString("source", "云知") + "\n" + item.optString("message"), 19);
56
+ description.setPadding(0, dp(14), 0, dp(24));
57
+ screen.addView(description);
58
+ Button acknowledge = new Button(this);
59
+ acknowledge.setText("停止响铃");
60
+ acknowledge.setMinimumHeight(dp(56));
61
+ acknowledge.setOnClickListener(view -> {
62
+ UrgentAlerts.dismiss(this, id);
63
+ finish();
64
+ });
65
+ screen.addView(acknowledge);
66
+ Button details = new Button(this);
67
+ details.setText("打开消息记录");
68
+ details.setMinimumHeight(dp(56));
69
+ details.setOnClickListener(view -> {
70
+ UrgentAlerts.dismiss(this, id);
71
+ if (lock.isDeviceLocked()) {
72
+ lock.requestDismissKeyguard(this, new KeyguardManager.KeyguardDismissCallback() {
73
+ @Override public void onDismissSucceeded() { openInbox(); }
74
+ });
75
+ } else openInbox();
76
+ });
77
+ screen.addView(details);
78
+ setContentView(scroll);
79
+ }
80
+
81
+ private void openInbox() {
82
+ startActivity(new Intent(this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
83
+ finish();
84
+ }
85
+
86
+ private JSONObject lookup(String id) {
87
+ if (id == null) return null;
88
+ try {
89
+ JSONArray messages = Inbox.messages(this);
90
+ for (int i = 0; i < messages.length(); i++) {
91
+ JSONObject item = messages.getJSONObject(i);
92
+ if (id.equals(item.getString("id"))) return item;
93
+ }
94
+ } catch (Exception ignored) {}
95
+ return null;
96
+ }
97
+
98
+ private TextView label(String text, int size) {
99
+ TextView result = new TextView(this);
100
+ result.setText(text);
101
+ result.setTextColor(Color.WHITE);
102
+ result.setTextSize(size);
103
+ return result;
104
+ }
105
+
106
+ private int dp(int size) {
107
+ return Math.round(size * getResources().getDisplayMetrics().density);
108
+ }
109
+ }
@@ -0,0 +1,133 @@
1
+ package io.yunzhi.receiver;
2
+
3
+ import android.content.Context;
4
+ import android.content.SharedPreferences;
5
+ import java.io.File;
6
+ import java.io.FileOutputStream;
7
+ import java.io.IOException;
8
+ import java.io.InputStream;
9
+ import java.util.ArrayList;
10
+ import java.util.List;
11
+ import javax.net.ssl.HttpsURLConnection;
12
+ import org.json.JSONArray;
13
+ import org.json.JSONObject;
14
+
15
+ final class Inbox {
16
+ private static final int MAX_ITEMS = 50;
17
+ private static final long MAX_FILES = 64L * 1024 * 1024;
18
+ private static final int MAX_ATTACHMENT = 16 * 1024 * 1024;
19
+ static final int MAX_LINKS = 16;
20
+
21
+ static SharedPreferences preferences(Context context) {
22
+ return context.getSharedPreferences("yunzhi", Context.MODE_PRIVATE);
23
+ }
24
+
25
+ static synchronized List<Link> links(Context context) throws Exception {
26
+ JSONArray items = new JSONArray(preferences(context).getString("links", "[]"));
27
+ List<Link> links = new ArrayList<>();
28
+ for (int i = 0; i < items.length(); i++) links.add(Link.fromJson(items.getJSONObject(i)));
29
+ return links;
30
+ }
31
+
32
+ static synchronized Link addLink(Context context, Link link) throws Exception {
33
+ List<Link> current = links(context);
34
+ JSONArray items = new JSONArray();
35
+ Link previous = null;
36
+ for (Link item : current) {
37
+ if (item.address.equals(link.address)) previous = item;
38
+ else items.put(item.toJson());
39
+ }
40
+ if (items.length() >= MAX_LINKS) throw new IOException("最多绑定 16 台电脑。请先移除一个连接。");
41
+ items.put(link.toJson());
42
+ writeLinks(context, items);
43
+ return previous;
44
+ }
45
+
46
+ static synchronized void removeLink(Context context, String pin) throws Exception {
47
+ JSONArray items = new JSONArray();
48
+ for (Link link : links(context)) {
49
+ if (!link.pin.equals(pin)) items.put(link.toJson());
50
+ }
51
+ writeLinks(context, items);
52
+ }
53
+
54
+ private static void writeLinks(Context context, JSONArray items) throws IOException {
55
+ if (!preferences(context).edit().putString("links", items.toString()).commit()) {
56
+ throw new IOException("无法保存配对。");
57
+ }
58
+ }
59
+
60
+ static synchronized JSONArray messages(Context context) throws Exception {
61
+ return new JSONArray(preferences(context).getString("messages", "[]"));
62
+ }
63
+
64
+ static synchronized boolean contains(Context context, String id) throws Exception {
65
+ JSONArray items = messages(context);
66
+ for (int i = 0; i < items.length(); i++) {
67
+ if (id.equals(items.getJSONObject(i).getString("id"))) return true;
68
+ }
69
+ return false;
70
+ }
71
+
72
+ private static File folder(Context context) {
73
+ return new File(context.getFilesDir(), "attachments");
74
+ }
75
+
76
+ static File file(Context context, String id) {
77
+ if (!id.matches("[a-f0-9]{32}")) throw new IllegalArgumentException("Invalid attachment ID.");
78
+ return new File(folder(context), id + ".bin");
79
+ }
80
+
81
+ static void download(Context context, Link link, String id, long expected) throws Exception {
82
+ if (expected < 0 || expected > MAX_ATTACHMENT) throw new IOException("Invalid attachment size.");
83
+ File output = file(context, id);
84
+ File directory = folder(context);
85
+ if (!directory.isDirectory() && !directory.mkdirs() && !directory.isDirectory()) {
86
+ throw new IOException("Cannot create attachment directory.");
87
+ }
88
+ File temp = File.createTempFile(id, ".part", directory);
89
+ try {
90
+ HttpsURLConnection request = link.open("GET", "/attachment/" + id);
91
+ try (InputStream input = request.getInputStream(); FileOutputStream stream = new FileOutputStream(temp)) {
92
+ byte[] buffer = new byte[8192];
93
+ int count;
94
+ long total = 0;
95
+ while ((count = input.read(buffer)) != -1) {
96
+ total += count;
97
+ if (total > expected) throw new IOException("Attachment content exceeds declared size.");
98
+ stream.write(buffer, 0, count);
99
+ }
100
+ if (total != expected) throw new IOException("Attachment transfer was incomplete.");
101
+ stream.getFD().sync();
102
+ } finally {
103
+ request.disconnect();
104
+ }
105
+ if (!temp.renameTo(output)) throw new IOException("Cannot save attachment.");
106
+ } finally {
107
+ temp.delete();
108
+ }
109
+ }
110
+
111
+ static synchronized void store(Context context, Link link, JSONObject message) throws Exception {
112
+ JSONArray previous = messages(context);
113
+ message.put("source", message.optString("source", link.name));
114
+ message.put("desktop", link.name);
115
+ JSONArray next = new JSONArray().put(message);
116
+ long sizes = message.optLong("size", 0);
117
+ List<File> expired = new ArrayList<>();
118
+ for (int i = 0; i < previous.length(); i++) {
119
+ JSONObject item = previous.getJSONObject(i);
120
+ long size = item.optLong("size", 0);
121
+ if (next.length() >= MAX_ITEMS || sizes + size > MAX_FILES) {
122
+ if (!item.isNull("size")) expired.add(file(context, item.getString("id")));
123
+ } else {
124
+ next.put(item);
125
+ sizes += size;
126
+ }
127
+ }
128
+ if (!preferences(context).edit().putString("messages", next.toString()).commit()) {
129
+ throw new IOException("Cannot save inbox.");
130
+ }
131
+ for (File stale : expired) stale.delete();
132
+ }
133
+ }
@@ -0,0 +1,141 @@
1
+ package io.yunzhi.receiver;
2
+
3
+ import android.Manifest;
4
+ import android.app.Notification;
5
+ import android.app.NotificationChannel;
6
+ import android.app.NotificationManager;
7
+ import android.app.PendingIntent;
8
+ import android.app.Service;
9
+ import android.content.Intent;
10
+ import android.content.pm.PackageManager;
11
+ import android.os.Build;
12
+ import android.os.IBinder;
13
+ import java.io.IOException;
14
+ import java.util.HashMap;
15
+ import java.util.HashSet;
16
+ import java.util.Map;
17
+ import java.util.Set;
18
+ import java.util.concurrent.ConcurrentHashMap;
19
+ import java.util.concurrent.Executors;
20
+ import java.util.concurrent.ScheduledExecutorService;
21
+ import java.util.concurrent.ScheduledFuture;
22
+ import java.util.concurrent.TimeUnit;
23
+ import javax.net.ssl.HttpsURLConnection;
24
+ import org.json.JSONObject;
25
+
26
+ public final class InboxService extends Service {
27
+ private static final String SERVICE_CHANNEL = "receiver";
28
+ private static final String MESSAGE_CHANNEL = "messages";
29
+ private static final int SERVICE_ID = 7101;
30
+ static final Map<String, Boolean> online = new ConcurrentHashMap<>();
31
+ static volatile boolean running;
32
+ private final Map<String, String> pollTokens = new HashMap<>();
33
+ private final Map<String, ScheduledFuture<?>> polls = new HashMap<>();
34
+ private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(Inbox.MAX_LINKS);
35
+
36
+ @Override public int onStartCommand(Intent intent, int flags, int startId) {
37
+ NotificationManager notifications = getSystemService(NotificationManager.class);
38
+ notifications.createNotificationChannel(new NotificationChannel(
39
+ SERVICE_CHANNEL, "局域网接收", NotificationManager.IMPORTANCE_LOW));
40
+ NotificationChannel alerts = new NotificationChannel(MESSAGE_CHANNEL, "项目消息", NotificationManager.IMPORTANCE_HIGH);
41
+ alerts.enableVibration(true);
42
+ alerts.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
43
+ notifications.createNotificationChannel(alerts);
44
+
45
+ startForeground(SERVICE_ID, new Notification.Builder(this, SERVICE_CHANNEL)
46
+ .setSmallIcon(R.drawable.ic_yunzhi).setContentTitle("云知正在接收消息")
47
+ .setContentText("保持手机与电脑连接同一 Wi-Fi")
48
+ .setContentIntent(openInbox()).setOngoing(true).build());
49
+ running = true;
50
+ try {
51
+ Set<String> kept = new HashSet<>();
52
+ for (Link link : Inbox.links(this)) {
53
+ kept.add(link.pin);
54
+ if (!link.token.equals(pollTokens.get(link.pin))) {
55
+ ScheduledFuture<?> old = polls.remove(link.pin);
56
+ if (old != null) old.cancel(true);
57
+ pollTokens.put(link.pin, link.token);
58
+ polls.put(link.pin, executor.scheduleWithFixedDelay(() -> poll(link), 0, 1, TimeUnit.SECONDS));
59
+ }
60
+ }
61
+ for (String pin : new HashSet<>(polls.keySet())) {
62
+ if (!kept.contains(pin)) {
63
+ polls.remove(pin).cancel(true);
64
+ pollTokens.remove(pin);
65
+ online.remove(pin);
66
+ }
67
+ }
68
+ if (kept.isEmpty()) stopSelf();
69
+ } catch (Exception error) {
70
+ stopSelf();
71
+ }
72
+ return START_STICKY;
73
+ }
74
+
75
+ private void poll(Link link) {
76
+ try {
77
+ for (int i = 0; i < 8 && !Thread.currentThread().isInterrupted(); i++) {
78
+ JSONObject data = next(link);
79
+ online.put(link.pin, true);
80
+ if (data == null) return;
81
+ String id = data.getString("id");
82
+ if (!id.matches("[a-f0-9]{32}")) throw new IOException("Invalid message ID.");
83
+ if (!Inbox.contains(this, id)) {
84
+ if (!data.isNull("size")) Inbox.download(this, link, id, data.getLong("size"));
85
+ Inbox.store(this, link, data);
86
+ notifyMessage(link, data);
87
+ }
88
+ HttpsURLConnection ack = link.open("POST", "/ack/" + id);
89
+ try {
90
+ if (ack.getResponseCode() != 204) throw new IOException("Message acknowledgement failed.");
91
+ } finally {
92
+ ack.disconnect();
93
+ }
94
+ }
95
+ } catch (Exception error) {
96
+ online.put(link.pin, false);
97
+ }
98
+ }
99
+
100
+ private JSONObject next(Link link) throws Exception {
101
+ HttpsURLConnection request = link.open("GET", "/messages");
102
+ try {
103
+ int code = request.getResponseCode();
104
+ if (code == 204) return null;
105
+ if (code != 200) throw new IOException("Sender returned HTTP " + code);
106
+ return Link.readJson(request);
107
+ } finally {
108
+ request.disconnect();
109
+ }
110
+ }
111
+
112
+ private PendingIntent openInbox() {
113
+ Intent intent = new Intent(this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
114
+ return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
115
+ }
116
+
117
+ private void notifyMessage(Link link, JSONObject item) {
118
+ if (Build.VERSION.SDK_INT >= 33
119
+ && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) return;
120
+ if (item.optBoolean("urgent") && Inbox.preferences(this).getBoolean(UrgentAlerts.ENABLED, false)) {
121
+ UrgentAlerts.post(this, item);
122
+ return;
123
+ }
124
+ String message = item.optString("message").trim();
125
+ if (message.isEmpty()) message = "收到一个附件";
126
+ Notification notification = new Notification.Builder(this, MESSAGE_CHANNEL)
127
+ .setSmallIcon(R.drawable.ic_yunzhi).setAutoCancel(true)
128
+ .setContentTitle(item.optString("source", link.name)).setContentText(message).setStyle(new Notification.BigTextStyle().bigText(message))
129
+ .setVisibility(Notification.VISIBILITY_PRIVATE).setContentIntent(openInbox()).build();
130
+ getSystemService(NotificationManager.class).notify(item.optString("id"), 7102, notification);
131
+ }
132
+
133
+ @Override public void onDestroy() {
134
+ running = false;
135
+ executor.shutdownNow();
136
+ online.clear();
137
+ super.onDestroy();
138
+ }
139
+
140
+ @Override public IBinder onBind(Intent intent) { return null; }
141
+ }