Release 0.1.45: member phone locations and people-first family navigation
This commit is contained in:
@@ -1,10 +1,16 @@
|
|||||||
# 赵府智家 · 视觉系统
|
# 赵府智家 · 视觉系统
|
||||||
|
|
||||||
|
## v0.1.45 · 家人位置与家庭入口
|
||||||
|
|
||||||
|
手机打开「赵府家人位置」,凭本人家庭成员配对码使用,无需注册或登录。可查看明确授权给这台手机的家人;在「我的位置设置」选择查看人、实时(约 10 秒)/ 1 分钟 / 5 分钟上传,并由本人开启共享。查看家人不要求共享自己的位置。详见 [发布说明与操作步骤](RELEASE-v0.1.45.md)。
|
||||||
|
|
||||||
## v0.1.44 后续更新 · 系统账号、真实成员与世代目录
|
## v0.1.44 后续更新 · 系统账号、真实成员与世代目录
|
||||||
|
|
||||||
外层「系统用户」由平台管理员统一维护登录账号,并分别授权各家庭。家庭内「家庭成员」登记真实人物:老人和孩子不需要账号。账号可以绑定一个已确认的人物;家庭成员关系、活动参与和设备责任人均可引用人物。现有主要家庭授权保留,其他家庭通过独立授权增加,默认不授予摄像头控制。
|
外层「系统用户」由平台管理员统一维护登录账号,并分别授权各家庭。家庭内「家庭成员」登记真实人物:老人和孩子不需要账号。账号可以绑定一个已确认的人物;家庭成员关系、活动参与和设备责任人均可引用人物。现有主要家庭授权保留,其他家庭通过独立授权增加,默认不授予摄像头控制。
|
||||||
|
|
||||||
「我的家庭与场所 → 家族世代」按已确认的亲子关系展示一世、二世、三世及关联家庭。世次相对本支已知最早一代起算;独立分支和无法确定的世次明确标示,不猜测历史绝对世次。祖先没有当前家庭成员关系仍可列入族谱;迁居后的历史成员保留人物档案。同一人物可关联多个家庭。相关家庭需明确确认共用族谱,现有数据不自动合并或按姓名去重。家庭与房产、产权转移的完整分离尚未实现,本版不自动处理售房、产权或搬家。
|
「家族与家庭」默认按已确认的亲子关系展示一世、二世、三世及关联家庭,可按姓名查找家人,突出本人,直接查看人物档案、亲属与个人阅历。一个家庭可包含多代人;住在外地也可以是家庭成员。世次相对本支已知最早一代起算;独立分支和无法确定的世次明确标示,不猜测历史绝对世次。祖先没有当前成员关系仍可列入族谱;历史成员保留人物和参与过的记事。同一人物可关联多个家庭。相关家庭需明确确认共用族谱,现有数据不自动合并或按姓名去重。
|
||||||
|
|
||||||
|
家庭以真实人物、亲属关系、共同记忆和传承为主线,售房与迁居业务不纳入本轮范围。家庭总览优先展示成员、记事和传承;设备统计集中到设备页,网络图在「场所网络」查看。账号是登录与授权主体,家庭管理账号不等于家族辈分或亲属身份。成员的阅历同时检索其参与的记事及绑定账号原有的记事,仍先执行原可见范围检查。
|
||||||
|
|
||||||
位置共享改为「成员 + 手机配对 + 指定查看名单」:无需在手机登录系统,须本人核对姓名、家庭、账号和显示终端名单,并开启共享。管理者可以协助配对、撤销共享,不能替本人开启。旧版按账号共享的位置授权停用,需要更新配套 App 并重新配对。新协议与录制、下载更新详见 [发布说明](RELEASE-v0.1.44.md#成员与世代目录更新)。
|
位置共享改为「成员 + 手机配对 + 指定查看名单」:无需在手机登录系统,须本人核对姓名、家庭、账号和显示终端名单,并开启共享。管理者可以协助配对、撤销共享,不能替本人开启。旧版按账号共享的位置授权停用,需要更新配套 App 并重新配对。新协议与录制、下载更新详见 [发布说明](RELEASE-v0.1.44.md#成员与世代目录更新)。
|
||||||
|
|
||||||
|
|||||||
+9
-1
@@ -2,6 +2,14 @@
|
|||||||
|
|
||||||
## 成员与世代目录更新
|
## 成员与世代目录更新
|
||||||
|
|
||||||
|
### 以家人为中心的入口调整(2026-10-18)
|
||||||
|
|
||||||
|
- 「家族与家庭」默认显示家族世代,提供姓名搜索、本人突出显示,人物卡片可直接定位人物与亲属;在关联家庭中查看个人阅历,包括历史成员参与过的记事。
|
||||||
|
- 家庭总览把成员、记事与家庭传承放在前面,设备入口收在可展开的「家庭设备与监控」内;刷新保留展开状态。设备统计移入设备页,整体网络图可从「场所网络」主动进入。
|
||||||
|
- 人物、家庭成员关系与账号继续分开:无设备、无账号也能登记家人并记录共同经历。一个家庭允许多代人,同一个人物仍可关联多个家庭。
|
||||||
|
- 人物跳转选择已获族谱读取权限的家庭上下文;个人阅历先按记事原权限过滤,再匹配参与人物及其关联账号。管理权限和亲属关系均不会使私密记事自动公开。
|
||||||
|
- 售房、产权与迁居流程不纳入本轮;不因地址变化推断亲属变化,也不自动修改现有家庭、人物和设备归属。
|
||||||
|
|
||||||
- 系统用户在外层统一列出;只有超级管理员可创建、修改账号凭据。一个账号可以获得多个家庭的独立访问授权;现有主要家庭配置保留,新增家庭默认不含设备控制。家庭管理员角色只在对应家庭生效,不扩展到其他家庭。
|
- 系统用户在外层统一列出;只有超级管理员可创建、修改账号凭据。一个账号可以获得多个家庭的独立访问授权;现有主要家庭配置保留,新增家庭默认不含设备控制。家庭管理员角色只在对应家庭生效,不扩展到其他家庭。
|
||||||
- 新增真实人物的家庭成员关系,允许无账号成员、暂住外地与历史成员。登记不会自动创建账号、建立亲子关系或授予设备权限。已有绑定账号的原人物在首次升级时登记为本家庭成员;其余不猜测身份。
|
- 新增真实人物的家庭成员关系,允许无账号成员、暂住外地与历史成员。登记不会自动创建账号、建立亲子关系或授予设备权限。已有绑定账号的原人物在首次升级时登记为本家庭成员;其余不猜测身份。
|
||||||
- 「家族世代」根据已确认的亲子与配偶关系分支展开一世、二世、三世等;相对当前分支最早已知世代计算,不冒充历史绝对世次。关系不足或冲突时为“世次待考”。家族目录只呈现获授权的家庭,族谱读取权限仍单独校验。
|
- 「家族世代」根据已确认的亲子与配偶关系分支展开一世、二世、三世等;相对当前分支最早已知世代计算,不冒充历史绝对世次。关系不足或冲突时为“世次待考”。家族目录只呈现获授权的家庭,族谱读取权限仍单独校验。
|
||||||
@@ -9,7 +17,7 @@
|
|||||||
- 记事新增真实参与人,可按没有账号的家人查阅经历;同一条记事仍遵守原可见范围,选择参与人不会把私密记事分享给其他人。编辑恢复已选参与人,保存清空。
|
- 记事新增真实参与人,可按没有账号的家人查阅经历;同一条记事仍遵守原可见范围,选择参与人不会把私密记事分享给其他人。编辑恢复已选参与人,保存清空。
|
||||||
- 设备责任人优先选择真实成员,仍可选择授权账号作为办公或外部管理联系人。既有引用保留,不因人员分层重建设备或删除历史。
|
- 设备责任人优先选择真实成员,仍可选择授权账号作为办公或外部管理联系人。既有引用保留,不因人员分层重建设备或删除历史。
|
||||||
- 负责人选择支持已获本家庭授权的跨家庭账号;提升的是当前家庭角色。担任负责人或备用负责人的账号须先交接,再降权、撤权或停用。
|
- 负责人选择支持已获本家庭授权的跨家庭账号;提升的是当前家庭角色。担任负责人或备用负责人的账号须先交接,再降权、撤权或停用。
|
||||||
- 本版世代目录是人物与现有家庭的展示关系;独立房产实体、售房交接及完整迁居履历仍待后续建模,不能将家庭卡片当作产权记录。
|
- 世代目录以人物与家庭成员关系组织;家庭卡片不作为产权记录。
|
||||||
|
|
||||||
## 成员位置共享协议 2
|
## 成员位置共享协议 2
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# v0.1.45 · 家人位置与以人为中心的家庭入口
|
||||||
|
|
||||||
|
## 手机使用流程
|
||||||
|
|
||||||
|
1. 在本平台 `/downloads` 下载安装新版 APK(versionCode 3),保留原应用签名,可覆盖升级。
|
||||||
|
2. 手机桌面入口为「赵府家人位置」;Android TV 的入口仍为家庭显示终端。手机不再默认进入家庭看板。
|
||||||
|
3. 家庭管理者或关联本人的账号,在「家庭总览 → 为家庭成员配对手机」选择真实成员,生成十分钟有效、一次使用的八位手机配对码。默认先配对查看用途,手机无需注册、登录系统账号。
|
||||||
|
4. 查看家人位置与共享自己位置分别设置。要被某位家人看到,双方先配对;分享者在自己手机「我的位置设置」勾选对方手机。公共显示终端和平台账号分别选择,家庭身份或管理权限不自动获得位置。
|
||||||
|
5. 本人核对身份、有效期、具体查看名单,选择实时(约 10 秒)、1 分钟或 5 分钟(默认),勾选同意并打开「共享我的位置」。此时才请求系统定位许可并启动带常驻通知的定位服务。
|
||||||
|
6. 共享期间可从开关或通知停止。关闭自己共享仍可查看获授权家人。修改频率或名单先关闭共享,再确认开启。
|
||||||
|
|
||||||
|
下载可由有账号的家人协助,配对和手机使用不要求老人、孩子注册。手机配对码与显示终端配对码不同。当前支持 Android 8.0+ ARM64/ARMv7,非 iPhone 安装包。
|
||||||
|
|
||||||
|
## 位置协议 3 与边界
|
||||||
|
|
||||||
|
- `/api/location/update` 新增 `settings`、`configure`、`list`,只接受手机专用令牌,不要求账号 Cookie,也不接受账号会话替代。配对协议 2 的既有名单仍兼容;旧 App 无法消费协议 3 配对码。
|
||||||
|
- 配对本身不启用共享。`configure` 必须带本人确认和当前授权摘要,完成后停用旧共享并清除坐标;`start` 必须再次使用新摘要。更新频率严格限定 10、60、300 秒。
|
||||||
|
- 家人手机查看授权绑定本次手机配对编号。重新配对替换旧令牌,不能继承别人给旧手机的查看授权,需分享者重新选择。账号、手机、显示终端、成员有效状态和家庭范围逐次检查。
|
||||||
|
- 只保存内存中的最新坐标,不建立定位轨迹表。停止通知服务器成功后清除;断网时本机立即停止,联网后重试通知;超过 15 分钟的坐标隐藏。平台解除手机授权使旧令牌失效。
|
||||||
|
- 地图和家庭列表在手机转入后台、网络读取失败时清空;回到前台重新读取授权位置。底图随 APK 打包,为 Natural Earth 世界陆地轮廓,不含街道或地址搜索,不向第三方地图发送坐标。
|
||||||
|
- 采集由本人在前台明确启动,使用 Android 位置前台服务;开机不自动启动定位。系统省电、网络、权限与定位信号可能影响实际更新间隔;本版不承诺每次精确准点或强杀后自行恢复。
|
||||||
|
|
||||||
|
Android 实现依据:[位置权限与前台服务](https://developer.android.com/develop/sensors-and-location/location/permissions)、[前台服务类型](https://developer.android.com/develop/background-work/services/fgs/service-types)。
|
||||||
|
|
||||||
|
## 家庭入口
|
||||||
|
|
||||||
|
- 「家族与家庭」默认按已确认亲属关系展示世代,可搜索家人、突出本人、进入人物与亲属、查看真实成员的个人阅历;没有账号也可以参与记事。
|
||||||
|
- 世次为本分支最早已知世代的相对编号;关系不足时显示「世次待考」,不猜测祖先绝对世次。
|
||||||
|
- 家庭总览以成员、记事、传承为入口,设备与监控收在可展开区域,保留所有已有功能。售房和迁居流程不纳入本轮。
|
||||||
|
- 人物与亲属跳转选择可读取族谱的家庭上下文。个人阅历先检查原记事可见性,再匹配真实人物或其关联账号,不扩大私密记事权限。
|
||||||
|
|
||||||
|
## 发布与验证
|
||||||
|
|
||||||
|
- 发布前使用隔离数据验证配对、本人同意、手机相互授权、不同家庭隔离、名单变更、重新配对、停止、过期与失效坐标;没有采集或启用真实家人的位置。
|
||||||
|
- Vue 生产构建与签名 APK 均从本版代码生成;本地 Bootstrap、Vue、ECharts 和地图资源随版本提供。
|
||||||
|
- Computer Use 原生连接当前不可用,未完成本轮界面实操或真实手机锁屏、GPS、耗电验收。自动测试与编译不能代替真机验证。
|
||||||
|
- 部署前创建 SQLite 一致性备份并执行 quick_check,替换代码与安装包后检查服务、下载哈希和权限。设备、媒体服务、Tailscale 与现有家庭数据不作迁移。
|
||||||
|
|
||||||
|
本轮隔离回归:270 项 Python 测试、179 项 JavaScript 测试通过;独立 JVM 上传频率测试 23 条断言通过。Vue 生产构建、Android Java/Dex 编译及 APK 签名校验通过。真机验收限制见上。
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="2" android:versionName="0.1.44">
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="3" android:versionName="0.1.45">
|
||||||
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30"/>
|
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30"/>
|
||||||
<uses-permission android:name="android.permission.INTERNET"/>
|
<uses-permission android:name="android.permission.INTERNET"/>
|
||||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
|
||||||
@@ -7,12 +7,12 @@
|
|||||||
<uses-permission android:name="android.permission.WAKE_LOCK"/>
|
<uses-permission android:name="android.permission.WAKE_LOCK"/>
|
||||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
|
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
|
||||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
|
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
|
||||||
<application android:label="赵府家庭屏" android:allowBackup="false" android:usesCleartextTraffic="true" android:theme="@android:style/Theme.Material.Light.NoActionBar">
|
<application android:label="赵府智家" android:allowBackup="false" android:usesCleartextTraffic="true" android:theme="@android:style/Theme.Material.Light.NoActionBar">
|
||||||
<activity android:name=".MainActivity" android:exported="true" android:configChanges="orientation|screenSize|keyboardHidden" android:launchMode="singleTask">
|
<activity android:name=".MainActivity" android:label="赵府家庭显示终端" android:exported="true" android:configChanges="orientation|screenSize|keyboardHidden" android:launchMode="singleTask">
|
||||||
<intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/><category android:name="android.intent.category.LEANBACK_LAUNCHER"/></intent-filter>
|
<intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LEANBACK_LAUNCHER"/></intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
<service android:name=".MonitorService" android:exported="false"/>
|
<service android:name=".MonitorService" android:exported="false"/>
|
||||||
<activity android:name=".LocationActivity" android:label="赵府位置共享" android:exported="true"><intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter></activity>
|
<activity android:name=".LocationActivity" android:label="赵府家人位置" android:exported="true"><intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter></activity>
|
||||||
<service android:name=".LocationService" android:exported="false" android:foregroundServiceType="location"/>
|
<service android:name=".LocationService" android:exported="false" android:foregroundServiceType="location"/>
|
||||||
<receiver android:name=".BootReceiver" android:exported="true"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED"/></intent-filter></receiver>
|
<receiver android:name=".BootReceiver" android:exported="true"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED"/></intent-filter></receiver>
|
||||||
</application>
|
</application>
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ $zip=[IO.Compression.ZipFile]::Open("$build\with-dex.apk",[IO.Compression.ZipArc
|
|||||||
try{
|
try{
|
||||||
[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,"$build\dex\classes.dex",'classes.dex',[IO.Compression.CompressionLevel]::Optimal) | Out-Null
|
[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,"$build\dex\classes.dex",'classes.dex',[IO.Compression.CompressionLevel]::Optimal) | Out-Null
|
||||||
foreach($abi in @('arm64-v8a','armeabi-v7a')){foreach($lib in Get-ChildItem "$vlc\jni\$abi" -Filter '*.so'){[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,$lib.FullName,"lib/$abi/$($lib.Name)",[IO.Compression.CompressionLevel]::Optimal) | Out-Null}}
|
foreach($abi in @('arm64-v8a','armeabi-v7a')){foreach($lib in Get-ChildItem "$vlc\jni\$abi" -Filter '*.so'){[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,$lib.FullName,"lib/$abi/$($lib.Name)",[IO.Compression.CompressionLevel]::Optimal) | Out-Null}}
|
||||||
|
foreach($name in @('world-land.json','WORLD-LAND-LICENSE.txt')){[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,"$source\..\frontend\src\data\$name","assets/$name",[IO.Compression.CompressionLevel]::Optimal) | Out-Null}
|
||||||
[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,"$source\THIRD_PARTY.md",'assets/THIRD_PARTY.md',[IO.Compression.CompressionLevel]::Optimal) | Out-Null
|
[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,"$source\THIRD_PARTY.md",'assets/THIRD_PARTY.md',[IO.Compression.CompressionLevel]::Optimal) | Out-Null
|
||||||
foreach($license in Get-ChildItem "$source\licenses" -File){[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,$license.FullName,"assets/licenses/$($license.Name)",[IO.Compression.CompressionLevel]::Optimal) | Out-Null}
|
foreach($license in Get-ChildItem "$source\licenses" -File){[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,$license.FullName,"assets/licenses/$($license.Name)",[IO.Compression.CompressionLevel]::Optimal) | Out-Null}
|
||||||
}finally{$zip.Dispose()}
|
}finally{$zip.Dispose()}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ package cn.ucvl.zhaodisplay;
|
|||||||
import android.content.*;
|
import android.content.*;
|
||||||
public class BootReceiver extends BroadcastReceiver {
|
public class BootReceiver extends BroadcastReceiver {
|
||||||
@Override public void onReceive(Context context,Intent intent){
|
@Override public void onReceive(Context context,Intent intent){
|
||||||
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()) && !context.getSharedPreferences("display",0).getString("token","").isEmpty())
|
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()) && !context.getSharedPreferences("display",0).getBoolean("phoneMode",false) && !context.getSharedPreferences("display",0).getString("token","").isEmpty())
|
||||||
context.startForegroundService(new Intent(context,MonitorService.class));
|
context.startForegroundService(new Intent(context,MonitorService.class));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,57 +5,118 @@ import android.os.*;
|
|||||||
import android.content.*;
|
import android.content.*;
|
||||||
import android.content.pm.PackageManager;
|
import android.content.pm.PackageManager;
|
||||||
import android.Manifest;
|
import android.Manifest;
|
||||||
|
import android.view.View;
|
||||||
import android.widget.*;
|
import android.widget.*;
|
||||||
import android.text.InputType;
|
import android.text.InputType;
|
||||||
import org.json.JSONObject;
|
import org.json.*;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
/** Phone-only, explicit opt-in. The TV never requests location permission. */
|
/** Paired member identity, family viewing and voluntary sharing; no account or display UI. */
|
||||||
public class LocationActivity extends Activity {
|
public class LocationActivity extends Activity {
|
||||||
static volatile boolean pairing=false;
|
static volatile boolean pairing=false;
|
||||||
TextView status; EditText code; Button pair,start,stop; CheckBox consent;
|
TextView identity,status,viewStatus;EditText code;Button pair,reload;
|
||||||
|
CheckBox consent;Switch sharing;Spinner cadence;LinearLayout settings,recipients,familyList;
|
||||||
|
LocationMapView map;boolean rendering=false,visible=false,loading=false,settingsReady=false,pendingStart=false;
|
||||||
|
int generation=0,settingsRequest=0;long lastList=0;String settingsReceipt="",settingsError="";
|
||||||
|
final Map<String,List<CheckBox>> choices=new HashMap<>();
|
||||||
android.content.SharedPreferences prefs;
|
android.content.SharedPreferences prefs;
|
||||||
final Handler ui=new Handler();
|
final Handler ui=new Handler();
|
||||||
final Runnable refresh=new Runnable(){public void run(){render();ui.postDelayed(this,2000);}};
|
final Runnable refresh=new Runnable(){public void run(){if(!visible)return;render();if(SystemClock.elapsedRealtime()-lastList>15000)loadFamily();ui.postDelayed(this,2000);}};
|
||||||
|
TextView text(String value,int size,LinearLayout parent){TextView t=new TextView(this);t.setText(value);t.setTextSize(size);t.setTextColor(0xff263e35);t.setPadding(0,12,0,12);parent.addView(t);return t;}
|
||||||
|
Button button(String label,LinearLayout parent){Button b=new Button(this);b.setText(label);parent.addView(b);return b;}
|
||||||
public void onCreate(Bundle state){
|
public void onCreate(Bundle state){
|
||||||
super.onCreate(state);prefs=getSharedPreferences("location",0);
|
super.onCreate(state);prefs=getSharedPreferences("location",0);
|
||||||
LinearLayout layout=new LinearLayout(this);layout.setOrientation(1);int p=(int)(24*getResources().getDisplayMetrics().density);layout.setPadding(p,p,p,p);layout.setBackgroundColor(0xfff5f2e9);
|
getSharedPreferences("display",0).edit().putBoolean("phoneMode",true).apply();
|
||||||
|
stopService(new Intent(this,MonitorService.class));
|
||||||
|
// Process death/reboot cannot leave a stale switch claiming collection is active.
|
||||||
|
if(prefs.getBoolean("active",false)&&!LocationService.busy){
|
||||||
|
prefs.edit().putBoolean("active",false).putString("status","共享已中断,请本人重新开启").apply();
|
||||||
|
startService(new Intent(this,LocationService.class).setAction("STOP"));
|
||||||
|
}
|
||||||
|
LinearLayout layout=new LinearLayout(this);layout.setOrientation(1);int p=(int)(20*getResources().getDisplayMetrics().density);layout.setPadding(p,p,p,p);layout.setBackgroundColor(0xfff5f2e9);
|
||||||
ScrollView scroll=new ScrollView(this);scroll.addView(layout);setContentView(scroll);
|
ScrollView scroll=new ScrollView(this);scroll.addView(layout);setContentView(scroll);
|
||||||
TextView heading=new TextView(this);heading.setText("家人位置共享");heading.setTextSize(28);layout.addView(heading);
|
text("家人位置",30,layout);identity=text("",17,layout);
|
||||||
TextView help=new TextView(this);help.setText("不需要注册或登录。请家人从平台的家庭成员中选择你的档案,生成手机配对码。\n\n配对后核对你的姓名、家庭及允许查看的人。只有你同意并开启共享,才约每 5 分钟上传最新位置。通知栏可随时停止;不保存轨迹。断网或省电可能延迟更新。");help.setTextSize(16);help.setPadding(0,p,0,p);layout.addView(help);
|
text("只显示家人主动授权给这台手机的位置。查看家人不需要开启自己的定位。",16,layout);
|
||||||
status=new TextView(this);status.setTextSize(17);layout.addView(status);
|
button("我的位置设置",layout).setOnClickListener(v->{settings.setVisibility(settings.getVisibility()==View.VISIBLE?View.GONE:View.VISIBLE);if(settings.getVisibility()==View.VISIBLE)loadSettings();});
|
||||||
code=new EditText(this);code.setHint("输入家人为你生成的八位配对码");code.setInputType(InputType.TYPE_CLASS_NUMBER);code.setFilters(new android.text.InputFilter[]{new android.text.InputFilter.LengthFilter(8)});layout.addView(code);
|
status=text("",16,layout);
|
||||||
pair=new Button(this);pair.setText("绑定我的位置共享");layout.addView(pair);pair.setOnClickListener(v->pair());
|
settings=new LinearLayout(this);settings.setOrientation(1);layout.addView(settings);
|
||||||
consent=new CheckBox(this);consent.setText("我已核对上方的本人姓名、家庭、查看名单及有效期,同意开启位置共享。关闭后停止采集并清除位置。");layout.addView(consent);
|
text("配对本人 · 无需注册或登录",22,settings);
|
||||||
start=new Button(this);start.setText("同意并开启定位");layout.addView(start);start.setOnClickListener(v->start());
|
text("请家人在平台进入家庭总览 → 为家庭成员配对手机,选择你的成员档案。这里使用手机配对码,不使用显示终端配对码。",16,settings);
|
||||||
stop=new Button(this);stop.setText("停止共享并清除位置");layout.addView(stop);stop.setOnClickListener(v->{startService(new Intent(this,LocationService.class).setAction("STOP"));consent.setChecked(false);});
|
code=new EditText(this);code.setHint("八位手机配对码");code.setInputType(InputType.TYPE_CLASS_NUMBER);code.setFilters(new android.text.InputFilter[]{new android.text.InputFilter.LengthFilter(8)});settings.addView(code);
|
||||||
render();ui.post(refresh);
|
pair=button("配对我的手机",settings);pair.setOnClickListener(v->pair());
|
||||||
|
text("我的位置共享",22,settings);text("选择谁能看我的位置",16,settings);
|
||||||
|
recipients=new LinearLayout(this);recipients.setOrientation(1);settings.addView(recipients);
|
||||||
|
text("上传频率",16,settings);cadence=new Spinner(this);cadence.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"实时(约 10 秒)","每 1 分钟","每 5 分钟(默认)"}));cadence.setSelection(2);settings.addView(cadence);
|
||||||
|
text("实时档更耗电和流量;更新受信号、网络与系统省电影响。调整名单或频率前,先关闭共享。",14,settings);
|
||||||
|
consent=new CheckBox(this);consent.setText("我已核对本人身份、有效期和所选查看人,同意按上述频率共享位置。关闭后停止采集并清除位置。");settings.addView(consent);
|
||||||
|
sharing=new Switch(this);sharing.setText("共享我的位置");sharing.setTextSize(20);sharing.setPadding(0,20,0,20);settings.addView(sharing);
|
||||||
|
sharing.setOnCheckedChangeListener((v,checked)->{if(rendering)return;if(checked)start();else{startService(new Intent(this,LocationService.class).setAction("STOP"));consent.setChecked(false);}render();});
|
||||||
|
button("打开手机系统定位设置",settings).setOnClickListener(v->startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)));
|
||||||
|
settings.setVisibility(prefs.getString("token","").isEmpty()?View.VISIBLE:View.GONE);
|
||||||
|
text("家人现在的位置",22,layout);viewStatus=text("",16,layout);
|
||||||
|
map=new LocationMapView(this);layout.addView(map,new LinearLayout.LayoutParams(-1,(int)(260*getResources().getDisplayMetrics().density)));
|
||||||
|
text("世界位置概览 · 可拖动、双指缩放;点家人卡片定位。底图为本地陆地轮廓,不含道路。",13,layout);
|
||||||
|
button("查看全部位置",layout).setOnClickListener(v->map.reset());
|
||||||
|
reload=button("刷新家人位置",layout);reload.setOnClickListener(v->loadFamily());
|
||||||
|
familyList=new LinearLayout(this);familyList.setOrientation(1);layout.addView(familyList);render();
|
||||||
}
|
}
|
||||||
void render(){
|
void render(){
|
||||||
boolean paired=!prefs.getString("token","").isEmpty(),active=prefs.getBoolean("active",false);
|
boolean paired=!prefs.getString("token","").isEmpty(),active=prefs.getBoolean("active",false),busy=pairing||LocationService.busy;
|
||||||
long expires=prefs.getLong("expires",0);
|
long expires=prefs.getLong("expires",0);
|
||||||
status.setText("成员:"+prefs.getString("memberName","尚未绑定")+"\n允许查看:"+prefs.getString("recipients","无")+"\n家庭:"+prefs.getString("home","尚未绑定")+"\n"+(expires>0?"有效期至 "+java.text.DateFormat.getDateTimeInstance().format(new java.util.Date(expires))+"\n":"")+prefs.getString("status","共享关闭"));
|
identity.setText(prefs.getString("memberName","尚未配对本人")+" · "+prefs.getString("home","请在我的位置设置中配对")+(expires>0?"\n配对有效至 "+java.text.DateFormat.getDateTimeInstance().format(new Date(expires)):""));
|
||||||
boolean busy=pairing||LocationService.busy;
|
status.setText(settingsError.isEmpty()?"我的位置:"+prefs.getString("status","共享关闭,不采集定位"):settingsError);
|
||||||
start.setEnabled(paired&&!active&&!busy);stop.setEnabled(paired&&!pairing);pair.setEnabled(!active&&!busy);consent.setEnabled(!active&&!busy);
|
rendering=true;sharing.setChecked(active);rendering=false;
|
||||||
|
sharing.setEnabled(paired&&!pairing&&(active||!busy&&settingsReady));
|
||||||
|
pair.setEnabled(!active&&!busy);cadence.setEnabled(!active&&!busy);consent.setEnabled(!active&&!busy);
|
||||||
|
for(List<CheckBox> list:choices.values())for(CheckBox c:list)c.setEnabled(!active&&!busy);
|
||||||
|
reload.setEnabled(paired&&!loading&&!pairing);
|
||||||
|
}
|
||||||
|
void remember(JSONObject response)throws Exception{
|
||||||
|
StringBuilder names=new StringBuilder();for(String type:new String[]{"viewers","phones","displays"}){JSONArray list=response.optJSONArray(type);if(list==null)continue;for(int i=0;i<list.length();i++){if(names.length()>0)names.append("、");names.append(list.getJSONObject(i).getString("name"));if(type.equals("displays"))names.append("(显示终端)");}}
|
||||||
|
prefs.edit().putString("receipt",response.getString("receipt")).putString("recipients",names.toString()).putInt("intervalSeconds",response.optInt("intervalSeconds",300)).apply();
|
||||||
}
|
}
|
||||||
void pair(){
|
void pair(){
|
||||||
if(pairing||LocationService.busy||prefs.getBoolean("active",false))return;
|
if(pairing||LocationService.busy||prefs.getBoolean("active",false))return;
|
||||||
String value=code.getText().toString().trim();if(!value.matches("[0-9]{8}")){Toast.makeText(this,"请输入八位配对码",1).show();return;}
|
String value=code.getText().toString().trim();if(!value.matches("[0-9]{8}")){Toast.makeText(this,"请输入八位手机配对码",1).show();return;}
|
||||||
pairing=true;render();
|
pairing=true;render();
|
||||||
new Thread(()->{try{
|
new Thread(()->{try{
|
||||||
JSONObject response=DisplayApi.call("/api/location/pair",null,new JSONObject().put("code",value).put("consentProtocol",2));
|
JSONObject response=DisplayApi.call("/api/location/pair",null,new JSONObject().put("code",value).put("consentProtocol",3));remember(response);
|
||||||
StringBuilder viewers=new StringBuilder();for(String type:new String[]{"viewers","displays"}){org.json.JSONArray list=response.getJSONArray(type);for(int i=0;i<list.length();i++){if(viewers.length()>0)viewers.append("、");viewers.append(list.getJSONObject(i).getString("name"));if(type.equals("displays"))viewers.append("(公共显示终端)");}}
|
prefs.edit().putString("memberName",response.getString("memberName")).putString("token",response.getString("token")).putString("home",response.getString("home")).putLong("expires",(long)(response.getDouble("expires")*1000)).putBoolean("active",false).putString("status","已配对;共享关闭,可查看获授权家人").apply();
|
||||||
prefs.edit().putString("memberName",response.getString("memberName")).putString("receipt",response.getString("receipt")).putString("recipients",viewers.toString()).putString("token",response.getString("token")).putString("home",response.getString("home")).putLong("expires",(long)(response.getDouble("expires")*1000)).putBoolean("active",false).putString("status","已绑定,尚未开启定位").apply();
|
runOnUiThread(()->{if(isDestroyed())return;pairing=false;generation++;loading=false;familyList.removeAllViews();map.setItems(new JSONArray());code.setText("");consent.setChecked(false);settingsReady=false;loadSettings();loadFamily();});
|
||||||
runOnUiThread(()->{code.setText("");consent.setChecked(false);render();});
|
}catch(Exception e){runOnUiThread(()->{if(!isDestroyed())Toast.makeText(this,"配对未成功,请检查手机配对码或安装新版 App",1).show();});}finally{pairing=false;runOnUiThread(()->{if(!isDestroyed())render();});}},"location-pair").start();
|
||||||
}catch(Exception e){runOnUiThread(()->Toast.makeText(this,"绑定未成功,请检查网络或重新获取配对码",1).show());}finally{pairing=false;runOnUiThread(this::render);}},"location-pair").start();
|
}
|
||||||
|
void loadFamily(){
|
||||||
|
String token=prefs.getString("token","");if(!visible||loading||token.isEmpty())return;
|
||||||
|
int g=generation;loading=true;lastList=SystemClock.elapsedRealtime();render();
|
||||||
|
new Thread(()->{try{
|
||||||
|
JSONObject response=DisplayApi.call("/api/location/update",token,new JSONObject().put("action","list"));
|
||||||
|
runOnUiThread(()->{if(!visible||g!=generation)return;JSONArray list=response.optJSONArray("items");map.setItems(list);familyList.removeAllViews();viewStatus.setText(list==null||list.length()==0?"尚无家人授权给这台手机的位置。请对方在自己的位置设置里勾选你的手机,并开启共享。":"只显示仍在授权有效期内的最新位置。");
|
||||||
|
if(list!=null)for(int i=0;i<list.length();i++){JSONObject row=list.optJSONObject(i);if(row==null)continue;JSONObject pos=row.optJSONObject("position");String detail=pos==null?("stale".equals(row.optString("status"))?"更新中断,旧坐标已隐藏":"等待定位") : String.format(Locale.CHINA,"纬度 %.5f · 经度 %.5f\n精度约 %.0f 米 · %s",pos.optDouble("latitude"),pos.optDouble("longitude"),pos.optDouble("accuracy"),java.text.DateFormat.getTimeInstance().format(new Date((long)(pos.optDouble("at")*1000))));Button item=button(row.optString("name")+"\n"+detail,familyList);item.setAllCaps(false);item.setOnClickListener(v->{if(pos!=null)map.focus(pos);});}
|
||||||
|
});
|
||||||
|
}catch(Exception e){runOnUiThread(()->{if(!visible||g!=generation)return;familyList.removeAllViews();map.setItems(new JSONArray());viewStatus.setText(e instanceof DisplayApi.ApiError&&((DisplayApi.ApiError)e).status==401?"手机配对已过期或解除,请重新配对。":"位置未能刷新,已隐藏旧画面,请检查网络。");});}finally{runOnUiThread(()->{if(g==generation){loading=false;render();}});}},"family-positions").start();
|
||||||
|
}
|
||||||
|
void loadSettings(){
|
||||||
|
String token=prefs.getString("token","");if(token.isEmpty()||pairing)return;int g=generation,request=++settingsRequest;settingsReady=false;settingsError="";render();
|
||||||
|
new Thread(()->{try{
|
||||||
|
JSONObject result=DisplayApi.call("/api/location/update",token,new JSONObject().put("action","settings"));
|
||||||
|
runOnUiThread(()->{if(!visible||g!=generation||request!=settingsRequest)return;settingsReceipt=result.optString("receipt");recipients.removeAllViews();choices.clear();
|
||||||
|
for(String type:new String[]{"viewers","phones","displays"}){String key=type.equals("viewers")?"viewerIds":type.equals("phones")?"phoneIds":"displayIds";text(type.equals("viewers")?"平台查看账号":type.equals("phones")?"已配对的家人手机":"公共显示终端",16,recipients);JSONArray options=result.optJSONArray(type),selected=result.optJSONArray(key);Set<String> ids=new HashSet<>();if(selected!=null)for(int i=0;i<selected.length();i++)ids.add(selected.optString(i));List<CheckBox> list=new ArrayList<>();choices.put(key,list);if(options!=null)for(int i=0;i<options.length();i++){JSONObject item=options.optJSONObject(i);CheckBox c=new CheckBox(this);c.setText(item.optString("name"));c.setTag(item.optString("id"));c.setChecked(ids.contains(item.optString("id")));recipients.addView(c);list.add(c);}if(list.isEmpty())text("暂无可选对象",14,recipients);}
|
||||||
|
int seconds=result.optInt("intervalSeconds",300);cadence.setSelection(seconds==10?0:seconds==60?1:2);settingsReady=true;render();});
|
||||||
|
}catch(Exception e){runOnUiThread(()->{if(visible&&g==generation&&request==settingsRequest){settingsReady=false;settingsError="无法读取我的位置设置,请检查网络或配对有效期,重新打开设置重试。";render();}});}},"location-settings").start();
|
||||||
}
|
}
|
||||||
void start(){
|
void start(){
|
||||||
if(pairing||LocationService.busy||prefs.getBoolean("active",false))return;
|
if(pairing||LocationService.busy||prefs.getBoolean("active",false)||!settingsReady)return;
|
||||||
if(!consent.isChecked()){Toast.makeText(this,"请本人阅读并勾选共享说明",1).show();return;}
|
if(!consent.isChecked()){Toast.makeText(this,"请本人核对并勾选共享说明",1).show();return;}
|
||||||
if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED&&checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},45);return;}
|
if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED&&checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},45);return;}
|
||||||
LocationService.busy=true;render();
|
if(!LocationService.locationEnabled((android.location.LocationManager)getSystemService(LOCATION_SERVICE))){Toast.makeText(this,"请先打开手机系统定位开关",1).show();return;}
|
||||||
try{startForegroundService(new Intent(this,LocationService.class).setAction("START"));}
|
final JSONObject body=new JSONObject();try{int total=0;for(Map.Entry<String,List<CheckBox>> e:choices.entrySet()){JSONArray ids=new JSONArray();for(CheckBox c:e.getValue())if(c.isChecked()){ids.put((String)c.getTag());total++;}body.put(e.getKey(),ids);}if(total==0){Toast.makeText(this,"请选择至少一位查看人;只看家人无需开启此开关",1).show();return;}body.put("action","configure").put("consent",true).put("receipt",settingsReceipt).put("intervalSeconds",new int[]{10,60,300}[cadence.getSelectedItemPosition()]);}catch(Exception e){return;}
|
||||||
catch(Exception e){LocationService.busy=false;render();Toast.makeText(this,"无法启动共享,请保持本页面在前台后重试",1).show();}
|
final int g=generation;final String token=prefs.getString("token","");pairing=true;settingsReady=false;settingsError="";render();
|
||||||
|
new Thread(()->{try{JSONObject result=DisplayApi.call("/api/location/update",token,body);remember(result);runOnUiThread(()->{if(!visible||g!=generation)return;settingsReceipt=result.optString("receipt");settingsReady=true;LocationService.busy=true;try{startForegroundService(new Intent(this,LocationService.class).setAction("START"));}catch(Exception e){LocationService.busy=false;Toast.makeText(this,"未能启动定位,请保持页面在前台再试",1).show();}render();});}
|
||||||
|
catch(Exception e){runOnUiThread(()->{if(visible&&g==generation)Toast.makeText(this,"开启未成功,请重新读取设置并核对名单",1).show();});}
|
||||||
|
finally{pairing=false;runOnUiThread(()->{if(!isDestroyed()){if(visible&&!settingsReady)loadSettings();render();}});}},"location-configure").start();
|
||||||
}
|
}
|
||||||
public void onRequestPermissionsResult(int request,String[] permissions,int[] results){super.onRequestPermissionsResult(request,permissions,results);if(request==45){if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)==0||checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)==0)start();else Toast.makeText(this,"未开启定位权限,不采集位置",1).show();}}
|
public void onRequestPermissionsResult(int request,String[] permissions,int[] results){super.onRequestPermissionsResult(request,permissions,results);if(request==45){if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)==0||checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)==0){if(visible)start();else pendingStart=true;}else Toast.makeText(this,"未授权定位,不采集自己的位置;仍可查看获授权家人",1).show();render();}}
|
||||||
|
public void onResume(){super.onResume();visible=true;lastList=0;if(!settingsReady)loadSettings();ui.post(refresh);if(pendingStart){pendingStart=false;start();}}
|
||||||
|
public void onPause(){visible=false;generation++;loading=false;ui.removeCallbacksAndMessages(null);if(map!=null)map.setItems(new JSONArray());if(familyList!=null)familyList.removeAllViews();super.onPause();}
|
||||||
public void onDestroy(){ui.removeCallbacksAndMessages(null);super.onDestroy();}
|
public void onDestroy(){ui.removeCallbacksAndMessages(null);super.onDestroy();}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package cn.ucvl.zhaodisplay;
|
||||||
|
|
||||||
|
/** Shared scheduling rule, independent of Android for deterministic testing. */
|
||||||
|
final class LocationCadence {
|
||||||
|
static int seconds(int value){return value==10||value==60||value==300?value:300;}
|
||||||
|
static boolean due(long now,long lastAttempt,int interval,boolean firstFix){
|
||||||
|
return lastAttempt==0||now-lastAttempt>=1000L*(firstFix?10:seconds(interval));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package cn.ucvl.zhaodisplay;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.graphics.*;
|
||||||
|
import android.view.*;
|
||||||
|
import org.json.*;
|
||||||
|
import java.io.*;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** Bundled Natural Earth outline; no coordinates sent to third-party map providers. */
|
||||||
|
final class LocationMapView extends View {
|
||||||
|
final Paint paint=new Paint(3);final List<JSONArray> rings=new ArrayList<>();
|
||||||
|
JSONArray items=new JSONArray();float zoom=1,lastX,lastY;double lon=0,lat=10;
|
||||||
|
final ScaleGestureDetector scale;
|
||||||
|
LocationMapView(Context context){super(context);setContentDescription("家人位置地图,可拖动和双指缩放");
|
||||||
|
try(InputStream input=context.getAssets().open("world-land.json")){ByteArrayOutputStream out=new ByteArrayOutputStream();byte[] buffer=new byte[4096];int n;while((n=input.read(buffer))>0)out.write(buffer,0,n);JSONArray polygons=new JSONObject(out.toString("UTF-8")).getJSONArray("features").getJSONObject(0).getJSONObject("geometry").getJSONArray("coordinates");for(int i=0;i<polygons.length();i++)rings.add(polygons.getJSONArray(i).getJSONArray(0));}catch(Exception ignored){}
|
||||||
|
scale=new ScaleGestureDetector(context,new ScaleGestureDetector.SimpleOnScaleGestureListener(){public boolean onScale(ScaleGestureDetector detector){zoom=Math.max(1,Math.min(64,zoom*detector.getScaleFactor()));invalidate();return true;}});
|
||||||
|
}
|
||||||
|
void setItems(JSONArray value){items=value==null?new JSONArray():value;invalidate();}
|
||||||
|
void reset(){zoom=1;lon=0;lat=10;invalidate();}
|
||||||
|
void focus(JSONObject point){lon=point.optDouble("longitude");lat=point.optDouble("latitude");zoom=16;invalidate();}
|
||||||
|
float x(double value){return getWidth()/2f+(float)(value-lon)*getWidth()/360f*zoom;}
|
||||||
|
float y(double value){return getHeight()/2f-(float)(value-lat)*getWidth()/360f*zoom;}
|
||||||
|
protected void onDraw(Canvas canvas){super.onDraw(canvas);canvas.drawColor(0xffe6eeea);paint.setColor(0xffceddd4);paint.setStyle(Paint.Style.FILL);
|
||||||
|
for(JSONArray ring:rings){Path path=new Path();for(int i=0;i<ring.length();i++){JSONArray p=ring.optJSONArray(i);float px=x(p.optDouble(0)),py=y(p.optDouble(1));if(i==0)path.moveTo(px,py);else path.lineTo(px,py);}path.close();canvas.drawPath(path,paint);}
|
||||||
|
float density=getResources().getDisplayMetrics().density;paint.setTextSize(14*density);
|
||||||
|
for(int i=0;i<items.length();i++){JSONObject person=items.optJSONObject(i),point=person.optJSONObject("position");if(point==null)continue;float px=x(point.optDouble("longitude")),py=y(point.optDouble("latitude"));paint.setColor(0xff287764);canvas.drawCircle(px,py,5*density,paint);paint.setColor(0xff183e31);canvas.drawText(person.optString("name"),px+8*density,py-8*density,paint);}
|
||||||
|
}
|
||||||
|
public boolean onTouchEvent(MotionEvent event){scale.onTouchEvent(event);if(event.getActionMasked()==MotionEvent.ACTION_DOWN){lastX=event.getX();lastY=event.getY();getParent().requestDisallowInterceptTouchEvent(true);return true;}if(event.getActionMasked()==MotionEvent.ACTION_MOVE){if(!scale.isInProgress()){float unit=getWidth()/360f*zoom;lon=Math.max(-180,Math.min(180,lon-(event.getX()-lastX)/unit));lat=Math.max(-90,Math.min(90,lat+(event.getY()-lastY)/unit));invalidate();}lastX=event.getX();lastY=event.getY();return true;}if(event.getActionMasked()==MotionEvent.ACTION_UP||event.getActionMasked()==MotionEvent.ACTION_CANCEL){getParent().requestDisallowInterceptTouchEvent(false);performClick();}return true;}
|
||||||
|
public boolean performClick(){super.performClick();return true;}
|
||||||
|
}
|
||||||
@@ -16,6 +16,7 @@ public class LocationService extends Service implements LocationListener {
|
|||||||
volatile boolean destroyed=false;
|
volatile boolean destroyed=false;
|
||||||
ScheduledExecutorService worker;LocationManager manager;android.content.SharedPreferences prefs;
|
ScheduledExecutorService worker;LocationManager manager;android.content.SharedPreferences prefs;
|
||||||
volatile Location latest;volatile boolean active=false,stopping=false,starting=false;
|
volatile Location latest;volatile boolean active=false,stopping=false,starting=false;
|
||||||
|
long lastAttempt=0;boolean sentFix=false;int intervalSeconds=300;String lastSignal="";
|
||||||
final Handler ui=new Handler();
|
final Handler ui=new Handler();
|
||||||
public void onCreate(){
|
public void onCreate(){
|
||||||
super.onCreate();prefs=getSharedPreferences("location",0);manager=(LocationManager)getSystemService(LOCATION_SERVICE);
|
super.onCreate();prefs=getSharedPreferences("location",0);manager=(LocationManager)getSystemService(LOCATION_SERVICE);
|
||||||
@@ -40,33 +41,44 @@ public class LocationService extends Service implements LocationListener {
|
|||||||
worker.execute(()->{try{
|
worker.execute(()->{try{
|
||||||
JSONObject r=DisplayApi.call("/api/location/update",sessionToken,new JSONObject().put("action","start").put("consent",true).put("receipt",receipt));
|
JSONObject r=DisplayApi.call("/api/location/update",sessionToken,new JSONObject().put("action","start").put("consent",true).put("receipt",receipt));
|
||||||
if(stopping||destroyed)return;
|
if(stopping||destroyed)return;
|
||||||
|
intervalSeconds=LocationCadence.seconds(r.optInt("intervalSeconds",300));
|
||||||
active=true;prefs.edit().putBoolean("active",true).putLong("expires",(long)(r.getDouble("expires")*1000)).putString("status","共享中,等待定位").apply();
|
active=true;prefs.edit().putBoolean("active",true).putLong("expires",(long)(r.getDouble("expires")*1000)).putString("status","共享中,等待定位").apply();
|
||||||
ui.post(()->{if(!stopping){listen();notification("共享给 "+prefs.getString("recipients","")+" · 可随时停止");}});
|
ui.post(()->{if(!stopping){listen();notification("共享给 "+prefs.getString("recipients","")+" · 可随时停止");}});
|
||||||
worker.scheduleWithFixedDelay(this::upload,1,300,TimeUnit.SECONDS);
|
worker.scheduleWithFixedDelay(this::upload,1,10,TimeUnit.SECONDS);
|
||||||
}catch(Exception e){if(!destroyed){prefs.edit().putBoolean("active",false).putString("status","未开启:请检查网络、配对有效期").apply();stopSelf();}}});
|
}catch(Exception e){if(!destroyed){prefs.edit().putBoolean("active",false).putString("status","未开启:请检查网络、配对有效期").apply();stopSelf();}}});
|
||||||
return START_NOT_STICKY;
|
return START_NOT_STICKY;
|
||||||
}
|
}
|
||||||
void listen(){
|
void listen(){
|
||||||
if(!active||stopping)return;
|
if(!active||stopping)return;
|
||||||
try{for(String provider:new String[]{LocationManager.GPS_PROVIDER,LocationManager.NETWORK_PROVIDER})if(manager.getAllProviders().contains(provider))manager.requestLocationUpdates(provider,300000,0,this);}
|
try{for(String provider:new String[]{LocationManager.GPS_PROVIDER,LocationManager.NETWORK_PROVIDER})if(manager.getAllProviders().contains(provider))manager.requestLocationUpdates(provider,intervalSeconds*1000L,0,this);}
|
||||||
catch(SecurityException e){prefs.edit().putString("status","定位权限未开启").apply();}
|
catch(SecurityException e){prefs.edit().putString("status","定位权限未开启").apply();}
|
||||||
}
|
}
|
||||||
void upload(){
|
void upload(){
|
||||||
if(!active||stopping)return;
|
if(!active||stopping)return;
|
||||||
if(System.currentTimeMillis()>prefs.getLong("expires",0)){ui.post(this::stopSharing);return;}
|
if(System.currentTimeMillis()>prefs.getLong("expires",0)){ui.post(this::stopSharing);return;}
|
||||||
try{
|
try{
|
||||||
String signal=checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED||checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)==PackageManager.PERMISSION_GRANTED?manager.isLocationEnabled()?"waiting":"location_disabled":"permission_denied";
|
String signal=checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED||checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)==PackageManager.PERMISSION_GRANTED?locationEnabled(manager)?"waiting":"location_disabled":"permission_denied";
|
||||||
|
// Permission/setting loss must clear the server fix without waiting five minutes.
|
||||||
|
boolean safetyChange=(!"waiting".equals(signal)&&!signal.equals(lastSignal));
|
||||||
|
if(!LocationCadence.due(SystemClock.elapsedRealtime(),lastAttempt,intervalSeconds,safetyChange||latest!=null&&!sentFix))return;
|
||||||
|
lastAttempt=SystemClock.elapsedRealtime();
|
||||||
JSONObject body=new JSONObject().put("action","update");Location fix=latest;
|
JSONObject body=new JSONObject().put("action","update");Location fix=latest;
|
||||||
if(fix!=null&&"waiting".equals(signal)&&SystemClock.elapsedRealtimeNanos()-fix.getElapsedRealtimeNanos()<900000000000L){
|
if(fix!=null&&"waiting".equals(signal)&&SystemClock.elapsedRealtimeNanos()-fix.getElapsedRealtimeNanos()<900000000000L){
|
||||||
body.put("position",new JSONObject().put("latitude",fix.getLatitude()).put("longitude",fix.getLongitude()).put("accuracy",fix.getAccuracy()).put("at",fix.getTime()/1000d));signal="available";
|
body.put("position",new JSONObject().put("latitude",fix.getLatitude()).put("longitude",fix.getLongitude()).put("accuracy",fix.getAccuracy()).put("at",fix.getTime()/1000d));signal="available";
|
||||||
}
|
}
|
||||||
body.put("signal",signal);DisplayApi.call("/api/location/update",sessionToken,body);
|
body.put("signal",signal);DisplayApi.call("/api/location/update",sessionToken,body);
|
||||||
|
lastSignal=signal;
|
||||||
|
if("available".equals(signal))sentFix=true;
|
||||||
if(stopping||destroyed)return;
|
if(stopping||destroyed)return;
|
||||||
String message="available".equals(signal)?"共享中 · 最近更新 "+java.text.DateFormat.getTimeInstance().format(new java.util.Date()):"共享中 · 等待定位,请检查手机定位和权限";
|
String message="available".equals(signal)?"共享中 · 最近更新 "+java.text.DateFormat.getTimeInstance().format(new java.util.Date()):"共享中 · 等待定位,请检查手机定位和权限";
|
||||||
prefs.edit().putString("status",message).apply();
|
prefs.edit().putString("status",message).apply();
|
||||||
}catch(DisplayApi.ApiError e){if(e.status==401||e.status==403)ui.post(this::stopSharing);else prefs.edit().putString("status","网络未同步,稍后自动重试").apply();}
|
}catch(DisplayApi.ApiError e){if(e.status==401||e.status==403)ui.post(this::stopSharing);else prefs.edit().putString("status","网络未同步,稍后自动重试").apply();}
|
||||||
catch(Exception e){prefs.edit().putString("status","网络未同步,稍后自动重试").apply();}
|
catch(Exception e){prefs.edit().putString("status","网络未同步,稍后自动重试").apply();}
|
||||||
}
|
}
|
||||||
|
static boolean locationEnabled(LocationManager manager){
|
||||||
|
if(Build.VERSION.SDK_INT>=28)return manager.isLocationEnabled();
|
||||||
|
return manager.isProviderEnabled(LocationManager.GPS_PROVIDER)||manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
|
||||||
|
}
|
||||||
void stopSharing(){
|
void stopSharing(){
|
||||||
if(stopping)return;stopping=true;busy=true;active=false;latest=null;
|
if(stopping)return;stopping=true;busy=true;active=false;latest=null;
|
||||||
try{manager.removeUpdates(this);}catch(Exception ignored){}
|
try{manager.removeUpdates(this);}catch(Exception ignored){}
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ public class MainActivity extends Activity {
|
|||||||
final Runnable themeTick=new Runnable(){public void run(){applyTimeMode();themeHandler.postDelayed(this,60000);}};
|
final Runnable themeTick=new Runnable(){public void run(){applyTimeMode();themeHandler.postDelayed(this,60000);}};
|
||||||
@Override public void onCreate(Bundle state) {
|
@Override public void onCreate(Bundle state) {
|
||||||
super.onCreate(state);
|
super.onCreate(state);
|
||||||
|
getSharedPreferences("display",0).edit().putBoolean("phoneMode",false).apply();
|
||||||
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||||
immersive();
|
immersive();
|
||||||
web=new WebView(this);
|
web=new WebView(this);
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package cn.ucvl.zhaodisplay;
|
||||||
|
|
||||||
|
/** Run with javac/java; requires no emulator and does not collect coordinates. */
|
||||||
|
public class LocationCadenceTest {
|
||||||
|
static void require(boolean value){if(!value)throw new AssertionError();}
|
||||||
|
public static void main(String[] args){
|
||||||
|
int assertions=0;
|
||||||
|
for(int seconds:new int[]{10,60,300}){
|
||||||
|
require(LocationCadence.seconds(seconds)==seconds);assertions++;
|
||||||
|
require(LocationCadence.due(100000,0,seconds,false));assertions++;
|
||||||
|
require(!LocationCadence.due(1000+seconds*1000L-1,1000,seconds,false));assertions++;
|
||||||
|
require(LocationCadence.due(1000+seconds*1000L,1000,seconds,false));assertions++;
|
||||||
|
require(!LocationCadence.due(10999,1000,seconds,true));assertions++;
|
||||||
|
require(LocationCadence.due(11000,1000,seconds,true));assertions++;
|
||||||
|
}
|
||||||
|
for(int invalid:new int[]{-1,0,9,59,301}){require(LocationCadence.seconds(invalid)==300);assertions++;}
|
||||||
|
System.out.println("Location cadence: "+assertions+" assertions passed");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -694,7 +694,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
path = url.urlsplit(self.path).path
|
path = url.urlsplit(self.path).path
|
||||||
if path == '/api/location/update':
|
if path == '/api/location/update':
|
||||||
authorization=self.headers.get('Authorization','')
|
authorization=self.headers.get('Authorization','')
|
||||||
self.answer(LOCATIONS.native(authorization[7:] if authorization.startswith('Bearer ') else '',self.body(4096)))
|
self.answer(LOCATIONS.native(authorization[7:] if authorization.startswith('Bearer ') else '',self.body(16384)))
|
||||||
return
|
return
|
||||||
if path in ('/api/display/heartbeat','/api/display/preview'):
|
if path in ('/api/display/heartbeat','/api/display/preview'):
|
||||||
authorization = self.headers.get('Authorization','')
|
authorization = self.headers.get('Authorization','')
|
||||||
|
|||||||
+17
-8
@@ -33,14 +33,19 @@ class Members:
|
|||||||
account = a.get_object('users', user['id']) or user
|
account = a.get_object('users', user['id']) or user
|
||||||
homes = a.HOUSEHOLDS.list(user)
|
homes = a.HOUSEHOLDS.list(user)
|
||||||
home_map = {h['id']: h for h in homes}
|
home_map = {h['id']: h for h in homes}
|
||||||
trees, placed = {}, set()
|
readable = {}
|
||||||
for home in homes:
|
for home in homes:
|
||||||
actor = a.HOUSEHOLDS.context(account, home['id'])
|
actor = a.HOUSEHOLDS.context(account, home['id'])
|
||||||
if not a.HOUSEHOLDS.manager(actor) and actor.get('familyAccess') not in ('read', 'edit'):
|
if home.get('kind', 'home') == 'home' and (a.HOUSEHOLDS.manager(actor) or actor.get('familyAccess') in ('read', 'edit')):
|
||||||
continue
|
readable.setdefault(a.HOUSEHOLDS.genealogy_of(home['id']), []).append(home['id'])
|
||||||
|
trees, placed = {}, set()
|
||||||
|
for home in homes:
|
||||||
tree = a.HOUSEHOLDS.genealogy_of(home['id'])
|
tree = a.HOUSEHOLDS.genealogy_of(home['id'])
|
||||||
if tree in trees:
|
if tree in trees or tree not in readable:
|
||||||
continue
|
continue
|
||||||
|
context_id = a.HOUSEHOLDS.scope(user)
|
||||||
|
context_id = context_id if context_id in readable[tree] else readable[tree][0]
|
||||||
|
actor = a.HOUSEHOLDS.context(account, context_id)
|
||||||
people = a.HOUSEHOLDS.objects(actor, 'people')
|
people = a.HOUSEHOLDS.objects(actor, 'people')
|
||||||
links = a.HOUSEHOLDS.objects(actor, 'family_links')
|
links = a.HOUSEHOLDS.objects(actor, 'family_links')
|
||||||
connected = {}
|
connected = {}
|
||||||
@@ -61,19 +66,22 @@ class Members:
|
|||||||
branch, level = connected[person['id']]
|
branch, level = connected[person['id']]
|
||||||
branches.setdefault(branch, {})[person['id']] = dict(
|
branches.setdefault(branch, {})[person['id']] = dict(
|
||||||
id=person['id'], name=person['name'], generation=level,
|
id=person['id'], name=person['name'], generation=level,
|
||||||
lifeStatus=person.get('lifeStatus', 'alive'), homes=[])
|
self=person['id'] == account.get('personId'),
|
||||||
|
lifeStatus=person.get('lifeStatus', 'alive'), homes=[], journalHomes=[])
|
||||||
for member in a.objects('family_members'):
|
for member in a.objects('family_members'):
|
||||||
if member['familyId'] not in home_map or member['personId'] not in connected:
|
if member['familyId'] not in home_map or member['personId'] not in connected:
|
||||||
continue
|
continue
|
||||||
if member['status'] == 'historical':
|
|
||||||
continue
|
|
||||||
pid = member['personId']
|
pid = member['personId']
|
||||||
branch, _ = connected[pid]
|
branch, _ = connected[pid]
|
||||||
|
branches[branch][pid]['journalHomes'].append(dict(
|
||||||
|
id=member['familyId'], name=home_map[member['familyId']]['name']))
|
||||||
|
if member['status'] == 'historical':
|
||||||
|
continue
|
||||||
branches[branch][pid]['homes'].append(dict(
|
branches[branch][pid]['homes'].append(dict(
|
||||||
id=member['familyId'], name=home_map[member['familyId']]['name'], status=member['status']))
|
id=member['familyId'], name=home_map[member['familyId']]['name'], status=member['status']))
|
||||||
placed.add(member['familyId'])
|
placed.add(member['familyId'])
|
||||||
trees[tree] = dict(
|
trees[tree] = dict(
|
||||||
id=tree, homes=[dict(id=h['id'], name=h['name']) for h in homes
|
id=tree, familyId=context_id, homes=[dict(id=h['id'], name=h['name']) for h in homes
|
||||||
if a.HOUSEHOLDS.genealogy_of(h['id']) == tree],
|
if a.HOUSEHOLDS.genealogy_of(h['id']) == tree],
|
||||||
branches=[dict(id=k, people=sorted(v.values(), key=lambda p: (p['generation'] or 100000, p['name'])))
|
branches=[dict(id=k, people=sorted(v.values(), key=lambda p: (p['generation'] or 100000, p['name'])))
|
||||||
for k, v in branches.items()])
|
for k, v in branches.items()])
|
||||||
@@ -99,6 +107,7 @@ class Members:
|
|||||||
items.append(dict(row, name=person['name'], lifeStatus=person.get('lifeStatus', 'alive'),
|
items.append(dict(row, name=person['name'], lifeStatus=person.get('lifeStatus', 'alive'),
|
||||||
hasAccount=bool(accounts), self=person['id'] == user.get('personId')))
|
hasAccount=bool(accounts), self=person['id'] == user.get('personId')))
|
||||||
return dict(items=items, canManage=a.HOUSEHOLDS.manager(user),
|
return dict(items=items, canManage=a.HOUSEHOLDS.manager(user),
|
||||||
|
canViewGenealogy=a.HOUSEHOLDS.manager(user) or user.get('familyAccess') in ('read', 'edit'),
|
||||||
genealogyId=a.HOUSEHOLDS.genealogy_of(family),
|
genealogyId=a.HOUSEHOLDS.genealogy_of(family),
|
||||||
genealogyHomes=[dict(id=h['id'], name=h['name']) for h in a.HOUSEHOLDS.list(user)
|
genealogyHomes=[dict(id=h['id'], name=h['name']) for h in a.HOUSEHOLDS.list(user)
|
||||||
if a.HOUSEHOLDS.genealogy_of(h['id']) == a.HOUSEHOLDS.genealogy_of(family)],
|
if a.HOUSEHOLDS.genealogy_of(h['id']) == a.HOUSEHOLDS.genealogy_of(family)],
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "zhao-steward-ui",
|
"name": "zhao-steward-ui",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.1.44",
|
"version": "0.1.45",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
<template>
|
<template>
|
||||||
<header><div><div class="eyebrow" id="brand-motto">赵氏家宅 · 起居有序</div><h1 id="page-title">我的家庭与场所</h1><p id="page-note">从一个空间,看到每一个位置。</p></div><div class="header-status"><span id="service-status" class="badge">等待连接</span><span id="clock"></span></div></header>
|
<header><div><div class="eyebrow" id="brand-motto">赵氏家宅 · 起居有序</div><h1 id="page-title">家族与家庭</h1><p id="page-note">从家人出发,连接每一代的亲情与记忆。</p></div><div class="header-status"><span id="service-status" class="badge">等待连接</span><span id="clock"></span></div></header>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -7,20 +7,20 @@ import AppIcon from './AppIcon.vue'
|
|||||||
<button id="mobile-nav-toggle" class="quiet mobile-nav-toggle" aria-expanded="false" aria-controls="main-navigation" type="button">☰ 菜单</button>
|
<button id="mobile-nav-toggle" class="quiet mobile-nav-toggle" aria-expanded="false" aria-controls="main-navigation" type="button">☰ 菜单</button>
|
||||||
<div class="nav-label">家宅 · 起居</div>
|
<div class="nav-label">家宅 · 起居</div>
|
||||||
<nav class="nav flex-column" id="main-navigation" aria-label="主导航">
|
<nav class="nav flex-column" id="main-navigation" aria-label="主导航">
|
||||||
<button data-page="households" class="active"><AppIcon name="home" /> <span>我的家庭与场所</span></button>
|
<button data-page="households" class="active"><AppIcon name="home" /> <span>家族与家庭</span></button>
|
||||||
<div id="scope-navigation" hidden><div id="scope-nav-name" class="nav-label"></div>
|
<div id="scope-navigation" hidden><div id="scope-nav-name" class="nav-label"></div>
|
||||||
<button data-page="journal"><AppIcon name="journal" /> <span>记事与阅历</span></button>
|
<button data-page="overview"><AppIcon name="grid" /> <span>家庭总览</span></button>
|
||||||
<button data-page="overview"><AppIcon name="grid" /> <span>场所总览</span></button>
|
|
||||||
<button data-page="objects"><AppIcon name="devices" /> <span>区域与设备</span></button>
|
|
||||||
<button data-page="heritage"><AppIcon name="tree" /> <span>家庭传承</span></button>
|
|
||||||
<button data-page="members"><AppIcon name="users" /> <span>家庭成员</span></button>
|
<button data-page="members"><AppIcon name="users" /> <span>家庭成员</span></button>
|
||||||
|
<button data-page="journal"><AppIcon name="journal" /> <span>记事与阅历</span></button>
|
||||||
|
<button data-page="heritage"><AppIcon name="tree" /> <span>家庭传承</span></button>
|
||||||
|
<button data-page="objects"><AppIcon name="devices" /> <span>区域与设备</span></button>
|
||||||
</div>
|
</div>
|
||||||
<button data-page="accounts"><AppIcon name="users" /> <span>系统用户</span></button>
|
<button data-page="accounts"><AppIcon name="users" /> <span>系统用户</span></button>
|
||||||
<button data-page="settings"><AppIcon name="settings" /> <span>设置中心</span></button>
|
<button data-page="settings"><AppIcon name="settings" /> <span>设置中心</span></button>
|
||||||
<a class="btn text-start text-reset" href="/downloads" target="_blank" rel="noreferrer">↓ 配套 App 下载</a>
|
<a class="btn text-start text-reset" href="/downloads" target="_blank" rel="noreferrer">↓ 配套 App 下载</a>
|
||||||
<button data-page="storage"><AppIcon name="database" /> <span>平台存储与审计</span></button>
|
<button data-page="storage"><AppIcon name="database" /> <span>平台存储与审计</span></button>
|
||||||
</nav>
|
</nav>
|
||||||
<div class="side-note"><span class="dot"></span> 独立部署 · 数据自有<p>按空间组织画面<br>让每一段记录有处可寻</p></div>
|
<div class="side-note"><span class="dot"></span> 独立部署 · 数据自有<p>记下每一位家人<br>让共同的记忆代代相传</p></div>
|
||||||
<p id="current-user" class="description"></p><button id="account-password" class="quiet" hidden>修改我的密码</button><button id="logout" class="quiet">退出登录</button>
|
<p id="current-user" class="description"></p><button id="account-password" class="quiet" hidden>修改我的密码</button><button id="logout" class="quiet">退出登录</button>
|
||||||
</aside>
|
</aside>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import {ref,computed,watch,onBeforeUnmount} from 'vue'
|
|||||||
import {snapshot,bridge} from '../composables/bridge.js'
|
import {snapshot,bridge} from '../composables/bridge.js'
|
||||||
import LocalChart from './LocalChart.vue'
|
import LocalChart from './LocalChart.vue'
|
||||||
const result=ref(null),error=ref(''),consent=ref(false),days=ref(7),code=ref(''),expires=ref(0),busy=ref(false),selected=ref('')
|
const result=ref(null),error=ref(''),consent=ref(false),days=ref(7),code=ref(''),expires=ref(0),busy=ref(false),selected=ref('')
|
||||||
const memberId=ref(''),viewerIds=ref([]),displayIds=ref([])
|
const memberId=ref(''),viewerIds=ref([]),displayIds=ref([]),phoneIds=ref([]),viewOnly=ref(true)
|
||||||
const binding=computed(()=>result.value?.bindings?.find(x=>x.memberId===memberId.value))
|
const binding=computed(()=>result.value?.bindings?.find(x=>x.memberId===memberId.value))
|
||||||
const active=computed(()=>snapshot.value.loggedIn&&snapshot.value.page==='overview')
|
const active=computed(()=>snapshot.value.loggedIn&&snapshot.value.page==='overview')
|
||||||
const home=computed(()=>snapshot.value.state.households?.find(x=>x.id===snapshot.value.state.familyId))
|
const home=computed(()=>snapshot.value.state.households?.find(x=>x.id===snapshot.value.state.familyId))
|
||||||
@@ -22,11 +22,11 @@ async function load(){const e=epoch,r=++requestId;if(!active.value)return
|
|||||||
finally{if(e===epoch&&r===requestId&&active.value)timer=setTimeout(load,30000)}
|
finally{if(e===epoch&&r===requestId&&active.value)timer=setTimeout(load,30000)}
|
||||||
}
|
}
|
||||||
async function action(name){if(busy.value)return;busy.value=true;error.value='';const e=epoch;requestId++;clearTimeout(timer)
|
async function action(name){if(busy.value)return;busy.value=true;error.value='';const e=epoch;requestId++;clearTimeout(timer)
|
||||||
try{const value=await bridge().api('/api/locations',{action:name,memberId:memberId.value,viewerIds:viewerIds.value,displayIds:displayIds.value,days:days.value});if(e!==epoch)return;code.value=value.code||'';expires.value=value.expires||0;if(name==='stop')consent.value=false;clearTimeout(timer);await load()}
|
try{const value=await bridge().api('/api/locations',{action:name,memberId:memberId.value,viewerIds:viewerIds.value,displayIds:displayIds.value,phoneIds:phoneIds.value,viewOnly:viewOnly.value,days:days.value});if(e!==epoch)return;code.value=value.code||'';expires.value=value.expires||0;if(name==='stop')consent.value=false;clearTimeout(timer);await load()}
|
||||||
catch(err){if(e===epoch)error.value=err.message}finally{if(e===epoch){busy.value=false;clearTimeout(timer);if(active.value)timer=setTimeout(load,30000)}}
|
catch(err){if(e===epoch)error.value=err.message}finally{if(e===epoch){busy.value=false;clearTimeout(timer);if(active.value)timer=setTimeout(load,30000)}}
|
||||||
}
|
}
|
||||||
watch([active,()=>snapshot.value.state.familyId,()=>snapshot.value.session],()=>{epoch++;clearTimeout(timer);result.value=null;code.value='';memberId.value='';viewerIds.value=[];displayIds.value=[];selected.value='';consent.value=false;busy.value=false;if(active.value)load()},{immediate:true})
|
watch([active,()=>snapshot.value.state.familyId,()=>snapshot.value.session],()=>{epoch++;clearTimeout(timer);result.value=null;code.value='';memberId.value='';viewerIds.value=[];displayIds.value=[];phoneIds.value=[];viewOnly.value=true;selected.value='';consent.value=false;busy.value=false;if(active.value)load()},{immediate:true})
|
||||||
watch([memberId,viewerIds,displayIds,days],()=>{code.value=''}, {deep:true})
|
watch([memberId,viewerIds,displayIds,phoneIds,viewOnly,days],()=>{code.value=''}, {deep:true})
|
||||||
onBeforeUnmount(()=>{epoch++;clearTimeout(timer)})
|
onBeforeUnmount(()=>{epoch++;clearTimeout(timer)})
|
||||||
</script>
|
</script>
|
||||||
<template><section v-if="active" class="panel family-locations mb-4" aria-label="家庭位置共享">
|
<template><section v-if="active" class="panel family-locations mb-4" aria-label="家庭位置共享">
|
||||||
@@ -37,13 +37,13 @@ onBeforeUnmount(()=>{epoch++;clearTimeout(timer)})
|
|||||||
<details class="mt-3 border-top pt-3"><summary>为家庭成员配对手机</summary>
|
<details class="mt-3 border-top pt-3"><summary>为家庭成员配对手机</summary>
|
||||||
<p class="small text-secondary mt-2">老人和孩子无需登录。先选择真实成员及具体查看人,再将配对码输入本人的手机。本人核对授权内容、允许定位并打开共享后才上传;管理员生成配对码不能代替本人同意。家庭屏需单独勾选。</p>
|
<p class="small text-secondary mt-2">老人和孩子无需登录。先选择真实成员及具体查看人,再将配对码输入本人的手机。本人核对授权内容、允许定位并打开共享后才上传;管理员生成配对码不能代替本人同意。家庭屏需单独勾选。</p>
|
||||||
<p v-if="!result?.members?.length" class="alert alert-info">请先在“家庭成员”登记本人或家人;普通账号需关联本人档案。</p>
|
<p v-if="!result?.members?.length" class="alert alert-info">请先在“家庭成员”登记本人或家人;普通账号需关联本人档案。</p>
|
||||||
<form v-else @submit.prevent="action('pair')"><div class="row g-3"><label class="col-sm-8">绑定的家庭成员<select v-model="memberId" required class="form-select" :disabled="busy"><option value="">请选择成员</option><option v-for="m in result.members" :key="m.id" :value="m.id" :disabled="m.status==='historical'||m.lifeStatus==='deceased'">{{m.name}} {{m.label?`· ${m.label}`:''}}</option></select></label><label class="col-sm-4">共享有效期<select v-model.number="days" class="form-select" :disabled="busy"><option :value="1">1 天</option><option :value="7">7 天</option><option :value="30">30 天</option></select></label></div>
|
<form v-else @submit.prevent="action('pair')"><div class="row g-3"><label class="col-sm-8">绑定的家庭成员<select v-model="memberId" required class="form-select" :disabled="busy"><option value="">请选择成员</option><option v-for="m in result.members" :key="m.id" :value="m.id" :disabled="m.status==='historical'||m.lifeStatus==='deceased'">{{m.name}} {{m.label?`· ${m.label}`:''}}</option></select></label><label class="col-sm-4">手机配对有效期<select v-model.number="days" class="form-select" :disabled="busy"><option :value="1">1 天</option><option :value="7">7 天</option><option :value="30">30 天</option></select></label></div>
|
||||||
<fieldset class="mt-3"><legend class="fs-6">允许哪些账号查看</legend><label v-for="u in result.viewers" :key="u.id" class="d-inline-flex gap-2 me-4 mb-2"><input type="checkbox" v-model="viewerIds" :value="u.id" :disabled="busy">{{u.name}}({{u.username}})</label></fieldset>
|
<label class="d-flex gap-2 mt-3"><input type="checkbox" v-model="viewOnly" :disabled="busy">先仅配对手机查看家人,本人可稍后在手机设置自己的共享</label><fieldset v-if="!viewOnly" class="mt-3"><legend class="fs-6">允许哪些账号查看</legend><label v-for="u in result.viewers" :key="u.id" class="d-inline-flex gap-2 me-4 mb-2"><input type="checkbox" v-model="viewerIds" :value="u.id" :disabled="busy">{{u.name}}({{u.username}})</label></fieldset>
|
||||||
<fieldset class="mt-3"><legend class="fs-6">允许哪些公共显示终端展示(默认不选)</legend><p v-if="!result.displays.length" class="small text-secondary">尚无已配对显示终端。</p><label v-for="d in result.displays" :key="d.id" class="d-inline-flex gap-2 me-4 mb-2"><input type="checkbox" v-model="displayIds" :value="d.id" :disabled="busy">{{d.name}}</label></fieldset>
|
<fieldset v-if="!viewOnly" class="mt-3"><legend class="fs-6">允许哪些家人手机查看</legend><label v-for="p in result.phones||[]" :key="p.id" class="d-inline-flex gap-2 me-4 mb-2"><input type="checkbox" v-model="phoneIds" :value="p.id" :disabled="busy">{{p.name}}的手机</label></fieldset><fieldset v-if="!viewOnly" class="mt-3"><legend class="fs-6">允许哪些公共显示终端展示(默认不选)</legend><p v-if="!result.displays.length" class="small text-secondary">尚无已配对显示终端。</p><label v-for="d in result.displays" :key="d.id" class="d-inline-flex gap-2 me-4 mb-2"><input type="checkbox" v-model="displayIds" :value="d.id" :disabled="busy">{{d.name}}</label></fieldset>
|
||||||
<p v-if="binding">{{binding.enabled?'手机已开启共享':'手机已绑定,共享关闭'}} · {{time(binding.expires)}} 到期</p>
|
<p v-if="binding">{{binding.enabled?'手机已开启共享':'手机已绑定,共享关闭'}} · {{time(binding.expires)}} 到期</p>
|
||||||
<div class="d-flex flex-wrap gap-2 mt-3"><button class="btn btn-primary" :disabled="busy||!memberId||(!viewerIds.length&&!displayIds.length)">生成配对码</button><button v-if="binding||code" type="button" class="btn btn-outline-danger" :disabled="busy" @click="action('stop')">解除该手机授权</button><a class="btn btn-outline-secondary" href="/downloads" target="_blank" rel="noreferrer">下载配套 App</a></div>
|
<div class="d-flex flex-wrap gap-2 mt-3"><button class="btn btn-primary" :disabled="busy||!memberId||(!viewOnly&&!viewerIds.length&&!displayIds.length&&!phoneIds.length)">生成配对码</button><button v-if="binding||code" type="button" class="btn btn-outline-danger" :disabled="busy" @click="action('stop')">解除该手机授权</button><a class="btn btn-outline-secondary" href="/downloads" target="_blank" rel="noreferrer">下载配套 App</a></div>
|
||||||
<div v-if="code" class="alert alert-success mt-3" role="status">配对码 <strong class="font-monospace fs-3">{{code}}</strong> · 10 分钟内使用一次<br>请在成员本人的手机核对姓名与查看名单,共享截至 {{time(expires)}}。重新配对会替换旧手机授权。</div>
|
<div v-if="code" class="alert alert-success mt-3" role="status">配对码 <strong class="font-monospace fs-3">{{code}}</strong> · 10 分钟内使用一次<br>请在成员本人的手机核对姓名与查看名单,手机授权有效至 {{time(expires)}}。重新配对会替换旧手机授权。</div>
|
||||||
</form><p class="small text-secondary mt-3">约每 5 分钟更新,仅保存内存中的最新位置。关闭共享后清除;定位或网络中断超过 15 分钟隐藏旧坐标,提示更新中断,不表示人员失联。</p></details>
|
</form><p class="small text-secondary mt-3">手机可在“我的位置设置”选择实时(约 10 秒)、1 分钟或 5 分钟上传,默认 5 分钟;仅保存内存中的最新位置。关闭共享后清除;定位或网络中断超过 15 分钟隐藏旧坐标,提示更新中断,不表示人员失联。</p></details>
|
||||||
<p v-if="error" class="text-danger mt-2" role="alert">{{error}}</p>
|
<p v-if="error" class="text-danger mt-2" role="alert">{{error}}</p>
|
||||||
</section></template>
|
</section></template>
|
||||||
<style scoped>.family-locations h2{font-size:1.3rem}.location-empty{display:grid;align-content:center;min-height:270px;text-align:center;color:var(--ui-muted,#64776f);padding:1rem}.location-empty>span{font-size:3rem;color:#6c9685}.location-person{display:flex;flex-direction:column;gap:.35rem;background:var(--panel,#fff);border:1px solid var(--ui-line,#d9e3dd);border-radius:12px;padding:14px;margin-bottom:10px;color:var(--ink,#243c32)}.location-person>span,.location-person small{font-size:.85rem}.location-selected{border-color:#257a68;box-shadow:inset 3px 0 #257a68}.family-locations summary{cursor:pointer}.family-locations input[type=checkbox]{min-width:18px;width:18px;min-height:18px}</style>
|
<style scoped>.family-locations h2{font-size:1.3rem}.location-empty{display:grid;align-content:center;min-height:270px;text-align:center;color:var(--ui-muted,#64776f);padding:1rem}.location-empty>span{font-size:3rem;color:#6c9685}.location-person{display:flex;flex-direction:column;gap:.35rem;background:var(--panel,#fff);border:1px solid var(--ui-line,#d9e3dd);border-radius:12px;padding:14px;margin-bottom:10px;color:var(--ink,#243c32)}.location-person>span,.location-person small{font-size:.85rem}.location-selected{border-color:#257a68;box-shadow:inset 3px 0 #257a68}.family-locations summary{cursor:pointer}.family-locations input[type=checkbox]{min-width:18px;width:18px;min-height:18px}</style>
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ watch([active,()=>snapshot.value.state.familyId,()=>snapshot.value.session],()=>
|
|||||||
function edit(member){draft.value=member?{id:member.id,revision:member.revision,personId:member.personId,name:member.name,label:member.label,status:member.status}:{name:'',personId:'',label:'',status:'active',revision:0}}
|
function edit(member){draft.value=member?{id:member.id,revision:member.revision,personId:member.personId,name:member.name,label:member.label,status:member.status}:{name:'',personId:'',label:'',status:'active',revision:0}}
|
||||||
async function save(){if(busy.value)return;busy.value=true;error.value='';const e=epoch;try{await bridge().api('/api/members',draft.value);if(e!==epoch)return;draft.value=null;await load();await bridge().refresh()}catch(err){if(e===epoch)error.value=err.message}finally{busy.value=false}}
|
async function save(){if(busy.value)return;busy.value=true;error.value='';const e=epoch;try{await bridge().api('/api/members',draft.value);if(e!==epoch)return;draft.value=null;await load();await bridge().refresh()}catch(err){if(e===epoch)error.value=err.message}finally{busy.value=false}}
|
||||||
async function share(){if(busy.value)return;busy.value=true;error.value='';const e=epoch;try{await bridge().api('/api/genealogy/share',{targetFamilyId:target.value,confirm:confirm.value});if(e!==epoch)return;confirm.value=false;target.value='';await load();await bridge().refresh()}catch(err){if(e===epoch)error.value=err.message}finally{busy.value=false}}
|
async function share(){if(busy.value)return;busy.value=true;error.value='';const e=epoch;try{await bridge().api('/api/genealogy/share',{targetFamilyId:target.value,confirm:confirm.value});if(e!==epoch)return;confirm.value=false;target.value='';await load();await bridge().refresh()}catch(err){if(e===epoch)error.value=err.message}finally{busy.value=false}}
|
||||||
|
async function view(member,history=false){if(busy.value)return;const e=epoch;busy.value=true;error.value='';try{if(history)await bridge().viewMemberHistory(member.personId,member.name,snapshot.value.state.familyId);else await bridge().viewPerson(member.personId,snapshot.value.state.familyId)}catch(err){if(e===epoch&&!err.stale)error.value=err.message}finally{if(e===epoch)busy.value=false}}
|
||||||
</script>
|
</script>
|
||||||
<template><section v-if="active" class="panel">
|
<template><section v-if="active" class="panel">
|
||||||
<div class="d-flex justify-content-between flex-wrap gap-3"><div><h2>家庭成员</h2><p class="text-secondary">登记真实家人。老人、孩子无需账号;亲属关系与登录权限分别管理。</p></div><button v-if="data?.canManage" class="btn btn-primary align-self-start" @click="edit()">+ 登记成员</button></div>
|
<div class="d-flex justify-content-between flex-wrap gap-3"><div><h2>家庭成员</h2><p class="text-secondary">登记真实家人。老人、孩子无需账号;亲属关系与登录权限分别管理。</p></div><button v-if="data?.canManage" class="btn btn-primary align-self-start" @click="edit()">+ 登记成员</button></div>
|
||||||
@@ -19,10 +20,10 @@ async function share(){if(busy.value)return;busy.value=true;error.value='';const
|
|||||||
<label v-if="!draft.id" class="d-block mb-3">关联已有族谱人物<select class="form-select" v-model="draft.personId"><option value="">新建人物(尚未录入族谱)</option><option v-for="p in data?.candidates||[]" :key="p.id" :value="p.id">{{p.name}}</option></select></label>
|
<label v-if="!draft.id" class="d-block mb-3">关联已有族谱人物<select class="form-select" v-model="draft.personId"><option value="">新建人物(尚未录入族谱)</option><option v-for="p in data?.candidates||[]" :key="p.id" :value="p.id">{{p.name}}</option></select></label>
|
||||||
<label v-if="!draft.personId" class="d-block mb-3">姓名<input v-model="draft.name" class="form-control" maxlength="80" required></label><p v-else-if="draft.id">人物:{{draft.name}}。姓名、生平及亲属关系在族谱中维护,仍遵守五代限制。</p>
|
<label v-if="!draft.personId" class="d-block mb-3">姓名<input v-model="draft.name" class="form-control" maxlength="80" required></label><p v-else-if="draft.id">人物:{{draft.name}}。姓名、生平及亲属关系在族谱中维护,仍遵守五代限制。</p>
|
||||||
<div class="row g-3"><label class="col-md-6">家庭称呼/身份备注<input v-model="draft.label" class="form-control" maxlength="60" placeholder="例如:妈妈、长子、亲友"></label><label class="col-md-6">成员状态<select v-model="draft.status" class="form-select"><option value="active">当前成员</option><option value="away">暂住外地</option><option value="historical">历史成员</option></select></label></div>
|
<div class="row g-3"><label class="col-md-6">家庭称呼/身份备注<input v-model="draft.label" class="form-control" maxlength="60" placeholder="例如:妈妈、长子、亲友"></label><label class="col-md-6">成员状态<select v-model="draft.status" class="form-select"><option value="active">当前成员</option><option value="away">暂住外地</option><option value="historical">历史成员</option></select></label></div>
|
||||||
<p class="small text-secondary mt-2">称呼是本家庭的备注,不自动建立父母、配偶关系或授予管理权限。迁居、历史成员状态不会删除人物和经历。</p>
|
<p class="small text-secondary mt-2">称呼是本家庭的备注,不自动建立父母、配偶关系或授予管理权限。成员状态不会删除人物和经历;住在外地也可以是家人。</p>
|
||||||
<div class="d-flex gap-2"><button class="btn btn-primary" :disabled="busy">保存成员</button><button type="button" class="btn btn-outline-secondary" :disabled="busy" @click="draft=null">取消</button></div>
|
<div class="d-flex gap-2"><button class="btn btn-primary" :disabled="busy">保存成员</button><button type="button" class="btn btn-outline-secondary" :disabled="busy" @click="draft=null">取消</button></div>
|
||||||
</form>
|
</form>
|
||||||
<div class="row g-3"><article v-for="m in data?.items||[]" :key="m.id" class="col-md-6 col-xl-4"><div class="card h-100"><div class="card-body"><h3 class="fs-5">{{m.name}} <span v-if="m.self" class="badge text-bg-success">本人</span></h3><p>{{m.label||'家庭身份待补充'}} · {{({active:'当前成员',away:'暂住外地',historical:'历史成员'})[m.status]}}</p><p class="small text-secondary">{{m.hasAccount?'已有关联账号':'无需注册账号'}}{{m.lifeStatus==='deceased'?' · 已故':''}}</p><button v-if="data.canManage" class="btn btn-sm btn-outline-secondary" @click="edit(m)">编辑成员关系</button></div></div></article></div>
|
<div class="row g-3"><article v-for="m in data?.items||[]" :key="m.id" class="col-md-6 col-xl-4"><div class="card h-100" :class="{'border-primary bg-primary-subtle':m.self}"><div class="card-body"><h3 class="fs-5">{{m.name}} <span v-if="m.self" class="badge text-bg-success">本人</span></h3><p>{{m.label||'家庭身份待补充'}} · {{({active:'当前成员',away:'暂住外地',historical:'历史成员'})[m.status]}}</p><p class="small text-secondary">{{m.hasAccount?'已有关联账号':'无需注册账号'}}{{m.lifeStatus==='deceased'?' · 已故':''}}</p><div class="d-flex flex-wrap gap-2"><button v-if="data.canViewGenealogy" class="btn btn-sm btn-outline-primary" :disabled="busy" @click="view(m)">人物与亲属</button><button class="btn btn-sm btn-outline-primary" :disabled="busy" @click="view(m,true)">个人阅历</button><button v-if="data.canManage" class="btn btn-sm btn-outline-secondary" :disabled="busy" @click="edit(m)">编辑成员关系</button></div></div></div></article></div>
|
||||||
<p v-if="data&&!data.items.length" class="alert alert-info mt-3">还没有登记成员。已有族谱人物可直接关联,避免重复建人。</p>
|
<p v-if="data&&!data.items.length" class="alert alert-info mt-3">还没有登记成员。已有族谱人物可直接关联,避免重复建人。</p>
|
||||||
<details v-if="snapshot.platformAdmin" class="border-top pt-3 mt-4"><summary>与相关家庭共用族谱</summary><p class="small text-secondary mt-2">相关家庭共用人物与亲属关系;活动、设备、位置授权继续独立。现有同名人物不会自动合并,需核对身份。世代范围限制继续有效。</p><p>当前已关联:{{data?.genealogyHomes?.map(h=>h.name).join('、')}}</p><form @submit.prevent="share"><label>关联家庭<select v-model="target" class="form-select" required><option value="">请选择</option><option v-for="h in homes" :value="h.id" :key="h.id">{{h.name}}</option></select></label><label class="d-flex gap-2 my-3"><input v-model="confirm" type="checkbox" required>确认双方族谱人物与关系共用,有族谱查看权限的账号可以查看合并后的族谱</label><button class="btn btn-outline-primary" :disabled="busy||!confirm||!target">确认共用族谱</button></form></details>
|
<details v-if="snapshot.platformAdmin" class="border-top pt-3 mt-4"><summary>与相关家庭共用族谱</summary><p class="small text-secondary mt-2">相关家庭共用人物与亲属关系;活动、设备、位置授权继续独立。现有同名人物不会自动合并,需核对身份。世代范围限制继续有效。</p><p>当前已关联:{{data?.genealogyHomes?.map(h=>h.name).join('、')}}</p><form @submit.prevent="share"><label>关联家庭<select v-model="target" class="form-select" required><option value="">请选择</option><option v-for="h in homes" :value="h.id" :key="h.id">{{h.name}}</option></select></label><label class="d-flex gap-2 my-3"><input v-model="confirm" type="checkbox" required>确认双方族谱人物与关系共用,有族谱查看权限的账号可以查看合并后的族谱</label><button class="btn btn-outline-primary" :disabled="busy||!confirm||!target">确认共用族谱</button></form></details>
|
||||||
</section></template>
|
</section></template>
|
||||||
|
|||||||
@@ -1,15 +1,17 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { ref, watch } from 'vue';
|
import { computed, ref, watch } from 'vue';
|
||||||
import { bridge, snapshot } from '../composables/bridge.js';
|
import { bridge, snapshot } from '../composables/bridge.js';
|
||||||
|
|
||||||
const props = defineProps({ active: Boolean });
|
const props = defineProps({ active: Boolean });
|
||||||
const data = ref(null), error = ref('');
|
const data = ref(null), error = ref(''), search = ref(''), busy = ref(false);
|
||||||
let epoch = 0;
|
let epoch = 0;
|
||||||
|
|
||||||
async function load() {
|
async function load() {
|
||||||
const request = ++epoch;
|
const request = ++epoch;
|
||||||
data.value = null;
|
data.value = null;
|
||||||
error.value = '';
|
error.value = '';
|
||||||
|
search.value = '';
|
||||||
|
busy.value = false;
|
||||||
if (!props.active || !snapshot.value.loggedIn) return;
|
if (!props.active || !snapshot.value.loggedIn) return;
|
||||||
try {
|
try {
|
||||||
const result = await bridge().api('/api/family-directory');
|
const result = await bridge().api('/api/family-directory');
|
||||||
@@ -21,16 +23,40 @@ async function load() {
|
|||||||
watch(() => [props.active, snapshot.value.loggedIn, snapshot.value.session], load, { immediate: true });
|
watch(() => [props.active, snapshot.value.loggedIn, snapshot.value.session], load, { immediate: true });
|
||||||
const label = n => n ? (n <= 10 ? ['', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'][n] : '第' + n) + '世' : '世次待考';
|
const label = n => n ? (n <= 10 ? ['', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'][n] : '第' + n) + '世' : '世次待考';
|
||||||
const levels = people => [...new Set(people.map(p => p.generation))];
|
const levels = people => [...new Set(people.map(p => p.generation))];
|
||||||
|
const trees = computed(() => {
|
||||||
|
const term = search.value.trim().toLocaleLowerCase();
|
||||||
|
return (data.value?.trees || []).map(tree => ({...tree, branches: tree.branches.map(branch => ({...branch,
|
||||||
|
people: branch.people.filter(p => !term || [p.name, ...p.homes.map(h => h.name)].join(' ').toLocaleLowerCase().includes(term))
|
||||||
|
})).filter(branch => branch.people.length)})).filter(tree => !term || tree.branches.length);
|
||||||
|
});
|
||||||
|
const count = computed(() => new Set((data.value?.trees || []).flatMap(t => t.branches.flatMap(b => b.people.map(p => p.id)))).size);
|
||||||
|
async function openPerson(person, familyId, history = false) {
|
||||||
|
if (busy.value) return;
|
||||||
|
const request = epoch;
|
||||||
|
busy.value = true;
|
||||||
|
error.value = '';
|
||||||
|
try {
|
||||||
|
if (history) await bridge().viewMemberHistory(person.id, person.name, familyId);
|
||||||
|
else await bridge().viewPerson(person.id, familyId);
|
||||||
|
} catch (err) {
|
||||||
|
if (request === epoch && !err.stale) error.value = err.message;
|
||||||
|
} finally {
|
||||||
|
if (request === epoch) busy.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<section v-if="active" class="panel" aria-label="按世代浏览家庭">
|
<section v-if="active" class="panel" aria-label="按世代浏览家庭">
|
||||||
<h2>家族世代与家庭</h2>
|
<div class="d-flex justify-content-between align-items-start flex-wrap gap-3">
|
||||||
<p class="text-secondary">从长辈到晚辈,按亲属关系展开,再进入家人关联的家庭。</p>
|
<div><h2>家族世代 <span v-if="data" class="count-pill">{{ count }} 位家人</span></h2>
|
||||||
|
<p class="text-secondary">从长辈到晚辈,查看每个人的亲属、故事与家庭。一个家庭可以包含多代人。</p></div>
|
||||||
|
<label class="mb-3">找家人<input v-model="search" type="search" class="form-control" placeholder="姓名或家庭名称" :disabled="!data"></label>
|
||||||
|
</div>
|
||||||
<p class="small text-secondary">一世从本支已知最早一代相对起算,不代表历史族谱中的绝对世次。未连接的分支分别展示,关系不足时标为“世次待考”。</p>
|
<p class="small text-secondary">一世从本支已知最早一代相对起算,不代表历史族谱中的绝对世次。未连接的分支分别展示,关系不足时标为“世次待考”。</p>
|
||||||
<div v-if="error" class="alert alert-danger" role="alert">{{ error }} <button class="btn btn-sm btn-outline-danger ms-2" @click="load">重新加载</button></div>
|
<div v-if="error" class="alert alert-danger" role="alert">{{ error }} <button class="btn btn-sm btn-outline-danger ms-2" @click="load">重新加载</button></div>
|
||||||
<p v-else-if="!data" role="status" class="text-secondary">正在整理世代关系…</p>
|
<p v-else-if="!data" role="status" class="text-secondary">正在整理世代关系…</p>
|
||||||
<details v-for="tree in data?.trees || []" :key="tree.id" class="border rounded p-3 mb-3" open>
|
<details v-for="tree in trees" :key="tree.id" class="border rounded p-3 mb-3" open>
|
||||||
<summary class="fw-semibold">共用族谱 · {{ tree.homes.map(h => h.name).join('、') }}</summary>
|
<summary class="fw-semibold">共用族谱 · {{ tree.homes.map(h => h.name).join('、') }}</summary>
|
||||||
<p v-if="!tree.branches.length" class="mt-3 text-secondary">请先登记家庭成员,再连接亲属关系。</p>
|
<p v-if="!tree.branches.length" class="mt-3 text-secondary">请先登记家庭成员,再连接亲属关系。</p>
|
||||||
<section v-for="(branch, index) in tree.branches" :key="branch.id" class="mt-4">
|
<section v-for="(branch, index) in tree.branches" :key="branch.id" class="mt-4">
|
||||||
@@ -39,22 +65,27 @@ const levels = people => [...new Set(people.map(p => p.generation))];
|
|||||||
<summary class="fw-semibold text-primary">{{ label(level) }} <small class="fw-normal text-secondary ms-2">{{ branch.people.filter(p => p.generation === level).length }} 人</small></summary>
|
<summary class="fw-semibold text-primary">{{ label(level) }} <small class="fw-normal text-secondary ms-2">{{ branch.people.filter(p => p.generation === level).length }} 人</small></summary>
|
||||||
<div class="row g-3 mt-1">
|
<div class="row g-3 mt-1">
|
||||||
<article v-for="person in branch.people.filter(p => p.generation === level)" :key="person.id" class="col-12 col-md-6 col-xl-4">
|
<article v-for="person in branch.people.filter(p => p.generation === level)" :key="person.id" class="col-12 col-md-6 col-xl-4">
|
||||||
<div class="card h-100"><div class="card-body">
|
<div class="card h-100" :class="{'border-primary bg-primary-subtle':person.self}"><div class="card-body">
|
||||||
<strong>{{ person.name }}</strong><small v-if="person.lifeStatus === 'deceased'" class="text-secondary ms-2">已故</small>
|
<button class="btn btn-link p-0 fw-semibold fs-5 text-start" :disabled="busy" @click="openPerson(person,tree.familyId)">{{ person.name }}</button><span v-if="person.self" class="badge text-bg-primary ms-2">本人</span><small v-if="person.lifeStatus === 'deceased'" class="text-secondary ms-2">已故</small>
|
||||||
|
<p class="small text-secondary mt-2 mb-0">{{ person.self ? '当前账号关联的家人' : '人物档案 · 亲属关系 · 生平' }}</p>
|
||||||
<div class="d-flex flex-wrap gap-2 mt-3">
|
<div class="d-flex flex-wrap gap-2 mt-3">
|
||||||
<button v-for="home in person.homes" :key="home.id" class="btn btn-sm btn-outline-primary" @click="bridge().enterHome(home.id)">{{ home.name }} →</button>
|
<button v-for="home in person.homes" :key="home.id" class="btn btn-sm btn-outline-primary" @click="bridge().enterHome(home.id)">{{ home.name }} →</button>
|
||||||
<span v-if="!person.homes.length" class="small text-secondary">暂无可访问的当前家庭关联</span>
|
<span v-if="!person.homes.length" class="small text-secondary">暂无可访问的当前家庭关联</span>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="d-flex flex-wrap gap-2 mt-3"><button class="btn btn-sm btn-outline-primary" :disabled="busy" @click="openPerson(person,tree.familyId)">查看人物与亲属</button></div>
|
||||||
|
<details v-if="person.journalHomes?.length" class="mt-3"><summary class="small">个人阅历</summary><div class="d-flex flex-wrap gap-2 mt-2"><button v-for="home in person.journalHomes" :key="home.id" class="btn btn-sm btn-outline-secondary" :disabled="busy" @click="openPerson(person,home.id,true)">{{ home.name }}的记事</button></div><p class="small text-secondary mt-2 mb-0">按记事所属家庭查看,仅展示已授权的内容。</p></details>
|
||||||
</div></div>
|
</div></div>
|
||||||
</article>
|
</article>
|
||||||
</div>
|
</div>
|
||||||
</details>
|
</details>
|
||||||
</section>
|
</section>
|
||||||
</details>
|
</details>
|
||||||
|
<p v-if="data && search.trim() && !trees.length" class="text-secondary" role="status">没有找到这位家人,可尝试其他姓名或清空搜索。</p>
|
||||||
|
<p v-if="data && !data.trees.length" class="alert alert-info">暂无可查看的家族资料。进入下方已授权家庭登记成员,或请家庭管理员授予族谱查看权限。</p>
|
||||||
<details v-if="data?.unplaced?.length" class="border rounded p-3" open>
|
<details v-if="data?.unplaced?.length" class="border rounded p-3" open>
|
||||||
<summary>尚未关联成员或族谱 · 其他场所</summary>
|
<summary>我的家庭与其他场所</summary>
|
||||||
<div class="d-flex flex-wrap gap-2 mt-3"><button v-for="home in data.unplaced" :key="home.id" class="btn btn-outline-secondary" @click="bridge().enterHome(home.id)">{{ home.name }} →</button></div>
|
<div class="d-flex flex-wrap gap-2 mt-3"><button v-for="home in data.unplaced" :key="home.id" class="btn btn-outline-secondary" @click="bridge().enterHome(home.id)">{{ home.name }} →</button></div>
|
||||||
</details>
|
</details>
|
||||||
<p v-if="data" class="small text-secondary mt-3 mb-0">同一人物、同一家庭沿用同一份档案。此处仅展示已有授权范围;世代关系不会授予设备或位置访问权限。</p>
|
<p v-if="data" class="small text-secondary mt-3 mb-0">家人无需注册账号。人物档案沿用同一份,居住地址不决定亲属关系;这里仅展示你有权查看的资料。</p>
|
||||||
</section>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ const draft = ref({
|
|||||||
saving = ref(false),
|
saving = ref(false),
|
||||||
page = ref(0),
|
page = ref(0),
|
||||||
arrange = ref(false),
|
arrange = ref(false),
|
||||||
mode = ref("cards"),
|
mode = ref("generations"),
|
||||||
layoutOptions = ref(false),
|
layoutOptions = ref(false),
|
||||||
drag = ref(""),
|
drag = ref(""),
|
||||||
message = ref("");
|
message = ref("");
|
||||||
@@ -32,7 +32,7 @@ watch(
|
|||||||
saving.value = false;
|
saving.value = false;
|
||||||
page.value = 0;
|
page.value = 0;
|
||||||
arrange.value = false;
|
arrange.value = false;
|
||||||
mode.value = "cards";
|
mode.value = "generations";
|
||||||
layoutOptions.value = false;
|
layoutOptions.value = false;
|
||||||
drag.value = "";
|
drag.value = "";
|
||||||
message.value = "";
|
message.value = "";
|
||||||
@@ -136,10 +136,10 @@ async function enter(h, network = false) {
|
|||||||
<div class="section-head">
|
<div class="section-head">
|
||||||
<div>
|
<div>
|
||||||
<h2>
|
<h2>
|
||||||
我的空间 <span class="count-pill">{{ homes.length }}</span>
|
家人与家庭
|
||||||
</h2>
|
</h2>
|
||||||
<p class="description mb-0">
|
<p class="description mb-0">
|
||||||
家庭、办公与工厂,各自管理成员、区域和设备。
|
以家人为起点,串起亲属关系、共同记忆与日常生活。
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
@@ -150,9 +150,9 @@ async function enter(h, network = false) {
|
|||||||
+ 新建家庭或场所
|
+ 新建家庭或场所
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<HomeInsights />
|
|
||||||
<div class="home-toolbar" :class="{ 'home-options-open': layoutOptions }">
|
<div class="home-toolbar" :class="{ 'home-options-open': layoutOptions }">
|
||||||
<div class="btn-group" role="group" aria-label="场所显示方式">
|
<div class="btn-group" role="group" aria-label="浏览方式">
|
||||||
|
<button class="btn btn-outline-secondary" :class="{active:mode==='generations'}" :aria-pressed="mode==='generations'" @click="mode='generations'"><AppIcon name="tree" /> 家族世代</button>
|
||||||
<button
|
<button
|
||||||
id="home-card-view"
|
id="home-card-view"
|
||||||
class="btn btn-outline-secondary"
|
class="btn btn-outline-secondary"
|
||||||
@@ -160,7 +160,7 @@ async function enter(h, network = false) {
|
|||||||
:aria-pressed="mode === 'cards'"
|
:aria-pressed="mode === 'cards'"
|
||||||
@click="mode = 'cards'"
|
@click="mode = 'cards'"
|
||||||
>
|
>
|
||||||
<AppIcon name="grid" /> 卡片</button
|
<AppIcon name="grid" /> 家庭卡片</button
|
||||||
><button
|
><button
|
||||||
id="home-topology-view"
|
id="home-topology-view"
|
||||||
class="btn btn-outline-secondary"
|
class="btn btn-outline-secondary"
|
||||||
@@ -168,9 +168,8 @@ async function enter(h, network = false) {
|
|||||||
:aria-pressed="mode === 'topology'"
|
:aria-pressed="mode === 'topology'"
|
||||||
@click="mode = 'topology'"
|
@click="mode = 'topology'"
|
||||||
>
|
>
|
||||||
<AppIcon name="network" /> 整体拓扑
|
<AppIcon name="network" /> 场所网络
|
||||||
</button>
|
</button>
|
||||||
<button class="btn btn-outline-secondary" :class="{active:mode==='generations'}" :aria-pressed="mode==='generations'" @click="mode='generations'">家族世代</button>
|
|
||||||
</div>
|
</div>
|
||||||
<button v-show="mode === 'cards'" class="btn btn-outline-secondary home-layout-toggle" :aria-expanded="layoutOptions" aria-controls="home-layout-options" @click="layoutOptions = !layoutOptions">{{ layoutOptions ? '收起设置' : '布局设置' }}</button>
|
<button v-show="mode === 'cards'" class="btn btn-outline-secondary home-layout-toggle" :aria-expanded="layoutOptions" aria-controls="home-layout-options" @click="layoutOptions = !layoutOptions">{{ layoutOptions ? '收起设置' : '布局设置' }}</button>
|
||||||
<div id="home-layout-options" v-show="mode === 'cards'" class="home-layout-controls">
|
<div id="home-layout-options" v-show="mode === 'cards'" class="home-layout-controls">
|
||||||
@@ -233,6 +232,7 @@ async function enter(h, network = false) {
|
|||||||
{{ message || "布局仅影响你的账号;手机端自动适配为单列。" }}
|
{{ message || "布局仅影响你的账号;手机端自动适配为单列。" }}
|
||||||
</p>
|
</p>
|
||||||
<GenerationDirectory :active="mode==='generations' && snapshot.loggedIn && snapshot.page==='households'" />
|
<GenerationDirectory :active="mode==='generations' && snapshot.loggedIn && snapshot.page==='households'" />
|
||||||
|
<HomeInsights v-if="mode==='topology' && snapshot.page==='households' && snapshot.loggedIn" />
|
||||||
<div
|
<div
|
||||||
id="household-list"
|
id="household-list"
|
||||||
v-show="mode === 'cards'"
|
v-show="mode === 'cards'"
|
||||||
@@ -310,18 +310,17 @@ async function enter(h, network = false) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<p class="home-summary">
|
<p class="home-summary">
|
||||||
{{ home.note || "成员、空间与设备,独立管理。" }}
|
{{ home.note || "记录家人、共同经历与日常生活。" }}
|
||||||
</p>
|
</p>
|
||||||
<div class="home-numbers">
|
<div class="home-numbers">
|
||||||
<span
|
<span
|
||||||
><b>{{ home.deviceCount || 0 }}</b
|
|
||||||
>设备</span
|
|
||||||
><span
|
|
||||||
><b>{{ home.sites || 0 }}</b
|
|
||||||
>区域</span
|
|
||||||
><span
|
|
||||||
><b>{{ home.members || 0 }}</b
|
><b>{{ home.members || 0 }}</b
|
||||||
>成员</span
|
>成员</span
|
||||||
|
><span
|
||||||
|
><b>{{ home.accounts || 0 }}</b
|
||||||
|
>授权账号</span
|
||||||
|
><span
|
||||||
|
>{{ kind(home) }}</span
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
<dl class="compact-details">
|
<dl class="compact-details">
|
||||||
@@ -330,7 +329,7 @@ async function enter(h, network = false) {
|
|||||||
{{
|
{{
|
||||||
home.kind === "office" || home.kind === "factory"
|
home.kind === "office" || home.kind === "factory"
|
||||||
? "主要负责人"
|
? "主要负责人"
|
||||||
: "一家之主"
|
: "家庭管理账号"
|
||||||
}}
|
}}
|
||||||
</dt>
|
</dt>
|
||||||
<dd>{{ home.ownerName || "待指定" }}</dd>
|
<dd>{{ home.ownerName || "待指定" }}</dd>
|
||||||
@@ -342,7 +341,7 @@ async function enter(h, network = false) {
|
|||||||
</dl>
|
</dl>
|
||||||
<div class="home-card-actions">
|
<div class="home-card-actions">
|
||||||
<button class="btn btn-primary" @click="enter(home)">
|
<button class="btn btn-primary" @click="enter(home)">
|
||||||
进入空间 <AppIcon name="arrow" /></button
|
进入{{ kind(home) }} <AppIcon name="arrow" /></button
|
||||||
><button
|
><button
|
||||||
v-if="home.canAssignOwner"
|
v-if="home.canAssignOwner"
|
||||||
class="btn btn-link"
|
class="btn btn-link"
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { snapshot } from '../composables/bridge.js';
|
|||||||
import { summarizeDevices, bars, distribution, palette } from '../composables/charts.mjs';
|
import { summarizeDevices, bars, distribution, palette } from '../composables/charts.mjs';
|
||||||
import LocalChart from './LocalChart.vue';
|
import LocalChart from './LocalChart.vue';
|
||||||
const summary = computed(() => summarizeDevices(snapshot.value.state));
|
const summary = computed(() => summarizeDevices(snapshot.value.state));
|
||||||
const active = computed(() => snapshot.value.loggedIn && snapshot.value.page === 'overview');
|
const active = computed(() => snapshot.value.loggedIn && snapshot.value.page === 'objects');
|
||||||
</script>
|
</script>
|
||||||
<template>
|
<template>
|
||||||
<section class="row g-3 mb-4" aria-label="当前场所设备统计" v-if="active && summary.total">
|
<section class="row g-3 mb-4" aria-label="当前场所设备统计" v-if="active && summary.total">
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ import AccountAccess from './AccountAccess.vue'
|
|||||||
<form id="journal-filter" class="panel journal-filters"><label>查看方式<select id="journal-mode"><option value="feed">家庭/场所动态</option><option value="mine">我的个人阅历</option><option value="person">某个人的阅历</option></select></label><label id="journal-person-label" hidden>人物<select id="journal-person"></select></label><label>分类<select id="journal-category"><option value="">全部分类</option><option>日常</option><option>成长</option><option>家庭</option><option>旅行</option><option>工作</option><option>其他</option></select></label><label>关键词<input id="journal-search" type="search" maxlength="120" placeholder="在文字中查找"></label><label>开始日期<input id="journal-from" type="date"></label><label>结束日期<input id="journal-to" type="date"></label><button type="submit">查询阅历</button><button id="journal-filter-clear" type="button" class="quiet">清除筛选</button></form><p class="description">个人阅历保留同一条记事的正文、媒体和互动;查看他人时只展示其分享给当前家庭/场所的内容。删除正文中的媒体或整条记事,会解除对应引用;最后一个引用删除后,网盘原文件自动清理。</p><div class="section-head"><p id="journal-query-status" role="status"></p><div><button id="journal-prev" class="quiet">上一页</button><button id="journal-next" class="quiet">下一页</button></div></div><div id="journal-list" class="journal-feed"></div>
|
<form id="journal-filter" class="panel journal-filters"><label>查看方式<select id="journal-mode"><option value="feed">家庭/场所动态</option><option value="mine">我的个人阅历</option><option value="person">某个人的阅历</option></select></label><label id="journal-person-label" hidden>人物<select id="journal-person"></select></label><label>分类<select id="journal-category"><option value="">全部分类</option><option>日常</option><option>成长</option><option>家庭</option><option>旅行</option><option>工作</option><option>其他</option></select></label><label>关键词<input id="journal-search" type="search" maxlength="120" placeholder="在文字中查找"></label><label>开始日期<input id="journal-from" type="date"></label><label>结束日期<input id="journal-to" type="date"></label><button type="submit">查询阅历</button><button id="journal-filter-clear" type="button" class="quiet">清除筛选</button></form><p class="description">个人阅历保留同一条记事的正文、媒体和互动;查看他人时只展示其分享给当前家庭/场所的内容。删除正文中的媒体或整条记事,会解除对应引用;最后一个引用删除后,网盘原文件自动清理。</p><div class="section-head"><p id="journal-query-status" role="status"></p><div><button id="journal-prev" class="quiet">上一页</button><button id="journal-next" class="quiet">下一页</button></div></div><div id="journal-list" class="journal-feed"></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section id="page-overview" class="page" hidden><FamilyLocations /><ScopeInsights /><div id="scope-overview"></div></section><section id="page-device" class="page" hidden><DeviceNetworkPanel /><div id="device-detail"></div></section><section id="page-heritage" class="page" hidden><div id="heritage-home"></div></section>
|
<section id="page-overview" class="page" hidden><FamilyLocations /><div id="scope-overview"></div></section><section id="page-device" class="page" hidden><DeviceNetworkPanel /><div id="device-detail"></div></section><section id="page-heritage" class="page" hidden><div id="heritage-home"></div></section>
|
||||||
<section id="page-live" class="page"><div class="section-head"><h2 id="live-heading">本场所监控墙</h2><div><label>清晰度 <select id="quality"><option value="hd">主码流</option><option value="compat">子码流</option></select></label></div></div><details class="live-help"><summary>画面与清晰度说明</summary><p id="wall-context" class="description">这里汇总当前场所内已授权的镜头;点击摄像头详情可进入单台设备。</p><p class="description" id="quality-note">主码流画面更清晰,最高 1920×1080;子码流更流畅,最高 768×432,适合网络较慢时使用。</p></details><div class="wall-toolbar"><label>分屏 <select id="wall-layout"><option value="auto">自适应</option><option value="1">1 画面</option><option value="2">2 画面</option><option value="4">4 画面</option><option value="6">6 画面</option><option value="9">9 画面</option><option value="16">16 画面</option></select></label><label class="check"><input id="wall-arrange" type="checkbox">调整顺序</label><div class="wall-paging"><button id="wall-prev" class="quiet" aria-label="上一组画面">‹</button><span id="wall-page"></span><button id="wall-next" class="quiet" aria-label="下一组画面">›</button></div><span id="wall-clock"></span><button id="wall-fullscreen">全屏监控</button></div><div id="live-grid" class="live-grid"></div><section id="ptz-panel" class="ptz-panel" hidden><div><strong id="ptz-title">云台</strong><p id="ptz-status" role="status"></p></div><div class="ptz-pad"><button data-ptz-action="up" aria-label="云台向上">↑</button><button data-ptz-action="left" aria-label="云台向左">←</button><button data-ptz-action="stop">停止</button><button data-ptz-action="right" aria-label="云台向右">→</button><button data-ptz-action="down" aria-label="云台向下">↓</button></div><div id="ptz-presets"><div class="section-head"><strong>常用位置 <small id="preset-count"></small></strong><button id="preset-reload" class="quiet">重新读取</button></div><p id="preset-status" role="status"></p><div id="preset-list"></div><p class="description">调整位置后可另存为新预置位。本版不覆盖已有位置,避免设备固件拒绝或误改。</p><form id="preset-form" hidden><label>当前位置名称<input id="preset-name" required maxlength="40" placeholder="例如:大门、院子"></label><button type="submit">保存当前位置</button></form><div id="preset-confirmation" hidden><p id="preset-confirm-text"></p><button id="preset-confirm-yes">确认</button><button id="preset-confirm-cancel" class="quiet">取消</button></div></div><button id="ptz-close" class="quiet">收起云台</button></section></section>
|
<section id="page-live" class="page"><div class="section-head"><h2 id="live-heading">本场所监控墙</h2><div><label>清晰度 <select id="quality"><option value="hd">主码流</option><option value="compat">子码流</option></select></label></div></div><details class="live-help"><summary>画面与清晰度说明</summary><p id="wall-context" class="description">这里汇总当前场所内已授权的镜头;点击摄像头详情可进入单台设备。</p><p class="description" id="quality-note">主码流画面更清晰,最高 1920×1080;子码流更流畅,最高 768×432,适合网络较慢时使用。</p></details><div class="wall-toolbar"><label>分屏 <select id="wall-layout"><option value="auto">自适应</option><option value="1">1 画面</option><option value="2">2 画面</option><option value="4">4 画面</option><option value="6">6 画面</option><option value="9">9 画面</option><option value="16">16 画面</option></select></label><label class="check"><input id="wall-arrange" type="checkbox">调整顺序</label><div class="wall-paging"><button id="wall-prev" class="quiet" aria-label="上一组画面">‹</button><span id="wall-page"></span><button id="wall-next" class="quiet" aria-label="下一组画面">›</button></div><span id="wall-clock"></span><button id="wall-fullscreen">全屏监控</button></div><div id="live-grid" class="live-grid"></div><section id="ptz-panel" class="ptz-panel" hidden><div><strong id="ptz-title">云台</strong><p id="ptz-status" role="status"></p></div><div class="ptz-pad"><button data-ptz-action="up" aria-label="云台向上">↑</button><button data-ptz-action="left" aria-label="云台向左">←</button><button data-ptz-action="stop">停止</button><button data-ptz-action="right" aria-label="云台向右">→</button><button data-ptz-action="down" aria-label="云台向下">↓</button></div><div id="ptz-presets"><div class="section-head"><strong>常用位置 <small id="preset-count"></small></strong><button id="preset-reload" class="quiet">重新读取</button></div><p id="preset-status" role="status"></p><div id="preset-list"></div><p class="description">调整位置后可另存为新预置位。本版不覆盖已有位置,避免设备固件拒绝或误改。</p><form id="preset-form" hidden><label>当前位置名称<input id="preset-name" required maxlength="40" placeholder="例如:大门、院子"></label><button type="submit">保存当前位置</button></form><div id="preset-confirmation" hidden><p id="preset-confirm-text"></p><button id="preset-confirm-yes">确认</button><button id="preset-confirm-cancel" class="quiet">取消</button></div></div><button id="ptz-close" class="quiet">收起云台</button></section></section>
|
||||||
<section id="page-playback" class="page" hidden>
|
<section id="page-playback" class="page" hidden>
|
||||||
<div class="section-head"><h2>回到那一刻 <small>光阴</small></h2></div>
|
<div class="section-head"><h2>回到那一刻 <small>光阴</small></h2></div>
|
||||||
@@ -67,7 +67,7 @@ import AccountAccess from './AccountAccess.vue'
|
|||||||
<div class="panel"><div class="playback-tools"><label class="check"><input id="play-autonext" type="checkbox" checked>自动续播下一时段(跳过空档)</label><button id="play-snapshot" class="quiet">回放截图</button><span id="play-position" role="status"></span></div><details class="clip-editor"><summary>选取并下载指定片段</summary><form id="clip-form"><div class="form-grid"><label>开始时间<input id="clip-start" type="datetime-local" step="1" required></label><label>结束时间<input id="clip-end" type="datetime-local" step="1" required></label></div><div class="playback-tools"><button type="button" class="quiet" data-clip-mark="start">当前位置作起点</button><button type="button" class="quiet" data-clip-mark="end">当前位置作终点</button><button type="submit">生成下载链接</button><a id="clip-download" class="button secondary" hidden>下载所选片段</a></div><p id="clip-status" role="status" class="description"></p><p class="description">每段最多一小时,不可跨越无录像时段。下载保留原始编码,剪辑边界可能受设备关键帧影响。</p></form></details></div><div id="recording-list" class="recording-list"></div>
|
<div class="panel"><div class="playback-tools"><label class="check"><input id="play-autonext" type="checkbox" checked>自动续播下一时段(跳过空档)</label><button id="play-snapshot" class="quiet">回放截图</button><span id="play-position" role="status"></span></div><details class="clip-editor"><summary>选取并下载指定片段</summary><form id="clip-form"><div class="form-grid"><label>开始时间<input id="clip-start" type="datetime-local" step="1" required></label><label>结束时间<input id="clip-end" type="datetime-local" step="1" required></label></div><div class="playback-tools"><button type="button" class="quiet" data-clip-mark="start">当前位置作起点</button><button type="button" class="quiet" data-clip-mark="end">当前位置作终点</button><button type="submit">生成下载链接</button><a id="clip-download" class="button secondary" hidden>下载所选片段</a></div><p id="clip-status" role="status" class="description"></p><p class="description">每段最多一小时,不可跨越无录像时段。下载保留原始编码,剪辑边界可能受设备关键帧影响。</p></form></details></div><div id="recording-list" class="recording-list"></div>
|
||||||
</section>
|
</section>
|
||||||
<section id="page-cameras" class="page" hidden><div class="section-head"><h2>镜头通道 <small>通道</small></h2><button data-action="new-camera">+ 添加镜头通道</button></div><div class="panel discovery"><div><strong>发现局域网设备</strong><p>探测 RTSP 服务,添加后用设备账号连接。</p></div><input id="scan-network" placeholder="例如 192.168.1.0/24" aria-label="局域网网段"><button id="scan-button" class="secondary">开始探测</button></div><div id="scan-result"></div><div id="camera-list"></div></section>
|
<section id="page-cameras" class="page" hidden><div class="section-head"><h2>镜头通道 <small>通道</small></h2><button data-action="new-camera">+ 添加镜头通道</button></div><div class="panel discovery"><div><strong>发现局域网设备</strong><p>探测 RTSP 服务,添加后用设备账号连接。</p></div><input id="scan-network" placeholder="例如 192.168.1.0/24" aria-label="局域网网段"><button id="scan-button" class="secondary">开始探测</button></div><div id="scan-result"></div><div id="camera-list"></div></section>
|
||||||
<section id="page-objects" class="page" hidden><div class="section-head"><h2>一物一档 <small>设备 · 归属</small></h2><div class="device-actions"><button class="quiet" data-page="sites" data-admin>管理区域</button><button data-action="new-asset">+ 摄像机</button><button data-action="new-recorder">+ 录像机</button><button id="new-device" data-admin>+ 其他设备</button></div></div><p class="description">同一设备可同时记录类型、区域、所有人、负责人和标签。分组顺序可自由组合,例如“灯 → 卧室”或“负责人 → 类型 → 区域”。人员归属不自动授予访问权限。</p><div class="panel device-view-controls"><div class="device-search-row"><label>设备类型<select id="device-type"><option value="">所有类型</option></select></label><label>搜索设备或人员<input id="device-search" type="search" placeholder="例如:卧室 灯;也可查 IP、品牌、型号、人员"></label><button id="device-clear" type="button" class="quiet" hidden>清除设备筛选</button></div><div class="device-actions view-presets" role="group" aria-label="设备分组方式"><button type="button" class="quiet" data-group-preset="space,type">按区域查看</button><button type="button" class="quiet" data-group-preset="type,space">按类型查看</button><button type="button" class="quiet" data-group-preset="manager,type,space">按负责人查看</button></div><details class="group-custom"><summary>自定义分组顺序</summary><p class="description">依次分组(前面的维度优先,区域按你定义的完整层级展示)</p><div id="device-group-order" class="device-group-order"></div><div class="device-actions"><button id="device-group-add" class="quiet">+ 增加分组维度</button><button data-admin id="device-view-save" class="secondary">保存为本归属的默认视图</button></div></details><p id="device-count" class="description"></p></div><div class="device-actions" role="group" aria-label="设备展示方式"><button id="devices-card-view" class="quiet" aria-pressed="true">设备卡片</button><button id="devices-topology-view" class="quiet" aria-pressed="false">网络拓扑</button></div><DeviceCollection /><NetworkMap /></section>
|
<section id="page-objects" class="page" hidden><div class="section-head"><h2>一物一档 <small>设备 · 归属</small></h2><div class="device-actions"><button class="quiet" data-page="sites" data-admin>管理区域</button><button data-action="new-asset">+ 摄像机</button><button data-action="new-recorder">+ 录像机</button><button id="new-device" data-admin>+ 其他设备</button></div></div><p class="description">同一设备可同时记录类型、区域、所有人、负责人和标签。分组顺序可自由组合,例如“灯 → 卧室”或“负责人 → 类型 → 区域”。人员归属不自动授予访问权限。</p><div class="panel device-view-controls"><div class="device-search-row"><label>设备类型<select id="device-type"><option value="">所有类型</option></select></label><label>搜索设备或人员<input id="device-search" type="search" placeholder="例如:卧室 灯;也可查 IP、品牌、型号、人员"></label><button id="device-clear" type="button" class="quiet" hidden>清除设备筛选</button></div><div class="device-actions view-presets" role="group" aria-label="设备分组方式"><button type="button" class="quiet" data-group-preset="space,type">按区域查看</button><button type="button" class="quiet" data-group-preset="type,space">按类型查看</button><button type="button" class="quiet" data-group-preset="manager,type,space">按负责人查看</button></div><details class="group-custom"><summary>自定义分组顺序</summary><p class="description">依次分组(前面的维度优先,区域按你定义的完整层级展示)</p><div id="device-group-order" class="device-group-order"></div><div class="device-actions"><button id="device-group-add" class="quiet">+ 增加分组维度</button><button data-admin id="device-view-save" class="secondary">保存为本归属的默认视图</button></div></details><p id="device-count" class="description"></p></div><div class="device-actions" role="group" aria-label="设备展示方式"><button id="devices-card-view" class="quiet" aria-pressed="true">设备卡片</button><button id="devices-topology-view" class="quiet" aria-pressed="false">网络拓扑</button></div><DeviceCollection /><NetworkMap /><ScopeInsights /></section>
|
||||||
<section id="page-recorders" class="page" hidden><div class="section-head"><h2>录像机 <small>存影</small></h2><button data-action="new-recorder">+ 添加录像机</button></div><p class="description">统一保存录像机地址与账号,镜头通道关联录像机。实时取流使用 RTSP;读取录像机已有历史录像,需要该型号的回放接口适配。</p><div id="recorder-list" class="site-grid"></div></section>
|
<section id="page-recorders" class="page" hidden><div class="section-head"><h2>录像机 <small>存影</small></h2><button data-action="new-recorder">+ 添加录像机</button></div><p class="description">统一保存录像机地址与账号,镜头通道关联录像机。实时取流使用 RTSP;读取录像机已有历史录像,需要该型号的回放接口适配。</p><div id="recorder-list" class="site-grid"></div></section>
|
||||||
<section id="page-sites" class="page" hidden><div class="section-head"><h2>区域与空间 <small>自定层级</small></h2><button data-action="new-site">+ 新建空间</button></div><p class="description">在当前家庭或场所下自行划分区域,不限定层级数量。例如“一楼 → 卧室”或“厂区 → 车间 → 产线”。名称和区域类别均由你定义,地址信息按需填写。</p><div id="site-list" class="site-grid"></div></section>
|
<section id="page-sites" class="page" hidden><div class="section-head"><h2>区域与空间 <small>自定层级</small></h2><button data-action="new-site">+ 新建空间</button></div><p class="description">在当前家庭或场所下自行划分区域,不限定层级数量。例如“一楼 → 卧室”或“厂区 → 车间 → 产线”。名称和区域类别均由你定义,地址信息按需填写。</p><div id="site-list" class="site-grid"></div></section>
|
||||||
<section id="page-storage" class="page" hidden><UploadTasks /><div class="section-head"><h2>录像与存储 <small>留存</small></h2></div><div class="storage-grid"><form id="storage-form" class="panel"><h3>录像上传与保留策略</h3><label>云端录像保留天数<input name="retentionDays" type="number" min="1" max="365" required></label><label>每段录制时长(分钟)<input name="segmentMinutes" type="number" min="1" max="15" value="5" required></label><label>录像容量上限(GB)<input name="maxGB" type="number" min="5" max="100000" required></label><label>磁盘预留空间(GB)<input name="reserveGB" type="number" min="2" max="1000" required></label><p class="description">网盘录像默认每段 5 分钟,按录制时间上传;云端大小及 SHA-256 校验成功后删除本地片段。上传失败会保留并自动重试,未上传片段不会按天数清理。云端默认保留 30 天。容量上限由全部摄像头共用;临时录像分区另有硬容量限制,空间不足时暂停并在释放后恢复。</p><button type="submit">保存策略</button><span class="form-error"></span></form><div class="panel"><h3>运行状态</h3><dl id="storage-status"></dl><p class="description">每台摄像头可选择录像机或百度网盘。网盘方式临时保存原始主码流,上传并校验后腾出本机空间。预览默认使用主码流高清画面(最高 1920×1080、15 帧/秒),也可切换子码流流畅画面(最高 768×432、10 帧/秒)。本机录像保留设备原始编码。</p><h3>最近操作</h3><div id="audit-list"></div></div></div></section>
|
<section id="page-storage" class="page" hidden><UploadTasks /><div class="section-head"><h2>录像与存储 <small>留存</small></h2></div><div class="storage-grid"><form id="storage-form" class="panel"><h3>录像上传与保留策略</h3><label>云端录像保留天数<input name="retentionDays" type="number" min="1" max="365" required></label><label>每段录制时长(分钟)<input name="segmentMinutes" type="number" min="1" max="15" value="5" required></label><label>录像容量上限(GB)<input name="maxGB" type="number" min="5" max="100000" required></label><label>磁盘预留空间(GB)<input name="reserveGB" type="number" min="2" max="1000" required></label><p class="description">网盘录像默认每段 5 分钟,按录制时间上传;云端大小及 SHA-256 校验成功后删除本地片段。上传失败会保留并自动重试,未上传片段不会按天数清理。云端默认保留 30 天。容量上限由全部摄像头共用;临时录像分区另有硬容量限制,空间不足时暂停并在释放后恢复。</p><button type="submit">保存策略</button><span class="form-error"></span></form><div class="panel"><h3>运行状态</h3><dl id="storage-status"></dl><p class="description">每台摄像头可选择录像机或百度网盘。网盘方式临时保存原始主码流,上传并校验后腾出本机空间。预览默认使用主码流高清画面(最高 1920×1080、15 帧/秒),也可切换子码流流畅画面(最高 768×432、10 帧/秒)。本机录像保留设备原始编码。</p><h3>最近操作</h3><div id="audit-list"></div></div></div></section>
|
||||||
|
|||||||
+8
-1
@@ -185,7 +185,14 @@ class Journal:
|
|||||||
mode = query.get('mode', 'feed')
|
mode = query.get('mode', 'feed')
|
||||||
if mode == 'feed': entries = [e for e in entries if e['visibility'] == 'household']
|
if mode == 'feed': entries = [e for e in entries if e['visibility'] == 'household']
|
||||||
elif mode == 'mine': entries = [e for e in entries if e['ownerId'] == user['id']]
|
elif mode == 'mine': entries = [e for e in entries if e['ownerId'] == user['id']]
|
||||||
elif mode == 'person': entries = [e for e in entries if e['ownerId'] == query.get('person') or query.get('person') in e.get('participantIds', [])]
|
elif mode == 'person':
|
||||||
|
person_id = query.get('person', '')
|
||||||
|
authors = {person_id} if person_id else set()
|
||||||
|
if person_id:
|
||||||
|
authors.update(u['id'] for u in a.objects('users') if u.get('personId') == person_id)
|
||||||
|
# Querying the real person also finds their linked account's earlier notes.
|
||||||
|
# Visibility was checked first: being family or an admin never reveals private notes.
|
||||||
|
entries = [e for e in entries if e['ownerId'] in authors or person_id in e.get('participantIds', [])]
|
||||||
for field, compare in [('from', lambda x, y: x >= y), ('to', lambda x, y: x <= y)]:
|
for field, compare in [('from', lambda x, y: x >= y), ('to', lambda x, y: x <= y)]:
|
||||||
if query.get(field):
|
if query.get(field):
|
||||||
self.date(query[field]); entries = [e for e in entries if compare(e['occurredOn'], query[field])]
|
self.date(query[field]); entries = [e for e in entries if compare(e['occurredOn'], query[field])]
|
||||||
|
|||||||
+63
-16
@@ -37,6 +37,28 @@ class Locations:
|
|||||||
if device and a.HOUSEHOLDS.family_of(device)==family:displays.append(dict(id=row['id'],name=device['name']))
|
if device and a.HOUSEHOLDS.family_of(device)==family:displays.append(dict(id=row['id'],name=device['name']))
|
||||||
return users,displays
|
return users,displays
|
||||||
|
|
||||||
|
def phones(self, family):
|
||||||
|
items=[]
|
||||||
|
for row in self.a.DB.execute('SELECT id,member_id FROM member_location_shares WHERE family_id=? AND expires>?',(family,time.time())):
|
||||||
|
valid=self.eligible(family,row['member_id'])
|
||||||
|
if valid:items.append(dict(id=row['id'],memberId=row['member_id'],name=valid[1]['name']))
|
||||||
|
return items
|
||||||
|
|
||||||
|
def select_recipients(self, family, data, own_id=None):
|
||||||
|
users,displays=self.recipients(family)
|
||||||
|
phones=[p for p in self.phones(family) if p['id']!=own_id]
|
||||||
|
chosen={}
|
||||||
|
for key,options,name in [('viewerIds',users,'viewers'),('displayIds',displays,'displays'),('phoneIds',phones,'phones')]:
|
||||||
|
ids=data.get(key,[])
|
||||||
|
if not isinstance(ids,list) or len(ids)>100 or any(not isinstance(i,str) for i in ids) or len(ids)!=len(set(ids)) or not set(ids)<={r['id'] for r in options}:
|
||||||
|
raise self.a.Problem('请选择本家庭仍有效的查看账号、家人手机或显示终端')
|
||||||
|
chosen[name]=[r for r in options if r['id'] in ids]
|
||||||
|
return chosen
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def refresh_receipt(grant):
|
||||||
|
grant['receipt']=hashlib.sha256(json.dumps({k:v for k,v in grant.items() if k!='receipt'},sort_keys=True).encode()).hexdigest()
|
||||||
|
|
||||||
def manage(self, user, data):
|
def manage(self, user, data):
|
||||||
a=self.a; family=a.HOUSEHOLDS.scope(user); now=time.time()
|
a=self.a; family=a.HOUSEHOLDS.scope(user); now=time.time()
|
||||||
with a.LOCK,a.DB:
|
with a.LOCK,a.DB:
|
||||||
@@ -51,13 +73,11 @@ class Locations:
|
|||||||
if data.get('action')!='pair' or not self.eligible(family,member['id']): raise a.Problem('请选择当前家庭的在世成员')
|
if data.get('action')!='pair' or not self.eligible(family,member['id']): raise a.Problem('请选择当前家庭的在世成员')
|
||||||
days=data.get('days',7)
|
days=data.get('days',7)
|
||||||
if type(days) is not int or days not in (1,7,30): raise a.Problem('请选择 1、7 或 30 天')
|
if type(days) is not int or days not in (1,7,30): raise a.Problem('请选择 1、7 或 30 天')
|
||||||
users,displays=self.recipients(family);chosen={}
|
chosen=self.select_recipients(family,data)
|
||||||
for key,options in [('viewerIds',users),('displayIds',displays)]:
|
view_only=data.get('viewOnly',False)
|
||||||
ids=data.get(key,[])
|
if type(view_only) is not bool:raise a.Problem('配对用途不正确')
|
||||||
if not isinstance(ids,list) or len(ids)>100 or any(not isinstance(i,str) for i in ids) or len(ids)!=len(set(ids)) or not set(ids)<={r['id'] for r in options}:
|
if view_only:chosen=dict(viewers=[],displays=[],phones=[])
|
||||||
raise a.Problem('请选择仍有本家庭访问权限的账号或显示终端')
|
elif not any(chosen.values()):raise a.Problem('请明确选择查看人,或选择仅查看家人位置')
|
||||||
chosen[key]=[r for r in options if r['id'] in ids]
|
|
||||||
if not chosen['viewerIds'] and not chosen['displayIds']: raise a.Problem('请明确选择至少一位查看人或一台显示终端')
|
|
||||||
self.codes={k:v for k,v in self.codes.items() if v['until']>now and v['memberId']!=member['id']}
|
self.codes={k:v for k,v in self.codes.items() if v['until']>now and v['memberId']!=member['id']}
|
||||||
if len(self.codes)>=128: raise a.Problem('配对繁忙,请稍后再试',429)
|
if len(self.codes)>=128: raise a.Problem('配对繁忙,请稍后再试',429)
|
||||||
while True:
|
while True:
|
||||||
@@ -65,14 +85,15 @@ class Locations:
|
|||||||
if digest not in self.codes:break
|
if digest not in self.codes:break
|
||||||
grant=dict(memberId=member['id'],personId=person['id'],memberName=person['name'],familyId=family,
|
grant=dict(memberId=member['id'],personId=person['id'],memberName=person['name'],familyId=family,
|
||||||
home=a.get_object('households',family)['name'],until=now+600,expires=now+days*86400,
|
home=a.get_object('households',family)['name'],until=now+600,expires=now+days*86400,
|
||||||
viewers=chosen['viewerIds'],displays=chosen['displayIds'],createdBy=user['id'],consentProtocol=2)
|
**chosen,viewOnly=view_only,intervalSeconds=300,createdBy=user['id'],
|
||||||
grant['receipt']=hashlib.sha256(json.dumps(grant,sort_keys=True).encode()).hexdigest()
|
consentProtocol=3 if view_only or chosen['phones'] else 2)
|
||||||
|
self.refresh_receipt(grant)
|
||||||
self.codes[digest]=grant
|
self.codes[digest]=grant
|
||||||
return dict(code=code,validSeconds=600,expires=grant['expires'])
|
return dict(code=code,validSeconds=600,expires=grant['expires'])
|
||||||
|
|
||||||
def pair(self, body, ip):
|
def pair(self, body, ip):
|
||||||
a=self.a;now=time.time();code=body.get('code')
|
a=self.a;now=time.time();code=body.get('code')
|
||||||
if body.get('consentProtocol')!=2:raise a.Problem('请更新配套 App,在手机上确认具体查看人后开启共享',409)
|
if body.get('consentProtocol') not in (2,3):raise a.Problem('请更新配套 App,在手机上确认具体查看人后开启共享',409)
|
||||||
if not isinstance(code,str) or len(code)!=8 or not code.isascii() or not code.isdigit():raise a.Problem('请输入八位配对码')
|
if not isinstance(code,str) or len(code)!=8 or not code.isascii() or not code.isdigit():raise a.Problem('请输入八位配对码')
|
||||||
with a.LOCK,a.DB:
|
with a.LOCK,a.DB:
|
||||||
self.attempts={k:v for k,v in self.attempts.items() if now-v[0]<600}
|
self.attempts={k:v for k,v in self.attempts.items() if now-v[0]<600}
|
||||||
@@ -81,6 +102,7 @@ class Locations:
|
|||||||
self.attempts[ip]=(at,count+1)
|
self.attempts[ip]=(at,count+1)
|
||||||
key=hashlib.sha256(code.encode()).hexdigest();grant=self.codes.get(key)
|
key=hashlib.sha256(code.encode()).hexdigest();grant=self.codes.get(key)
|
||||||
if not grant or grant['until']<now or not self.eligible(grant['familyId'],grant['memberId']):raise a.Problem('配对码已失效',401)
|
if not grant or grant['until']<now or not self.eligible(grant['familyId'],grant['memberId']):raise a.Problem('配对码已失效',401)
|
||||||
|
if body['consentProtocol']<grant['consentProtocol']:raise a.Problem('此配对需要新版家人位置 App',409)
|
||||||
issuer=a.get_object('users',grant['createdBy'])
|
issuer=a.get_object('users',grant['createdBy'])
|
||||||
try:issuer=a.HOUSEHOLDS.context(issuer,grant['familyId']) if issuer else None
|
try:issuer=a.HOUSEHOLDS.context(issuer,grant['familyId']) if issuer else None
|
||||||
except a.Problem:issuer=None
|
except a.Problem:issuer=None
|
||||||
@@ -91,7 +113,7 @@ class Locations:
|
|||||||
a.DB.execute('INSERT OR REPLACE INTO member_location_shares VALUES (?,?,?,?,?,0,?,?)',
|
a.DB.execute('INSERT OR REPLACE INTO member_location_shares VALUES (?,?,?,?,?,0,?,?)',
|
||||||
(sid,grant['memberId'],grant['familyId'],hashlib.sha256(token.encode()).hexdigest(),grant['expires'],now,json.dumps(grant)))
|
(sid,grant['memberId'],grant['familyId'],hashlib.sha256(token.encode()).hexdigest(),grant['expires'],now,json.dumps(grant)))
|
||||||
self.codes.pop(key);self.attempts.pop(ip,None)
|
self.codes.pop(key);self.attempts.pop(ip,None)
|
||||||
return dict(token=token,**{k:grant[k] for k in ('home','memberName','viewers','displays','expires','receipt','consentProtocol')})
|
return dict(token=token,**{k:grant[k] for k in ('home','memberName','viewers','displays','phones','viewOnly','intervalSeconds','expires','receipt','consentProtocol')})
|
||||||
|
|
||||||
def native(self, token, body):
|
def native(self, token, body):
|
||||||
a=self.a;now=time.time()
|
a=self.a;now=time.time()
|
||||||
@@ -106,11 +128,31 @@ class Locations:
|
|||||||
self.latest.pop(sid,None);return {'ok':True}
|
self.latest.pop(sid,None);return {'ok':True}
|
||||||
if row['expires']<now or not self.eligible(row['family_id'],row['member_id']):
|
if row['expires']<now or not self.eligible(row['family_id'],row['member_id']):
|
||||||
self.latest.pop(sid,None);raise a.Problem('位置共享授权已结束',401)
|
self.latest.pop(sid,None);raise a.Problem('位置共享授权已结束',401)
|
||||||
|
if action=='list':
|
||||||
|
return dict(items=self.listing(row['family_id'],phone_id=sid),memberName=grant['memberName'],home=grant['home'],expires=row['expires'])
|
||||||
|
if action=='settings':
|
||||||
|
users,displays=self.recipients(row['family_id'])
|
||||||
|
return dict(viewers=users,displays=displays,phones=[p for p in self.phones(row['family_id']) if p['id']!=sid],
|
||||||
|
viewerIds=[v['id'] for v in grant['viewers']],displayIds=[v['id'] for v in grant['displays']],
|
||||||
|
phoneIds=[v['id'] for v in grant.get('phones',[])],receipt=grant['receipt'],
|
||||||
|
intervalSeconds=grant.get('intervalSeconds',300),viewOnly=grant.get('viewOnly',False))
|
||||||
|
if action=='configure':
|
||||||
|
if body.get('consent') is not True or body.get('receipt')!=grant['receipt']:raise a.Problem('请本人确认新的共享设置',403)
|
||||||
|
chosen=self.select_recipients(row['family_id'],body,own_id=sid)
|
||||||
|
interval=body.get('intervalSeconds',300)
|
||||||
|
if type(interval) is not int or interval not in (10,60,300):raise a.Problem('请选择实时、1 分钟或 5 分钟')
|
||||||
|
if not any(chosen.values()):raise a.Problem('至少选择一位查看人;只查看家人无需开启自己的共享')
|
||||||
|
grant.update(chosen,viewOnly=False,intervalSeconds=interval,consentProtocol=3)
|
||||||
|
self.refresh_receipt(grant)
|
||||||
|
a.DB.execute('UPDATE member_location_shares SET enabled=0,grant_json=? WHERE id=?',(json.dumps(grant),sid))
|
||||||
|
self.latest.pop(sid,None)
|
||||||
|
return dict(ok=True,receipt=grant['receipt'],intervalSeconds=interval,**chosen)
|
||||||
if action=='start':
|
if action=='start':
|
||||||
|
if grant.get('viewOnly'):raise a.Problem('此手机仅用于查看家人,请先由本人设置共享对象',403)
|
||||||
if body.get('consent') is not True or body.get('receipt')!=grant['receipt']:raise a.Problem('请本人核对姓名及查看人,并同意开启共享',403)
|
if body.get('consent') is not True or body.get('receipt')!=grant['receipt']:raise a.Problem('请本人核对姓名及查看人,并同意开启共享',403)
|
||||||
a.DB.execute('UPDATE member_location_shares SET enabled=1 WHERE id=?',(sid,))
|
a.DB.execute('UPDATE member_location_shares SET enabled=1 WHERE id=?',(sid,))
|
||||||
self.latest[sid]=dict(seen=now,started=now,fix=None,signal='waiting')
|
self.latest[sid]=dict(seen=0,started=now,fix=None,signal='waiting')
|
||||||
return dict(ok=True,expires=row['expires'])
|
return dict(ok=True,expires=row['expires'],intervalSeconds=grant.get('intervalSeconds',300))
|
||||||
if action!='update' or not row['enabled']:raise a.Problem('位置共享尚未开启',403)
|
if action!='update' or not row['enabled']:raise a.Problem('位置共享尚未开启',403)
|
||||||
old=self.latest.get(sid,dict(started=now,fix=None))
|
old=self.latest.get(sid,dict(started=now,fix=None))
|
||||||
if now-old.get('seen',0)<10:raise a.Problem('位置更新过于频繁',429)
|
if now-old.get('seen',0)<10:raise a.Problem('位置更新过于频繁',429)
|
||||||
@@ -127,11 +169,14 @@ class Locations:
|
|||||||
self.latest[sid]=dict(started=old['started'],seen=now,fix=fix,signal=signal)
|
self.latest[sid]=dict(started=old['started'],seen=now,fix=fix,signal=signal)
|
||||||
return dict(ok=True,expires=row['expires'])
|
return dict(ok=True,expires=row['expires'])
|
||||||
|
|
||||||
def listing(self, family, user=None, display_id=None):
|
def listing(self, family, user=None, display_id=None, phone_id=None):
|
||||||
a=self.a;now=time.time();items=[]
|
a=self.a;now=time.time();items=[]
|
||||||
if not user and not display_id:return items
|
if not user and not display_id and not phone_id:return items
|
||||||
if user and not a.HOUSEHOLDS.grant(a.get_object('users',user.get('id')),family):return items
|
if user and not a.HOUSEHOLDS.grant(a.get_object('users',user.get('id')),family):return items
|
||||||
with a.LOCK:
|
with a.LOCK:
|
||||||
|
if phone_id:
|
||||||
|
phone=a.DB.execute('SELECT member_id FROM member_location_shares WHERE id=? AND family_id=? AND expires>?',(phone_id,family,now)).fetchone()
|
||||||
|
if not phone or not self.eligible(family,phone['member_id']):return items
|
||||||
if display_id:
|
if display_id:
|
||||||
d=a.DB.execute('SELECT device_id FROM household_displays WHERE id=? AND family_id=? AND revoked=0 AND expires_at>?',(display_id,family,now)).fetchone()
|
d=a.DB.execute('SELECT device_id FROM household_displays WHERE id=? AND family_id=? AND revoked=0 AND expires_at>?',(display_id,family,now)).fetchone()
|
||||||
obj=a.get_object('devices',d['device_id']) if d else None
|
obj=a.get_object('devices',d['device_id']) if d else None
|
||||||
@@ -145,6 +190,7 @@ class Locations:
|
|||||||
grant=json.loads(row['grant_json'])
|
grant=json.loads(row['grant_json'])
|
||||||
if user and user['id'] not in {v['id'] for v in grant['viewers']}:continue
|
if user and user['id'] not in {v['id'] for v in grant['viewers']}:continue
|
||||||
if display_id and display_id not in {v['id'] for v in grant['displays']}:continue
|
if display_id and display_id not in {v['id'] for v in grant['displays']}:continue
|
||||||
|
if phone_id and phone_id!=row['id'] and phone_id not in {v['id'] for v in grant.get('phones',[])}:continue
|
||||||
recent=self.latest.get(row['id'],{});fix=recent.get('fix');seen=recent.get('seen',0)
|
recent=self.latest.get(row['id'],{});fix=recent.get('fix');seen=recent.get('seen',0)
|
||||||
age=now-(fix['at'] if fix else recent.get('started',row['created']))
|
age=now-(fix['at'] if fix else recent.get('started',row['created']))
|
||||||
state='stale' if age>900 or seen and now-seen>900 else 'live' if fix else 'waiting'
|
state='stale' if age>900 or seen and now-seen>900 else 'live' if fix else 'waiting'
|
||||||
@@ -162,4 +208,5 @@ class Locations:
|
|||||||
bindings=[dict(memberId=r['member_id'],enabled=bool(r['enabled']),expires=r['expires'])
|
bindings=[dict(memberId=r['member_id'],enabled=bool(r['enabled']),expires=r['expires'])
|
||||||
for r in a.DB.execute('SELECT * FROM member_location_shares WHERE family_id=? AND expires>?',(family,time.time()))
|
for r in a.DB.execute('SELECT * FROM member_location_shares WHERE family_id=? AND expires>?',(family,time.time()))
|
||||||
if r['member_id'] in {m['id'] for m in manageable}]
|
if r['member_id'] in {m['id'] for m in manageable}]
|
||||||
return dict(items=self.listing(family,user=user),members=manageable,viewers=users,displays=displays,bindings=bindings)
|
return dict(items=self.listing(family,user=user),members=manageable,viewers=users,displays=displays,
|
||||||
|
phones=self.phones(family) if manageable else [],bindings=bindings)
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
"""Installer routing and permission contracts; not a physical phone test."""
|
||||||
|
from pathlib import Path
|
||||||
|
import unittest
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent
|
||||||
|
ANDROID = ROOT/'android-display'
|
||||||
|
NS = '{http://schemas.android.com/apk/res/android}'
|
||||||
|
|
||||||
|
|
||||||
|
class AndroidLocationContractTests(unittest.TestCase):
|
||||||
|
def test_phone_launcher_is_location_only(self):
|
||||||
|
manifest = ET.parse(ANDROID/'AndroidManifest.xml').getroot()
|
||||||
|
entries = manifest.findall('application/activity')
|
||||||
|
launchers = [a.get(NS+'name') for a in entries if any(c.get(NS+'name') ==
|
||||||
|
'android.intent.category.LAUNCHER' for c in a.findall('intent-filter/category'))]
|
||||||
|
television = [a.get(NS+'name') for a in entries if any(c.get(NS+'name') ==
|
||||||
|
'android.intent.category.LEANBACK_LAUNCHER' for c in a.findall('intent-filter/category'))]
|
||||||
|
self.assertEqual(launchers, ['.LocationActivity'])
|
||||||
|
self.assertEqual(television, ['.MainActivity'])
|
||||||
|
self.assertEqual(manifest.get(NS+'versionName'), (ROOT/'VERSION').read_text().strip())
|
||||||
|
self.assertEqual(manifest.get(NS+'versionCode'), '3')
|
||||||
|
|
||||||
|
def test_collection_is_visible_foreground_and_never_boot_started(self):
|
||||||
|
manifest = ET.parse(ANDROID/'AndroidManifest.xml').getroot()
|
||||||
|
service = next(s for s in manifest.findall('application/service') if s.get(NS+'name') == '.LocationService')
|
||||||
|
self.assertEqual(service.get(NS+'exported'), 'false')
|
||||||
|
self.assertEqual(service.get(NS+'foregroundServiceType'), 'location')
|
||||||
|
boot = (ANDROID/'src/cn/ucvl/zhaodisplay/BootReceiver.java').read_text()
|
||||||
|
self.assertNotIn('LocationService', boot)
|
||||||
|
self.assertIn('phoneMode', boot)
|
||||||
|
ui = (ANDROID/'src/cn/ucvl/zhaodisplay/LocationActivity.java').read_text(encoding='utf-8')
|
||||||
|
self.assertNotIn('WebView', ui)
|
||||||
|
self.assertIn('共享我的位置', ui)
|
||||||
|
self.assertIn('new int[]{10,60,300}', ui)
|
||||||
|
self.assertIn('consent.isChecked()', ui)
|
||||||
|
|
||||||
|
def test_map_has_local_assets_no_external_coordinate_requests(self):
|
||||||
|
source = (ANDROID/'src/cn/ucvl/zhaodisplay/LocationMapView.java').read_text(encoding='utf-8')
|
||||||
|
self.assertIn('getAssets().open("world-land.json")', source)
|
||||||
|
self.assertNotIn('http', source)
|
||||||
|
build = (ANDROID/'build.ps1').read_text(encoding='utf-8')
|
||||||
|
for name in ('world-land.json', 'WORLD-LAND-LICENSE.txt'):
|
||||||
|
self.assertIn(name, build)
|
||||||
|
self.assertTrue((ROOT/'frontend/src/data'/name).exists())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__': unittest.main()
|
||||||
@@ -66,6 +66,17 @@ class JournalTests(unittest.TestCase):
|
|||||||
with self.assertRaises(app.Problem):
|
with self.assertRaises(app.Problem):
|
||||||
app.JOURNAL.save(self.actor, self.note(participantIds=[foreign['personId']]))
|
app.JOURNAL.save(self.actor, self.note(participantIds=[foreign['personId']]))
|
||||||
|
|
||||||
|
def test_real_person_history_includes_linked_account_notes_without_exposing_private_notes(self):
|
||||||
|
member = app.MEMBERS.save(self.owner, dict(name='有账号的家人'))
|
||||||
|
self.actor = app.ACCOUNTS.save(dict(self.actor, personId=member['personId']), self.root)
|
||||||
|
private_id = self.saved()
|
||||||
|
public_id = self.saved(visibility='household')
|
||||||
|
query = dict(mode='person', person=member['personId'])
|
||||||
|
self.assertEqual({e['id'] for e in app.JOURNAL.snapshot(self.actor, query)['items']}, {private_id, public_id})
|
||||||
|
self.assertEqual([e['id'] for e in app.JOURNAL.snapshot(self.root, query)['items']], [public_id])
|
||||||
|
self.assertEqual(app.JOURNAL.snapshot(self.other, query)['items'], [])
|
||||||
|
self.assertEqual(app.JOURNAL.snapshot(self.actor, dict(mode='person'))['items'], [])
|
||||||
|
|
||||||
def test_shared_feed_history_search_and_date_filters_reference_the_same_record(self):
|
def test_shared_feed_history_search_and_date_filters_reference_the_same_record(self):
|
||||||
key = self.saved(visibility='household')
|
key = self.saved(visibility='household')
|
||||||
for mode in ('feed','person'):
|
for mode in ('feed','person'):
|
||||||
|
|||||||
@@ -55,6 +55,42 @@ class MemberTests(unittest.TestCase):
|
|||||||
app.ACCOUNTS.save(dict(account, password='attempt-change'), actor)
|
app.ACCOUNTS.save(dict(account, password='attempt-change'), actor)
|
||||||
self.assertEqual(error.exception.status, 403)
|
self.assertEqual(error.exception.status, 403)
|
||||||
|
|
||||||
|
def test_people_directory_needs_no_hardware_and_links_historical_experience(self):
|
||||||
|
member = app.MEMBERS.save(self.owner, dict(name='无账号长辈'))
|
||||||
|
app.MEMBERS.save(self.owner, dict(member, status='historical'))
|
||||||
|
with app.DB:
|
||||||
|
for table in ('cameras', 'assets', 'recorders', 'devices', 'sites'):
|
||||||
|
app.DB.execute('DELETE FROM ' + table)
|
||||||
|
tree = app.MEMBERS.directory(self.owner)['trees'][0]
|
||||||
|
person = tree['branches'][0]['people'][0]
|
||||||
|
self.assertEqual(tree['familyId'], self.aid)
|
||||||
|
self.assertEqual(person['id'], member['personId'])
|
||||||
|
self.assertFalse(person['self'])
|
||||||
|
self.assertEqual(person['homes'], [])
|
||||||
|
self.assertEqual([h['id'] for h in person['journalHomes']], [self.aid])
|
||||||
|
self.assertFalse(app.MEMBERS.snapshot(self.owner)['items'][0]['hasAccount'])
|
||||||
|
|
||||||
|
def test_directory_profile_context_requires_genealogy_access_and_marks_self(self):
|
||||||
|
member = app.MEMBERS.save(self.owner, dict(name='跨家庭亲人'))
|
||||||
|
app.MEMBERS.share_genealogy(self.root, dict(targetFamilyId=self.bid, confirm=True))
|
||||||
|
app.MEMBERS.save(self.other, dict(personId=member['personId']))
|
||||||
|
account = app.ACCOUNTS.save(dict(self.members[self.aid], personId=member['personId'], familyAccess='none'), self.root)
|
||||||
|
app.ACCOUNTS.grant_household(self.root, dict(userId=account['id'], familyId=self.bid, role='member', familyAccess='read'))
|
||||||
|
actor = app.get_object('users', account['id'])
|
||||||
|
tree = app.MEMBERS.directory(actor)['trees'][0]
|
||||||
|
self.assertEqual(tree['familyId'], self.bid)
|
||||||
|
person = tree['branches'][0]['people'][0]
|
||||||
|
self.assertTrue(person['self'])
|
||||||
|
self.assertEqual({h['id'] for h in person['journalHomes']}, {self.aid, self.bid})
|
||||||
|
self.assertFalse(app.MEMBERS.snapshot(actor)['canViewGenealogy'])
|
||||||
|
self.assertTrue(app.MEMBERS.snapshot(app.HOUSEHOLDS.context(actor, self.bid))['canViewGenealogy'])
|
||||||
|
# Removing the other grant hides its name and all of its history entry points.
|
||||||
|
app.ACCOUNTS.grant_household(self.root, dict(userId=account['id'], familyId=self.bid, role='none'))
|
||||||
|
app.ACCOUNTS.save(dict(app.get_object('users', account['id']), familyAccess='read'), self.root)
|
||||||
|
tree = app.MEMBERS.directory(app.get_object('users', account['id']))['trees'][0]
|
||||||
|
self.assertEqual(tree['familyId'], self.aid)
|
||||||
|
self.assertEqual([h['id'] for h in tree['branches'][0]['people'][0]['journalHomes']], [self.aid])
|
||||||
|
|
||||||
def test_additional_household_leader_promotion_does_not_promote_primary_home(self):
|
def test_additional_household_leader_promotion_does_not_promote_primary_home(self):
|
||||||
account = self.members[self.aid]
|
account = self.members[self.aid]
|
||||||
app.ACCOUNTS.grant_household(self.root, dict(userId=account['id'], familyId=self.bid, role='member'))
|
app.ACCOUNTS.grant_household(self.root, dict(userId=account['id'], familyId=self.bid, role='member'))
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm');
|
||||||
|
const read=path=>fs.readFileSync(path,'utf8');
|
||||||
|
const part=(text,start,end)=>text.slice(text.indexOf(start),text.indexOf(end,text.indexOf(start)+start.length));
|
||||||
|
|
||||||
|
function bridgeHarness(allow=true){
|
||||||
|
const calls=[];
|
||||||
|
const c=vm.createContext({window:{ZhaoVue:{}},bootApplication(){},api(){},refresh(){},toast(){},ZhaoGeography:{describe(){}},
|
||||||
|
state:{familyId:'a'},loggedIn:true,enterDevice(){},showPage:(...args)=>calls.push(args),
|
||||||
|
async switchHousehold(id){calls.push(['switch',id]);if(allow)c.state.familyId=id;return allow;}});
|
||||||
|
vm.runInContext(read('web/vue-bridge.js'),c);
|
||||||
|
return {c,calls,bridge:c.window.ZhaoVue};
|
||||||
|
}
|
||||||
|
test('opening a person selects the actual person instead of the account holder',async()=>{
|
||||||
|
const {bridge,calls}=bridgeHarness();await bridge.viewPerson('mother','a');
|
||||||
|
assert.equal(calls.length,1);assert.equal(calls[0][0],'family');assert.equal(calls[0][1].personId,'mother');
|
||||||
|
});
|
||||||
|
test('person navigation switches only to the explicitly selected authorized household',async()=>{
|
||||||
|
const {bridge,calls}=bridgeHarness();await bridge.viewMemberHistory('mother','妈妈','b');
|
||||||
|
assert.equal(calls[0][0],'switch');assert.equal(calls[0][1],'b');
|
||||||
|
assert.equal(calls[1][0],'journal');assert.equal(calls[1][1].person.id,'mother');
|
||||||
|
});
|
||||||
|
test('cancelled or denied household switch cannot open a person in the old scope',async()=>{
|
||||||
|
const {bridge,calls}=bridgeHarness(false);await bridge.viewPerson('mother','b');await bridge.viewMemberHistory('mother','妈妈','b');
|
||||||
|
assert.ok(calls.every(call=>call[0]==='switch'));
|
||||||
|
});
|
||||||
|
test('logging out blocks same-household person navigation',async()=>{
|
||||||
|
const {c,bridge,calls}=bridgeHarness();c.loggedIn=false;await bridge.viewPerson('mother','a');
|
||||||
|
assert.equal(calls.length,0);
|
||||||
|
});
|
||||||
|
test('member history preselects a real person without an account and clears stale filters',()=>{
|
||||||
|
const nodes={};const selector={options:[],value:'',add(option){this.options.push(option);}};
|
||||||
|
const c=vm.createContext({$:id=>id==='#journal-person'?selector:(nodes[id]??={value:'old'}),journalPage:7,
|
||||||
|
Option:function(text,value){this.text=text;this.value=value;}});
|
||||||
|
const journal=read('web/journal.js');
|
||||||
|
vm.runInContext(part(journal,'function resetJournalFilters(','function journalEmptyMessage(')+part(journal,'function selectJournalPerson(','async function loadJournal('),c);
|
||||||
|
const person={id:'person-only',name:'<亲人>'};c.selectJournalPerson(person);c.selectJournalPerson(person);
|
||||||
|
assert.equal(selector.value,'person-only');assert.equal(selector.options.length,1);assert.equal(selector.options[0].text,'<亲人>');
|
||||||
|
assert.equal(nodes['#journal-mode'].value,'person');assert.equal(nodes['#journal-search'].value,'');assert.equal(c.journalPage,0);
|
||||||
|
});
|
||||||
|
test('generation directory is the default and hardware graphs are confined to network mode',()=>{
|
||||||
|
const home=read('frontend/src/components/HomeExplorer.vue');
|
||||||
|
assert.match(home,/mode = ref\("generations"\)/);
|
||||||
|
assert.match(home,/<HomeInsights v-if="mode==='topology'/);
|
||||||
|
const workspace=read('frontend/src/components/Workspace.vue');
|
||||||
|
const overview=part(workspace,'<section id="page-overview"','<section id="page-device"');
|
||||||
|
assert.ok(!overview.includes('ScopeInsights'));
|
||||||
|
});
|
||||||
|
test('family overview puts people first and preserves an opened optional equipment section',()=>{
|
||||||
|
const nodes={'#overview-equipment':{open:true},'#scope-overview':{}};
|
||||||
|
const c=vm.createContext({currentHome:()=>({name:'家人',kind:'home',members:2}),state:{sites:[],cameras:[]},
|
||||||
|
ZhaoDevices:{catalog:()=>[]},isAdmin:()=>true,currentUser:{},scopeKind:()=>'家庭',esc:s=>s,$:id=>nodes[id]});
|
||||||
|
vm.runInContext(part(read('web/steward.js'),'function renderOverview(){','function renderDeviceDetail('),c);c.renderOverview();
|
||||||
|
const html=nodes['#scope-overview'].innerHTML;
|
||||||
|
assert.ok(html.indexOf('data-page="members"')<html.indexOf('data-page="objects"'));
|
||||||
|
assert.match(html,/<details id="overview-equipment"[^>]* open>/);
|
||||||
|
assert.match(html,/2 位家人/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
"""No-login member phones: independent viewing, explicit consent and cadence."""
|
||||||
|
import http.client
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
import unittest
|
||||||
|
import test_households as fixtures
|
||||||
|
|
||||||
|
app = fixtures.app
|
||||||
|
|
||||||
|
|
||||||
|
class PhoneLocationTests(unittest.TestCase):
|
||||||
|
setUp = fixtures.HouseholdTests.setUp
|
||||||
|
stop_server = fixtures.HouseholdTests.stop_server
|
||||||
|
|
||||||
|
def phone(self, name, owner=None):
|
||||||
|
owner = owner or self.owner
|
||||||
|
member = app.MEMBERS.save(owner, dict(name=name))
|
||||||
|
code = app.LOCATIONS.manage(owner, dict(action='pair', memberId=member['id'], viewOnly=True))['code']
|
||||||
|
grant = app.LOCATIONS.pair(dict(code=code, consentProtocol=3), 'fixture')
|
||||||
|
sid = app.DB.execute('SELECT id FROM member_location_shares WHERE member_id=?', (member['id'],)).fetchone()[0]
|
||||||
|
return dict(grant, sid=sid, member=member)
|
||||||
|
|
||||||
|
def configure(self, phone, **options):
|
||||||
|
body = dict(action='configure', consent=True, receipt=phone['receipt'],
|
||||||
|
viewerIds=[], displayIds=[], phoneIds=[], intervalSeconds=300)
|
||||||
|
body.update(options)
|
||||||
|
result = app.LOCATIONS.native(phone['token'], body)
|
||||||
|
phone['receipt'] = result['receipt']
|
||||||
|
return result
|
||||||
|
|
||||||
|
def start(self, phone):
|
||||||
|
return app.LOCATIONS.native(phone['token'], dict(action='start', consent=True, receipt=phone['receipt']))
|
||||||
|
|
||||||
|
def point(self, phone):
|
||||||
|
app.LOCATIONS.native(phone['token'], dict(action='update', signal='available',
|
||||||
|
position=dict(latitude=36.61, longitude=117.1, accuracy=9, at=time.time())))
|
||||||
|
|
||||||
|
def listing(self, phone):
|
||||||
|
return app.LOCATIONS.native(phone['token'], dict(action='list'))['items']
|
||||||
|
|
||||||
|
def test_pair_only_needs_no_account_or_location(self):
|
||||||
|
phone = self.phone('妈妈')
|
||||||
|
self.assertTrue(phone['viewOnly'])
|
||||||
|
self.assertEqual(self.listing(phone), [])
|
||||||
|
self.assertFalse(any(u.get('personId') == phone['member']['personId'] for u in app.objects('users')))
|
||||||
|
with self.assertRaises(app.Problem): self.start(phone)
|
||||||
|
with self.assertRaises(app.Problem): self.point(phone)
|
||||||
|
settings = app.LOCATIONS.native(phone['token'], dict(action='settings'))
|
||||||
|
self.assertEqual(settings['intervalSeconds'], 300)
|
||||||
|
self.assertEqual(settings['phoneIds'], [])
|
||||||
|
self.assertFalse(app.LOCATIONS.latest)
|
||||||
|
|
||||||
|
def test_viewing_does_not_require_sharing_and_admin_has_no_bypass(self):
|
||||||
|
viewer, source, stranger = [self.phone(name) for name in ('儿子', '妈妈', '另一位家人')]
|
||||||
|
self.configure(source, phoneIds=[viewer['sid']])
|
||||||
|
self.start(source); self.point(source)
|
||||||
|
self.assertEqual([r['name'] for r in self.listing(viewer)], ['妈妈'])
|
||||||
|
self.assertEqual(self.listing(stranger), [])
|
||||||
|
self.assertEqual(app.LOCATIONS.listing(self.aid, user=self.root), [])
|
||||||
|
self.assertEqual(len(self.listing(source)), 1) # Can view one's own current fix.
|
||||||
|
app.LOCATIONS.native(viewer['token'], dict(action='stop'))
|
||||||
|
self.assertEqual(len(self.listing(viewer)), 1)
|
||||||
|
app.LOCATIONS.native(source['token'], dict(action='stop'))
|
||||||
|
self.assertEqual(self.listing(viewer), [])
|
||||||
|
|
||||||
|
def test_consent_receipt_interval_and_first_immediate_fix(self):
|
||||||
|
source, viewer = self.phone('本人'), self.phone('查看人')
|
||||||
|
for seconds in (10, 60, 300):
|
||||||
|
result = self.configure(source, phoneIds=[viewer['sid']], intervalSeconds=seconds)
|
||||||
|
self.assertEqual(result['intervalSeconds'], seconds)
|
||||||
|
self.assertEqual(self.start(source)['intervalSeconds'], seconds)
|
||||||
|
self.point(source) # First upload cannot hit the ten-second limit.
|
||||||
|
self.assertEqual(self.listing(viewer)[0]['status'], 'live')
|
||||||
|
app.LOCATIONS.native(source['token'], dict(action='stop'))
|
||||||
|
for seconds in (True, '60', 0, 9, 59, 301, 60.0):
|
||||||
|
with self.subTest(seconds=seconds), self.assertRaises(app.Problem):
|
||||||
|
self.configure(source, phoneIds=[viewer['sid']], intervalSeconds=seconds)
|
||||||
|
for extra in (dict(consent=False), dict(receipt='old')):
|
||||||
|
body = dict(action='configure', consent=True, receipt=source['receipt'], phoneIds=[viewer['sid']])
|
||||||
|
body.update(extra)
|
||||||
|
with self.assertRaises(app.Problem): app.LOCATIONS.native(source['token'], body)
|
||||||
|
|
||||||
|
def test_configuration_stops_old_share_until_explicit_restart(self):
|
||||||
|
source, viewer = self.phone('本人'), self.phone('查看人')
|
||||||
|
self.configure(source, phoneIds=[viewer['sid']]); self.start(source); self.point(source)
|
||||||
|
old_receipt = source['receipt']
|
||||||
|
self.configure(source, viewerIds=[self.members[self.aid]['id']], intervalSeconds=60)
|
||||||
|
self.assertNotEqual(old_receipt, source['receipt'])
|
||||||
|
self.assertEqual(self.listing(viewer), [])
|
||||||
|
self.assertNotIn(source['sid'], app.LOCATIONS.latest)
|
||||||
|
with self.assertRaises(app.Problem): self.point(source)
|
||||||
|
with self.assertRaises(app.Problem):
|
||||||
|
app.LOCATIONS.native(source['token'], dict(action='start', consent=True, receipt=old_receipt))
|
||||||
|
self.start(source); self.point(source)
|
||||||
|
self.assertEqual(self.listing(viewer), [])
|
||||||
|
self.assertEqual(len(app.LOCATIONS.listing(self.aid, user=self.members[self.aid])), 1)
|
||||||
|
|
||||||
|
def test_other_family_self_and_invalid_recipients_rejected(self):
|
||||||
|
source, foreign = self.phone('本人'), self.phone('乙家庭', self.other)
|
||||||
|
for options in (dict(phoneIds=[foreign['sid']]), dict(phoneIds=[source['sid']]),
|
||||||
|
dict(viewerIds=[self.other['id']]), dict(phoneIds=['missing']),
|
||||||
|
dict(phoneIds='not-a-list'), dict(phoneIds=[])):
|
||||||
|
with self.subTest(options=options), self.assertRaises(app.Problem): self.configure(source, **options)
|
||||||
|
self.assertEqual(app.LOCATIONS.listing(self.aid, phone_id=foreign['sid']), [])
|
||||||
|
settings = app.LOCATIONS.native(source['token'], dict(action='settings'))
|
||||||
|
self.assertNotIn(foreign['sid'], [p['id'] for p in settings['phones']])
|
||||||
|
|
||||||
|
def test_repaired_phone_does_not_inherit_viewer_consent(self):
|
||||||
|
source, viewer = self.phone('本人'), self.phone('查看人')
|
||||||
|
self.configure(source, phoneIds=[viewer['sid']]); self.start(source); self.point(source)
|
||||||
|
self.assertEqual(len(self.listing(viewer)), 1)
|
||||||
|
code = app.LOCATIONS.manage(self.owner, dict(action='pair', memberId=viewer['member']['id'], viewOnly=True))['code']
|
||||||
|
replacement = app.LOCATIONS.pair(dict(code=code, consentProtocol=3), 'fixture')
|
||||||
|
with self.assertRaises(app.Problem): self.listing(viewer)
|
||||||
|
self.assertEqual(self.listing(replacement), [])
|
||||||
|
|
||||||
|
def test_revoked_inactive_or_expired_viewer_cannot_read(self):
|
||||||
|
source, viewer = self.phone('本人'), self.phone('查看人')
|
||||||
|
self.configure(source, phoneIds=[viewer['sid']]); self.start(source); self.point(source)
|
||||||
|
changed = app.MEMBERS.save(self.owner, dict(viewer['member'], status='historical'))
|
||||||
|
with self.assertRaises(app.Problem): self.listing(viewer)
|
||||||
|
app.MEMBERS.save(self.owner, dict(changed, status='active'))
|
||||||
|
app.DB.execute('UPDATE member_location_shares SET expires=? WHERE id=?', (time.time()-1, viewer['sid']))
|
||||||
|
with self.assertRaises(app.Problem): self.listing(viewer)
|
||||||
|
app.LOCATIONS.native(source['token'], dict(action='revoke'))
|
||||||
|
with self.assertRaises(app.Problem): self.listing(source)
|
||||||
|
|
||||||
|
def test_old_protocol_cannot_consume_new_pair_code(self):
|
||||||
|
member = app.MEMBERS.save(self.owner, dict(name='新手机'))
|
||||||
|
code = app.LOCATIONS.manage(self.owner, dict(action='pair', memberId=member['id'], viewOnly=True))['code']
|
||||||
|
with self.assertRaises(app.Problem): app.LOCATIONS.pair(dict(code=code, consentProtocol=2), 'fixture')
|
||||||
|
grant = app.LOCATIONS.pair(dict(code=code, consentProtocol=3), 'fixture')
|
||||||
|
self.assertTrue(grant['viewOnly'])
|
||||||
|
|
||||||
|
def test_native_http_has_no_cookie_and_requires_exact_phone_token(self):
|
||||||
|
source, viewer = self.phone('本人'), self.phone('查看人')
|
||||||
|
self.configure(source, phoneIds=[viewer['sid']]); self.start(source); self.point(source)
|
||||||
|
for token, expected in ((viewer['token'], 200), ('', 401), ('invalid', 401),
|
||||||
|
(self.tokens[self.root['id']], 401)):
|
||||||
|
connection = http.client.HTTPConnection(*self.server.server_address, timeout=3)
|
||||||
|
connection.request('POST', '/api/location/update', json.dumps(dict(action='list')),
|
||||||
|
{'Authorization': 'Bearer '+token, 'Content-Type': 'application/json'})
|
||||||
|
response = connection.getresponse(); payload = json.loads(response.read()); connection.close()
|
||||||
|
self.assertEqual(response.status, expected)
|
||||||
|
if expected == 200: self.assertEqual(payload['items'][0]['name'], '本人')
|
||||||
|
raw = '\n'.join(app.DB.iterdump())
|
||||||
|
for secret in (viewer['token'], source['token'], '36.61'): self.assertNotIn(secret, raw)
|
||||||
|
|
||||||
|
def test_permission_loss_and_staleness_hide_coordinates(self):
|
||||||
|
source, viewer = self.phone('本人'), self.phone('查看人')
|
||||||
|
self.configure(source, phoneIds=[viewer['sid']]); self.start(source); self.point(source)
|
||||||
|
app.LOCATIONS.latest[source['sid']]['seen'] = 0
|
||||||
|
app.LOCATIONS.native(source['token'], dict(action='update', signal='permission_denied'))
|
||||||
|
self.assertIsNone(self.listing(viewer)[0]['position'])
|
||||||
|
app.LOCATIONS.latest[source['sid']]['seen'] = 0
|
||||||
|
self.point(source)
|
||||||
|
app.LOCATIONS.latest[source['sid']]['seen'] = time.time()-901
|
||||||
|
row = self.listing(viewer)[0]
|
||||||
|
self.assertEqual(row['status'], 'stale')
|
||||||
|
self.assertIsNone(row['position'])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__': unittest.main()
|
||||||
+1
-1
@@ -41,7 +41,7 @@ test('late heritage response cannot populate a different view',async()=>{
|
|||||||
|
|
||||||
test('family timeline entry preserves its explicitly selected view',()=>{
|
test('family timeline entry preserves its explicitly selected view',()=>{
|
||||||
assert.match(code,/familyView=b.dataset.familySection;showPage\('family',\{keepFamilyView:true\}\)/);
|
assert.match(code,/familyView=b.dataset.familySection;showPage\('family',\{keepFamilyView:true\}\)/);
|
||||||
assert.match(app,/loadFamily\(!options.keepFamilyView\)/);
|
assert.match(app,/loadFamily\(!options.keepFamilyView,options.personId\)/);
|
||||||
});
|
});
|
||||||
test('culture and property entry requires its separate permission',()=>{
|
test('culture and property entry requires its separate permission',()=>{
|
||||||
const c=vm.createContext({isAdmin:()=>false,currentUser:{familyAccess:'read',heritageAccess:'none'},currentHome:()=>({name:'赵府'}),esc:s=>s,$:()=>output}),output={innerHTML:''};
|
const c=vm.createContext({isAdmin:()=>false,currentUser:{familyAccess:'read',heritageAccess:'none'},currentHome:()=>({name:'赵府'}),esc:s=>s,$:()=>output}),output={innerHTML:''};
|
||||||
|
|||||||
+4
-3
@@ -75,7 +75,7 @@ function showPage(page, options={}) {
|
|||||||
if(page!=='family'&&typeof closeFamilyFullscreen==='function')closeFamilyFullscreen();
|
if(page!=='family'&&typeof closeFamilyFullscreen==='function')closeFamilyFullscreen();
|
||||||
if(page!=='live'&&typeof closeWallFullscreen==='function')closeWallFullscreen();
|
if(page!=='live'&&typeof closeWallFullscreen==='function')closeWallFullscreen();
|
||||||
const pageChanged=activePage!==page;activePage = page;
|
const pageChanged=activePage!==page;activePage = page;
|
||||||
$('.metrics').hidden=['members','accounts','family','users','households','heritage','heritage-records','settings','journal','device'].includes(page);
|
$('.metrics').hidden=['members','accounts','family','users','households','overview','heritage','heritage-records','settings','journal','device'].includes(page);
|
||||||
$('.filter-row').hidden=!['objects','sites','live','playback','cameras'].includes(page)||!!deviceContext;
|
$('.filter-row').hidden=!['objects','sites','live','playback','cameras'].includes(page)||!!deviceContext;
|
||||||
$$('.page').forEach(el => el.hidden = el.id !== 'page-' + page);
|
$$('.page').forEach(el => el.hidden = el.id !== 'page-' + page);
|
||||||
$$('nav button').forEach(b => b.classList.toggle('active', b.dataset.page === page || b.dataset.page==='objects'&&['sites','device','cameras','recorders','live','playback'].includes(page)||b.dataset.page==='heritage'&&['family','heritage-records'].includes(page)));
|
$$('nav button').forEach(b => b.classList.toggle('active', b.dataset.page === page || b.dataset.page==='objects'&&['sites','device','cameras','recorders','live','playback'].includes(page)||b.dataset.page==='heritage'&&['family','heritage-records'].includes(page)));
|
||||||
@@ -85,11 +85,11 @@ function showPage(page, options={}) {
|
|||||||
if(pageChanged)window.scrollTo({top:0,left:0,behavior:'instant'});
|
if(pageChanged)window.scrollTo({top:0,left:0,behavior:'instant'});
|
||||||
if(page==='playback'){$('#archive-source').value=state.cameras.find(c=>c.id===$('#play-camera').value)?.archiveSource==='recorder'?'recorder':'baidu';playbackSourceHint();}
|
if(page==='playback'){$('#archive-source').value=state.cameras.find(c=>c.id===$('#play-camera').value)?.archiveSource==='recorder'?'recorder':'baidu';playbackSourceHint();}
|
||||||
if (page === 'storage') loadAudit();
|
if (page === 'storage') loadAudit();
|
||||||
if (page === 'family') loadFamily(!options.keepFamilyView);
|
if (page === 'family') loadFamily(!options.keepFamilyView,options.personId);
|
||||||
if (page === 'users') loadUsers();
|
if (page === 'users') loadUsers();
|
||||||
if(page==='heritage-records')loadHeritage();
|
if(page==='heritage-records')loadHeritage();
|
||||||
if(page==='settings'&&typeof loadSettings==='function')loadSettings();
|
if(page==='settings'&&typeof loadSettings==='function')loadSettings();
|
||||||
if(page==='journal'&&typeof loadJournal==='function')loadJournal();
|
if(page==='journal'&&typeof loadJournal==='function')loadJournal('',options.person);
|
||||||
}
|
}
|
||||||
function render() {
|
function render() {
|
||||||
$('#metric-all').textContent = state.assets.length+state.recorders.length+(state.devices||[]).length;
|
$('#metric-all').textContent = state.assets.length+state.recorders.length+(state.devices||[]).length;
|
||||||
@@ -97,6 +97,7 @@ function render() {
|
|||||||
$('#metric-sites').textContent = state.sites.length;
|
$('#metric-sites').textContent = state.sites.length;
|
||||||
$('#metric-used').textContent = state.storage.usedGB == null ? '—' : state.storage.usedGB + ' GB';
|
$('#metric-used').textContent = state.storage.usedGB == null ? '—' : state.storage.usedGB + ' GB';
|
||||||
$('#service-status').textContent = state.mediaOnline ? '视频服务已连接' : '视频服务未连接';
|
$('#service-status').textContent = state.mediaOnline ? '视频服务已连接' : '视频服务未连接';
|
||||||
|
$('#service-status').hidden=!['objects','device','live','playback','cameras','recorders','storage'].includes(activePage);
|
||||||
$('#service-status').classList.toggle('off', !state.mediaOnline);
|
$('#service-status').classList.toggle('off', !state.mediaOnline);
|
||||||
$('#version').textContent = state.version ? 'v' + state.version + ' / 独立部署 · 数据自有' : '独立部署 / 数据自有';
|
$('#version').textContent = state.version ? 'v' + state.version + ' / 独立部署 · 数据自有' : '独立部署 / 数据自有';
|
||||||
const warning = state.storage.paused ? state.storage.reason + ',已暂停录像。' : '';
|
const warning = state.storage.paused ? state.storage.reason + ',已暂停录像。' : '';
|
||||||
|
|||||||
+2
-2
@@ -1,6 +1,6 @@
|
|||||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>配套 App · 赵府智家</title><link rel="icon" href="/brand-icon.png"><link rel="stylesheet" href="/vendor/bootstrap.min.css"><link rel="stylesheet" href="/downloads.css"><script src="/downloads.js" defer></script></head>
|
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>配套 App · 赵府智家</title><link rel="icon" href="/brand-icon.png"><link rel="stylesheet" href="/vendor/bootstrap.min.css"><link rel="stylesheet" href="/downloads.css"><script src="/downloads.js" defer></script></head>
|
||||||
<body><main class="container py-4 py-md-5"><a href="/" class="back">← 返回赵府智家</a><section class="card border-0 shadow-sm p-4 p-md-5 mt-4"><div class="d-flex gap-3 align-items-center"><img src="/brand-icon.png" width="60" height="60" alt="赵府"><div><span class="text-secondary small">家庭成员均可下载</span><h1 class="h3 mb-0 mt-1">赵府智家 · 配套 App</h1></div></div><p class="mt-4 text-secondary">一个安装包,支持家庭显示终端和手机位置共享。使用平台账号登录即可下载。</p>
|
<body><main class="container py-4 py-md-5"><a href="/" class="back">← 返回赵府智家</a><section class="card border-0 shadow-sm p-4 p-md-5 mt-4"><div class="d-flex gap-3 align-items-center"><img src="/brand-icon.png" width="60" height="60" alt="赵府"><div><span class="text-secondary small">家庭成员均可下载</span><h1 class="h3 mb-0 mt-1">赵府智家 · 配套 App</h1></div></div><p class="mt-4 text-secondary">一个安装包,支持家庭显示终端和手机家人位置。使用平台账号登录即可下载。</p>
|
||||||
<div class="row g-3 my-2"><div class="col-md-6"><article class="p-3 rounded bg-light h-100"><h2 class="h5">家庭显示终端</h2><p class="mb-0">用于显示时间、天气、家人位置及家庭设备。安装后使用管理员提供的配对码,绑定指定家庭。</p></article></div><div class="col-md-6"><article class="p-3 rounded bg-light h-100"><h2 class="h5">手机位置共享</h2><p class="mb-0">打开“赵府位置共享”,输入绑定到本人档案的配对码,无需登录。核对查看人后由本人开启共享,可随时关闭。</p></article></div></div>
|
<div class="row g-3 my-2"><div class="col-md-6"><article class="p-3 rounded bg-light h-100"><h2 class="h5">家庭显示终端</h2><p class="mb-0">用于显示时间、天气、家人位置及家庭设备。安装后使用管理员提供的配对码,绑定指定家庭。</p></article></div><div class="col-md-6"><article class="p-3 rounded bg-light h-100"><h2 class="h5">手机家人位置</h2><p class="mb-0">手机打开“赵府家人位置”,输入绑定本人档案的手机配对码,无需注册或登录。可查看获授权的家人;“我的位置设置”可选择查看人、实时(约 10 秒)/ 1 分钟 / 5 分钟上传,再由本人打开共享开关。查看家人无需开启自己的定位。</p></article></div></div>
|
||||||
<form id="download-login" class="mt-4" hidden><h2 class="h5">登录后下载</h2><div class="row g-3"><label class="col-md-6">用户名<input class="form-control mt-1" name="username" autocomplete="username" required></label><label class="col-md-6">密码<input class="form-control mt-1" type="password" name="password" autocomplete="current-password" required></label></div><button class="btn btn-success mt-3" type="submit">登录并准备下载</button></form>
|
<form id="download-login" class="mt-4" hidden><h2 class="h5">登录后下载</h2><div class="row g-3"><label class="col-md-6">用户名<input class="form-control mt-1" name="username" autocomplete="username" required></label><label class="col-md-6">密码<input class="form-control mt-1" type="password" name="password" autocomplete="current-password" required></label></div><button class="btn btn-success mt-3" type="submit">登录并准备下载</button></form>
|
||||||
<div id="download-ready" class="mt-4" hidden><a id="apk-link" class="btn btn-success btn-lg" href="/downloads/ZhaoDisplay.apk">下载 Android 安装包</a><p id="release-info" class="small text-secondary mt-3"></p><details class="small"><summary>校验安装包</summary><p class="mt-2">SHA-256</p><code id="apk-hash"></code></details></div><p id="download-status" class="mt-3" role="status">正在检查登录状态…</p><button id="download-retry" class="btn btn-outline-secondary" hidden>重新检查</button>
|
<div id="download-ready" class="mt-4" hidden><a id="apk-link" class="btn btn-success btn-lg" href="/downloads/ZhaoDisplay.apk">下载 Android 安装包</a><p id="release-info" class="small text-secondary mt-3"></p><details class="small"><summary>校验安装包</summary><p class="mt-2">SHA-256</p><code id="apk-hash"></code></details></div><p id="download-status" class="mt-3" role="status">正在检查登录状态…</p><button id="download-retry" class="btn btn-outline-secondary" hidden>重新检查</button>
|
||||||
<hr class="my-4"><p class="small text-secondary mb-0">支持 Android 8.0 及以上,ARM64 / ARMv7。下载后打开 APK,按系统提示完成安装。iPhone 可使用网页;此安装包不适用于 iOS。安装后仍按家庭授权访问资料。</p></section></main></body></html>
|
<hr class="my-4"><p class="small text-secondary mb-0">支持 Android 8.0 及以上,ARM64 / ARMv7。下载后打开 APK,按系统提示完成安装。iPhone 可使用网页;此安装包不适用于 iOS。安装后仍按家庭授权访问资料。</p></section></main></body></html>
|
||||||
|
|||||||
+4
-2
@@ -34,13 +34,15 @@ function familyFormError(form,error){
|
|||||||
button.onclick=async()=>{button.disabled=true;try{if(await loadFamily()){const id=form.elements.id.value;form.closest('dialog').close();if(form.id==='person-form')openPerson(id);else if(form.id==='relation-form')openRelation(id);else editFamilyEvent(id);}}finally{button.disabled=false;}};
|
button.onclick=async()=>{button.disabled=true;try{if(await loadFamily()){const id=form.elements.id.value;form.closest('dialog').close();if(form.id==='person-form')openPerson(id);else if(form.id==='relation-form')openRelation(id);else editFamilyEvent(id);}}finally{button.disabled=false;}};
|
||||||
box.append(button);
|
box.append(button);
|
||||||
}
|
}
|
||||||
async function loadFamily(resetView=false){
|
async function loadFamily(resetView=false,personId=''){
|
||||||
const generation=++familyGeneration;
|
const generation=++familyGeneration;
|
||||||
try{const result=await api('/api/family');if(!loggedIn||generation!==familyGeneration)return;family=result;
|
try{const result=await api('/api/family');if(!loggedIn||generation!==familyGeneration)return;family=result;
|
||||||
if(resetView===true||!family.people.some(p=>p.id===focusPerson))focusPerson=family.selfId||family.people.find(p=>!p.archived)?.id||'';
|
if(resetView===true||!family.people.some(p=>p.id===focusPerson))focusPerson=family.selfId||family.people.find(p=>!p.archived)?.id||'';
|
||||||
|
if(personId&&family.people.some(p=>p.id===personId))focusPerson=personId;
|
||||||
setOptions($('#family-reference'),peopleOptions(false));if(!$('#family-reference').value&&family.selfId)$('#family-reference').value=family.selfId;
|
setOptions($('#family-reference'),peopleOptions(false));if(!$('#family-reference').value&&family.selfId)$('#family-reference').value=family.selfId;
|
||||||
if(!$('#family-reference').dataset.initialized&&family.selfId){$('#family-reference').value=family.selfId;$('#family-reference').dataset.initialized='true';}
|
if(!$('#family-reference').dataset.initialized&&family.selfId){$('#family-reference').value=family.selfId;$('#family-reference').dataset.initialized='true';}
|
||||||
$('#family-error').textContent='';if(resetView===true){familyView='tree';$('#family-search').value='';}renderFamily();if(resetView===true)familyMap.fit();return true;
|
$('#family-error').textContent='';if(resetView===true){familyView='tree';$('#family-search').value='';}renderFamily();if(resetView===true)familyMap.fit();
|
||||||
|
if(personId){if(family.people.some(p=>p.id===personId))selectFamilyPerson(personId,true);else $('#family-error').textContent='该人物已不在当前可查看的族谱中,请返回重新选择。';}return true;
|
||||||
}catch(e){if(!e.stale&&loggedIn&&generation===familyGeneration)$('#family-error').textContent=e.message;return false;}
|
}catch(e){if(!e.stale&&loggedIn&&generation===familyGeneration)$('#family-error').textContent=e.message;return false;}
|
||||||
}
|
}
|
||||||
function relationText(e){return personName(e.fromId)+(e.kind==='parent'?' → 子女:':' ↔ 配偶:')+personName(e.toId)+(e.active?'':'(已停用)');}
|
function relationText(e){return personName(e.fromId)+(e.kind==='parent'?' → 子女:':' ↔ 配偶:')+personName(e.toId)+(e.active?'':'(已停用)');}
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
pageInfo.households=['我的家庭与场所','家庭、办公室或工厂,分别组织,各自授权。'];
|
pageInfo.households=['家族与家庭','从家人出发,连接每一代的亲情与记忆。'];
|
||||||
const scopeKind=h=>({home:'家庭',office:'办公场所',factory:'工厂'}[h.kind||'home']||'家庭');
|
const scopeKind=h=>({home:'家庭',office:'办公场所',factory:'工厂'}[h.kind||'home']||'家庭');
|
||||||
let coverSaving=false;
|
let coverSaving=false;
|
||||||
let homeLayoutDraft=null,homeLayoutOwner='',homeLayoutDirty=false,homeLayoutSaving=false,homePage=0,homeArrange=false,homeDragId='';
|
let homeLayoutDraft=null,homeLayoutOwner='',homeLayoutDirty=false,homeLayoutSaving=false,homePage=0,homeArrange=false,homeDragId='';
|
||||||
|
|||||||
+8
-1
@@ -104,8 +104,15 @@ function leaveJournal(){
|
|||||||
function clearJournalForm(){const f=$('#journal-form');f.reset();for(const key of ['id','revision','clientId','draftId'])f.elements[key].value='';window.ZhaoJournalEditor?.reset();}
|
function clearJournalForm(){const f=$('#journal-form');f.reset();for(const key of ['id','revision','clientId','draftId'])f.elements[key].value='';window.ZhaoJournalEditor?.reset();}
|
||||||
function resetJournal(){leaveJournal();journalQueue.clear();journalBaseline='';journalSaving=false;$('#journal-library-list').replaceChildren();$('#journal-trash-list').replaceChildren();journalData=null;journalPage=0;clearJournalForm();window.ZhaoJournalEditor?.clearMedia();$('#journal-filter').reset();$('#journal-upload-list').replaceChildren();$('#journal-status').textContent='';$('#journal-upload-status').textContent='';$('#journal-person').replaceChildren();$('#journal-files').disabled=true;$('#journal-record').disabled=true;$('#baidu-config').reset();$('#baidu-status').textContent='';$('#baidu-config-status').textContent='';}
|
function resetJournal(){leaveJournal();journalQueue.clear();journalBaseline='';journalSaving=false;$('#journal-library-list').replaceChildren();$('#journal-trash-list').replaceChildren();journalData=null;journalPage=0;clearJournalForm();window.ZhaoJournalEditor?.clearMedia();$('#journal-filter').reset();$('#journal-upload-list').replaceChildren();$('#journal-status').textContent='';$('#journal-upload-status').textContent='';$('#journal-person').replaceChildren();$('#journal-files').disabled=true;$('#journal-record').disabled=true;$('#baidu-config').reset();$('#baidu-status').textContent='';$('#baidu-config-status').textContent='';}
|
||||||
function newJournal(){abandonJournalDraft();stopJournalVoice();clearJournalForm();const f=$('#journal-form');f.elements.clientId.value=journalId();f.elements.draftId.value=journalId();f.elements.occurredOn.value=journalToday();$('#journal-save').textContent='保存记事';journalMessage('默认仅自己可见。选择“当前家庭/场所”后才会进入动态。');journalBaseline=journalDraftSignature();}
|
function newJournal(){abandonJournalDraft();stopJournalVoice();clearJournalForm();const f=$('#journal-form');f.elements.clientId.value=journalId();f.elements.draftId.value=journalId();f.elements.occurredOn.value=journalToday();$('#journal-save').textContent='保存记事';journalMessage('默认仅自己可见。选择“当前家庭/场所”后才会进入动态。');journalBaseline=journalDraftSignature();}
|
||||||
async function loadJournal(focus=''){
|
function selectJournalPerson(person){
|
||||||
|
resetJournalFilters('person');
|
||||||
|
const select=$('#journal-person');
|
||||||
|
if(!Array.from(select.options).some(option=>option.value===person.id))select.add(new Option(person.name,person.id));
|
||||||
|
select.value=person.id;
|
||||||
|
}
|
||||||
|
async function loadJournal(focus='',person=null){
|
||||||
if(journalSaving)return;const g=++journalGeneration;if(!loggedIn)return;
|
if(journalSaving)return;const g=++journalGeneration;if(!loggedIn)return;
|
||||||
|
if(person)selectJournalPerson(person);
|
||||||
if(!$('#journal-form').elements.clientId.value)newJournal();
|
if(!$('#journal-form').elements.clientId.value)newJournal();
|
||||||
$('#journal-person-label').hidden=$('#journal-mode').value!=='person';
|
$('#journal-person-label').hidden=$('#journal-mode').value!=='person';
|
||||||
const query=new URLSearchParams({mode:$('#journal-mode').value,person:$('#journal-person').value,category:$('#journal-category').value,search:$('#journal-search').value,from:$('#journal-from').value,to:$('#journal-to').value,page:String(journalPage),focus});
|
const query=new URLSearchParams({mode:$('#journal-mode').value,person:$('#journal-person').value,category:$('#journal-category').value,search:$('#journal-search').value,from:$('#journal-from').value,to:$('#journal-to').value,page:String(journalPage),focus});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
const appearanceChoices={theme:{paper:'庭院书卷',clean:'清爽明亮',ink:'静夜墨色'},layout:{sidebar:'左侧目录',top:'顶部目录'},density:{comfortable:'舒展',compact:'紧凑'},backdrop:{mountains:'山水背景',plain:'纯色背景'},font:{serif:'宋体标题',sans:'简洁标题'},startPage:{households:'我的家庭与场所',overview:'场所总览',objects:'区域与设备',heritage:'家庭传承'}};
|
const appearanceChoices={theme:{paper:'庭院书卷',clean:'清爽明亮',ink:'静夜墨色'},layout:{sidebar:'左侧目录',top:'顶部目录'},density:{comfortable:'舒展',compact:'紧凑'},backdrop:{mountains:'山水背景',plain:'纯色背景'},font:{serif:'宋体标题',sans:'简洁标题'},startPage:{households:'家族与家庭',overview:'家庭/场所总览',objects:'区域与设备',heritage:'家庭传承'}};
|
||||||
const appearanceLabels={theme:'配色主题',layout:'后台版式',density:'内容疏密',backdrop:'页面背景',font:'标题字体',startPage:'登录后首页'};
|
const appearanceLabels={theme:'配色主题',layout:'后台版式',density:'内容疏密',backdrop:'页面背景',font:'标题字体',startPage:'登录后首页'};
|
||||||
const initialDefaults={theme:'paper',layout:'sidebar',density:'comfortable',backdrop:'mountains',font:'serif',startPage:'households'};
|
const initialDefaults={theme:'paper',layout:'sidebar',density:'comfortable',backdrop:'mountains',font:'serif',startPage:'households'};
|
||||||
let branding={name:'赵府',subtitle:'智能数字管家',motto:'赵氏家宅 · 起居有序',loginTitle:'欢迎回来',loginNote:'输入用户名和密码,进入家庭空间。',footer:'赵府 · 智能数字管家',logoUrl:'/zhao-icon.png',iconUrl:'/zhao-icon.png',defaults:initialDefaults};
|
let branding={name:'赵府',subtitle:'智能数字管家',motto:'赵氏家宅 · 起居有序',loginTitle:'欢迎回来',loginNote:'输入用户名和密码,进入家庭空间。',footer:'赵府 · 智能数字管家',logoUrl:'/zhao-icon.png',iconUrl:'/zhao-icon.png',defaults:initialDefaults};
|
||||||
|
|||||||
+15
-4
@@ -1,12 +1,12 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
let deviceContext=null,scopeEntered=false;
|
let deviceContext=null,scopeEntered=false;
|
||||||
Object.assign(pageInfo,{members:['家庭成员','真实人物与家庭关系,账号可选。'],accounts:['系统用户','统一账号,分别授予家庭访问权限。'],overview:['场所总览','人、区域与设备,在这里各有归属。'],device:['设备档案','查看这台设备的位置、责任人与功能。'],heritage:['家庭传承','把人物、记忆、文化与物品的来历留存下来。']});
|
Object.assign(pageInfo,{members:['家庭成员','真实人物与家庭关系,账号可选。'],accounts:['系统用户','统一账号,分别授予家庭访问权限。'],overview:['家庭总览','家人、共同经历与传承,在这里相连。'],device:['设备档案','查看这台设备的位置、责任人与功能。'],heritage:['家庭传承','把人物、记忆、文化与物品的来历留存下来。']});
|
||||||
function currentHome(){return (state.households||[]).find(h=>h.id===state.familyId);}
|
function currentHome(){return (state.households||[]).find(h=>h.id===state.familyId);}
|
||||||
function scopeReturn(page,device){
|
function scopeReturn(page,device){
|
||||||
if(page==='overview')return {page:'households',label:'所有家庭与场所'};
|
if(page==='overview')return {page:'households',label:'返回家族与家庭'};
|
||||||
if(device||page==='sites')return {page:'objects',label:'返回区域与设备'};
|
if(device||page==='sites')return {page:'objects',label:'返回区域与设备'};
|
||||||
if(['family','heritage-records'].includes(page))return {page:'heritage',label:'返回家庭传承'};
|
if(['family','heritage-records'].includes(page))return {page:'heritage',label:'返回家庭传承'};
|
||||||
return {page:'overview',label:'返回场所总览'};
|
return {page:'overview',label:'返回家庭/场所总览'};
|
||||||
}
|
}
|
||||||
function selectedDevice(){return deviceContext?ZhaoDevices.catalog(state).find(d=>d.id===deviceContext.id&&d.source===deviceContext.source):null;}
|
function selectedDevice(){return deviceContext?ZhaoDevices.catalog(state).find(d=>d.id===deviceContext.id&&d.source===deviceContext.source):null;}
|
||||||
function deviceCameras(cameras,context=deviceContext){
|
function deviceCameras(cameras,context=deviceContext){
|
||||||
@@ -44,12 +44,23 @@ function renderSteward(){
|
|||||||
if(activePage==='device')renderDeviceDetail(device);
|
if(activePage==='device')renderDeviceDetail(device);
|
||||||
if(activePage==='heritage')renderHeritageHome();
|
if(activePage==='heritage')renderHeritageHome();
|
||||||
const homeKind=!home?.kind||home.kind==='home';
|
const homeKind=!home?.kind||home.kind==='home';
|
||||||
|
$('nav [data-page="overview"] span').textContent=homeKind?'家庭总览':'场所总览';
|
||||||
|
if(activePage==='overview')$('#page-title').textContent=homeKind?'家庭总览':'场所总览';
|
||||||
$('nav [data-page="heritage"]').hidden=!homeKind||(!isAdmin()&¤tUser?.familyAccess==='none'&¤tUser?.heritageAccess!=='read'&¤tUser?.heritageAccess!=='edit');
|
$('nav [data-page="heritage"]').hidden=!homeKind||(!isAdmin()&¤tUser?.familyAccess==='none'&¤tUser?.heritageAccess!=='read'&¤tUser?.heritageAccess!=='edit');
|
||||||
}
|
}
|
||||||
function renderOverview(){
|
function renderOverview(){
|
||||||
const home=currentHome();if(!home){$('#scope-overview').replaceChildren();return;}
|
const home=currentHome();if(!home){$('#scope-overview').replaceChildren();return;}
|
||||||
const devices=ZhaoDevices.catalog(state),homeKind=!home.kind||home.kind==='home';
|
const devices=ZhaoDevices.catalog(state),homeKind=!home.kind||home.kind==='home';
|
||||||
$('#scope-overview').innerHTML=`<div class="scope-intro"><span class="eyebrow">${esc(scopeKind(home))} · 日常有序</span><h2>${esc(home.name)}</h2><p>${esc(home.note||'从每一处空间,照看每一件事物。')}</p></div><div class="steward-grid"><button class="steward-tile" data-page="journal"><strong>记事与阅历</strong><span>写日常 · 看动态 · 查阅历</span><small>文字、照片和录音;每条记事自行选择谁可以看</small></button><button class="steward-tile" data-page="objects"><strong>区域与设备</strong><span>${devices.length} 台设备 · ${state.sites.length} 处区域</span><small>按位置、类型或负责人查找,再进入具体设备</small></button><button class="steward-tile" data-open-wall><strong>本场所监控墙</strong><span>${state.cameras.length} 个已授权镜头</span><small>集中观看、排列或全屏;回放可进入对应摄像头</small></button>${homeKind&&(isAdmin()||currentUser?.familyAccess!=='none'||['read','edit'].includes(currentUser?.heritageAccess))?'<button class="steward-tile" data-page="heritage"><strong>家庭传承</strong><span>人物 · 记事 · 文化 · 物品</span><small>从家谱追溯记忆,也保存资料与物品来历</small></button>':''}${homeKind?'<button class="steward-tile" data-page="members"><strong>家庭成员</strong><span>真实人物 · 亲属关系</span><small>登记老人和孩子,无需为每个人注册账号</small></button>':''}</div>`;
|
const canHeritage=homeKind&&(isAdmin()||currentUser?.familyAccess!=='none'||['read','edit'].includes(currentUser?.heritageAccess));
|
||||||
|
const equipmentOpen=$('#overview-equipment')?.open===true;
|
||||||
|
const equipment=`<div class="steward-grid"><button class="steward-tile" data-page="objects"><strong>区域与设备</strong><span>${devices.length} 台设备 · ${state.sites.length} 处区域</span><small>按位置、类型或负责人查找,再进入具体设备</small></button><button class="steward-tile" data-open-wall><strong>监控墙</strong><span>${state.cameras.length} 个已授权镜头</span><small>集中观看、排列或全屏;回放可进入对应摄像头</small></button></div>`;
|
||||||
|
$('#scope-overview').innerHTML=`<div class="scope-intro"><span class="eyebrow">${esc(scopeKind(home))} · ${homeKind?'家人在一起':'日常有序'}</span><h2>${esc(home.name)}</h2><p>${esc(home.note||(homeKind?'记下每一位家人,留住共同的经历。':'查看本场所的日常记录与设备。'))}</p></div>
|
||||||
|
<div class="steward-grid">
|
||||||
|
${homeKind?`<button class="steward-tile" data-page="members"><strong>家庭成员</strong><span>${home.members||0} 位家人 · 多代同属一个家庭</span><small>查看亲属、人物档案和阅历;家人无需注册账号</small></button>`:''}
|
||||||
|
<button class="steward-tile" data-page="journal"><strong>记事与阅历</strong><span>写日常 · 看动态 · 查阅历</span><small>文字、照片和录音,记录共同参与的故事</small></button>
|
||||||
|
${canHeritage?'<button class="steward-tile" data-page="heritage"><strong>家庭传承</strong><span>人物 · 记事 · 文化 · 物品</span><small>从家谱追溯记忆,留存家风与珍贵的来历</small></button>':''}
|
||||||
|
</div>
|
||||||
|
${homeKind?`<details id="overview-equipment" class="panel mt-4" ${equipmentOpen?'open':''}><summary>家庭设备与监控</summary><div class="mt-3">${equipment}</div></details>`:equipment}`;
|
||||||
}
|
}
|
||||||
function renderDeviceDetail(device){
|
function renderDeviceDetail(device){
|
||||||
if(!device){$('#device-detail').innerHTML=empty('设备暂不可用','返回设备目录重新选择');return;}
|
if(!device){$('#device-detail').innerHTML=empty('设备暂不可用','返回设备目录重新选择');return;}
|
||||||
|
|||||||
+1
-1
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+3
-3
@@ -1,5 +1,5 @@
|
|||||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#244d43"><link rel="icon" href="/zhao-icon.png"><link rel="apple-touch-icon" href="/zhao-icon.png"><title>赵府 · 智能数字管家</title> <script type="module" crossorigin src="/ui/assets/index-CqaRDB4R.js"></script>
|
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#244d43"><link rel="icon" href="/zhao-icon.png"><link rel="apple-touch-icon" href="/zhao-icon.png"><title>赵府 · 智能数字管家</title> <script type="module" crossorigin src="/ui/assets/index-BQy_ONYB.js"></script>
|
||||||
<link rel="modulepreload" crossorigin href="/ui/assets/bootstrap.min-C5Nka04t.js">
|
<link rel="modulepreload" crossorigin href="/ui/assets/bootstrap.min-CBPvWlfP.js">
|
||||||
<link rel="stylesheet" crossorigin href="/ui/assets/bootstrap-DBkz-poX.css">
|
<link rel="stylesheet" crossorigin href="/ui/assets/bootstrap-DBkz-poX.css">
|
||||||
<link rel="stylesheet" crossorigin href="/ui/assets/index-Bd4o8mRo.css">
|
<link rel="stylesheet" crossorigin href="/ui/assets/index-COmDIIIH.css">
|
||||||
</head><body><div id="app"></div></body></html>
|
</head><body><div id="app"></div></body></html>
|
||||||
|
|||||||
+2
-2
@@ -1,5 +1,5 @@
|
|||||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f3eee4"><meta name="referrer" content="no-referrer"><link rel="icon" href="/zhao-icon.png"><title>赵府 · 家庭时光</title> <script type="module" crossorigin src="/ui/assets/tv-DDoY_KKv.js"></script>
|
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f3eee4"><meta name="referrer" content="no-referrer"><link rel="icon" href="/zhao-icon.png"><title>赵府 · 家庭时光</title> <script type="module" crossorigin src="/ui/assets/tv-D-PRuWjc.js"></script>
|
||||||
<link rel="modulepreload" crossorigin href="/ui/assets/bootstrap.min-C5Nka04t.js">
|
<link rel="modulepreload" crossorigin href="/ui/assets/bootstrap.min-CBPvWlfP.js">
|
||||||
<link rel="stylesheet" crossorigin href="/ui/assets/bootstrap-DBkz-poX.css">
|
<link rel="stylesheet" crossorigin href="/ui/assets/bootstrap-DBkz-poX.css">
|
||||||
<link rel="stylesheet" crossorigin href="/ui/assets/tv-B6bAW3Pb.css">
|
<link rel="stylesheet" crossorigin href="/ui/assets/tv-B6bAW3Pb.css">
|
||||||
</head><body><div id="app"></div></body></html>
|
</head><body><div id="app"></div></body></html>
|
||||||
|
|||||||
@@ -6,6 +6,16 @@ Object.assign(window.ZhaoVue,{
|
|||||||
async saveLayout(value){const saved=await api('/api/households/layout',value);state.householdLayout=saved;this.publish();return saved;},
|
async saveLayout(value){const saved=await api('/api/households/layout',value);state.householdLayout=saved;this.publish();return saved;},
|
||||||
async enterHome(id,network=false){try{if(id!==state.familyId&&!await switchHousehold(id))return;if(network){devicePresentation='topology';showPage('objects');}else showPage('overview');}catch(e){if(!e.stale)toast(e.message);}},
|
async enterHome(id,network=false){try{if(id!==state.familyId&&!await switchHousehold(id))return;if(network){devicePresentation='topology';showPage('objects');}else showPage('overview');}catch(e){if(!e.stale)toast(e.message);}},
|
||||||
enterDevice,showPage,
|
enterDevice,showPage,
|
||||||
|
async viewPerson(id,familyId){
|
||||||
|
if(familyId!==state.familyId&&!await switchHousehold(familyId))return;
|
||||||
|
if(!loggedIn||state.familyId!==familyId)return;
|
||||||
|
showPage('family',{personId:id});
|
||||||
|
},
|
||||||
|
async viewMemberHistory(id,name,familyId){
|
||||||
|
if(familyId!==state.familyId&&!await switchHousehold(familyId))return;
|
||||||
|
if(!loggedIn||state.familyId!==familyId)return;
|
||||||
|
showPage('journal',{person:{id,name}});
|
||||||
|
},
|
||||||
async editAccount(id,familyId){if(familyId!==state.familyId&&!await switchHousehold(familyId))return;showPage('users');if(await loadUsers())openUser(id);},
|
async editAccount(id,familyId){if(familyId!==state.familyId&&!await switchHousehold(familyId))return;showPage('users');if(await loadUsers())openUser(id);},
|
||||||
location(id){return siteName(id);},
|
location(id){return siteName(id);},
|
||||||
network(device){return ZhaoDevices.network(device,state);}
|
network(device){return ZhaoDevices.network(device,state);}
|
||||||
|
|||||||
Reference in New Issue
Block a user