fix display pairing and add scoped family voice announcements
This commit is contained in:
@@ -1,5 +1,9 @@
|
|||||||
# 赵府智家 · 视觉系统
|
# 赵府智家 · 视觉系统
|
||||||
|
|
||||||
|
## v0.1.48 · 显示终端与家人喊话
|
||||||
|
|
||||||
|
修复重新配对后的旧授权残留;手机配对后直接进入家人位置,并提供按住说话、松开发送。接收方选择具体喊话人,默认关闭;显示终端可以先接收,装好话筒后再发送。手机与显示终端分别提供普通 APK。[本版说明](RELEASE-v0.1.48.md)。
|
||||||
|
|
||||||
## v0.1.45 · 家人位置与家庭入口
|
## v0.1.45 · 家人位置与家庭入口
|
||||||
|
|
||||||
手机打开「赵府家人位置」,凭本人家庭成员配对码使用,无需注册或登录。可查看明确授权给这台手机的家人;在「我的位置设置」选择查看人、实时(约 10 秒)/ 1 分钟 / 5 分钟上传,并由本人开启共享。查看家人不要求共享自己的位置。详见 [发布说明与操作步骤](RELEASE-v0.1.45.md)。
|
手机打开「赵府家人位置」,凭本人家庭成员配对码使用,无需注册或登录。可查看明确授权给这台手机的家人;在「我的位置设置」选择查看人、实时(约 10 秒)/ 1 分钟 / 5 分钟上传,并由本人开启共享。查看家人不要求共享自己的位置。详见 [发布说明与操作步骤](RELEASE-v0.1.45.md)。
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# v0.1.48 · 显示终端恢复与家人喊话
|
||||||
|
|
||||||
|
## 显示终端
|
||||||
|
|
||||||
|
- 修复 App 配对后只改变 URL 片段、网页沿用旧展示授权的问题。新链接立即切换;旧请求迟到的 401 不会清除新授权。网络暂时中断继续重试,真正失效则清空家庭资料并显示重新连接说明。
|
||||||
|
- 原生 App 配对后加载新页面,防止停留在旧家庭。显示终端安装包为普通 APK,保留桌面图标,不声明 HOME,不替换系统桌面,不注册开机广播。
|
||||||
|
- 手机和显示终端提供分别下载的安装包,同一应用签名及包名,versionCode 4。手机安装「家人位置版」,显示终端安装「显示终端版」;不能在同一设备并排安装。
|
||||||
|
- 手机未配对时先进入配对页;已配对直接显示获授权家人位置。定位共享仍由本人主动开启,喊话不打开定位。
|
||||||
|
|
||||||
|
## 按住说话,松开发送
|
||||||
|
|
||||||
|
1. 双方使用本版 App 并完成各自的手机或显示终端配对。
|
||||||
|
2. 接收方在底部「接收设置」选择允许的具体家人手机或终端,并确认开启接收。管理员也可在平台的「显示终端管理 → 家人喊话」设置该终端的接收名单。默认关闭,不因同家庭、能看位置或超级管理员身份自动接收喊话。
|
||||||
|
3. 发送方选择在线对象,按住话筒录音、松开发送。首次使用需同意 Android 麦克风权限;授权动作不自动开始录音。录制时移出按钮后松开、系统取消触摸或切到后台,都会丢弃录音。
|
||||||
|
4. 单条最多 30 秒;到上限结束并发送。发送方显示排队、接收、播放或未播放状态;接收方显示喊话人,可停止播放、关闭接收。使用系统媒体音量,不强行调高音量。
|
||||||
|
5. App 打开在前台时接收;不做锁屏后台呼叫。显示终端没有话筒也可接收;连接话筒后可发送。此版为短语音喊话,不是连续双向通话。
|
||||||
|
|
||||||
|
## 存储与权限
|
||||||
|
|
||||||
|
- 每条 AAC 语音最多 150 KB,服务端内存中短暂排队,90 秒未接收过期;接收即移除音频。回执最多保留 180 秒,后台定时清理。音频不写数据库、不上传百度网盘。
|
||||||
|
- 手机和终端在自己的缓存目录暂存录制/播放文件,发送完、取消、播放完或退出页面删除;App 下次打开清理上次异常退出留下的语音缓存。
|
||||||
|
- 原生显示终端使用单独的 nativeToken,网页展示令牌不能喊话。家庭范围、有效配对、有效成员、接收名单在发送和领取时复查。跨家庭、已撤销、已过期和已迁移设备不可访问。
|
||||||
|
- 重新配对产生新身份,需要接收方重新允许。请求编号去重、队列与频率均有上限,不重复自动播放已领取的语音。
|
||||||
|
|
||||||
|
Android 录音和焦点处理依据:[MediaRecorder](https://developer.android.com/media/platform/mediarecorder)、[音频焦点](https://developer.android.com/media/optimize/audio-focus)。
|
||||||
|
|
||||||
|
## 验收
|
||||||
|
|
||||||
|
包含展示授权切换与请求竞争、家庭隔离、单向接收授权、重复发送、过期/静音/撤销清理、下载包权限、手机与终端入口测试。实机录音仍取决于用户后续安装的麦克风;软件编译和接收测试不能替代该话筒的实测。
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="4" android:versionName="0.1.48">
|
||||||
|
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30" />
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
|
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_COARSE_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">
|
||||||
|
<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.LEANBACK_LAUNCHER" />
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
<service android:name=".MonitorService" android:exported="false" />
|
||||||
|
<activity android:name=".LocationActivity" android:label="赵府家人位置" android:exported="true" />
|
||||||
|
<service android:name=".LocationService" android:exported="false" android:foregroundServiceType="location" />
|
||||||
|
</application>
|
||||||
|
</manifest>
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="3" android:versionName="0.1.45">
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="4" android:versionName="0.1.48">
|
||||||
<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.RECORD_AUDIO"/>
|
||||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
|
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
param([string]$ToolRoot='C:\Users\Administrator\Documents\ChatGPT\优创未来\services\toplc-vpn-android\.tools')
|
param([string]$ToolRoot='C:\Users\Administrator\Documents\ChatGPT\优创未来\services\toplc-vpn-android\.tools',[switch]$Terminal)
|
||||||
$ErrorActionPreference='Stop'
|
$ErrorActionPreference='Stop'
|
||||||
$source=Split-Path -Parent $MyInvocation.MyCommand.Path
|
$source=Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||||
$stage=Join-Path 'C:\CodexBuild' ('ZhaoDisplay-'+[guid]::NewGuid().ToString('N'))
|
$stage=Join-Path 'C:\CodexBuild' ('ZhaoDisplay-'+[guid]::NewGuid().ToString('N'))
|
||||||
New-Item -ItemType Directory -Path $stage | Out-Null
|
New-Item -ItemType Directory -Path $stage | Out-Null
|
||||||
Copy-Item -LiteralPath (Join-Path $source 'AndroidManifest.xml') -Destination $stage
|
$manifest=if($Terminal){'AndroidManifest-terminal.xml'}else{'AndroidManifest.xml'}
|
||||||
|
$apkName=if($Terminal){'ZhaoTerminal.apk'}else{'ZhaoDisplay.apk'}
|
||||||
|
Copy-Item -LiteralPath (Join-Path $source $manifest) -Destination (Join-Path $stage 'AndroidManifest.xml')
|
||||||
Copy-Item -LiteralPath (Join-Path $source 'res'),(Join-Path $source 'src') -Destination $stage -Recurse
|
Copy-Item -LiteralPath (Join-Path $source 'res'),(Join-Path $source 'src') -Destination $stage -Recurse
|
||||||
$jdk=Join-Path $ToolRoot 'jdk-staging\jdk-21.0.12.1+1'
|
$jdk=Join-Path $ToolRoot 'jdk-staging\jdk-21.0.12.1+1'
|
||||||
$sdk=Join-Path $ToolRoot 'android-sdk'
|
$sdk=Join-Path $ToolRoot 'android-sdk'
|
||||||
@@ -53,8 +55,8 @@ if(!(Test-Path -LiteralPath $keystore)){
|
|||||||
if($LASTEXITCODE){throw 'Signing key generation failed'}
|
if($LASTEXITCODE){throw 'Signing key generation failed'}
|
||||||
}
|
}
|
||||||
New-Item -ItemType Directory -Force -Path "$source\build" | Out-Null
|
New-Item -ItemType Directory -Force -Path "$source\build" | Out-Null
|
||||||
& "$bt\apksigner.bat" sign --ks $keystore --ks-pass pass:android --key-pass pass:android --ks-key-alias zhaodisplay --out "$source\build\ZhaoDisplay.apk" "$build\aligned.apk"
|
& "$bt\apksigner.bat" sign --ks $keystore --ks-pass pass:android --key-pass pass:android --ks-key-alias zhaodisplay --out "$source\build\$apkName" "$build\aligned.apk"
|
||||||
if($LASTEXITCODE){throw 'APK signing failed'}
|
if($LASTEXITCODE){throw 'APK signing failed'}
|
||||||
& "$bt\apksigner.bat" verify "$source\build\ZhaoDisplay.apk"
|
& "$bt\apksigner.bat" verify "$source\build\$apkName"
|
||||||
if($LASTEXITCODE){throw 'APK verification failed'}
|
if($LASTEXITCODE){throw 'APK verification failed'}
|
||||||
Write-Output "$source\build\ZhaoDisplay.apk"
|
Write-Output "$source\build\$apkName"
|
||||||
|
|||||||
@@ -15,7 +15,8 @@ import java.util.*;
|
|||||||
public class LocationActivity extends Activity {
|
public class LocationActivity extends Activity {
|
||||||
static volatile boolean pairing=false;
|
static volatile boolean pairing=false;
|
||||||
TextView identity,status,viewStatus;EditText code;Button pair,reload;
|
TextView identity,status,viewStatus;EditText code;Button pair,reload;
|
||||||
CheckBox consent;Switch sharing;Spinner cadence;LinearLayout settings,recipients,familyList;
|
CheckBox consent;Switch sharing;Spinner cadence;LinearLayout settings,recipients,familyList,homeContent,shareControls;
|
||||||
|
VoicePanel voice;Button settingsButton;
|
||||||
LocationMapView map;boolean rendering=false,visible=false,loading=false,settingsReady=false,pendingStart=false;
|
LocationMapView map;boolean rendering=false,visible=false,loading=false,settingsReady=false,pendingStart=false;
|
||||||
int generation=0,settingsRequest=0;long lastList=0;String settingsReceipt="",settingsError="";
|
int generation=0,settingsRequest=0;long lastList=0;String settingsReceipt="",settingsError="";
|
||||||
final Map<String,List<CheckBox>> choices=new HashMap<>();
|
final Map<String,List<CheckBox>> choices=new HashMap<>();
|
||||||
@@ -34,34 +35,39 @@ public class LocationActivity extends Activity {
|
|||||||
startService(new Intent(this,LocationService.class).setAction("STOP"));
|
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);
|
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);
|
LinearLayout root=new LinearLayout(this);root.setOrientation(1);ScrollView scroll=new ScrollView(this);scroll.addView(layout);root.addView(scroll,new LinearLayout.LayoutParams(-1,0,1));setContentView(root);
|
||||||
text("家人位置",30,layout);identity=text("",17,layout);
|
text("家人位置",30,layout);identity=text("",17,layout);
|
||||||
text("只显示家人主动授权给这台手机的位置。查看家人不需要开启自己的定位。",16,layout);
|
text("只显示家人主动授权给这台手机的位置。查看家人不需要开启自己的定位。",16,layout);
|
||||||
button("我的位置设置",layout).setOnClickListener(v->{settings.setVisibility(settings.getVisibility()==View.VISIBLE?View.GONE:View.VISIBLE);if(settings.getVisibility()==View.VISIBLE)loadSettings();});
|
settingsButton=button("我的位置设置",layout);settingsButton.setOnClickListener(v->{settings.setVisibility(settings.getVisibility()==View.VISIBLE?View.GONE:View.VISIBLE);if(settings.getVisibility()==View.VISIBLE)loadSettings();});
|
||||||
status=text("",16,layout);
|
status=text("",16,layout);
|
||||||
settings=new LinearLayout(this);settings.setOrientation(1);layout.addView(settings);
|
settings=new LinearLayout(this);settings.setOrientation(1);layout.addView(settings);
|
||||||
text("配对本人 · 无需注册或登录",22,settings);
|
text("配对本人 · 无需注册或登录",22,settings);
|
||||||
text("请家人在平台进入家庭总览 → 为家庭成员配对手机,选择你的成员档案。这里使用手机配对码,不使用显示终端配对码。",16,settings);
|
text("请家人在平台进入家庭总览 → 为家庭成员配对手机,选择你的成员档案。这里使用手机配对码,不使用显示终端配对码。",16,settings);
|
||||||
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);
|
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);
|
||||||
pair=button("配对我的手机",settings);pair.setOnClickListener(v->pair());
|
pair=button("配对我的手机",settings);pair.setOnClickListener(v->pair());
|
||||||
text("我的位置共享",22,settings);text("选择谁能看我的位置",16,settings);
|
shareControls=new LinearLayout(this);shareControls.setOrientation(1);settings.addView(shareControls);
|
||||||
recipients=new LinearLayout(this);recipients.setOrientation(1);settings.addView(recipients);
|
text("我的位置共享",22,shareControls);text("选择谁能看我的位置",16,shareControls);
|
||||||
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);
|
recipients=new LinearLayout(this);recipients.setOrientation(1);shareControls.addView(recipients);
|
||||||
text("实时档更耗电和流量;更新受信号、网络与系统省电影响。调整名单或频率前,先关闭共享。",14,settings);
|
text("上传频率",16,shareControls);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);shareControls.addView(cadence);
|
||||||
consent=new CheckBox(this);consent.setText("我已核对本人身份、有效期和所选查看人,同意按上述频率共享位置。关闭后停止采集并清除位置。");settings.addView(consent);
|
text("实时档更耗电和流量;更新受信号、网络与系统省电影响。调整名单或频率前,先关闭共享。",14,shareControls);
|
||||||
sharing=new Switch(this);sharing.setText("共享我的位置");sharing.setTextSize(20);sharing.setPadding(0,20,0,20);settings.addView(sharing);
|
consent=new CheckBox(this);consent.setText("我已核对本人身份、有效期和所选查看人,同意按上述频率共享位置。关闭后停止采集并清除位置。");shareControls.addView(consent);
|
||||||
|
sharing=new Switch(this);sharing.setText("共享我的位置");sharing.setTextSize(20);sharing.setPadding(0,20,0,20);shareControls.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();});
|
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)));
|
button("打开手机系统定位设置",shareControls).setOnClickListener(v->startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)));
|
||||||
settings.setVisibility(prefs.getString("token","").isEmpty()?View.VISIBLE:View.GONE);
|
settings.setVisibility(prefs.getString("token","").isEmpty()?View.VISIBLE:View.GONE);
|
||||||
text("家人现在的位置",22,layout);viewStatus=text("",16,layout);
|
homeContent=new LinearLayout(this);homeContent.setOrientation(1);layout.addView(homeContent);
|
||||||
map=new LocationMapView(this);layout.addView(map,new LinearLayout.LayoutParams(-1,(int)(260*getResources().getDisplayMetrics().density)));
|
text("家人现在的位置",22,homeContent);viewStatus=text("",16,homeContent);
|
||||||
text("世界位置概览 · 可拖动、双指缩放;点家人卡片定位。底图为本地陆地轮廓,不含道路。",13,layout);
|
map=new LocationMapView(this);homeContent.addView(map,new LinearLayout.LayoutParams(-1,(int)(260*getResources().getDisplayMetrics().density)));
|
||||||
button("查看全部位置",layout).setOnClickListener(v->map.reset());
|
text("世界位置概览 · 可拖动、双指缩放;点家人卡片定位。底图为本地陆地轮廓,不含道路。",13,homeContent);
|
||||||
reload=button("刷新家人位置",layout);reload.setOnClickListener(v->loadFamily());
|
button("查看全部位置",homeContent).setOnClickListener(v->map.reset());
|
||||||
familyList=new LinearLayout(this);familyList.setOrientation(1);layout.addView(familyList);render();
|
reload=button("刷新家人位置",homeContent);reload.setOnClickListener(v->loadFamily());
|
||||||
|
familyList=new LinearLayout(this);familyList.setOrientation(1);homeContent.addView(familyList);
|
||||||
|
voice=new VoicePanel(this,"phone",()->prefs.getString("token",""));root.addView(voice,new LinearLayout.LayoutParams(-1,-2));render();
|
||||||
}
|
}
|
||||||
void render(){
|
void render(){
|
||||||
boolean paired=!prefs.getString("token","").isEmpty(),active=prefs.getBoolean("active",false),busy=pairing||LocationService.busy;
|
boolean paired=!prefs.getString("token","").isEmpty(),active=prefs.getBoolean("active",false),busy=pairing||LocationService.busy;
|
||||||
|
homeContent.setVisibility(paired?View.VISIBLE:View.GONE);shareControls.setVisibility(paired?View.VISIBLE:View.GONE);settingsButton.setVisibility(paired?View.VISIBLE:View.GONE);voice.setVisibility(paired?View.VISIBLE:View.GONE);
|
||||||
|
if(!paired)settings.setVisibility(View.VISIBLE);
|
||||||
long expires=prefs.getLong("expires",0);
|
long expires=prefs.getLong("expires",0);
|
||||||
identity.setText(prefs.getString("memberName","尚未配对本人")+" · "+prefs.getString("home","请在我的位置设置中配对")+(expires>0?"\n配对有效至 "+java.text.DateFormat.getDateTimeInstance().format(new Date(expires)):""));
|
identity.setText(prefs.getString("memberName","尚未配对本人")+" · "+prefs.getString("home","请在我的位置设置中配对")+(expires>0?"\n配对有效至 "+java.text.DateFormat.getDateTimeInstance().format(new Date(expires)):""));
|
||||||
status.setText(settingsError.isEmpty()?"我的位置:"+prefs.getString("status","共享关闭,不采集定位"):settingsError);
|
status.setText(settingsError.isEmpty()?"我的位置:"+prefs.getString("status","共享关闭,不采集定位"):settingsError);
|
||||||
@@ -82,7 +88,7 @@ public class LocationActivity extends Activity {
|
|||||||
new Thread(()->{try{
|
new Thread(()->{try{
|
||||||
JSONObject response=DisplayApi.call("/api/location/pair",null,new JSONObject().put("code",value).put("consentProtocol",3));remember(response);
|
JSONObject response=DisplayApi.call("/api/location/pair",null,new JSONObject().put("code",value).put("consentProtocol",3));remember(response);
|
||||||
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("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(()->{if(isDestroyed())return;pairing=false;generation++;loading=false;familyList.removeAllViews();map.setItems(new JSONArray());code.setText("");consent.setChecked(false);settingsReady=false;settings.setVisibility(View.GONE);voice.rebound();loadSettings();loadFamily();});
|
||||||
}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(()->{if(!isDestroyed())Toast.makeText(this,"配对未成功,请检查手机配对码或安装新版 App",1).show();});}finally{pairing=false;runOnUiThread(()->{if(!isDestroyed())render();});}},"location-pair").start();
|
||||||
}
|
}
|
||||||
void loadFamily(){
|
void loadFamily(){
|
||||||
@@ -93,7 +99,7 @@ public class LocationActivity extends Activity {
|
|||||||
runOnUiThread(()->{if(!visible||g!=generation)return;JSONArray list=response.optJSONArray("items");map.setItems(list);familyList.removeAllViews();viewStatus.setText(list==null||list.length()==0?"尚无家人授权给这台手机的位置。请对方在自己的位置设置里勾选你的手机,并开启共享。":"只显示仍在授权有效期内的最新位置。");
|
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);});}
|
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();
|
}catch(Exception e){runOnUiThread(()->{if(!visible||g!=generation)return;familyList.removeAllViews();map.setItems(new JSONArray());if(e instanceof DisplayApi.ApiError&&(((DisplayApi.ApiError)e).status==401||((DisplayApi.ApiError)e).status==403)){prefs.edit().remove("token").putBoolean("active",false).apply();startService(new Intent(this,LocationService.class).setAction("STOP"));voice.rebound();settings.setVisibility(View.VISIBLE);}viewStatus.setText(e instanceof DisplayApi.ApiError&&((DisplayApi.ApiError)e).status==401?"手机配对已过期或解除,请重新配对。":"位置未能刷新,已隐藏旧画面,请检查网络。");});}finally{runOnUiThread(()->{if(g==generation){loading=false;render();}});}},"family-positions").start();
|
||||||
}
|
}
|
||||||
void loadSettings(){
|
void loadSettings(){
|
||||||
String token=prefs.getString("token","");if(token.isEmpty()||pairing)return;int g=generation,request=++settingsRequest;settingsReady=false;settingsError="";render();
|
String token=prefs.getString("token","");if(token.isEmpty()||pairing)return;int g=generation,request=++settingsRequest;settingsReady=false;settingsError="";render();
|
||||||
@@ -116,7 +122,7 @@ public class LocationActivity extends Activity {
|
|||||||
finally{pairing=false;runOnUiThread(()->{if(!isDestroyed()){if(visible&&!settingsReady)loadSettings();render();}});}},"location-configure").start();
|
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){if(visible)start();else pendingStart=true;}else Toast.makeText(this,"未授权定位,不采集自己的位置;仍可查看获授权家人",1).show();render();}}
|
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 onResume(){super.onResume();visible=true;voice.active(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 onPause(){visible=false;voice.active(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(){if(voice!=null)voice.close();ui.removeCallbacksAndMessages(null);super.onDestroy();}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ public class MainActivity extends Activity {
|
|||||||
static volatile MainActivity active;
|
static volatile MainActivity active;
|
||||||
WebView web;
|
WebView web;
|
||||||
CameraStrip cameras;
|
CameraStrip cameras;
|
||||||
|
VoicePanel voice;
|
||||||
final Handler themeHandler=new Handler();
|
final Handler themeHandler=new Handler();
|
||||||
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) {
|
||||||
@@ -47,6 +48,7 @@ public class MainActivity extends Activity {
|
|||||||
LinearLayout layout=new LinearLayout(this);layout.setOrientation(LinearLayout.VERTICAL);
|
LinearLayout layout=new LinearLayout(this);layout.setOrientation(LinearLayout.VERTICAL);
|
||||||
layout.addView(web,new LinearLayout.LayoutParams(-1,0,88));
|
layout.addView(web,new LinearLayout.LayoutParams(-1,0,88));
|
||||||
cameras=new CameraStrip(this);layout.addView(cameras,new LinearLayout.LayoutParams(-1,0,12));
|
cameras=new CameraStrip(this);layout.addView(cameras,new LinearLayout.LayoutParams(-1,0,12));
|
||||||
|
voice=new VoicePanel(this,"display",()->getSharedPreferences("display",0).getString("nativeToken",""));layout.addView(voice,new LinearLayout.LayoutParams(-1,-2));
|
||||||
setContentView(layout);
|
setContentView(layout);
|
||||||
themeHandler.post(themeTick);
|
themeHandler.post(themeTick);
|
||||||
configure(getIntent());
|
configure(getIntent());
|
||||||
@@ -55,14 +57,15 @@ public class MainActivity extends Activity {
|
|||||||
String code=intent.getStringExtra("pairing_code");
|
String code=intent.getStringExtra("pairing_code");
|
||||||
if(code!=null&&code.matches("[0-9]{8}")){intent.removeExtra("pairing_code");pair(code);return;}
|
if(code!=null&&code.matches("[0-9]{8}")){intent.removeExtra("pairing_code");pair(code);return;}
|
||||||
String token=getSharedPreferences("display",MODE_PRIVATE).getString("token","");
|
String token=getSharedPreferences("display",MODE_PRIVATE).getString("token","");
|
||||||
web.loadUrl("https://zhao.ucvl.cn/tv"+(token.isEmpty()?"":"#display="+token));
|
// A changed fragment alone does not reload an existing WebView document.
|
||||||
|
web.loadUrl("https://zhao.ucvl.cn/tv?client=android&load="+System.currentTimeMillis()+(token.isEmpty()?"":"#display="+token));
|
||||||
if(!token.isEmpty())startForegroundService(new Intent(this,MonitorService.class));
|
if(!token.isEmpty())startForegroundService(new Intent(this,MonitorService.class));
|
||||||
else pairDialog();
|
else pairDialog();
|
||||||
}
|
}
|
||||||
void pairDialog(){
|
void pairDialog(){
|
||||||
EditText code=new EditText(this);code.setInputType(InputType.TYPE_CLASS_NUMBER);code.setHint("8 位家庭屏配对码");
|
EditText code=new EditText(this);code.setInputType(InputType.TYPE_CLASS_NUMBER);code.setHint("8 位家庭屏配对码");
|
||||||
code.setFilters(new android.text.InputFilter[]{new android.text.InputFilter.LengthFilter(8)});
|
code.setFilters(new android.text.InputFilter[]{new android.text.InputFilter.LengthFilter(8)});
|
||||||
new AlertDialog.Builder(this).setTitle("绑定家庭中心").setMessage("在赵府智家中进入目标家庭 → 电视设备 → 电视管理 → 生成配对码。更换家庭前,请先由管理员移动这台设备的归属。")
|
new AlertDialog.Builder(this).setTitle("绑定家庭显示终端").setMessage("在赵府智家中进入目标家庭 → 显示终端设备 → 显示终端管理 → 生成配对码。更换家庭前,请先由管理员移动这台设备的归属。")
|
||||||
.setView(code).setNegativeButton("取消",null).setPositiveButton("绑定",(dialog,which)->pair(code.getText().toString().trim())).show();
|
.setView(code).setNegativeButton("取消",null).setPositiveButton("绑定",(dialog,which)->pair(code.getText().toString().trim())).show();
|
||||||
}
|
}
|
||||||
void pair(String code){
|
void pair(String code){
|
||||||
@@ -71,19 +74,20 @@ public class MainActivity extends Activity {
|
|||||||
try{
|
try{
|
||||||
JSONObject value=DisplayApi.call("/api/display/pair",null,new JSONObject().put("code",code));
|
JSONObject value=DisplayApi.call("/api/display/pair",null,new JSONObject().put("code",code));
|
||||||
getSharedPreferences("display",MODE_PRIVATE).edit().putString("token",value.getString("token")).putString("nativeToken",value.getString("nativeToken")).apply();
|
getSharedPreferences("display",MODE_PRIVATE).edit().putString("token",value.getString("token")).putString("nativeToken",value.getString("nativeToken")).apply();
|
||||||
runOnUiThread(()->{configure(new Intent());cameras.refresh();Toast.makeText(this,"已绑定:"+value.optString("home"),Toast.LENGTH_LONG).show();});
|
runOnUiThread(()->{configure(new Intent());cameras.refresh();voice.rebound();Toast.makeText(this,"已绑定:"+value.optString("home"),Toast.LENGTH_LONG).show();});
|
||||||
}catch(Exception e){runOnUiThread(()->Toast.makeText(this,"绑定未成功,请检查网络或重新生成配对码",Toast.LENGTH_LONG).show());}
|
}catch(Exception e){runOnUiThread(()->Toast.makeText(this,"绑定未成功,请检查网络或重新生成配对码",Toast.LENGTH_LONG).show());}
|
||||||
},"display-pair").start();
|
},"display-pair").start();
|
||||||
}
|
}
|
||||||
@Override public void onNewIntent(Intent intent){super.onNewIntent(intent);setIntent(intent);configure(intent);}
|
@Override public void onNewIntent(Intent intent){super.onNewIntent(intent);setIntent(intent);configure(intent);}
|
||||||
@Override public void onResume(){super.onResume();active=this;immersive();if(cameras!=null)cameras.foreground(true);}
|
@Override public void onResume(){super.onResume();active=this;immersive();if(cameras!=null)cameras.foreground(true);if(voice!=null)voice.active(true);}
|
||||||
@Override public void onPause(){if(active==this)active=null;if(cameras!=null)cameras.foreground(false);super.onPause();}
|
@Override public void onPause(){if(active==this)active=null;if(cameras!=null)cameras.foreground(false);if(voice!=null)voice.active(false);super.onPause();}
|
||||||
@Override public void onDestroy(){if(active==this)active=null;themeHandler.removeCallbacksAndMessages(null);if(cameras!=null)cameras.close();web.destroy();super.onDestroy();}
|
@Override public void onDestroy(){if(active==this)active=null;themeHandler.removeCallbacksAndMessages(null);if(cameras!=null)cameras.close();if(voice!=null)voice.close();web.destroy();super.onDestroy();}
|
||||||
void applyTimeMode(){
|
void applyTimeMode(){
|
||||||
java.util.Calendar cal=java.util.Calendar.getInstance(java.util.TimeZone.getTimeZone("Asia/Shanghai"));
|
java.util.Calendar cal=java.util.Calendar.getInstance(java.util.TimeZone.getTimeZone("Asia/Shanghai"));
|
||||||
int hour=cal.get(java.util.Calendar.HOUR_OF_DAY);boolean night=hour>=20||hour<7;
|
int hour=cal.get(java.util.Calendar.HOUR_OF_DAY);boolean night=hour>=20||hour<7;
|
||||||
WindowManager.LayoutParams params=getWindow().getAttributes();params.screenBrightness=night?.12f:.75f;getWindow().setAttributes(params);
|
WindowManager.LayoutParams params=getWindow().getAttributes();params.screenBrightness=night?.12f:.75f;getWindow().setAttributes(params);
|
||||||
if(cameras!=null){cameras.setBackgroundColor(night?0xff18221b:0xffe8e5db);cameras.title.setTextColor(night?0xff98a48c:0xff57634e);}
|
if(cameras!=null){cameras.setBackgroundColor(night?0xff18221b:0xffe8e5db);cameras.title.setTextColor(night?0xff98a48c:0xff57634e);}
|
||||||
|
if(voice!=null)voice.night(night);
|
||||||
}
|
}
|
||||||
@Override public void onWindowFocusChanged(boolean hasFocus){super.onWindowFocusChanged(hasFocus);if(hasFocus)immersive();}
|
@Override public void onWindowFocusChanged(boolean hasFocus){super.onWindowFocusChanged(hasFocus);if(hasFocus)immersive();}
|
||||||
void immersive(){getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN|View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_LAYOUT_STABLE|View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);}
|
void immersive(){getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN|View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_LAYOUT_STABLE|View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);}
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ public class MonitorService extends Service {
|
|||||||
@Override public void onDestroy(){if(worker!=null)worker.shutdownNow();super.onDestroy();}
|
@Override public void onDestroy(){if(worker!=null)worker.shutdownNow();super.onDestroy();}
|
||||||
JSONObject hardware()throws Exception{
|
JSONObject hardware()throws Exception{
|
||||||
JSONObject result=new JSONObject();
|
JSONObject result=new JSONObject();
|
||||||
result.put("model",Build.MODEL);result.put("osVersion",Build.VERSION.RELEASE);result.put("appVersion","0.1.44");
|
result.put("model",Build.MODEL);result.put("osVersion",Build.VERSION.RELEASE);result.put("appVersion",getPackageManager().getPackageInfo(getPackageName(),0).versionName);
|
||||||
result.put("foreground",MainActivity.active!=null);
|
result.put("foreground",MainActivity.active!=null);
|
||||||
result.put("cameraStates",new org.json.JSONArray(CameraStrip.report));
|
result.put("cameraStates",new org.json.JSONArray(CameraStrip.report));
|
||||||
result.put("networkStates",new org.json.JSONArray(CameraStrip.networkReport));
|
result.put("networkStates",new org.json.JSONArray(CameraStrip.networkReport));
|
||||||
|
|||||||
@@ -0,0 +1,142 @@
|
|||||||
|
package cn.ucvl.zhaodisplay;
|
||||||
|
|
||||||
|
import android.Manifest;
|
||||||
|
import android.app.*;
|
||||||
|
import android.content.*;
|
||||||
|
import android.media.*;
|
||||||
|
import android.os.*;
|
||||||
|
import android.util.Base64;
|
||||||
|
import android.view.*;
|
||||||
|
import android.widget.*;
|
||||||
|
import org.json.*;
|
||||||
|
import java.io.*;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
/** Foreground, press-to-record announcements; never opens the microphone on receipt. */
|
||||||
|
final class VoicePanel extends LinearLayout {
|
||||||
|
final Activity app;final String kind;final Supplier<String> token;
|
||||||
|
final Handler ui=new Handler();final ExecutorService worker=Executors.newSingleThreadExecutor();
|
||||||
|
final TextView status;final Spinner targets;final Button speak,settings,stop;
|
||||||
|
final AudioManager audio;final AudioAttributes attributes=new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build();
|
||||||
|
AudioFocusRequest focus;MediaRecorder recorder;MediaPlayer player;File recording,playing;
|
||||||
|
JSONArray choices=new JSONArray(),allowed=new JSONArray(),destinations=new JSONArray();
|
||||||
|
boolean enabled=false,cancelled=false,sending=false,night=false,polling=false;volatile boolean visible=false,closed=false;volatile int epoch=0;
|
||||||
|
long started;String recordTarget="",recordToken="",playingId="",playingToken="",lastMessage="";
|
||||||
|
final Runnable refresh=new Runnable(){public void run(){if(!visible||closed)return;poll();ui.postDelayed(this,5000);}};
|
||||||
|
final Runnable limit=()->finish(true);
|
||||||
|
VoicePanel(Activity activity,String type,Supplier<String> credentials){
|
||||||
|
super(activity);app=activity;kind=type;token=credentials;audio=(AudioManager)app.getSystemService(Context.AUDIO_SERVICE);
|
||||||
|
setOrientation(VERTICAL);int p=(int)(8*getResources().getDisplayMetrics().density);setPadding(p,p,p,p);setBackgroundColor(0xffe5ebe5);
|
||||||
|
status=new TextView(app);status.setTextSize(14);status.setTextColor(0xff254b3f);status.setText("家人喊话 · 先配对,再选择接收人");addView(status);
|
||||||
|
LinearLayout row=new LinearLayout(app);row.setGravity(Gravity.CENTER_VERTICAL);addView(row);
|
||||||
|
targets=new Spinner(app);row.addView(targets,new LayoutParams(0,-2,1));
|
||||||
|
speak=new Button(app);speak.setText("🎙 按住说话");speak.setEnabled(false);row.addView(speak);
|
||||||
|
speak.setOnTouchListener((v,event)->{
|
||||||
|
switch(event.getActionMasked()){
|
||||||
|
case MotionEvent.ACTION_DOWN:begin();return true;
|
||||||
|
case MotionEvent.ACTION_MOVE:cancelled=event.getX()<0||event.getY()<0||event.getX()>v.getWidth()||event.getY()>v.getHeight();if(recorder!=null)speak.setText(cancelled?"松开取消":"松开发送");return true;
|
||||||
|
case MotionEvent.ACTION_UP:finish(!cancelled);v.performClick();return true;
|
||||||
|
case MotionEvent.ACTION_CANCEL:finish(false);return true;
|
||||||
|
}return false;
|
||||||
|
});
|
||||||
|
speak.setOnKeyListener((v,key,event)->{if(key!=KeyEvent.KEYCODE_DPAD_CENTER&&key!=KeyEvent.KEYCODE_ENTER)return false;if(event.getAction()==KeyEvent.ACTION_DOWN){if(event.getRepeatCount()==0)begin();}else finish(true);return true;});
|
||||||
|
LinearLayout tools=new LinearLayout(app);addView(tools);
|
||||||
|
settings=new Button(app);settings.setText("接收设置");settings.setOnClickListener(v->configure());tools.addView(settings,new LayoutParams(0,-2,1));
|
||||||
|
stop=new Button(app);stop.setText("停止播放");stop.setEnabled(false);stop.setOnClickListener(v->stopPlayer("rejected"));tools.addView(stop,new LayoutParams(0,-2,1));
|
||||||
|
for(File file:Optional.ofNullable(app.getCacheDir().listFiles()).orElse(new File[0]))if(file.getName().startsWith("voice-"))file.delete();
|
||||||
|
}
|
||||||
|
JSONObject body(String action)throws Exception{return new JSONObject().put("kind",kind).put("action",action);}
|
||||||
|
boolean current(int e,String t){return visible&&!closed&&e==epoch&&t.equals(token.get());}
|
||||||
|
void active(boolean value){
|
||||||
|
if(closed)return;visible=value;epoch++;ui.removeCallbacks(refresh);
|
||||||
|
if(value){ui.post(refresh);}else{finish(false);stopPlayer("rejected");String t=token.get();if(!t.isEmpty())worker.execute(()->{try{DisplayApi.call("/api/voice",t,body("offline"));}catch(Exception ignored){}});}
|
||||||
|
}
|
||||||
|
void rebound(){active(false);choices=new JSONArray();allowed=new JSONArray();destinations=new JSONArray();enabled=false;lastMessage="";active(true);}
|
||||||
|
void close(){active(false);closed=true;ui.removeCallbacksAndMessages(null);worker.shutdown();}
|
||||||
|
void poll(){
|
||||||
|
if(polling||closed||!visible)return;
|
||||||
|
String t=token.get();if(t.isEmpty()){speak.setEnabled(false);settings.setEnabled(false);return;}final int e=epoch;polling=true;
|
||||||
|
worker.execute(()->{try{
|
||||||
|
JSONObject value=DisplayApi.call("/api/voice",t,body("status"));
|
||||||
|
ui.post(()->{if(!current(e,t))return;choices=value.optJSONArray("candidates");allowed=value.optJSONArray("allowed");enabled=value.optBoolean("enabled");settings.setEnabled(true);
|
||||||
|
if(!enabled&&player!=null)stopPlayer("rejected");
|
||||||
|
if(recorder==null&&!sending){String selected=selectedTarget();destinations=value.optJSONArray("targets");List<String> names=new ArrayList<>();int index=0;
|
||||||
|
if(destinations!=null)for(int i=0;i<destinations.length();i++){JSONObject d=destinations.optJSONObject(i);names.add(d.optString("name")+(d.optBoolean("online")?" · 在线":" · 未打开 App"));if(d.optString("id").equals(selected))index=i;}
|
||||||
|
if(names.isEmpty())names.add("暂无允许接收的对象");targets.setAdapter(new ArrayAdapter<String>(app,android.R.layout.simple_spinner_dropdown_item,names){public View getView(int position,View convert,ViewGroup parent){TextView view=(TextView)super.getView(position,convert,parent);view.setTextColor(night?0xffa6b5ac:0xff254b3f);return view;}});targets.setSelection(index);
|
||||||
|
speak.setEnabled(destinations!=null&&destinations.length()>0&µphone());speak.setText(microphone()?"🎙 按住说话":"待接入话筒");
|
||||||
|
}
|
||||||
|
JSONArray sent=value.optJSONArray("sent");if(sent!=null&&!lastMessage.isEmpty())for(int i=0;i<sent.length();i++){JSONObject r=sent.optJSONObject(i);if(lastMessage.equals(r.optString("id"))){String s=r.optString("status");status.setText(s.equals("played")?"对方已播放":s.equals("rejected")?"对方已停止或未播放":s.equals("expired")?"喊话已过期,未播放":s.equals("received")?"对方正在接收":"已发送,等待对方播放");}}
|
||||||
|
if(lastMessage.isEmpty()&&player==null&&recorder==null)status.setText("家人喊话 · "+(enabled?"接收已开启":"接收已关闭")+" · 最长 30 秒");
|
||||||
|
JSONArray inbox=value.optJSONArray("inbox");if(enabled&&player==null&&recorder==null&&!sending&&inbox!=null&&inbox.length()>0)take(inbox.optJSONObject(0).optString("id"));
|
||||||
|
});
|
||||||
|
}catch(Exception error){ui.post(()->{if(current(e,t)){speak.setEnabled(false);settings.setEnabled(false);if(error instanceof DisplayApi.ApiError&&(((DisplayApi.ApiError)error).status==401||((DisplayApi.ApiError)error).status==403)){finish(false);stopPlayer("rejected");enabled=false;destinations=new JSONArray();}status.setText("喊话连接暂不可用,请检查网络和配对");}});}finally{ui.post(()->polling=false);}});
|
||||||
|
}
|
||||||
|
String selectedTarget(){JSONObject d=destinations==null?null:destinations.optJSONObject(targets.getSelectedItemPosition());return d==null?"":d.optString("id");}
|
||||||
|
void night(boolean value){night=value;setBackgroundColor(value?0xff17231e:0xffe5ebe5);status.setTextColor(value?0xffa6b5ac:0xff254b3f);for(Button b:new Button[]{speak,settings,stop}){b.setTextColor(value?0xffa6b5ac:0xff254b3f);b.setBackgroundTintList(android.content.res.ColorStateList.valueOf(value?0xff25362d:0xffd0dfd6));}View selected=targets.getSelectedView();if(selected instanceof TextView)((TextView)selected).setTextColor(value?0xffa6b5ac:0xff254b3f);}
|
||||||
|
boolean microphone(){try{return audio.getDevices(AudioManager.GET_DEVICES_INPUTS).length>0;}catch(Exception e){return false;}}
|
||||||
|
void configure(){
|
||||||
|
if(choices==null)return;final JSONArray options=choices;String[] names=new String[options.length()];boolean[] checked=new boolean[names.length];
|
||||||
|
for(int i=0;i<names.length;i++){JSONObject d=options.optJSONObject(i);names[i]=d.optString("name");if(allowed!=null)for(int j=0;j<allowed.length();j++)if(d.optString("id").equals(allowed.optString(j)))checked[i]=true;}
|
||||||
|
new AlertDialog.Builder(app).setTitle("允许谁向我喊话").setMultiChoiceItems(names,checked,(d,index,value)->checked[index]=value)
|
||||||
|
.setNegativeButton("取消",null).setNeutralButton("关闭接收",(d,w)->saveSettings(false,new JSONArray()))
|
||||||
|
.setPositiveButton("允许所选对象",(d,w)->{JSONArray selected=new JSONArray();for(int i=0;i<checked.length;i++)if(checked[i])selected.put(options.optJSONObject(i).optString("id"));saveSettings(true,selected);}).show();
|
||||||
|
}
|
||||||
|
void saveSettings(boolean receive,JSONArray ids){
|
||||||
|
if(receive&&ids.length()==0){status.setText("请先选择允许的家人或终端");return;}
|
||||||
|
if(!receive){enabled=false;stopPlayer("rejected");}String t=token.get();int e=epoch;
|
||||||
|
worker.execute(()->{try{DisplayApi.call("/api/voice",t,body("configure").put("enabled",receive).put("allowed",ids).put("consent",true));ui.post(()->{if(current(e,t)){lastMessage="";poll();}});}catch(Exception error){ui.post(()->{if(current(e,t))status.setText("接收设置保存失败,请检查网络后重试");});}});
|
||||||
|
}
|
||||||
|
void begin(){
|
||||||
|
if(!visible||recorder!=null||sending||selectedTarget().isEmpty())return;
|
||||||
|
JSONObject target=destinations.optJSONObject(targets.getSelectedItemPosition());if(target==null||!target.optBoolean("online")){status.setText("请先让对方打开 App");return;}
|
||||||
|
if(!microphone()){status.setText("请先连接麦克风;仍可接收家人喊话");return;}
|
||||||
|
if(app.checkSelfPermission(Manifest.permission.RECORD_AUDIO)!=0){app.requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO},46);status.setText("授权麦克风后,再次按住说话");return;}
|
||||||
|
stopPlayer("rejected");cancelled=false;recordTarget=selectedTarget();recordToken=token.get();lastMessage="";
|
||||||
|
try{
|
||||||
|
recording=File.createTempFile("voice-record-",".aac",app.getCacheDir());recorder=new MediaRecorder();recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
|
||||||
|
recorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS);recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);recorder.setAudioSamplingRate(16000);recorder.setAudioChannels(1);recorder.setAudioEncodingBitRate(32000);recorder.setOutputFile(recording.getAbsolutePath());recorder.prepare();recorder.start();started=SystemClock.elapsedRealtime();
|
||||||
|
speak.setText("松开发送");targets.setEnabled(false);settings.setEnabled(false);status.setText("正在录音 · 移出按钮后松开取消");ui.postDelayed(limit,30000);
|
||||||
|
}catch(Exception error){finish(false);status.setText("无法录音,请检查话筒和权限");}
|
||||||
|
}
|
||||||
|
void finish(boolean send){
|
||||||
|
ui.removeCallbacks(limit);if(recorder==null)return;MediaRecorder r=recorder;recorder=null;
|
||||||
|
try{r.stop();}catch(Exception error){send=false;}finally{r.release();}
|
||||||
|
File file=recording;recording=null;speak.setText("🎙 按住说话");targets.setEnabled(true);settings.setEnabled(true);
|
||||||
|
if(!send||SystemClock.elapsedRealtime()-started<350||file==null){if(file!=null)file.delete();status.setText("录音已取消");return;}
|
||||||
|
final String t=recordToken,destination=recordTarget;final int e=epoch;sending=true;speak.setEnabled(false);status.setText("正在发送喊话…");
|
||||||
|
worker.execute(()->{try{
|
||||||
|
if(!current(e,t))return;byte[] bytes=Files.readAllBytes(file.toPath());if(bytes.length>150000)throw new IOException("Too large");
|
||||||
|
JSONObject result=DisplayApi.call("/api/voice",t,body("send").put("target",destination).put("id",UUID.randomUUID().toString().replace("-","")).put("audio",Base64.encodeToString(bytes,Base64.NO_WRAP)));
|
||||||
|
ui.post(()->{if(current(e,t)){lastMessage=result.optString("id");status.setText("已发送,等待对方播放");}});
|
||||||
|
}catch(Exception error){ui.post(()->{if(current(e,t))status.setText("发送未成功,请检查对方的接收权限和在线状态");});}
|
||||||
|
finally{file.delete();ui.post(()->{sending=false;if(current(e,t))poll();});}});
|
||||||
|
}
|
||||||
|
void take(String id){
|
||||||
|
// Reserve the playback slot while the download is in flight.
|
||||||
|
if(!playingId.isEmpty())return;playingId=id;String t=token.get();int e=epoch;
|
||||||
|
worker.execute(()->{try{
|
||||||
|
JSONObject clip=DisplayApi.call("/api/voice",t,body("take").put("id",id));byte[] bytes=Base64.decode(clip.getString("audio"),Base64.DEFAULT);
|
||||||
|
ui.post(()->{if(!current(e,t)||!enabled||recorder!=null||!playingId.equals(id)){ack(t,id,"rejected");return;}play(clip,t,bytes);});
|
||||||
|
}catch(Exception error){ui.post(()->{if(current(e,t)&&playingId.equals(id))playingId="";});}});
|
||||||
|
}
|
||||||
|
void play(JSONObject clip,String t,byte[] bytes){
|
||||||
|
try{
|
||||||
|
playingToken=t;focus=new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT).setAudioAttributes(attributes).setOnAudioFocusChangeListener(change->{if(change<0)stopPlayer("rejected");}).build();
|
||||||
|
if(audio.requestAudioFocus(focus)!=AudioManager.AUDIOFOCUS_REQUEST_GRANTED)throw new IOException("Audio busy");
|
||||||
|
playing=File.createTempFile("voice-play-",".aac",app.getCacheDir());Files.write(playing.toPath(),bytes);player=new MediaPlayer();player.setAudioAttributes(attributes);player.setDataSource(playing.getAbsolutePath());
|
||||||
|
player.setOnPreparedListener(p->{if(visible&&enabled&&p==player){p.start();stop.setEnabled(true);status.setText(clip.optString("senderName")+"正在喊话 · "+clip.optDouble("seconds")+" 秒");}else stopPlayer("rejected");});
|
||||||
|
player.setOnCompletionListener(p->stopPlayer("played"));player.setOnErrorListener((p,what,extra)->{stopPlayer("rejected");return true;});player.prepareAsync();
|
||||||
|
}catch(Exception error){stopPlayer("rejected");status.setText("语音未能播放,请检查扬声器");}
|
||||||
|
}
|
||||||
|
void stopPlayer(String outcome){
|
||||||
|
if(player!=null){try{player.release();}catch(Exception ignored){}player=null;}
|
||||||
|
if(focus!=null){audio.abandonAudioFocusRequest(focus);focus=null;}
|
||||||
|
if(playing!=null){playing.delete();playing=null;}
|
||||||
|
if(!playingId.isEmpty()&&!playingToken.isEmpty())ack(playingToken,playingId,outcome);
|
||||||
|
playingId="";playingToken="";stop.setEnabled(false);
|
||||||
|
}
|
||||||
|
void ack(String t,String id,String state){if(!worker.isShutdown())worker.execute(()->{try{DisplayApi.call("/api/voice",t,body("ack").put("id",id).put("status",state));}catch(Exception ignored){}});}
|
||||||
|
}
|
||||||
@@ -44,6 +44,7 @@ import journal
|
|||||||
import ptz
|
import ptz
|
||||||
import displays
|
import displays
|
||||||
import member_locations as family_locations
|
import member_locations as family_locations
|
||||||
|
import family_voice
|
||||||
import family_members
|
import family_members
|
||||||
import recording_archive
|
import recording_archive
|
||||||
import app_downloads
|
import app_downloads
|
||||||
@@ -100,6 +101,7 @@ JOURNAL = journal.Journal(sys.modules[__name__])
|
|||||||
CLOUD_IMAGES = cloud_images.CloudImages(sys.modules[__name__])
|
CLOUD_IMAGES = cloud_images.CloudImages(sys.modules[__name__])
|
||||||
DISPLAYS = displays.Displays(sys.modules[__name__])
|
DISPLAYS = displays.Displays(sys.modules[__name__])
|
||||||
LOCATIONS = family_locations.Locations(sys.modules[__name__])
|
LOCATIONS = family_locations.Locations(sys.modules[__name__])
|
||||||
|
VOICE = family_voice.Voice(sys.modules[__name__])
|
||||||
MEMBERS = family_members.Members(sys.modules[__name__])
|
MEMBERS = family_members.Members(sys.modules[__name__])
|
||||||
ARCHIVE = recording_archive.Archive(sys.modules[__name__])
|
ARCHIVE = recording_archive.Archive(sys.modules[__name__])
|
||||||
|
|
||||||
@@ -692,6 +694,10 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
def do_POST(self):
|
def do_POST(self):
|
||||||
try:
|
try:
|
||||||
path = url.urlsplit(self.path).path
|
path = url.urlsplit(self.path).path
|
||||||
|
if path == '/api/voice':
|
||||||
|
authorization=self.headers.get('Authorization','')
|
||||||
|
self.answer(VOICE.native(authorization[7:] if authorization.startswith('Bearer ') else '',self.body(220000)))
|
||||||
|
return
|
||||||
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(16384)))
|
self.answer(LOCATIONS.native(authorization[7:] if authorization.startswith('Bearer ') else '',self.body(16384)))
|
||||||
@@ -737,6 +743,8 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
self.answer({'ok': True}, cookie='vision=; Path=/; Max-Age=0; HttpOnly; SameSite=Strict')
|
self.answer({'ok': True}, cookie='vision=; Path=/; Max-Age=0; HttpOnly; SameSite=Strict')
|
||||||
elif path == '/api/locations':
|
elif path == '/api/locations':
|
||||||
self.answer(LOCATIONS.manage(self.user,data))
|
self.answer(LOCATIONS.manage(self.user,data))
|
||||||
|
elif path == '/api/display-voice':
|
||||||
|
self.answer(VOICE.manage_display(self.user,data))
|
||||||
elif path == '/api/members':
|
elif path == '/api/members':
|
||||||
self.answer(MEMBERS.save(self.user,data))
|
self.answer(MEMBERS.save(self.user,data))
|
||||||
elif path == '/api/genealogy/share':
|
elif path == '/api/genealogy/share':
|
||||||
@@ -980,10 +988,10 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
self.connection.settimeout(old_timeout)
|
self.connection.settimeout(old_timeout)
|
||||||
|
|
||||||
def do_HEAD(self):
|
def do_HEAD(self):
|
||||||
if url.urlsplit(self.path).path != '/downloads/ZhaoDisplay.apk':
|
if url.urlsplit(self.path).path not in ('/downloads/ZhaoDisplay.apk','/downloads/ZhaoTerminal.apk'):
|
||||||
self.send_response(405); self.send_header('Content-Length','0'); self.end_headers(); return
|
self.send_response(405); self.send_header('Content-Length','0'); self.end_headers(); return
|
||||||
try:
|
try:
|
||||||
self.require_auth(); app_downloads.serve(self,sys.modules[__name__])
|
self.require_auth(); app_downloads.serve(self,sys.modules[__name__],'terminal' if url.urlsplit(self.path).path.endswith('ZhaoTerminal.apk') else 'phone')
|
||||||
except Problem as exc:
|
except Problem as exc:
|
||||||
self.send_response(exc.status); self.send_header('Content-Length','0'); self.end_headers()
|
self.send_response(exc.status); self.send_header('Content-Length','0'); self.end_headers()
|
||||||
|
|
||||||
@@ -992,10 +1000,10 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
parsed = url.urlsplit(self.path)
|
parsed = url.urlsplit(self.path)
|
||||||
path = parsed.path
|
path = parsed.path
|
||||||
query = {k: v[0] for k, v in url.parse_qs(parsed.query).items()}
|
query = {k: v[0] for k, v in url.parse_qs(parsed.query).items()}
|
||||||
if path in ('/api/app-release','/downloads/ZhaoDisplay.apk'):
|
if path in ('/api/app-release','/downloads/ZhaoDisplay.apk','/downloads/ZhaoTerminal.apk'):
|
||||||
self.require_auth()
|
self.require_auth()
|
||||||
if path == '/api/app-release': self.answer(app_downloads.release(sys.modules[__name__])[1])
|
if path == '/api/app-release': self.answer(app_downloads.release(sys.modules[__name__],query.get('variant','phone'))[1])
|
||||||
else: app_downloads.serve(self,sys.modules[__name__])
|
else: app_downloads.serve(self,sys.modules[__name__],'terminal' if path.endswith('ZhaoTerminal.apk') else 'phone')
|
||||||
return
|
return
|
||||||
if path == baidu.CALLBACK:
|
if path == baidu.CALLBACK:
|
||||||
try:
|
try:
|
||||||
@@ -1273,6 +1281,7 @@ def initialize():
|
|||||||
MEMBERS.initialize()
|
MEMBERS.initialize()
|
||||||
DISPLAYS.initialize()
|
DISPLAYS.initialize()
|
||||||
LOCATIONS.initialize()
|
LOCATIONS.initialize()
|
||||||
|
VOICE.initialize()
|
||||||
ARCHIVE.initialize()
|
ARCHIVE.initialize()
|
||||||
HERITAGE.initialize()
|
HERITAGE.initialize()
|
||||||
JOURNAL.initialize()
|
JOURNAL.initialize()
|
||||||
@@ -1295,6 +1304,7 @@ if __name__ == '__main__':
|
|||||||
threading.Thread(target=media_config_watch, daemon=True).start()
|
threading.Thread(target=media_config_watch, daemon=True).start()
|
||||||
threading.Thread(target=BACKUPS.watch, daemon=True).start()
|
threading.Thread(target=BACKUPS.watch, daemon=True).start()
|
||||||
threading.Thread(target=DISPLAYS.watch, daemon=True).start()
|
threading.Thread(target=DISPLAYS.watch, daemon=True).start()
|
||||||
|
threading.Thread(target=VOICE.watch, daemon=True).start()
|
||||||
threading.Thread(target=ARCHIVE.watch, daemon=True).start()
|
threading.Thread(target=ARCHIVE.watch, daemon=True).start()
|
||||||
threading.Thread(target=JOURNAL.watch, daemon=True).start()
|
threading.Thread(target=JOURNAL.watch, daemon=True).start()
|
||||||
bindings = [h.strip() for h in os.environ.get('VISION_BIND', '127.0.0.1').split(',') if h.strip()]
|
bindings = [h.strip() for h in os.environ.get('VISION_BIND', '127.0.0.1').split(',') if h.strip()]
|
||||||
|
|||||||
+8
-6
@@ -8,10 +8,12 @@ _lock = threading.Lock()
|
|||||||
_cached = None
|
_cached = None
|
||||||
|
|
||||||
|
|
||||||
def release(app):
|
def release(app, variant='phone'):
|
||||||
global _cached
|
global _cached
|
||||||
folder = app.DATA / 'app-downloads'
|
folder = app.DATA / 'app-downloads'
|
||||||
file, manifest = folder / 'ZhaoDisplay.apk', folder / 'android.json'
|
if variant not in ('phone','terminal'):raise app.Problem('安装包类型不正确')
|
||||||
|
filename,metadata=('ZhaoTerminal.apk','terminal.json') if variant=='terminal' else ('ZhaoDisplay.apk','android.json')
|
||||||
|
file, manifest = folder / filename, folder / metadata
|
||||||
try:
|
try:
|
||||||
if file.is_symlink() or manifest.is_symlink(): raise ValueError()
|
if file.is_symlink() or manifest.is_symlink(): raise ValueError()
|
||||||
stat, meta_stat = file.stat(), manifest.stat()
|
stat, meta_stat = file.stat(), manifest.stat()
|
||||||
@@ -27,15 +29,15 @@ def release(app):
|
|||||||
source.seek(0)
|
source.seek(0)
|
||||||
if hashlib.file_digest(source, 'sha256').hexdigest() != meta['sha256']: raise ValueError()
|
if hashlib.file_digest(source, 'sha256').hexdigest() != meta['sha256']: raise ValueError()
|
||||||
public = dict(version=meta['version'], size=stat.st_size, sha256=meta['sha256'],
|
public = dict(version=meta['version'], size=stat.st_size, sha256=meta['sha256'],
|
||||||
minimumAndroid=8, url='/downloads/ZhaoDisplay.apk')
|
minimumAndroid=8, url='/downloads/'+filename)
|
||||||
_cached = (key, public)
|
_cached = (key, public)
|
||||||
return file, dict(public)
|
return file, dict(public)
|
||||||
except (OSError, ValueError, KeyError, TypeError):
|
except (OSError, ValueError, KeyError, TypeError):
|
||||||
raise app.Problem('安装包暂未就绪,请稍后重试或联系管理员', 503)
|
raise app.Problem('安装包暂未就绪,请稍后重试或联系管理员', 503)
|
||||||
|
|
||||||
|
|
||||||
def serve(handler, app):
|
def serve(handler, app, variant='phone'):
|
||||||
file, meta = release(app)
|
file, meta = release(app,variant)
|
||||||
size, start, end = meta['size'], 0, meta['size'] - 1
|
size, start, end = meta['size'], 0, meta['size'] - 1
|
||||||
requested = handler.headers.get('Range', '')
|
requested = handler.headers.get('Range', '')
|
||||||
if requested:
|
if requested:
|
||||||
@@ -57,7 +59,7 @@ def serve(handler, app):
|
|||||||
handler.send_response(206 if requested else 200)
|
handler.send_response(206 if requested else 200)
|
||||||
for name, value in {
|
for name, value in {
|
||||||
'Content-Type': 'application/vnd.android.package-archive',
|
'Content-Type': 'application/vnd.android.package-archive',
|
||||||
'Content-Disposition': f'attachment; filename="ZhaoDisplay-{meta["version"]}.apk"',
|
'Content-Disposition': f'attachment; filename="{file.stem}-{meta["version"]}.apk"',
|
||||||
'Content-Length': str(end-start+1), 'Accept-Ranges': 'bytes',
|
'Content-Length': str(end-start+1), 'Accept-Ranges': 'bytes',
|
||||||
'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff',
|
'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff',
|
||||||
'ETag': '"'+meta['sha256']+'"',
|
'ETag': '"'+meta['sha256']+'"',
|
||||||
|
|||||||
+168
@@ -0,0 +1,168 @@
|
|||||||
|
"""Explicitly permitted, short household announcements. Audio is RAM-only with a TTL."""
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
class Voice:
|
||||||
|
def __init__(self, app):
|
||||||
|
self.a=app; self.online={}; self.messages={}; self.receipts={}; self.rates={}
|
||||||
|
|
||||||
|
def initialize(self):
|
||||||
|
with self.a.LOCK,self.a.DB:
|
||||||
|
self.a.DB.execute('CREATE TABLE IF NOT EXISTS voice_receivers '
|
||||||
|
'(endpoint TEXT PRIMARY KEY, family_id TEXT, enabled INTEGER, allowed TEXT)')
|
||||||
|
self.online.clear(); self.messages.clear(); self.receipts.clear(); self.rates.clear()
|
||||||
|
|
||||||
|
def watch(self):
|
||||||
|
while True:
|
||||||
|
time.sleep(10)
|
||||||
|
with self.a.LOCK:self.sweep()
|
||||||
|
|
||||||
|
def endpoint(self, key):
|
||||||
|
a=self.a;now=time.time()
|
||||||
|
if not isinstance(key,str):return None
|
||||||
|
kind,_,sid=key.partition(':')
|
||||||
|
if kind=='phone':
|
||||||
|
row=a.DB.execute('SELECT * FROM member_location_shares WHERE id=? AND expires>?',(sid,now)).fetchone()
|
||||||
|
valid=a.LOCATIONS.eligible(row['family_id'],row['member_id']) if row else None
|
||||||
|
if valid:return dict(id=key,kind=kind,familyId=row['family_id'],name=valid[1]['name']+'的手机')
|
||||||
|
elif kind=='display':
|
||||||
|
row=a.DB.execute('SELECT * FROM household_displays WHERE id=? AND revoked=0 AND expires_at>?',(sid,now)).fetchone()
|
||||||
|
device=a.get_object('devices',row['device_id']) if row else None
|
||||||
|
if device and a.HOUSEHOLDS.family_of(device)==row['family_id']:
|
||||||
|
return dict(id=key,kind=kind,familyId=row['family_id'],name=device['name'])
|
||||||
|
return None
|
||||||
|
|
||||||
|
def authorize(self, token, kind):
|
||||||
|
a=self.a
|
||||||
|
if not isinstance(token,str) or not re.fullmatch(r'[A-Za-z0-9_-]{43}',token):raise a.Problem('请先完成设备配对',401)
|
||||||
|
if kind=='phone':
|
||||||
|
row=a.DB.execute('SELECT id FROM member_location_shares WHERE token_hash=?',(hashlib.sha256(token.encode()).hexdigest(),)).fetchone()
|
||||||
|
actor=self.endpoint('phone:'+row['id']) if row else None
|
||||||
|
elif kind=='display':
|
||||||
|
grant=a.DISPLAYS.authorize_native(token)
|
||||||
|
actor=self.endpoint('display:'+grant['id'])
|
||||||
|
else:actor=None
|
||||||
|
if not actor:raise a.Problem('设备配对已失效,请重新配对',401)
|
||||||
|
return actor
|
||||||
|
|
||||||
|
def settings(self, actor):
|
||||||
|
row=self.a.DB.execute('SELECT * FROM voice_receivers WHERE endpoint=? AND family_id=?',(actor['id'],actor['familyId'])).fetchone()
|
||||||
|
return dict(enabled=bool(row['enabled']),allowed=json.loads(row['allowed'])) if row else dict(enabled=False,allowed=[])
|
||||||
|
|
||||||
|
def candidates(self, actor):
|
||||||
|
a=self.a;family=actor['familyId'];keys=[]
|
||||||
|
keys+=['phone:'+r['id'] for r in a.DB.execute('SELECT id FROM member_location_shares WHERE family_id=?',(family,))]
|
||||||
|
keys+=['display:'+r['id'] for r in a.DB.execute('SELECT id FROM household_displays WHERE family_id=? AND revoked=0',(family,))]
|
||||||
|
return [ep for key in keys if key!=actor['id'] and (ep:=self.endpoint(key))]
|
||||||
|
|
||||||
|
def permitted(self, sender, receiver):
|
||||||
|
if not sender or not receiver or sender['id']==receiver['id'] or sender['familyId']!=receiver['familyId']:return False
|
||||||
|
settings=self.settings(receiver)
|
||||||
|
return settings['enabled'] and sender['id'] in settings['allowed']
|
||||||
|
|
||||||
|
def sweep(self):
|
||||||
|
now=time.time()
|
||||||
|
for key,message in list(self.messages.items()):
|
||||||
|
if message['expires']<=now or not self.permitted(self.endpoint(message['sender']),self.endpoint(message['target'])):
|
||||||
|
self.messages.pop(key,None)
|
||||||
|
if key in self.receipts:self.receipts[key]['status']='expired'
|
||||||
|
self.receipts={k:v for k,v in self.receipts.items() if v['expires']>now}
|
||||||
|
self.online={k:v for k,v in self.online.items() if now-v<60}
|
||||||
|
self.rates={k:v for k,v in self.rates.items() if now-v[0]<60}
|
||||||
|
|
||||||
|
def configure(self, actor, body):
|
||||||
|
enabled=body.get('enabled');allowed=body.get('allowed',[])
|
||||||
|
choices={r['id'] for r in self.candidates(actor)}
|
||||||
|
if type(enabled) is not bool or not isinstance(allowed,list) or len(allowed)>100 or any(not isinstance(k,str) for k in allowed) or len(set(allowed))!=len(allowed) or not set(allowed)<=choices:
|
||||||
|
raise self.a.Problem('请选择本家庭有效的喊话人')
|
||||||
|
if enabled and (body.get('consent') is not True or not allowed):raise self.a.Problem('请确认接收喊话并选择允许的家人或终端')
|
||||||
|
self.a.DB.execute('INSERT OR REPLACE INTO voice_receivers VALUES (?,?,?,?)',
|
||||||
|
(actor['id'],actor['familyId'],int(enabled),json.dumps(allowed)))
|
||||||
|
self.sweep()
|
||||||
|
return dict(ok=True,enabled=enabled,allowed=allowed)
|
||||||
|
|
||||||
|
def manage_display(self, user, body):
|
||||||
|
a=self.a;device=a.DISPLAYS.device(user,body.get('deviceId'))
|
||||||
|
with a.LOCK,a.DB:
|
||||||
|
row=a.DB.execute('SELECT id FROM household_displays WHERE device_id=? AND family_id=? AND revoked=0 AND expires_at>?',
|
||||||
|
(device['id'],a.HOUSEHOLDS.scope(user),time.time())).fetchone()
|
||||||
|
if not row:raise a.Problem('请先配对显示终端',409)
|
||||||
|
actor=self.endpoint('display:'+row['id'])
|
||||||
|
if body.get('action')=='configure':return self.configure(actor,body)
|
||||||
|
if body.get('action')!='settings':raise a.Problem('喊话设置操作不正确')
|
||||||
|
return dict(**self.settings(actor),candidates=self.candidates(actor))
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def duration(raw):
|
||||||
|
# Bound actual ADTS frame duration, rather than trusting client-supplied metadata.
|
||||||
|
rates=(96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,7350)
|
||||||
|
cursor=0;seconds=0
|
||||||
|
while cursor<len(raw):
|
||||||
|
h=raw[cursor:cursor+7]
|
||||||
|
if len(h)<7 or h[0]!=255 or h[1]&0xf6!=0xf0:raise ValueError()
|
||||||
|
rate=(h[2]>>2)&15
|
||||||
|
length=((h[3]&3)<<11)|(h[4]<<3)|(h[5]>>5)
|
||||||
|
header=7 if h[1]&1 else 9
|
||||||
|
if rate>=len(rates) or length<=header or cursor+length>len(raw):raise ValueError()
|
||||||
|
seconds+=1024*((h[6]&3)+1)/rates[rate];cursor+=length
|
||||||
|
if seconds>31:raise ValueError()
|
||||||
|
if seconds<.3:raise ValueError()
|
||||||
|
return round(seconds,2)
|
||||||
|
|
||||||
|
def native(self, token, body):
|
||||||
|
a=self.a;now=time.time()
|
||||||
|
with a.LOCK,a.DB:
|
||||||
|
actor=self.authorize(token,body.get('kind'));self.sweep()
|
||||||
|
action=body.get('action');me=actor['id']
|
||||||
|
if action=='configure':return self.configure(actor,body)
|
||||||
|
if action=='offline':
|
||||||
|
self.online.pop(me,None)
|
||||||
|
for key,m in list(self.messages.items()):
|
||||||
|
if m['target']==me:self.messages.pop(key);self.receipts[key]['status']='rejected'
|
||||||
|
return dict(ok=True)
|
||||||
|
if action=='status':
|
||||||
|
self.online[me]=now
|
||||||
|
candidates=self.candidates(actor)
|
||||||
|
targets=[dict(ep,online=now-self.online.get(ep['id'],0)<20) for ep in candidates if self.permitted(actor,ep)]
|
||||||
|
inbox=[dict(id=k,senderName=m['senderName'],seconds=m['seconds']) for k,m in self.messages.items() if m['target']==me]
|
||||||
|
sent=[dict(id=k,status=r['status']) for k,r in self.receipts.items() if r['sender']==me]
|
||||||
|
return dict(me=actor,**self.settings(actor),candidates=candidates,targets=targets,inbox=inbox,sent=sent)
|
||||||
|
if action=='send':
|
||||||
|
target=self.endpoint(body.get('target'))
|
||||||
|
if not self.permitted(actor,target):raise a.Problem('对方尚未允许你喊话,或已关闭接收',403)
|
||||||
|
if now-self.online.get(target['id'],0)>=20:raise a.Problem('对方不在线,请等对方打开 App',409)
|
||||||
|
message_id=body.get('id','')
|
||||||
|
if not isinstance(message_id,str) or not re.fullmatch(r'[a-f0-9]{32}',message_id):raise a.Problem('喊话编号不正确')
|
||||||
|
key=me+':'+message_id
|
||||||
|
if key in self.receipts:return dict(ok=True,id=key,status=self.receipts[key]['status'])
|
||||||
|
at,count=self.rates.get(me,(now,0))
|
||||||
|
if count>=10:raise a.Problem('喊话过于频繁,请稍后再试',429)
|
||||||
|
encoded=body.get('audio','')
|
||||||
|
if not isinstance(encoded,str) or not 0<len(encoded)<=200000:raise a.Problem('语音大小超出限制')
|
||||||
|
try:
|
||||||
|
raw=base64.b64decode(encoded,validate=True)
|
||||||
|
if len(raw)>150000:raise ValueError()
|
||||||
|
seconds=self.duration(raw)
|
||||||
|
except (ValueError,TypeError):raise a.Problem('请上传 0.3 至 30 秒的 AAC 语音')
|
||||||
|
if len(self.messages)>=48 or len(self.receipts)>=2048 or sum(m['target']==target['id'] for m in self.messages.values())>=3:raise a.Problem('对方还有待播放的喊话,请稍候',429)
|
||||||
|
self.rates[me]=(at,count+1)
|
||||||
|
self.messages[key]=dict(sender=me,target=target['id'],senderName=actor['name'],audio=raw,seconds=seconds,expires=now+90)
|
||||||
|
self.receipts[key]=dict(sender=me,target=target['id'],status='queued',expires=now+180)
|
||||||
|
return dict(ok=True,id=key,status='queued')
|
||||||
|
key=body.get('id','')
|
||||||
|
if not isinstance(key,str):raise a.Problem('喊话编号不正确')
|
||||||
|
receipt=self.receipts.get(key)
|
||||||
|
if action=='take':
|
||||||
|
m=self.messages.get(key)
|
||||||
|
if not m or m['target']!=me or not self.permitted(self.endpoint(m['sender']),actor):raise a.Problem('语音已过期或没有接收权限',404)
|
||||||
|
del self.messages[key];receipt['status']='received'
|
||||||
|
return dict(id=key,senderName=m['senderName'],seconds=m['seconds'],audio=base64.b64encode(m['audio']).decode())
|
||||||
|
if action=='ack':
|
||||||
|
if not receipt or receipt['target']!=me or receipt['status']!='received':raise a.Problem('喊话回执不存在',404)
|
||||||
|
if body.get('status') not in ('played','rejected'):raise a.Problem('回执不正确')
|
||||||
|
receipt['status']=body['status'];return dict(ok=True)
|
||||||
|
raise a.Problem('喊话操作不正确')
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "zhao-steward-ui",
|
"name": "zhao-steward-ui",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.1.45",
|
"version": "0.1.48",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import {ref,watch,onUnmounted,computed} from 'vue'
|
import {ref,watch,onUnmounted,computed} from 'vue'
|
||||||
import {snapshot,bridge} from '../composables/bridge.js'
|
import {snapshot,bridge} from '../composables/bridge.js'
|
||||||
|
import VoicePermissions from './VoicePermissions.vue'
|
||||||
const props=defineProps({device:Object})
|
const props=defineProps({device:Object})
|
||||||
const open=ref(false),result=ref(null),grants=ref([]),error=ref(''),busy=ref(false),link=ref(''),preview=ref(''),previewUntil=ref(0)
|
const open=ref(false),result=ref(null),grants=ref([]),error=ref(''),busy=ref(false),link=ref(''),preview=ref(''),previewUntil=ref(0)
|
||||||
let timer,epoch=0,blob=''
|
let timer,epoch=0,blob=''
|
||||||
@@ -29,17 +30,18 @@ watch(open,async value=>{epoch++;clearTimeout(timer);link.value='';pairingCode.v
|
|||||||
watch(()=>[snapshot.value.state.familyId,snapshot.value.session,snapshot.value.page,props.device.id].join('|'),()=>open.value=false)
|
watch(()=>[snapshot.value.state.familyId,snapshot.value.session,snapshot.value.page,props.device.id].join('|'),()=>open.value=false)
|
||||||
onUnmounted(()=>{epoch++;clearTimeout(timer);if(blob)URL.revokeObjectURL(blob)})
|
onUnmounted(()=>{epoch++;clearTimeout(timer);if(blob)URL.revokeObjectURL(blob)})
|
||||||
</script>
|
</script>
|
||||||
<template><div v-if="snapshot.admin" class="display-manager mt-3"><button class="btn btn-outline-primary btn-sm" @click="open=!open">{{open?'收起电视管理':'电视管理 · 状态与模拟屏'}}</button>
|
<template><div v-if="snapshot.admin" class="display-manager mt-3"><button class="btn btn-outline-primary btn-sm" @click="open=!open">{{open?'收起显示终端管理':'显示终端管理 · 状态与模拟屏'}}</button>
|
||||||
<section v-if="open" class="border rounded-3 p-3 mt-3">
|
<section v-if="open" class="border rounded-3 p-3 mt-3">
|
||||||
<div class="d-flex justify-content-between align-items-center gap-2 mb-3"><strong>{{device.name}}</strong><span class="badge" :class="result?.online?'text-bg-success':'text-bg-secondary'">{{result?.online?'在线 · 心跳正常':result?.paired?'未收到心跳':'尚未绑定'}}</span></div>
|
<div class="d-flex justify-content-between align-items-center gap-2 mb-3"><strong>{{device.name}}</strong><span class="badge" :class="result?.online?'text-bg-success':'text-bg-secondary'">{{result?.online?'在线 · 心跳正常':result?.paired?'未收到心跳':'尚未绑定'}}</span></div>
|
||||||
<p class="small text-secondary">所属:{{home?.name}} · 最后心跳 {{formatTime(result?.lastSeen)}}</p>
|
<p class="small text-secondary">所属:{{home?.name}} · 最后心跳 {{formatTime(result?.lastSeen)}}</p>
|
||||||
<div class="row g-2 hardware-grid"><div class="col-6"><span>处理器温度</span><strong>{{number(hardware.temperatureC)}}{{hardware.temperatureC!=null?' °C':''}}</strong><small>{{hardware.temperatureSource||'等待传感器上报'}}</small></div><div class="col-6"><span>整机功率</span><strong>{{number(hardware.powerW)}}{{hardware.powerW!=null?' W':''}}</strong><small>{{hardware.powerSource||'需设备传感器或计量插座'}}</small></div><div class="col-6"><span>可用内存</span><strong>{{number(hardware.memoryAvailableMB,0)}} / {{number(hardware.memoryTotalMB,0)}} MB</strong></div><div class="col-6"><span>可用存储</span><strong>{{number(hardware.storageAvailableGB)}} / {{number(hardware.storageTotalGB)}} GB</strong></div></div>
|
<div class="row g-2 hardware-grid"><div class="col-6"><span>处理器温度</span><strong>{{number(hardware.temperatureC)}}{{hardware.temperatureC!=null?' °C':''}}</strong><small>{{hardware.temperatureSource||'等待传感器上报'}}</small></div><div class="col-6"><span>整机功率</span><strong>{{number(hardware.powerW)}}{{hardware.powerW!=null?' W':''}}</strong><small>{{hardware.powerSource||'需设备传感器或计量插座'}}</small></div><div class="col-6"><span>可用内存</span><strong>{{number(hardware.memoryAvailableMB,0)}} / {{number(hardware.memoryTotalMB,0)}} MB</strong></div><div class="col-6"><span>可用存储</span><strong>{{number(hardware.storageAvailableGB)}} / {{number(hardware.storageTotalGB)}} GB</strong></div></div>
|
||||||
<p class="small text-secondary mt-3">{{hardware.model||device.model}} · Android {{hardware.osVersion||'—'}} · IP {{hardware.ip||device.managementHost||'—'}}<br>{{hardware.screenWidth||'—'}} × {{hardware.screenHeight||'—'}} · {{hardware.foreground?'看板在前台':'看板未在前台'}} · {{hardware.screenOn?'屏幕亮':'屏幕状态待确认'}}<span v-if="!result?.online"> · 当前数值为最后一次上报</span></p>
|
<p class="small text-secondary mt-3">{{hardware.model||device.model}} · Android {{hardware.osVersion||'—'}} · IP {{hardware.ip||device.managementHost||'—'}}<br>{{hardware.screenWidth||'—'}} × {{hardware.screenHeight||'—'}} · {{hardware.foreground?'看板在前台':'看板未在前台'}} · {{hardware.screenOn?'屏幕亮':'屏幕状态待确认'}}<span v-if="!result?.online"> · 当前数值为最后一次上报</span></p>
|
||||||
<h4 class="fs-6">异常与报警</h4><p v-if="!result?.alerts?.some(a=>!a.cleared)" class="small text-secondary">{{result?.online?'当前无活动报警':'连接恢复后继续检查硬件状态'}}</p><div v-for="a in result?.alerts?.filter(a=>!a.cleared)" :key="a.code" class="alert py-2 small" :class="a.severity==='critical'?'alert-danger':'alert-warning'">{{a.message}} · {{formatTime(a.opened)}}</div>
|
<h4 class="fs-6">异常与报警</h4><p v-if="!result?.alerts?.some(a=>!a.cleared)" class="small text-secondary">{{result?.online?'当前无活动报警':'连接恢复后继续检查硬件状态'}}</p><div v-for="a in result?.alerts?.filter(a=>!a.cleared)" :key="a.code" class="alert py-2 small" :class="a.severity==='critical'?'alert-danger':'alert-warning'">{{a.message}} · {{formatTime(a.opened)}}</div>
|
||||||
<details class="small mb-3"><summary>报警记录与规则</summary><p>心跳中断超过 100 秒;处理器 ≥75°C 提醒、≥85°C 严重;可用内存低于 5%;可用存储低于 0.5 GB;看板退出前台。数值来自电视上报。</p><div v-for="(a,i) in result?.alerts" :key="i">{{a.cleared?'已恢复':'处理中'}} · {{a.message}} · {{formatTime(a.opened)}}</div></details>
|
<details class="small mb-3"><summary>报警记录与规则</summary><p>心跳中断超过 100 秒;处理器 ≥75°C 提醒、≥85°C 严重;可用内存低于 5%;可用存储低于 0.5 GB;看板退出前台。数值来自显示终端上报。</p><div v-for="(a,i) in result?.alerts" :key="i">{{a.cleared?'已恢复':'处理中'}} · {{a.message}} · {{formatTime(a.opened)}}</div></details>
|
||||||
<button class="btn btn-primary btn-sm" :disabled="busy||!result?.online" @click="change('preview')">查看模拟屏 · 60 秒</button><p class="small text-secondary mt-2">显示电视当前家庭看板的应用画面,约 20 秒更新一次;退出看板后不显示其他应用。预览仅短时保存在内存。</p><figure v-if="preview" class="tv-remote-preview"><img :src="preview" alt="电视家庭看板的真实应用画面"><figcaption class="small text-secondary">画面时间:{{formatTime(result?.previewAt)}}</figcaption></figure>
|
<button class="btn btn-primary btn-sm" :disabled="busy||!result?.online" @click="change('preview')">查看模拟屏 · 60 秒</button><p class="small text-secondary mt-2">显示显示终端当前家庭看板的应用画面,约 20 秒更新一次;退出看板后不显示其他应用。预览仅短时保存在内存。</p><figure v-if="preview" class="tv-remote-preview"><img :src="preview" alt="显示终端家庭看板的真实应用画面"><figcaption class="small text-secondary">画面时间:{{formatTime(result?.previewAt)}}</figcaption></figure>
|
||||||
<details class="mt-3"><summary>展示授权与天气设置</summary><div class="row g-2 my-2"><label class="col-12">天气城市<input v-model="city" class="form-control" maxlength="60"></label><label class="col-6">纬度<input v-model="latitude" class="form-control" type="number" step="0.0001" min="-90" max="90"></label><label class="col-6">经度<input v-model="longitude" class="form-control" type="number" step="0.0001" min="-180" max="180"></label></div><p class="small text-secondary">链接有效期一年,仅可展示本家庭概况、设备状态与本人同意共享的家人位置。重新生成会停用旧链接。</p><button class="btn btn-outline-primary btn-sm" :disabled="busy" @click="change('create')">生成 App 配对码</button><div v-if="link" class="my-3"><label>本次展示链接(请仅交给这台电视)<input class="form-control" :value="link" readonly @focus="$event.target.select()"></label><a class="btn btn-sm btn-outline-secondary mt-2" :href="link" target="_blank" rel="noreferrer">打开看板</a></div><div v-for="g in grants.filter(g=>!g.revoked)" :key="g.id" class="d-flex gap-2 align-items-center small mt-2"><span>授权至 {{formatTime(g.expires_at)}}</span><button class="btn btn-sm btn-outline-danger" :disabled="busy" @click="change('revoke',g.id)">停用展示权限</button></div></details>
|
<details class="mt-3"><summary>展示授权与天气设置</summary><div class="row g-2 my-2"><label class="col-12">天气城市<input v-model="city" class="form-control" maxlength="60"></label><label class="col-6">纬度<input v-model="latitude" class="form-control" type="number" step="0.0001" min="-90" max="90"></label><label class="col-6">经度<input v-model="longitude" class="form-control" type="number" step="0.0001" min="-180" max="180"></label></div><p class="small text-secondary">链接有效期一年,仅可展示本家庭概况、设备状态与本人同意共享的家人位置。重新生成会停用旧链接。</p><button class="btn btn-outline-primary btn-sm" :disabled="busy" @click="change('create')">生成 App 配对码</button><div v-if="link" class="my-3"><label>本次展示链接(请仅交给这台显示终端)<input class="form-control" :value="link" readonly @focus="$event.target.select()"></label><a class="btn btn-sm btn-outline-secondary mt-2" :href="link" target="_blank" rel="noreferrer">打开看板</a></div><div v-for="g in grants.filter(g=>!g.revoked)" :key="g.id" class="d-flex gap-2 align-items-center small mt-2"><span>授权至 {{formatTime(g.expires_at)}}</span><button class="btn btn-sm btn-outline-danger" :disabled="busy" @click="change('revoke',g.id)">停用展示权限</button></div></details>
|
||||||
<div v-if="pairingCode&&link" class="alert alert-success mt-3">App 配对码:<strong class="fs-3 font-monospace">{{pairingCode}}</strong><div class="small">在“赵府家庭屏”App 输入,10 分钟内有效,使用一次即失效。App 摄像头画面在本地网络直接播放。</div></div>
|
<div v-if="pairingCode&&link" class="alert alert-success mt-3">App 配对码:<strong class="fs-3 font-monospace">{{pairingCode}}</strong><div class="small">在“赵府家庭屏”App 输入,10 分钟内有效,使用一次即失效。App 摄像头画面在本地网络直接播放。</div></div>
|
||||||
|
<VoicePermissions v-if="result?.paired" :key="device.id" :device-id="device.id"/>
|
||||||
<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></div></template>
|
</section></div></template>
|
||||||
<style scoped>.hardware-grid>div{display:flex;flex-direction:column;gap:4px;background:#f5f7f7;padding:12px;border:3px solid white;border-radius:12px}.hardware-grid span,.hardware-grid small{font-size:12px;color:#637471}.hardware-grid strong{font-size:18px}.tv-remote-preview{margin:16px 0;text-align:center}.tv-remote-preview img{max-height:640px;max-width:100%;border:6px solid #303b38;border-radius:12px}.display-manager summary{cursor:pointer}details p{margin-top:12px}</style>
|
<style scoped>.hardware-grid>div{display:flex;flex-direction:column;gap:4px;background:#f5f7f7;padding:12px;border:3px solid white;border-radius:12px}.hardware-grid span,.hardware-grid small{font-size:12px;color:#637471}.hardware-grid strong{font-size:18px}.tv-remote-preview{margin:16px 0;text-align:center}.tv-remote-preview img{max-height:640px;max-width:100%;border:6px solid #303b38;border-radius:12px}.display-manager summary{cursor:pointer}details p{margin-top:12px}</style>
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<script setup>
|
||||||
|
import {ref,onMounted,onBeforeUnmount} from 'vue'
|
||||||
|
import {bridge} from '../composables/bridge.js'
|
||||||
|
const props=defineProps({deviceId:String})
|
||||||
|
const enabled=ref(false),allowed=ref([]),candidates=ref([]),busy=ref(true),error=ref(''),message=ref('')
|
||||||
|
let alive=true
|
||||||
|
async function load(){try{const result=await bridge().api('/api/display-voice',{deviceId:props.deviceId,action:'settings'});if(alive){enabled.value=result.enabled;allowed.value=result.allowed;candidates.value=result.candidates}}catch(e){if(alive)error.value=e.message}finally{if(alive)busy.value=false}}
|
||||||
|
async function save(){if(busy.value)return;busy.value=true;error.value='';message.value='';try{await bridge().api('/api/display-voice',{deviceId:props.deviceId,action:'configure',enabled:enabled.value,allowed:allowed.value,consent:true});if(alive)message.value='喊话接收权限已保存'}catch(e){if(alive)error.value=e.message}finally{if(alive)busy.value=false}}
|
||||||
|
onMounted(load);onBeforeUnmount(()=>alive=false)
|
||||||
|
</script>
|
||||||
|
<template><details class="mt-3"><summary>家人喊话 · 接收权限</summary><p class="small text-secondary mt-2">选择可以向此终端喊话的家人手机。对方按住说话、松开发送;终端 App 打开时播放,屏幕上可以停止播放。重新配对后需要重新授权。</p>
|
||||||
|
<fieldset :disabled="busy"><label class="form-check"><input v-model="enabled" type="checkbox" class="form-check-input">允许接收所选家人的喊话</label><div class="d-flex flex-column gap-2 my-3"><label v-for="item in candidates" :key="item.id" class="form-check"><input v-model="allowed" type="checkbox" class="form-check-input" :value="item.id">{{item.name}}</label><span v-if="!candidates.length" class="small text-secondary">先让家人的手机完成配对,再选择喊话人。</span></div><button class="btn btn-outline-primary btn-sm" @click="save">保存接收权限</button></fieldset>
|
||||||
|
<p v-if="error" class="text-danger small" role="alert">{{error}}</p><p v-if="message" class="text-success small" role="status">{{message}}</p></details></template>
|
||||||
@@ -1,9 +1,14 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import {ref,computed,watch,onMounted,onBeforeUnmount} from 'vue'
|
import {ref,computed,watch,onMounted,onBeforeUnmount} from 'vue'
|
||||||
import {chinaParts,weatherLabel} from './time.mjs'
|
import {chinaParts,weatherLabel} from './time.mjs'
|
||||||
|
import {createDisplayConnection} from './connection.mjs'
|
||||||
const data=ref(null),clock=ref(Date.now()),error=ref(''),lastSync=ref(0),paging=ref(0),offset=ref(0),fullscreen=ref(false)
|
const data=ref(null),clock=ref(Date.now()),error=ref(''),lastSync=ref(0),paging=ref(0),offset=ref(0),fullscreen=ref(false)
|
||||||
let poll,tick,cycle,controller,token='',failures=0,wake
|
const authRequired=ref(false),loading=ref(false)
|
||||||
try {const found=new URLSearchParams(location.hash.slice(1)).get('display');if(found){localStorage.setItem('zhao.display',found);history.replaceState(null,'',location.pathname)} token=localStorage.getItem('zhao.display')||''}catch{}
|
let tick,cycle,wake
|
||||||
|
const connection=createDisplayConnection({onChange:state=>{
|
||||||
|
data.value=state.data;error.value=state.error;lastSync.value=state.lastSync;authRequired.value=state.authRequired;loading.value=state.loading
|
||||||
|
if(state.data){const serverTime=new Date(state.data.serverTime).getTime();if(Number.isFinite(serverTime))offset.value=serverTime-state.lastSync}
|
||||||
|
}})
|
||||||
const time=computed(()=>chinaParts(new Date(clock.value+offset.value)))
|
const time=computed(()=>chinaParts(new Date(clock.value+offset.value)))
|
||||||
const night=computed(()=>+time.value.hour>=20||+time.value.hour<7)
|
const night=computed(()=>+time.value.hour>=20||+time.value.hour<7)
|
||||||
const clockColor=n=>(night.value?['#978469','#739486','#8299aa','#ab8278']:['#ee8a25','#148a7e','#2585cb','#d44e6b'])[n%4]
|
const clockColor=n=>(night.value?['#978469','#739486','#8299aa','#ab8278']:['#ee8a25','#148a7e','#2585cb','#d44e6b'])[n%4]
|
||||||
@@ -16,24 +21,17 @@ const positions=computed(()=>{if(clock.value-lastSync.value>90000||error.value)r
|
|||||||
const locationText=d=>d.status==='stale'?'位置更新中断 · 请检查手机':d.position?`${d.position.latitude.toFixed(3)}°, ${d.position.longitude.toFixed(3)}°`:'等待手机定位'
|
const locationText=d=>d.status==='stale'?'位置更新中断 · 请检查手机':d.position?`${d.position.latitude.toFixed(3)}°, ${d.position.longitude.toFixed(3)}°`:'等待手机定位'
|
||||||
|
|
||||||
const weather=computed(()=>data.value?.weather)
|
const weather=computed(()=>data.value?.weather)
|
||||||
const syncLabel=computed(()=>!lastSync.value?'正在连接家庭':clock.value-lastSync.value>90000?'网络暂时中断 · 显示上次资料':'家庭资料已同步')
|
const syncLabel=computed(()=>authRequired.value?'等待重新连接':!lastSync.value?'正在连接家庭':error.value||clock.value-lastSync.value>90000?'网络暂时中断 · 显示上次资料':'家庭资料已同步')
|
||||||
const fmt=n=>typeof n==='number'?Math.round(n):'—'
|
const fmt=n=>typeof n==='number'?Math.round(n):'—'
|
||||||
async function load(){
|
|
||||||
if(!token){error.value='请从家庭设备页获取这台电视的展示授权';return}
|
|
||||||
controller=new AbortController();const timeout=setTimeout(()=>controller.abort(),12000)
|
|
||||||
try {const res=await fetch('/api/display/snapshot',{headers:{Authorization:'Bearer '+token},signal:controller.signal,cache:'no-store'});const value=await res.json();if(!res.ok){if(res.status===401||res.status===403){data.value=null;localStorage.removeItem('zhao.display');token=''}throw Error(value.error||'暂时无法同步')}
|
|
||||||
data.value=value;offset.value=new Date(value.serverTime).getTime()-Date.now();lastSync.value=Date.now();error.value='';failures=0
|
|
||||||
}catch(e){error.value=e.name==='AbortError'?'家庭连接暂时超时':e.message;failures++}
|
|
||||||
finally {clearTimeout(timeout);if(token)poll=setTimeout(load,Math.min(120000,30000*Math.max(1,failures)))}
|
|
||||||
}
|
|
||||||
async function enterFullscreen(){try{if(!document.fullscreenElement)await document.documentElement.requestFullscreen();else await document.exitFullscreen();fullscreen.value=!!document.fullscreenElement;if(navigator.wakeLock)wake=await navigator.wakeLock.request('screen')}catch{}}
|
async function enterFullscreen(){try{if(!document.fullscreenElement)await document.documentElement.requestFullscreen();else await document.exitFullscreen();fullscreen.value=!!document.fullscreenElement;if(navigator.wakeLock)wake=await navigator.wakeLock.request('screen')}catch{}}
|
||||||
const visibility=()=>{if(!document.hidden&&navigator.wakeLock)navigator.wakeLock.request('screen').then(v=>wake=v).catch(()=>{})}
|
const visibility=()=>{if(!document.hidden&&navigator.wakeLock)navigator.wakeLock.request('screen').then(v=>wake=v).catch(()=>{})}
|
||||||
onMounted(()=>{load();tick=setInterval(()=>clock.value=Date.now(),1000);cycle=setInterval(()=>paging.value++,15000);document.addEventListener('visibilitychange',visibility)})
|
onMounted(()=>{connection.start();tick=setInterval(()=>clock.value=Date.now(),1000);cycle=setInterval(()=>paging.value++,15000);document.addEventListener('visibilitychange',visibility);window.addEventListener('hashchange',connection.hashChanged);window.addEventListener('storage',connection.storageChanged)})
|
||||||
onBeforeUnmount(()=>{clearTimeout(poll);clearInterval(tick);clearInterval(cycle);controller?.abort();wake?.release();document.removeEventListener('visibilitychange',visibility)})
|
onBeforeUnmount(()=>{connection.stop();clearInterval(tick);clearInterval(cycle);wake?.release();document.removeEventListener('visibilitychange',visibility);window.removeEventListener('hashchange',connection.hashChanged);window.removeEventListener('storage',connection.storageChanged)})
|
||||||
</script>
|
</script>
|
||||||
<template>
|
<template>
|
||||||
<div class="tv-shell">
|
<div class="tv-shell">
|
||||||
<header class="tv-top"><span class="tv-brand"><img src="/zhao-icon.png" alt="赵">赵府 <span>家庭时光</span></span><button class="tv-fullscreen" @click="enterFullscreen" aria-label="切换全屏">{{fullscreen?'退出全屏':'全屏展示'}} ⛶</button></header>
|
<header class="tv-top"><span class="tv-brand"><img src="/zhao-icon.png" alt="赵">赵府 <span>家庭时光</span></span><button class="tv-fullscreen" @click="enterFullscreen" aria-label="切换全屏">{{fullscreen?'退出全屏':'全屏展示'}} ⛶</button></header>
|
||||||
|
<section v-if="authRequired" class="tv-reconnect" role="alert"><strong>显示终端需要重新连接</strong><p>{{error}}</p><p>若刚完成配对,请退出并重新打开 App。需要更换配对时,点击下方「绑定家庭」,输入管理员生成的 8 位显示终端配对码。</p><button @click="connection.retry()" :disabled="loading">{{loading?'正在连接…':'重试连接'}}</button></section>
|
||||||
<div class="tv-upper">
|
<div class="tv-upper">
|
||||||
<section class="square-clock" aria-label="北京时间时钟">
|
<section class="square-clock" aria-label="北京时间时钟">
|
||||||
<svg viewBox="0 0 440 440" role="img" :aria-label="`${time.hour}:${time.minute}:${time.second}`">
|
<svg viewBox="0 0 440 440" role="img" :aria-label="`${time.hour}:${time.minute}:${time.second}`">
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
// Native pairing can change only the URL fragment without creating a new page.
|
||||||
|
// Invalidate old requests before adopting the new household's display token.
|
||||||
|
export const DISPLAY_STORAGE_KEY='zhao.display'
|
||||||
|
const valid=value=>typeof value==='string'&&/^[A-Za-z0-9_-]{43}$/.test(value)
|
||||||
|
export function createDisplayConnection({fetcher=fetch,storage=localStorage,url=location,historyApi=history,onChange,
|
||||||
|
later=setTimeout,cancel=clearTimeout,now=Date.now}={}){
|
||||||
|
let token='',epoch=0,poll,controller,stopped=false,failures=0
|
||||||
|
let state={data:null,error:'',authRequired:false,loading:false,lastSync:0}
|
||||||
|
const publish=patch=>{state={...state,...patch};onChange({...state})}
|
||||||
|
const read=()=>{try{return storage.getItem(DISPLAY_STORAGE_KEY)||''}catch{return ''}}
|
||||||
|
const persist=value=>{try{value?storage.setItem(DISPLAY_STORAGE_KEY,value):storage.removeItem(DISPLAY_STORAGE_KEY)}catch{}}
|
||||||
|
function invalidate(){epoch++;cancel(poll);controller?.abort()}
|
||||||
|
function accept(value){
|
||||||
|
if(stopped)return
|
||||||
|
invalidate();token=valid(value)?value:'';persist(token);failures=0
|
||||||
|
publish({data:null,lastSync:0,error:token?'':'请在家庭的显示终端管理中获取配对码,完成绑定。',authRequired:!token,loading:!!token})
|
||||||
|
if(token)return load()
|
||||||
|
}
|
||||||
|
function consumeFragment(){
|
||||||
|
const params=new URLSearchParams(url.hash.slice(1))
|
||||||
|
if(!params.has('display'))return false
|
||||||
|
const value=params.get('display');params.delete('display')
|
||||||
|
// Never leave a bearer credential in the visible address or navigation history.
|
||||||
|
try{historyApi.replaceState(null,'',url.pathname+url.search+(params.toString()?'#'+params.toString():''))}catch{}
|
||||||
|
accept(value);return true
|
||||||
|
}
|
||||||
|
async function load(){
|
||||||
|
if(stopped||!token)return
|
||||||
|
cancel(poll)
|
||||||
|
const requestEpoch=++epoch,requestToken=token
|
||||||
|
controller?.abort();const active=new AbortController();controller=active
|
||||||
|
const timeout=later(()=>active.abort(),12000)
|
||||||
|
publish({loading:true})
|
||||||
|
try{
|
||||||
|
const response=await fetcher('/api/display/snapshot',{headers:{Authorization:'Bearer '+requestToken},signal:active.signal,cache:'no-store'})
|
||||||
|
const value=await response.json()
|
||||||
|
if(stopped||requestEpoch!==epoch)return
|
||||||
|
if(response.status===401||response.status===403){
|
||||||
|
// Another tab can have completed pairing while this request was in flight.
|
||||||
|
const current=read()
|
||||||
|
if(valid(current)&¤t!==requestToken){accept(current);return}
|
||||||
|
token='';persist('')
|
||||||
|
publish({data:null,lastSync:0,error:value.error||'展示授权已失效,请重新连接显示终端。',authRequired:true})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if(!response.ok)throw Error(value.error||'暂时无法同步家庭资料')
|
||||||
|
failures=0;publish({data:value,error:'',authRequired:false,lastSync:now()})
|
||||||
|
}catch(error){
|
||||||
|
if(!stopped&&requestEpoch===epoch){failures++;publish({error:error.name==='AbortError'?'家庭连接暂时超时':error.message||'家庭连接暂时中断'})}
|
||||||
|
}finally{
|
||||||
|
cancel(timeout)
|
||||||
|
if(!stopped&&requestEpoch===epoch){publish({loading:false});if(token)poll=later(load,Math.min(120000,30000*Math.max(1,failures)))}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
start(){if(!consumeFragment())return accept(read())},
|
||||||
|
hashChanged:consumeFragment,
|
||||||
|
storageChanged(event){if(event.key===DISPLAY_STORAGE_KEY||event.key===null)return accept(read())},
|
||||||
|
retry(){if(consumeFragment())return;const saved=read();if(valid(saved)&&saved!==token)return accept(saved);return token?load():accept('')},
|
||||||
|
stop(){stopped=true;invalidate()},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,3 +10,4 @@
|
|||||||
@media(max-aspect-ratio:1/1) and (min-width:601px){.tv-shell{height:100vh;min-height:100vh;padding:1vh 3vw .6vh;gap:.7vh}.tv-upper{gap:.5vh;padding:0}.square-clock{width:min(94vw,56vh);max-width:100%;border-radius:3.4vh;padding:.7vh}.tv-home h1{font-size:2.4vh;margin:0 0 .35vh}.tv-greeting{display:none}.tv-date{font-size:1.5vh}.tv-date-extra{font-size:1vh;margin-top:.3vh}.tv-card{padding:.7vh 1.7vw}.tv-weather{min-height:8vh}.weather-big strong{font-size:3.8vh}.weather-big b{font-size:1.4vh}.weather-symbol{font-size:3vh}.weather-note{font-size:.8vh}.weather-forecast>div{gap:.6vh}.tv-device-grid{grid-template-columns:repeat(3,minmax(0,1fr));gap:.8vw}.tv-device{min-height:4.7vh;padding:.5vh .8vw;gap:.6vw}.tv-device h3{font-size:1.1vh}.tv-device p{font-size:.8vh}.tv-status{font-size:.85vh}.device-emblem{width:2.3vh;height:2.3vh;font-size:1.5vh}.tv-section-heading h2{font-size:1.3vh}.tv-section-heading{margin-bottom:.5vh}.tv-family-presence h2{font-size:1.3vh}.tv-family-presence p{font-size:.9vh}.tv-bottom{gap:.7vh}.tv-footer{font-size:.7vh}}
|
@media(max-aspect-ratio:1/1) and (min-width:601px){.tv-shell{height:100vh;min-height:100vh;padding:1vh 3vw .6vh;gap:.7vh}.tv-upper{gap:.5vh;padding:0}.square-clock{width:min(94vw,56vh);max-width:100%;border-radius:3.4vh;padding:.7vh}.tv-home h1{font-size:2.4vh;margin:0 0 .35vh}.tv-greeting{display:none}.tv-date{font-size:1.5vh}.tv-date-extra{font-size:1vh;margin-top:.3vh}.tv-card{padding:.7vh 1.7vw}.tv-weather{min-height:8vh}.weather-big strong{font-size:3.8vh}.weather-big b{font-size:1.4vh}.weather-symbol{font-size:3vh}.weather-note{font-size:.8vh}.weather-forecast>div{gap:.6vh}.tv-device-grid{grid-template-columns:repeat(3,minmax(0,1fr));gap:.8vw}.tv-device{min-height:4.7vh;padding:.5vh .8vw;gap:.6vw}.tv-device h3{font-size:1.1vh}.tv-device p{font-size:.8vh}.tv-status{font-size:.85vh}.device-emblem{width:2.3vh;height:2.3vh;font-size:1.5vh}.tv-section-heading h2{font-size:1.3vh}.tv-section-heading{margin-bottom:.5vh}.tv-family-presence h2{font-size:1.3vh}.tv-family-presence p{font-size:.9vh}.tv-bottom{gap:.7vh}.tv-footer{font-size:.7vh}}
|
||||||
[data-theme=day] .clock-hour{stroke:#167f98}[data-theme=day] .clock-minute{stroke:#169881}[data-theme=day] .clock-second{stroke:#e05260}
|
[data-theme=day] .clock-hour{stroke:#167f98}[data-theme=day] .clock-minute{stroke:#169881}[data-theme=day] .clock-second{stroke:#e05260}
|
||||||
.tv-family-presence{order:-1;min-height:5vh}.tv-family-presence>div{flex:1}.tv-positions{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:1vw}.tv-positions>div{display:flex;flex-direction:column;gap:.2vh}.tv-positions b{font-size:1.1vh;font-weight:500}.tv-positions span,.tv-positions small{font-size:.85vh;color:#818b76}.tv-positions .warning{color:#bd8b5d}
|
.tv-family-presence{order:-1;min-height:5vh}.tv-family-presence>div{flex:1}.tv-positions{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:1vw}.tv-positions>div{display:flex;flex-direction:column;gap:.2vh}.tv-positions b{font-size:1.1vh;font-weight:500}.tv-positions span,.tv-positions small{font-size:.85vh;color:#818b76}.tv-positions .warning{color:#bd8b5d}
|
||||||
|
.tv-reconnect{padding:1.5vh 2vw;border:1px solid #a7774f;border-radius:1vh;background:#f3e7d7;color:#65462e;font-size:1.4vh}.tv-reconnect strong{font-size:1.8vh}.tv-reconnect p{margin:.6vh 0}.tv-reconnect button{padding:.7vh 1.5vw;border:1px solid currentColor;border-radius:.5vh;background:transparent;color:inherit;font-size:inherit}[data-theme=night] .tv-reconnect{background:#30271f;color:#c5ad8a}
|
||||||
|
|||||||
@@ -9,6 +9,25 @@ NS = '{http://schemas.android.com/apk/res/android}'
|
|||||||
|
|
||||||
|
|
||||||
class AndroidLocationContractTests(unittest.TestCase):
|
class AndroidLocationContractTests(unittest.TestCase):
|
||||||
|
def test_terminal_is_ordinary_app_without_home_or_boot_receiver(self):
|
||||||
|
manifest=ET.parse(ANDROID/'AndroidManifest-terminal.xml').getroot()
|
||||||
|
self.assertEqual(manifest.findall('application/receiver'),[])
|
||||||
|
categories=[c.get(NS+'name') for c in manifest.findall('.//category')]
|
||||||
|
self.assertNotIn('android.intent.category.HOME',categories)
|
||||||
|
self.assertEqual(categories.count('android.intent.category.LAUNCHER'),1)
|
||||||
|
self.assertEqual(manifest.get(NS+'versionName'),(ROOT/'VERSION').read_text().strip())
|
||||||
|
|
||||||
|
def test_voice_is_foreground_press_to_record_and_cleans_temp_media(self):
|
||||||
|
source=(ANDROID/'src/cn/ucvl/zhaodisplay/VoicePanel.java').read_text(encoding='utf-8')
|
||||||
|
for text in ('ACTION_CANCEL:finish(false)','Manifest.permission.RECORD_AUDIO','AAC_ADTS','file.delete()','stopPlayer("rejected")','getCacheDir()','AudioFocusRequest','current(e,t)'):
|
||||||
|
self.assertIn(text,source)
|
||||||
|
self.assertNotIn('setStreamVolume',source)
|
||||||
|
ui=(ANDROID/'src/cn/ucvl/zhaodisplay/LocationActivity.java').read_text(encoding='utf-8')
|
||||||
|
self.assertIn('homeContent.setVisibility(paired?View.VISIBLE:View.GONE)',ui)
|
||||||
|
self.assertIn('voice.active(false)',ui)
|
||||||
|
main=(ANDROID/'src/cn/ucvl/zhaodisplay/MainActivity.java').read_text(encoding='utf-8')
|
||||||
|
self.assertIn('client=android&load=',main)
|
||||||
|
|
||||||
def test_phone_launcher_is_location_only(self):
|
def test_phone_launcher_is_location_only(self):
|
||||||
manifest = ET.parse(ANDROID/'AndroidManifest.xml').getroot()
|
manifest = ET.parse(ANDROID/'AndroidManifest.xml').getroot()
|
||||||
entries = manifest.findall('application/activity')
|
entries = manifest.findall('application/activity')
|
||||||
@@ -19,7 +38,7 @@ class AndroidLocationContractTests(unittest.TestCase):
|
|||||||
self.assertEqual(launchers, ['.LocationActivity'])
|
self.assertEqual(launchers, ['.LocationActivity'])
|
||||||
self.assertEqual(television, ['.MainActivity'])
|
self.assertEqual(television, ['.MainActivity'])
|
||||||
self.assertEqual(manifest.get(NS+'versionName'), (ROOT/'VERSION').read_text().strip())
|
self.assertEqual(manifest.get(NS+'versionName'), (ROOT/'VERSION').read_text().strip())
|
||||||
self.assertEqual(manifest.get(NS+'versionCode'), '3')
|
self.assertEqual(manifest.get(NS+'versionCode'), '4')
|
||||||
|
|
||||||
def test_collection_is_visible_foreground_and_never_boot_started(self):
|
def test_collection_is_visible_foreground_and_never_boot_started(self):
|
||||||
manifest = ET.parse(ANDROID/'AndroidManifest.xml').getroot()
|
manifest = ET.parse(ANDROID/'AndroidManifest.xml').getroot()
|
||||||
|
|||||||
@@ -10,6 +10,18 @@ class DownloadTests(unittest.TestCase):
|
|||||||
setUp=fixtures.HouseholdTests.setUp
|
setUp=fixtures.HouseholdTests.setUp
|
||||||
stop_server=fixtures.HouseholdTests.stop_server
|
stop_server=fixtures.HouseholdTests.stop_server
|
||||||
|
|
||||||
|
def test_terminal_variant_has_separate_manifest_and_authenticated_download(self):
|
||||||
|
raw=self.package();folder=app.DATA/'app-downloads'
|
||||||
|
(folder/'ZhaoTerminal.apk').write_bytes(raw)
|
||||||
|
(folder/'terminal.json').write_bytes((folder/'android.json').read_bytes())
|
||||||
|
member=self.members[self.aid]
|
||||||
|
code,_,body=self.get('/api/app-release?variant=terminal',member)
|
||||||
|
self.assertEqual(code,200);self.assertEqual(json.loads(body)['url'],'/downloads/ZhaoTerminal.apk')
|
||||||
|
self.assertEqual(self.get('/downloads/ZhaoTerminal.apk',member)[2],raw)
|
||||||
|
self.assertEqual(self.get('/downloads/ZhaoTerminal.apk')[0],401)
|
||||||
|
self.assertEqual(self.get('/downloads/ZhaoTerminal.apk',member,method='HEAD')[2],b'')
|
||||||
|
self.assertEqual(self.get('/api/app-release?variant=../../vision.db',member)[0],400)
|
||||||
|
|
||||||
def package(self):
|
def package(self):
|
||||||
folder=app.DATA/'app-downloads';folder.mkdir(exist_ok=True)
|
folder=app.DATA/'app-downloads';folder.mkdir(exist_ok=True)
|
||||||
raw=b'PK fixture installer bytes'
|
raw=b'PK fixture installer bytes'
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import http.client
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
import test_households as fixtures
|
||||||
|
import test_phone_locations as phone_fixtures
|
||||||
|
|
||||||
|
app=fixtures.app
|
||||||
|
|
||||||
|
def audio(frames=10):
|
||||||
|
# 16 kHz ADTS frames; payload fixture is for transport validation, not playback.
|
||||||
|
return base64.b64encode(bytes([255,241,96,64,1,31,252,0])*frames).decode()
|
||||||
|
|
||||||
|
class VoiceTests(unittest.TestCase):
|
||||||
|
setUp=fixtures.HouseholdTests.setUp
|
||||||
|
stop_server=fixtures.HouseholdTests.stop_server
|
||||||
|
phone=phone_fixtures.PhoneLocationTests.phone
|
||||||
|
|
||||||
|
def call(self,phone,action,**data):return app.VOICE.native(phone['token'],dict(kind='phone',action=action,**data))
|
||||||
|
def receive(self,receiver,sender):
|
||||||
|
self.call(receiver,'configure',enabled=True,allowed=['phone:'+sender['sid']],consent=True)
|
||||||
|
self.call(receiver,'status')
|
||||||
|
def send(self,sender,receiver,**data):
|
||||||
|
body=dict(target='phone:'+receiver['sid'],audio=audio(),id='f'*32);body.update(data)
|
||||||
|
return self.call(sender,'send',**body)
|
||||||
|
|
||||||
|
def test_default_deny_and_explicit_two_way_consents(self):
|
||||||
|
a,b=self.phone('甲'),self.phone('乙')
|
||||||
|
with self.assertRaises(app.Problem):self.send(a,b)
|
||||||
|
self.receive(b,a)
|
||||||
|
result=self.send(a,b)
|
||||||
|
self.assertEqual(result['status'],'queued')
|
||||||
|
with self.assertRaises(app.Problem):self.send(b,a)
|
||||||
|
incoming=self.call(b,'status')['inbox'];self.assertEqual(len(incoming),1)
|
||||||
|
clip=self.call(b,'take',id=incoming[0]['id']);self.assertEqual(clip['audio'],audio())
|
||||||
|
self.assertEqual(len(app.VOICE.messages),0)
|
||||||
|
self.call(b,'ack',id=clip['id'],status='played')
|
||||||
|
self.assertEqual(self.call(a,'status')['sent'][0]['status'],'played')
|
||||||
|
with self.assertRaises(app.Problem):self.call(b,'take',id=clip['id'])
|
||||||
|
|
||||||
|
def test_idempotency_no_duplicate_delivery(self):
|
||||||
|
a,b=self.phone('甲'),self.phone('乙');self.receive(b,a)
|
||||||
|
result=self.send(a,b);self.assertEqual(self.send(a,b)['id'],result['id']);self.assertEqual(len(app.VOICE.messages),1)
|
||||||
|
self.call(b,'take',id=result['id']);self.send(a,b);self.assertEqual(len(app.VOICE.messages),0)
|
||||||
|
|
||||||
|
def test_cross_family_and_foreign_inbox_rejected(self):
|
||||||
|
a,b,c=self.phone('甲'),self.phone('乙'),self.phone('其他',self.other)
|
||||||
|
with self.assertRaises(app.Problem):self.receive(b,c)
|
||||||
|
self.receive(b,a);msg=self.send(a,b)
|
||||||
|
with self.assertRaises(app.Problem):self.call(c,'take',id=msg['id'])
|
||||||
|
with self.assertRaises(app.Problem):self.send(c,b)
|
||||||
|
with self.assertRaises(app.Problem):self.call(a,'ack',id=msg['id'],status='played')
|
||||||
|
|
||||||
|
def test_mute_expiry_and_repair_clear_audio(self):
|
||||||
|
a,b=self.phone('甲'),self.phone('乙');self.receive(b,a);self.send(a,b)
|
||||||
|
self.call(b,'configure',enabled=False,allowed=[]);self.assertEqual(app.VOICE.messages,{})
|
||||||
|
self.receive(b,a);self.send(a,b,id='a'*32)
|
||||||
|
with patch('family_voice.time.time',return_value=time.time()+91):app.VOICE.sweep()
|
||||||
|
self.assertEqual(app.VOICE.messages,{})
|
||||||
|
self.receive(b,a);self.send(a,b,id='b'*32)
|
||||||
|
app.LOCATIONS.native(a['token'],{'action':'revoke'});app.VOICE.sweep();self.assertEqual(app.VOICE.messages,{})
|
||||||
|
with self.assertRaises(app.Problem):self.call(a,'status')
|
||||||
|
|
||||||
|
def test_pairing_not_location_consent_and_offline_no_delivery(self):
|
||||||
|
a,b=self.phone('甲'),self.phone('乙');self.receive(b,a)
|
||||||
|
self.assertEqual(app.LOCATIONS.latest,{})
|
||||||
|
self.send(a,b);self.call(b,'offline');self.assertEqual(app.VOICE.messages,{})
|
||||||
|
with self.assertRaises(app.Problem):self.send(a,b,id='a'*32)
|
||||||
|
|
||||||
|
def test_bad_audio_bounds_and_queue_limit(self):
|
||||||
|
a,b=self.phone('甲'),self.phone('乙');self.receive(b,a)
|
||||||
|
for content in ('invalid',base64.b64encode(b'not audio').decode(),audio(500),audio(1),'A'*200001):
|
||||||
|
with self.subTest(content=content[:15]),self.assertRaises(app.Problem):self.send(a,b,audio=content)
|
||||||
|
for i in range(3):self.send(a,b,id=str(i)*32)
|
||||||
|
with self.assertRaises(app.Problem):self.send(a,b,id='a'*32)
|
||||||
|
with self.assertRaises(app.Problem):self.call(b,'take',id=[])
|
||||||
|
|
||||||
|
def test_display_uses_native_token_and_manager_scope(self):
|
||||||
|
phone=self.phone('家人')
|
||||||
|
device=app.INVENTORY.save(dict(name='屏幕',deviceType='显示终端'),self.roots[self.aid])
|
||||||
|
grant=app.DISPLAYS.manage(self.roots[self.aid],dict(action='create',deviceId=device['id']))
|
||||||
|
paired=app.DISPLAYS.pair({'code':grant['pairingCode']},'voice-test')
|
||||||
|
with self.assertRaises(app.Problem):app.VOICE.native(paired['token'],dict(kind='display',action='status'))
|
||||||
|
data=dict(deviceId=device['id'],action='configure',enabled=True,allowed=['phone:'+phone['sid']],consent=True)
|
||||||
|
for actor in (self.other,self.members[self.aid]):
|
||||||
|
with self.assertRaises(app.Problem):app.VOICE.manage_display(actor,data)
|
||||||
|
app.VOICE.manage_display(self.owner,data)
|
||||||
|
app.VOICE.native(paired['nativeToken'],dict(kind='display',action='status'))
|
||||||
|
self.assertEqual(self.call(phone,'status')['targets'][0]['name'],'屏幕')
|
||||||
|
app.INVENTORY.transfer(dict(source='device',id=device['id'],targetFamilyId=self.bid),self.root)
|
||||||
|
self.assertEqual(self.call(phone,'status')['targets'],[])
|
||||||
|
|
||||||
|
def test_http_auth_and_audio_not_persisted(self):
|
||||||
|
a,b=self.phone('甲'),self.phone('乙');self.receive(b,a);self.send(a,b)
|
||||||
|
raw='\n'.join(app.DB.iterdump());self.assertNotIn(audio(),raw);self.assertNotIn(a['token'],raw)
|
||||||
|
for token,expected in ((a['token'],200),(self.tokens[self.root['id']],401),('',401)):
|
||||||
|
connection=http.client.HTTPConnection(*self.server.server_address,timeout=3)
|
||||||
|
connection.request('POST','/api/voice',json.dumps(dict(kind='phone',action='status')),{'Authorization':'Bearer '+token,'Content-Type':'application/json'})
|
||||||
|
response=connection.getresponse();response.read();connection.close();self.assertEqual(response.status,expected)
|
||||||
|
|
||||||
|
if __name__=='__main__':unittest.main()
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import {createDisplayConnection,DISPLAY_STORAGE_KEY} from './frontend/src/tv/connection.mjs'
|
||||||
|
const a='a'.repeat(43),b='b'.repeat(43)
|
||||||
|
const flush=async()=>{for(let n=0;n<8;n++)await Promise.resolve()}
|
||||||
|
function fixture(saved=a){
|
||||||
|
const stored=new Map(saved?[[DISPLAY_STORAGE_KEY,saved]]:[]),requests=[],timers=new Map(),states=[]
|
||||||
|
let id=0;const url={hash:'',pathname:'/tv',search:'?client=android'}
|
||||||
|
const connection=createDisplayConnection({url,historyApi:{replaceState(_s,_t,path){url.hash=path.includes('#')?'#'+path.split('#')[1]:''}},
|
||||||
|
storage:{getItem:k=>stored.get(k),setItem:(k,v)=>stored.set(k,v),removeItem:k=>stored.delete(k)},
|
||||||
|
fetcher:(_path,options)=>new Promise((resolve,reject)=>requests.push({options,resolve:(status,body)=>resolve({status,ok:status===200,json:async()=>body}),reject})),
|
||||||
|
later:(fn,delay)=>{timers.set(++id,{fn,delay});return id},cancel:i=>timers.delete(i),now:()=>1000,onChange:s=>states.push(s)})
|
||||||
|
return {connection,url,stored,requests,timers,states,get state(){return states.at(-1)}}
|
||||||
|
}
|
||||||
|
test('new pairing fragment replaces cached authorization and clears private display data',async()=>{
|
||||||
|
const f=fixture();f.connection.start();f.requests[0].resolve(200,{home:{name:'Old'}});await flush()
|
||||||
|
f.url.hash='#display='+b;f.connection.hashChanged();assert.equal(f.state.data,null)
|
||||||
|
assert.equal(f.requests[1].options.headers.Authorization,'Bearer '+b);assert.equal(f.url.hash,'')
|
||||||
|
f.requests[1].resolve(200,{home:{name:'New'}});await flush();assert.equal(f.state.data.home.name,'New');assert.equal(f.stored.get(DISPLAY_STORAGE_KEY),b)
|
||||||
|
})
|
||||||
|
test('late unauthorized response cannot clear the newly paired token',async()=>{
|
||||||
|
const f=fixture();f.connection.start();f.url.hash='#display='+b;f.connection.hashChanged()
|
||||||
|
assert.ok(f.requests[0].options.signal.aborted);f.requests[0].resolve(401,{error:'Old revoked'});await flush()
|
||||||
|
assert.equal(f.stored.get(DISPLAY_STORAGE_KEY),b);assert.equal(f.state.authRequired,false)
|
||||||
|
f.requests[1].resolve(200,{home:{name:'New'}});await flush();assert.equal(f.state.data.home.name,'New')
|
||||||
|
})
|
||||||
|
test('real expiry hides household data and stops polling',async()=>{
|
||||||
|
const f=fixture();f.connection.start();f.requests[0].resolve(200,{locations:[{name:'Fixture'}]});await flush()
|
||||||
|
f.connection.retry();f.requests[1].resolve(401,{error:'Expired'});await flush()
|
||||||
|
assert.equal(f.state.data,null);assert.equal(f.state.authRequired,true);assert.equal(f.timers.size,0);assert.equal(f.stored.size,0)
|
||||||
|
})
|
||||||
|
test('network failure retains authorization and schedules bounded retry',async()=>{
|
||||||
|
const f=fixture();f.connection.start();f.requests[0].reject(Error('Offline'));await flush()
|
||||||
|
assert.equal(f.state.authRequired,false);assert.equal(f.stored.get(DISPLAY_STORAGE_KEY),a)
|
||||||
|
assert.deepEqual([...f.timers.values()].map(v=>v.delay),[30000])
|
||||||
|
})
|
||||||
|
test('fresh link works even if local storage is blocked',async()=>{
|
||||||
|
const requests=[];let state;const connection=createDisplayConnection({url:{hash:'#display='+a,pathname:'/tv',search:''},historyApi:{replaceState(){}},
|
||||||
|
storage:{getItem(){throw Error()},setItem(){throw Error()},removeItem(){throw Error()}},onChange:s=>state=s,
|
||||||
|
fetcher:async(_u,o)=>{requests.push(o);return {ok:true,status:200,json:async()=>({home:{name:'Home'}})}}})
|
||||||
|
connection.start();await flush();assert.equal(state.data.home.name,'Home');assert.equal(requests.length,1);connection.stop()
|
||||||
|
})
|
||||||
|
test('other-tab re-pair wins over stale 401, stop cancels all future work',async()=>{
|
||||||
|
const f=fixture();f.connection.start();f.stored.set(DISPLAY_STORAGE_KEY,b);f.requests[0].resolve(401,{});await flush()
|
||||||
|
assert.equal(f.requests.length,2);f.connection.stop();f.requests[1].resolve(200,{home:{name:'Ignore'}});await flush()
|
||||||
|
assert.equal(f.state.data,null);assert.equal(f.timers.size,0)
|
||||||
|
})
|
||||||
|
test('unpaired and invalid explicit links never reuse a previous household',()=>{
|
||||||
|
const f=fixture();f.url.hash='#display=bad';f.connection.start();assert.equal(f.requests.length,0);assert.equal(f.state.authRequired,true);assert.equal(f.stored.size,0)
|
||||||
|
})
|
||||||
+3
-3
@@ -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">按设备选择手机或显示终端安装包。使用平台账号登录下载;安装后凭配对码使用,无需在 App 注册。两种版本使用同一个应用身份,请按实际用途选择。</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">手机打开“赵府家人位置”,输入绑定本人档案的手机配对码,无需注册或登录。可查看获授权的家人;“我的位置设置”可选择查看人、实时(约 10 秒)/ 1 分钟 / 5 分钟上传,再由本人打开共享开关。查看家人无需开启自己的定位。</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">下载手机家人位置版</a><a id="terminal-link" class="btn btn-outline-success btn-lg ms-2" href="/downloads/ZhaoTerminal.apk" hidden>下载显示终端版</a><p id="terminal-info" class="small text-secondary mt-3"></p><details class="small"><summary>显示终端版校验</summary><code id="terminal-hash"></code></details><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。安装后仍按家庭授权访问资料。两端均提供“按住说话,松开发送”;接收方需先允许具体喊话人并打开 App。显示终端无需麦克风即可接收,接上话筒后可以发送。</p></section></main></body></html>
|
||||||
|
|||||||
+3
-2
@@ -2,5 +2,6 @@
|
|||||||
const login=document.querySelector('#download-login'),ready=document.querySelector('#download-ready'),status=document.querySelector('#download-status'),retry=document.querySelector('#download-retry');
|
const login=document.querySelector('#download-login'),ready=document.querySelector('#download-ready'),status=document.querySelector('#download-status'),retry=document.querySelector('#download-retry');
|
||||||
async function request(path,body){const response=await fetch(path,{credentials:'same-origin',cache:'no-store',...(body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{})});const result=await response.json();if(!response.ok){const err=new Error(result.error||'暂时无法下载,请重试');err.status=response.status;throw err}return result}
|
async function request(path,body){const response=await fetch(path,{credentials:'same-origin',cache:'no-store',...(body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{})});const result=await response.json();if(!response.ok){const err=new Error(result.error||'暂时无法下载,请重试');err.status=response.status;throw err}return result}
|
||||||
async function load(){retry.hidden=true;ready.hidden=true;status.textContent='正在准备安装包…';try{const session=await request('/api/session');login.hidden=session.authenticated;if(!session.authenticated){status.textContent='使用你的系统账号登录;可由家人下载后协助安装,无需代码仓库账号。';return}const r=await request('/api/app-release');document.querySelector('#apk-link').href=r.url;document.querySelector('#release-info').textContent=`版本 ${r.version} · ${(r.size/1024/1024).toFixed(1)} MB · Android ${r.minimumAndroid}.0 及以上`;document.querySelector('#apk-hash').textContent=r.sha256;ready.hidden=false;status.textContent='安装包已就绪。';}catch(e){if(e.status===401)login.hidden=false;status.textContent=e.message;retry.hidden=false}}
|
async function load(){retry.hidden=true;ready.hidden=true;status.textContent='正在准备安装包…';try{const session=await request('/api/session');login.hidden=session.authenticated;if(!session.authenticated){status.textContent='使用你的系统账号登录;可由家人下载后协助安装,无需代码仓库账号。';return}const r=await request('/api/app-release');document.querySelector('#apk-link').href=r.url;document.querySelector('#release-info').textContent=`版本 ${r.version} · ${(r.size/1024/1024).toFixed(1)} MB · Android ${r.minimumAndroid}.0 及以上`;document.querySelector('#apk-hash').textContent=r.sha256;ready.hidden=false;status.textContent='安装包已就绪。';}catch(e){if(e.status===401)login.hidden=false;status.textContent=e.message;retry.hidden=false}}
|
||||||
login.addEventListener('submit',async event=>{event.preventDefault();const button=login.querySelector('button');button.disabled=true;try{await request('/api/login',{username:login.elements.username.value,password:login.elements.password.value});login.elements.password.value='';await load()}catch(e){status.textContent=e.message}finally{button.disabled=false}});
|
async function loadTerminal(){const link=document.querySelector('#terminal-link'),info=document.querySelector('#terminal-info');link.hidden=true;try{const result=await request('/api/app-release?variant=terminal');link.href=result.url;link.hidden=false;info.textContent=`显示终端版 ${result.version} · ${(result.size/1024/1024).toFixed(1)} MB`;document.querySelector('#terminal-hash').textContent=result.sha256}catch(e){info.textContent=e.status===401?'登录后可下载显示终端版':'显示终端安装包暂未就绪'}}
|
||||||
retry.addEventListener('click',load);load();
|
login.addEventListener('submit',async event=>{event.preventDefault();const button=login.querySelector('button');button.disabled=true;try{await request('/api/login',{username:login.elements.username.value,password:login.elements.password.value});login.elements.password.value='';await load();await loadTerminal()}catch(e){status.textContent=e.message}finally{button.disabled=false}});
|
||||||
|
retry.addEventListener('click',()=>{load();loadTerminal()});load();loadTerminal();
|
||||||
|
|||||||
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
+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="#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>
|
<!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-0U8VZKRt.js"></script>
|
||||||
<link rel="modulepreload" crossorigin href="/ui/assets/bootstrap.min-CBPvWlfP.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-COmDIIIH.css">
|
<link rel="stylesheet" crossorigin href="/ui/assets/index-22eWvMYM.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-D-PRuWjc.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-CGtsIoJR.js"></script>
|
||||||
<link rel="modulepreload" crossorigin href="/ui/assets/bootstrap.min-CBPvWlfP.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-C-Rk3l6q.css">
|
||||||
</head><body><div id="app"></div></body></html>
|
</head><body><div id="app"></div></body></html>
|
||||||
|
|||||||
Reference in New Issue
Block a user