feat: household TV companion with scoped pairing and direct LAN camera strip
This commit is contained in:
@@ -16,3 +16,5 @@ mediamtx.exe
|
||||
|
||||
/frontend/node_modules/
|
||||
/frontend/.vite/
|
||||
/android-display/build/
|
||||
*.jks
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# v0.1.44 · 家庭电视与设备看板
|
||||
|
||||
- 新增 `/tv`:本地 Vue + Bootstrap,温暖简洁的竖屏 / 横屏家庭看板。方形模拟时钟、北京时间、农历、ISO 周数、家庭设备与未来 60 天已发布家庭记事。设备多于四台时分组轮换;网络短暂中断保留上次资料并标明状态,授权失效清空家庭数据。
|
||||
- 天气经管理员设置城市与经纬度后,由服务端读取 Open-Meteo。15 分钟缓存,过期标记,六小时后不再展示旧天气;没有外部 CDN 或字体。天气来源及协议:https://open-meteo.com/en/docs 。
|
||||
- 电视登记为所在家庭的设备对象。展示凭据仅能读取单家庭的精简数据,以及上报自身遥测;数据库只保存凭据摘要,一年有效,可随时停用。电视不持有管理员密码,不能调用设备控制或人员接口。
|
||||
- 电视管理提供心跳状态、最后采样时间、处理器温度、可用内存 / 存储、IP、Android 版本、屏幕分辨率与前台状态。没有传感器的指标明确显示未提供;本批硬件的 test_battery 节点不作为功耗传感器。
|
||||
- 安卓家庭屏应用:保留系统旋转设置,全屏展示,前台保持亮屏,20 秒硬件心跳;重启后启动遥测服务。系统是否允许自动打开前台应用仍取决于系统策略,本版不替换电视默认桌面。
|
||||
- App 使用 8 位一次性配对码绑定家庭,10 分钟有效;摄像头凭据使用独立的原生授权,普通展示链接不能读取。底部固定一行镜头,占屏幕约 12%,最多三路并排、更多镜头每分钟分组轮换。原生播放器直接连接同局域网 RTSP 子码流,断线隐藏旧帧并重连,不通过平台转发视频。授权连接失联超过五分钟停止画面。
|
||||
- 管理员按需查看模拟屏,60 秒内约每 20 秒回传当前应用窗口;使用 PixelCopy,非系统级远程桌面。退出应用后不采集其他应用。预览只在服务端内存短暂保存,90 秒失效,不写磁盘或网盘。
|
||||
- 自动告警:心跳中断超过 100 秒,温度 ≥75°C / ≥85°C,可用内存低于 5%,可用存储低于 0.5 GB,以及看板退出前台。记录触发与恢复,单授权保留最近 200 条已恢复记录。报警显示在家庭设备页,尚无短信或微信推送。
|
||||
- 超级管理员可跨家庭转移设备,原区域、人员引用与上级设备清空,电视旧展示授权立即撤销。直接接入的摄像头随同镜头转移;仍关联录像机的设备需先解除关联。家庭管理员不能跨家庭移动。
|
||||
|
||||
## 构建
|
||||
|
||||
前端:`pnpm --dir frontend build`。安卓:`android-display/build.ps1`,可通过 ToolRoot 参数指定本机 Android SDK / JDK。签名文件在本机 LOCALAPPDATA/ZhaoDisplay,APK 不包含任何授权令牌;安装后单独授权。
|
||||
|
||||
## 数据库
|
||||
|
||||
新增 `household_displays`、`display_native_keys`、`display_telemetry`、`display_alerts` 表。旧版服务可忽略新增表,原业务表结构未改变。上线前执行 SQLite 一致性备份。
|
||||
@@ -0,0 +1,15 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="1" android:versionName="0.1.44">
|
||||
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30"/>
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK"/>
|
||||
<application android:label="赵府家庭屏" android:allowBackup="false" android:usesCleartextTraffic="false" android:theme="@android:style/Theme.Material.Light.NoActionBar">
|
||||
<activity android:name=".MainActivity" android:exported="true" android:configChanges="orientation|screenSize|keyboardHidden" android:launchMode="singleTask">
|
||||
<intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/><category android:name="android.intent.category.LEANBACK_LAUNCHER"/></intent-filter>
|
||||
</activity>
|
||||
<service android:name=".MonitorService" android:exported="false"/>
|
||||
<receiver android:name=".BootReceiver" android:exported="true"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED"/></intent-filter></receiver>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,43 @@
|
||||
param([string]$ToolRoot='C:\Users\Administrator\Documents\ChatGPT\优创未来\services\toplc-vpn-android\.tools')
|
||||
$ErrorActionPreference='Stop'
|
||||
$source=Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
$stage=Join-Path 'C:\CodexBuild' ('ZhaoDisplay-'+[guid]::NewGuid().ToString('N'))
|
||||
New-Item -ItemType Directory -Path $stage | Out-Null
|
||||
Copy-Item -LiteralPath (Join-Path $source 'AndroidManifest.xml') -Destination $stage
|
||||
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'
|
||||
$sdk=Join-Path $ToolRoot 'android-sdk'
|
||||
$bt=Join-Path $sdk 'build-tools\36.0.0'
|
||||
$android=Join-Path $sdk 'platforms\android-37.0\android.jar'
|
||||
$env:JAVA_HOME=$jdk
|
||||
$env:Path="$jdk\bin;$env:Path"
|
||||
$build=Join-Path $stage 'build'
|
||||
New-Item -ItemType Directory -Path $build,"$build\classes","$build\dex","$build\generated" | Out-Null
|
||||
& "$bt\aapt2.exe" compile --dir "$stage\res" -o "$build\compiled.zip"
|
||||
if($LASTEXITCODE){throw 'Resource compilation failed'}
|
||||
& "$bt\aapt2.exe" link -o "$build\unsigned.apk" -I $android --manifest "$stage\AndroidManifest.xml" --java "$build\generated" "$build\compiled.zip"
|
||||
if($LASTEXITCODE){throw 'Resource linking failed'}
|
||||
$sources=@((Get-ChildItem "$stage\src","$build\generated" -Recurse -Filter '*.java').FullName)
|
||||
& "$jdk\bin\javac.exe" -encoding UTF-8 -source 8 -target 8 -cp $android -d "$build\classes" $sources
|
||||
if($LASTEXITCODE){throw 'Java compilation failed'}
|
||||
& "$jdk\bin\jar.exe" cf "$build\classes.jar" -C "$build\classes" .
|
||||
& "$bt\d8.bat" --lib $android --min-api 26 --output "$build\dex" "$build\classes.jar"
|
||||
if($LASTEXITCODE){throw 'Dex compilation failed'}
|
||||
Copy-Item "$build\unsigned.apk" "$build\with-dex.apk"
|
||||
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||
$zip=[IO.Compression.ZipFile]::Open("$build\with-dex.apk",[IO.Compression.ZipArchiveMode]::Update)
|
||||
try{[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,"$build\dex\classes.dex",'classes.dex',[IO.Compression.CompressionLevel]::Optimal) | Out-Null}finally{$zip.Dispose()}
|
||||
& "$bt\zipalign.exe" -f 4 "$build\with-dex.apk" "$build\aligned.apk"
|
||||
$keydir=Join-Path $env:LOCALAPPDATA 'ZhaoDisplay'
|
||||
New-Item -ItemType Directory -Force -Path $keydir | Out-Null
|
||||
$keystore=Join-Path $keydir 'display-signing.jks'
|
||||
if(!(Test-Path -LiteralPath $keystore)){
|
||||
& "$jdk\bin\keytool.exe" -genkeypair -keystore $keystore -storepass android -keypass android -alias zhaodisplay -keyalg RSA -keysize 2048 -validity 10000 -dname 'CN=Zhao Household Display,O=UCVL,C=CN'
|
||||
if($LASTEXITCODE){throw 'Signing key generation failed'}
|
||||
}
|
||||
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"
|
||||
if($LASTEXITCODE){throw 'APK signing failed'}
|
||||
& "$bt\apksigner.bat" verify "$source\build\ZhaoDisplay.apk"
|
||||
if($LASTEXITCODE){throw 'APK verification failed'}
|
||||
Write-Output "$source\build\ZhaoDisplay.apk"
|
||||
@@ -0,0 +1 @@
|
||||
<resources><string name="app_name">赵府家庭屏</string></resources>
|
||||
@@ -0,0 +1,8 @@
|
||||
package cn.ucvl.zhaodisplay;
|
||||
import android.content.*;
|
||||
public class BootReceiver extends BroadcastReceiver {
|
||||
@Override public void onReceive(Context context,Intent intent){
|
||||
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()) && !context.getSharedPreferences("display",0).getString("token","").isEmpty())
|
||||
context.startForegroundService(new Intent(context,MonitorService.class));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package cn.ucvl.zhaodisplay;
|
||||
|
||||
import android.graphics.*;
|
||||
import android.media.MediaPlayer;
|
||||
import android.view.*;
|
||||
import android.widget.*;
|
||||
import android.os.Handler;
|
||||
import android.os.SystemClock;
|
||||
import android.util.TypedValue;
|
||||
import org.json.*;
|
||||
import java.net.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
/** Direct LAN decoding. No video request is sent to the platform media server. */
|
||||
final class CameraStrip extends LinearLayout {
|
||||
final MainActivity app;
|
||||
final Handler ui=new Handler();
|
||||
final ScheduledExecutorService worker=Executors.newSingleThreadScheduledExecutor();
|
||||
final LinearLayout row;
|
||||
final TextView title;
|
||||
final List<Tile> tiles=new ArrayList<>();
|
||||
JSONArray cameras=new JSONArray();
|
||||
String signature="";
|
||||
int group=0;
|
||||
boolean stopped=false, foreground=false;
|
||||
long lease=0,lastRotation=0;
|
||||
static volatile String report="[]";
|
||||
CameraStrip(MainActivity a){
|
||||
super(a);app=a;setOrientation(VERTICAL);setBackgroundColor(0xffe8e5db);
|
||||
int pad=Math.max(12,a.getResources().getDisplayMetrics().widthPixels/50);
|
||||
setPadding(pad,pad/3,pad,pad/3);
|
||||
LinearLayout heading=new LinearLayout(a);heading.setGravity(Gravity.CENTER_VERTICAL);
|
||||
title=text("家中画面 · 局域网直连",0xff57634e,.009f);
|
||||
heading.addView(title,new LayoutParams(0,LayoutParams.WRAP_CONTENT,1));
|
||||
TextView setting=text("绑定家庭 ⚙",0xff5f6f52,.009f);setting.setPadding(pad,0,pad,0);setting.setFocusable(true);setting.setOnClickListener(v->app.pairDialog());
|
||||
heading.addView(setting);addView(heading);
|
||||
row=new LinearLayout(a);row.setGravity(Gravity.CENTER);addView(row,new LayoutParams(-1,0,1));
|
||||
worker.scheduleWithFixedDelay(this::fetch,0,60,TimeUnit.SECONDS);
|
||||
ui.postDelayed(watch,5000);
|
||||
}
|
||||
TextView text(String content,int color,float ratio){TextView t=new TextView(app);t.setText(content);t.setTextColor(color);t.setTextSize(TypedValue.COMPLEX_UNIT_PX,Math.max(18,app.getResources().getDisplayMetrics().heightPixels*ratio));return t;}
|
||||
void fetch(){
|
||||
if(stopped)return;
|
||||
String token=app.getSharedPreferences("display",0).getString("nativeToken","");
|
||||
if(token.isEmpty()){ui.post(()->{clear();title.setText("家中画面 · 请先绑定家庭");});return;}
|
||||
try{
|
||||
JSONObject value=DisplayApi.call("/api/display/cameras",token,null);
|
||||
JSONArray found=value.getJSONArray("items");String sig=found.toString();
|
||||
ui.post(()->{if(stopped)return;lease=SystemClock.elapsedRealtime()+300000;title.setText("家中画面 · 局域网直连");if(!signature.equals(sig)){cameras=found;signature=sig;group=0;render();}});
|
||||
}catch(DisplayApi.ApiError e){if(e.status==401||e.status==403)ui.post(()->{lease=0;clear();signature="";title.setText("展示授权已失效 · 请重新绑定家庭");});}
|
||||
catch(Exception ignored){}
|
||||
}
|
||||
void refresh(){signature="";clear();if(!worker.isShutdown())worker.execute(this::fetch);}
|
||||
void render(){
|
||||
clear();if(!foreground||lease<SystemClock.elapsedRealtime())return;
|
||||
if(cameras.length()==0){row.addView(text("本家庭还没有接入摄像头",0xff888471,.011f));return;}
|
||||
int start=group*3;
|
||||
for(int i=start;i<Math.min(start+3,cameras.length());i++){
|
||||
JSONObject camera=cameras.optJSONObject(i);if(camera==null)continue;
|
||||
Tile t=new Tile(camera);tiles.add(t);
|
||||
LayoutParams p=new LayoutParams(0,-1,1);p.setMargins(8,4,8,0);row.addView(t,p);
|
||||
}
|
||||
lastRotation=SystemClock.elapsedRealtime();
|
||||
}
|
||||
void clear(){for(Tile t:tiles)t.close();tiles.clear();row.removeAllViews();report="[]";}
|
||||
void foreground(boolean value){foreground=value;if(value)render();else clear();}
|
||||
void close(){stopped=true;ui.removeCallbacksAndMessages(null);worker.shutdownNow();clear();}
|
||||
final Runnable watch=new Runnable(){public void run(){
|
||||
if(stopped)return;
|
||||
long now=SystemClock.elapsedRealtime();
|
||||
if(lease>0&&lease<now){clear();signature="";title.setText("授权连接暂时中断 · 等待同步");}
|
||||
else if(foreground&&cameras.length()>3&&now-lastRotation>60000){group=(group+1)%((cameras.length()+2)/3);render();}
|
||||
JSONArray states=new JSONArray();
|
||||
for(Tile t:new ArrayList<>(tiles)){
|
||||
if(t.player!=null&&now-t.lastFrame>20000)t.fail("画面中断 · 自动重连","offline");
|
||||
try{states.put(new JSONObject().put("id",t.camera.optString("id")).put("state",t.state));}catch(Exception ignored){}
|
||||
}
|
||||
report=states.toString();ui.postDelayed(this,5000);
|
||||
}};
|
||||
static boolean sameNetwork(String host){
|
||||
try{
|
||||
if(!host.matches("[0-9.]+"))return false;
|
||||
byte[] remote=InetAddress.getByName(host).getAddress();
|
||||
if(remote.length!=4)return false;
|
||||
for(NetworkInterface net:Collections.list(NetworkInterface.getNetworkInterfaces())){
|
||||
if(!net.isUp()||net.isLoopback())continue;
|
||||
for(InterfaceAddress local:net.getInterfaceAddresses()){
|
||||
byte[] own=local.getAddress().getAddress();int prefix=local.getNetworkPrefixLength();
|
||||
if(own.length!=4||prefix<=0||prefix>32)continue;
|
||||
boolean match=true;for(int bit=0;bit<prefix;bit++)if((own[bit/8]&(1<<(7-bit%8)))!=(remote[bit/8]&(1<<(7-bit%8)))){match=false;break;}
|
||||
if(match)return true;
|
||||
}
|
||||
}
|
||||
}catch(Exception ignored){}
|
||||
return false;
|
||||
}
|
||||
final class Tile extends FrameLayout implements TextureView.SurfaceTextureListener {
|
||||
final JSONObject camera;final TextureView texture;final TextView label;final View curtain;
|
||||
MediaPlayer player;Surface surface;String state="connecting";long lastFrame=SystemClock.elapsedRealtime();
|
||||
int failures=0;boolean closed=false,visible=false;
|
||||
final Runnable retry=()->connect();
|
||||
Tile(JSONObject c){super(app);camera=c;setBackgroundColor(0xff24322b);
|
||||
texture=new TextureView(app);texture.setSurfaceTextureListener(this);addView(texture,new FrameLayout.LayoutParams(-1,-1));
|
||||
curtain=new View(app);curtain.setBackgroundColor(0xff24322b);addView(curtain,new FrameLayout.LayoutParams(-1,-1));
|
||||
label=text(camera.optString("name")+" · 正在直连",0xfffaf7eb,.009f);label.setPadding(16,4,12,4);label.setBackgroundColor(0xb0334237);
|
||||
FrameLayout.LayoutParams p=new FrameLayout.LayoutParams(-1,-2,Gravity.BOTTOM);addView(label,p);
|
||||
setFocusable(true);setOnClickListener(v->{failures=0;connect();});
|
||||
}
|
||||
void connect(){
|
||||
if(closed||!foreground||surface==null||lease<SystemClock.elapsedRealtime())return;
|
||||
release();ui.removeCallbacks(retry);
|
||||
if(!sameNetwork(camera.optString("host"))){fail("不在同一局域网","outside_lan");return;}
|
||||
try{
|
||||
URI uri=new URI(camera.getString("url"));
|
||||
if(!"rtsp".equals(uri.getScheme())||!camera.getString("host").equals(uri.getHost())){fail("直连地址不正确","unsupported");return;}
|
||||
state="connecting";label.setText(camera.optString("name")+" · 正在直连");curtain.setVisibility(VISIBLE);visible=false;lastFrame=SystemClock.elapsedRealtime();
|
||||
MediaPlayer p=new MediaPlayer();player=p;p.setSurface(surface);p.setVolume(0,0);
|
||||
p.setOnPreparedListener(mp->{if(player==mp&&!closed)mp.start();});
|
||||
p.setOnVideoSizeChangedListener((mp,w,h)->fit(w,h));
|
||||
p.setOnErrorListener((mp,what,extra)->{if(player==mp)fail(extra==-1010?"电视暂不支持此编码":"直连未成功 · 自动重试",extra==-1010?"unsupported":"offline");return true;});
|
||||
p.setOnCompletionListener(mp->{if(player==mp)fail("画面中断 · 自动重连","offline");});
|
||||
p.setDataSource(camera.getString("url"));p.prepareAsync();
|
||||
}catch(Exception e){fail("直连未成功 · 自动重试","offline");}
|
||||
}
|
||||
void fit(int w,int h){if(w<=0||h<=0||texture.getWidth()==0||texture.getHeight()==0)return;float scale=Math.min((float)texture.getWidth()/w,(float)texture.getHeight()/h);Matrix matrix=new Matrix();matrix.setScale(w*scale/texture.getWidth(),h*scale/texture.getHeight(),texture.getWidth()/2f,texture.getHeight()/2f);texture.setTransform(matrix);}
|
||||
void fail(String text,String value){if(closed)return;state=value;release();curtain.setVisibility(VISIBLE);visible=false;label.setText(camera.optString("name")+" · "+text);ui.removeCallbacks(retry);ui.postDelayed(retry,Math.min(60000,10000L*(++failures)));}
|
||||
void release(){MediaPlayer old=player;player=null;if(old!=null){try{old.reset();old.release();}catch(Exception ignored){}}}
|
||||
void close(){closed=true;ui.removeCallbacks(retry);release();if(surface!=null){surface.release();surface=null;}}
|
||||
public void onSurfaceTextureAvailable(SurfaceTexture s,int w,int h){surface=new Surface(s);connect();}
|
||||
public void onSurfaceTextureSizeChanged(SurfaceTexture s,int w,int h){if(player!=null)try{fit(player.getVideoWidth(),player.getVideoHeight());}catch(Exception ignored){}}
|
||||
public boolean onSurfaceTextureDestroyed(SurfaceTexture s){release();if(surface!=null)surface.release();surface=null;return true;}
|
||||
public void onSurfaceTextureUpdated(SurfaceTexture s){lastFrame=SystemClock.elapsedRealtime();if(player!=null&&!visible){visible=true;state="online";failures=0;curtain.setVisibility(GONE);label.setText(camera.optString("name")+" · 局域网直连");}}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package cn.ucvl.zhaodisplay;
|
||||
|
||||
import org.json.JSONObject;
|
||||
import java.net.URL;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
|
||||
final class DisplayApi {
|
||||
static JSONObject call(String path,String token,JSONObject body)throws Exception{
|
||||
HttpsURLConnection c=(HttpsURLConnection)new URL("https://zhao.ucvl.cn"+path).openConnection();
|
||||
c.setInstanceFollowRedirects(false);c.setConnectTimeout(10000);c.setReadTimeout(10000);
|
||||
if(token!=null&&!token.isEmpty())c.setRequestProperty("Authorization","Bearer "+token);
|
||||
try{
|
||||
if(body!=null){
|
||||
c.setRequestMethod("POST");c.setDoOutput(true);c.setRequestProperty("Content-Type","application/json");
|
||||
byte[] bytes=body.toString().getBytes(StandardCharsets.UTF_8);c.setFixedLengthStreamingMode(bytes.length);
|
||||
try(OutputStream out=c.getOutputStream()){out.write(bytes);}
|
||||
}
|
||||
int status=c.getResponseCode();
|
||||
if(status!=200)throw new ApiError(status);
|
||||
ByteArrayOutputStream out=new ByteArrayOutputStream();byte[] b=new byte[2048];
|
||||
try(InputStream in=c.getInputStream()){int n;while((n=in.read(b))>=0){out.write(b,0,n);if(out.size()>262144)throw new IOException("Response too large");}}
|
||||
return new JSONObject(out.toString("UTF-8"));
|
||||
}finally{c.disconnect();}
|
||||
}
|
||||
static final class ApiError extends IOException {final int status;ApiError(int code){super("HTTP "+code);status=code;}}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package cn.ucvl.zhaodisplay;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.AlertDialog;
|
||||
import android.content.Intent;
|
||||
import android.graphics.Bitmap;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.view.PixelCopy;
|
||||
import android.view.View;
|
||||
import android.view.WindowManager;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.EditText;
|
||||
import android.widget.Toast;
|
||||
import android.text.InputType;
|
||||
import org.json.JSONObject;
|
||||
import android.webkit.WebView;
|
||||
import android.webkit.WebViewClient;
|
||||
import android.webkit.WebResourceRequest;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class MainActivity extends Activity {
|
||||
static volatile MainActivity active;
|
||||
WebView web;
|
||||
CameraStrip cameras;
|
||||
@Override public void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
immersive();
|
||||
web=new WebView(this);
|
||||
web.setBackgroundColor(0xfff1ede4);
|
||||
web.getSettings().setJavaScriptEnabled(true);
|
||||
web.getSettings().setDomStorageEnabled(true);
|
||||
web.getSettings().setAllowFileAccess(false);
|
||||
web.getSettings().setAllowContentAccess(false);
|
||||
web.getSettings().setMixedContentMode(0);
|
||||
web.setWebViewClient(new WebViewClient(){
|
||||
@Override public boolean shouldOverrideUrlLoading(WebView view,WebResourceRequest request){
|
||||
return !"https".equals(request.getUrl().getScheme()) || !"zhao.ucvl.cn".equals(request.getUrl().getHost()) || !request.getUrl().getPath().startsWith("/tv");
|
||||
}
|
||||
});
|
||||
LinearLayout layout=new LinearLayout(this);layout.setOrientation(LinearLayout.VERTICAL);
|
||||
layout.addView(web,new LinearLayout.LayoutParams(-1,0,88));
|
||||
cameras=new CameraStrip(this);layout.addView(cameras,new LinearLayout.LayoutParams(-1,0,12));
|
||||
setContentView(layout);
|
||||
configure(getIntent());
|
||||
}
|
||||
void configure(Intent intent){
|
||||
String code=intent.getStringExtra("pairing_code");
|
||||
if(code!=null&&code.matches("[0-9]{8}")){intent.removeExtra("pairing_code");pair(code);return;}
|
||||
String token=getSharedPreferences("display",MODE_PRIVATE).getString("token","");
|
||||
web.loadUrl("https://zhao.ucvl.cn/tv"+(token.isEmpty()?"":"#display="+token));
|
||||
if(!token.isEmpty())startForegroundService(new Intent(this,MonitorService.class));
|
||||
else pairDialog();
|
||||
}
|
||||
void pairDialog(){
|
||||
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)});
|
||||
new AlertDialog.Builder(this).setTitle("绑定家庭中心").setMessage("在赵府智家中进入目标家庭 → 电视设备 → 电视管理 → 生成配对码。更换家庭前,请先由管理员移动这台设备的归属。")
|
||||
.setView(code).setNegativeButton("取消",null).setPositiveButton("绑定",(dialog,which)->pair(code.getText().toString().trim())).show();
|
||||
}
|
||||
void pair(String code){
|
||||
if(!code.matches("[0-9]{8}")){Toast.makeText(this,"请输入 8 位配对码",Toast.LENGTH_LONG).show();return;}
|
||||
new Thread(()->{
|
||||
try{
|
||||
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();
|
||||
runOnUiThread(()->{configure(new Intent());cameras.refresh();Toast.makeText(this,"已绑定:"+value.optString("home"),Toast.LENGTH_LONG).show();});
|
||||
}catch(Exception e){runOnUiThread(()->Toast.makeText(this,"绑定未成功,请检查网络或重新生成配对码",Toast.LENGTH_LONG).show());}
|
||||
},"display-pair").start();
|
||||
}
|
||||
@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 onPause(){if(active==this)active=null;if(cameras!=null)cameras.foreground(false);super.onPause();}
|
||||
@Override public void onDestroy(){if(active==this)active=null;if(cameras!=null)cameras.close();web.destroy();super.onDestroy();}
|
||||
@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);}
|
||||
static void capture(Consumer<byte[]> callback){
|
||||
MainActivity a=active;
|
||||
if(a==null){callback.accept(null);return;}
|
||||
a.runOnUiThread(()->{
|
||||
if(active!=a){callback.accept(null);return;}
|
||||
try {
|
||||
// PixelCopy captures this app's actual window, never other applications.
|
||||
Bitmap image=Bitmap.createBitmap(a.getWindow().getDecorView().getWidth(),a.getWindow().getDecorView().getHeight(),Bitmap.Config.ARGB_8888);
|
||||
PixelCopy.request(a.getWindow(),image,result->{
|
||||
if(result!=PixelCopy.SUCCESS){image.recycle();callback.accept(null);return;}
|
||||
Bitmap small=Bitmap.createScaledBitmap(image,480,Math.max(1,Math.round(480f*image.getHeight()/image.getWidth())),true);
|
||||
ByteArrayOutputStream out=new ByteArrayOutputStream();small.compress(Bitmap.CompressFormat.JPEG,65,out);
|
||||
small.recycle();image.recycle();callback.accept(out.toByteArray());
|
||||
},new Handler(a.getMainLooper()));
|
||||
}catch(Exception|OutOfMemoryError e){callback.accept(null);}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package cn.ucvl.zhaodisplay;
|
||||
|
||||
import android.app.*;
|
||||
import android.content.*;
|
||||
import android.os.*;
|
||||
import android.util.Base64;
|
||||
import android.util.DisplayMetrics;
|
||||
import android.view.WindowManager;
|
||||
import org.json.JSONObject;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
|
||||
public class MonitorService extends Service {
|
||||
ScheduledExecutorService worker;
|
||||
@Override public void onCreate(){
|
||||
super.onCreate();
|
||||
NotificationManager nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
|
||||
nm.createNotificationChannel(new NotificationChannel("display","家庭屏运行状态",NotificationManager.IMPORTANCE_LOW));
|
||||
PendingIntent open=PendingIntent.getActivity(this,0,new Intent(this,MainActivity.class),PendingIntent.FLAG_IMMUTABLE|PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
startForeground(44,new Notification.Builder(this,"display").setContentTitle("赵府家庭屏")
|
||||
.setContentText("家庭设备状态同步中 · 预览仅限当前看板画面").setSmallIcon(android.R.drawable.ic_menu_view).setContentIntent(open).setOngoing(true).build());
|
||||
worker=Executors.newSingleThreadScheduledExecutor();
|
||||
worker.scheduleWithFixedDelay(this::heartbeat,1,20,TimeUnit.SECONDS);
|
||||
}
|
||||
@Override public int onStartCommand(Intent intent,int flags,int startId){return START_STICKY;}
|
||||
@Override public IBinder onBind(Intent intent){return null;}
|
||||
@Override public void onDestroy(){if(worker!=null)worker.shutdownNow();super.onDestroy();}
|
||||
JSONObject hardware()throws Exception{
|
||||
JSONObject result=new JSONObject();
|
||||
result.put("model",Build.MODEL);result.put("osVersion",Build.VERSION.RELEASE);result.put("appVersion","0.1.44");
|
||||
result.put("foreground",MainActivity.active!=null);
|
||||
result.put("cameraStates",new org.json.JSONArray(CameraStrip.report));
|
||||
result.put("screenOn",((PowerManager)getSystemService(POWER_SERVICE)).isInteractive());
|
||||
ActivityManager.MemoryInfo memory=new ActivityManager.MemoryInfo();((ActivityManager)getSystemService(ACTIVITY_SERVICE)).getMemoryInfo(memory);
|
||||
result.put("memoryTotalMB",memory.totalMem/1048576d);result.put("memoryAvailableMB",memory.availMem/1048576d);
|
||||
StatFs disk=new StatFs(getFilesDir().getAbsolutePath());
|
||||
result.put("storageTotalGB",disk.getTotalBytes()/1073741824d);result.put("storageAvailableGB",disk.getAvailableBytes()/1073741824d);
|
||||
result.put("uptimeSeconds",SystemClock.elapsedRealtime()/1000);
|
||||
DisplayMetrics metrics=new DisplayMetrics();WindowManager wm=(WindowManager)getSystemService(WINDOW_SERVICE);wm.getDefaultDisplay().getRealMetrics(metrics);
|
||||
result.put("screenWidth",metrics.widthPixels);result.put("screenHeight",metrics.heightPixels);result.put("rotation",wm.getDefaultDisplay().getRotation());
|
||||
double hottest=-999;String source="系统未开放传感器";
|
||||
File[] zones=new File("/sys/class/thermal").listFiles();
|
||||
if(zones!=null)for(File zone:zones){
|
||||
if(!zone.getName().startsWith("thermal_zone"))continue;
|
||||
try{
|
||||
String type=new String(Files.readAllBytes(new File(zone,"type").toPath()),StandardCharsets.UTF_8).trim();
|
||||
if(!type.matches("(?i).*(soc|cpu|gpu).*"))continue;
|
||||
double value=Double.parseDouble(new String(Files.readAllBytes(new File(zone,"temp").toPath()),StandardCharsets.UTF_8).trim())/1000d;
|
||||
if(value>0 && value<150 && value>hottest){hottest=value;source=type;}
|
||||
}catch(Exception ignored){}
|
||||
}
|
||||
result.put("temperatureC",hottest>-999?hottest:JSONObject.NULL);result.put("temperatureSource",source);
|
||||
// This board exposes test_battery/test_ac; these are not power meters.
|
||||
result.put("powerW",JSONObject.NULL);result.put("powerSource","未提供整机功率传感器,需接入计量插座");
|
||||
String ip="";
|
||||
for(NetworkInterface net:Collections.list(NetworkInterface.getNetworkInterfaces())){
|
||||
if(!net.isUp()||net.isLoopback())continue;
|
||||
for(InetAddress addr:Collections.list(net.getInetAddresses()))if(addr instanceof Inet4Address && addr.isSiteLocalAddress())ip=addr.getHostAddress();
|
||||
}
|
||||
result.put("ip",ip);return result;
|
||||
}
|
||||
JSONObject post(String path,JSONObject body)throws Exception{
|
||||
String token=getSharedPreferences("display",MODE_PRIVATE).getString("token","");
|
||||
if(token.isEmpty())throw new IOException("Not paired");
|
||||
HttpsURLConnection c=(HttpsURLConnection)new URL("https://zhao.ucvl.cn"+path).openConnection();
|
||||
c.setInstanceFollowRedirects(false);c.setConnectTimeout(10000);c.setReadTimeout(10000);c.setRequestMethod("POST");c.setDoOutput(true);
|
||||
c.setRequestProperty("Authorization","Bearer "+token);c.setRequestProperty("Content-Type","application/json");
|
||||
byte[] bytes=body.toString().getBytes(StandardCharsets.UTF_8);c.setFixedLengthStreamingMode(bytes.length);
|
||||
try{
|
||||
try(OutputStream out=c.getOutputStream()){out.write(bytes);}
|
||||
if(c.getResponseCode()!=200)throw new IOException("HTTP "+c.getResponseCode());
|
||||
ByteArrayOutputStream out=new ByteArrayOutputStream();byte[] b=new byte[1024];
|
||||
try(InputStream in=c.getInputStream()){int n;while((n=in.read(b))>=0){out.write(b,0,n);if(out.size()>65536)throw new IOException("Response too large");}}
|
||||
return new JSONObject(out.toString("UTF-8"));
|
||||
}finally{c.disconnect();}
|
||||
}
|
||||
void heartbeat(){
|
||||
try{
|
||||
JSONObject response=post("/api/display/heartbeat",hardware());
|
||||
if(response.optBoolean("capturePreview"))MainActivity.capture(bytes->{
|
||||
if(bytes!=null && bytes.length<180000 && !worker.isShutdown())worker.execute(()->{
|
||||
try{post("/api/display/preview",new JSONObject().put("jpeg",Base64.encodeToString(bytes,Base64.NO_WRAP)));}catch(Exception ignored){}
|
||||
});
|
||||
});
|
||||
}catch(Exception ignored){}
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,7 @@ import backups
|
||||
import baidu
|
||||
import journal
|
||||
import ptz
|
||||
import displays
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
os.umask(0o077)
|
||||
@@ -93,6 +94,7 @@ BACKUPS = backups.Backups(sys.modules[__name__])
|
||||
BAIDU = baidu.Baidu(sys.modules[__name__])
|
||||
JOURNAL = journal.Journal(sys.modules[__name__])
|
||||
CLOUD_IMAGES = cloud_images.CloudImages(sys.modules[__name__])
|
||||
DISPLAYS = displays.Displays(sys.modules[__name__])
|
||||
|
||||
|
||||
def setting(key, default=None):
|
||||
@@ -665,6 +667,12 @@ class Handler(BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
try:
|
||||
path = url.urlsplit(self.path).path
|
||||
if path in ('/api/display/heartbeat','/api/display/preview'):
|
||||
authorization = self.headers.get('Authorization','')
|
||||
grant = DISPLAYS.authorize(authorization[7:] if authorization.startswith('Bearer ') else '')
|
||||
data = self.body(250000 if path.endswith('preview') else 16384)
|
||||
self.answer(DISPLAYS.accept_preview(grant,data) if path.endswith('preview') else DISPLAYS.heartbeat(grant,data))
|
||||
return
|
||||
if path == '/api/journal/chunk':
|
||||
self.validate_origin(); self.require_auth()
|
||||
query = dict(url.parse_qsl(url.urlsplit(self.path).query))
|
||||
@@ -680,6 +688,9 @@ class Handler(BaseHTTPRequestHandler):
|
||||
# 12,000 Chinese characters plus JSON escapes and linked people exceed 16 KiB.
|
||||
data = self.body(3*1024*1024 if path in ('/api/appearance','/api/households') else 131072 if path in ('/api/family/event','/api/heritage','/api/journal') else 16384)
|
||||
self.validate_origin()
|
||||
if path == '/api/display/pair':
|
||||
self.answer(DISPLAYS.pair(data, self.client_address[0]))
|
||||
return
|
||||
if path in ('/api/login', '/api/setup'):
|
||||
self.login(data, path == '/api/setup')
|
||||
return
|
||||
@@ -775,6 +786,10 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.answer(HERITAGE.save(data, self.user))
|
||||
elif path == '/api/devices':
|
||||
self.answer(INVENTORY.save(data, self.user))
|
||||
elif path == '/api/devices/transfer':
|
||||
self.answer(INVENTORY.transfer(data, self.user))
|
||||
elif path == '/api/displays':
|
||||
self.answer(DISPLAYS.manage(self.user, data))
|
||||
elif path in ('/api/family/person', '/api/family/link', '/api/family/event'):
|
||||
self.answer(FAMILY.save(path.rsplit('/', 1)[-1], data, self.user))
|
||||
elif path == '/api/sites':
|
||||
@@ -947,12 +962,33 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if path == '/healthz':
|
||||
self.answer({'status': 'running', 'version': (ROOT / 'VERSION').read_text().strip()})
|
||||
return
|
||||
if path in ('/api/display/snapshot', '/api/display/cameras'):
|
||||
authorization = self.headers.get('Authorization', '')
|
||||
token = authorization[7:] if authorization.startswith('Bearer ') else ''
|
||||
if path.endswith('/cameras'):
|
||||
self.answer(DISPLAYS.cameras(DISPLAYS.authorize_native(token)))
|
||||
else:
|
||||
self.answer(DISPLAYS.snapshot(DISPLAYS.authorize(token)))
|
||||
return
|
||||
if path.startswith(('/api/', '/media/')):
|
||||
self.require_auth()
|
||||
if path == '/api/state':
|
||||
self.answer(ACCOUNTS.state(self.user, status()))
|
||||
elif path == '/api/devices/network':
|
||||
self.require_manager(); self.answer(NETWORK.read(self.user, query))
|
||||
elif path == '/api/displays':
|
||||
self.require_manager(); self.answer(DISPLAYS.listing(self.user, query.get('deviceId')))
|
||||
elif path == '/api/displays/hardware':
|
||||
self.require_manager(); self.answer(DISPLAYS.hardware(self.user, query.get('deviceId')))
|
||||
elif path == '/api/displays/preview':
|
||||
self.require_manager()
|
||||
at, raw = DISPLAYS.preview(self.user, query.get('deviceId'))
|
||||
self.send_response(200)
|
||||
self.send_header('Content-Type','image/jpeg')
|
||||
self.send_header('Content-Length',str(len(raw)))
|
||||
self.send_header('Cache-Control','no-store')
|
||||
self.send_header('X-Content-Type-Options','nosniff')
|
||||
self.end_headers(); self.wfile.write(raw)
|
||||
elif path == '/api/baidu/config':
|
||||
self.require_admin(); self.answer(BAIDU.public_config())
|
||||
elif path == '/api/baidu/status':
|
||||
@@ -1100,8 +1136,10 @@ class Handler(BaseHTTPRequestHandler):
|
||||
'/monitor.js': 'monitor.js', '/calendar.js': 'calendar.js', '/date-fields.js': 'date-fields.js',
|
||||
'/zhao-icon.png': 'zhao-icon.png',
|
||||
'/vendor/hls.min.js': 'vendor/hls.min.js'}
|
||||
if re.fullmatch(r'/ui/assets/[A-Za-z0-9_-]+\.(?:js|css)', path):
|
||||
if re.fullmatch(r'/ui/assets/[A-Za-z0-9_.-]+\.(?:js|css)', path):
|
||||
files[path] = path[1:]
|
||||
if path in ('/tv', '/tv/'):
|
||||
files[path] = 'ui/tv.html'
|
||||
if path not in files or not (ROOT / 'web' / files[path]).is_file():
|
||||
raise Problem('页面不存在', 404)
|
||||
file = ROOT / 'web' / files[path]
|
||||
@@ -1131,6 +1169,7 @@ def initialize():
|
||||
FAMILY.initialize()
|
||||
ACCOUNTS.initialize()
|
||||
HOUSEHOLDS.initialize()
|
||||
DISPLAYS.initialize()
|
||||
HERITAGE.initialize()
|
||||
JOURNAL.initialize()
|
||||
if not setting('storage'):
|
||||
@@ -1149,6 +1188,7 @@ if __name__ == '__main__':
|
||||
threading.Thread(target=storage_watch, daemon=True).start()
|
||||
threading.Thread(target=media_config_watch, daemon=True).start()
|
||||
threading.Thread(target=BACKUPS.watch, daemon=True).start()
|
||||
threading.Thread(target=DISPLAYS.watch, daemon=True).start()
|
||||
bindings = [h.strip() for h in os.environ.get('VISION_BIND', '127.0.0.1').split(',') if h.strip()]
|
||||
port = int(os.environ.get('VISION_PORT', '8790'))
|
||||
servers = []
|
||||
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
"""Household display grants: revocable, read-only and bound to one registered TV."""
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import base64
|
||||
import ipaddress
|
||||
|
||||
TZ = dt.timezone(dt.timedelta(hours=8))
|
||||
|
||||
|
||||
class Displays:
|
||||
def __init__(self, app):
|
||||
self.a = app
|
||||
self.weather_cache = {}
|
||||
self.weather_lock = threading.Lock()
|
||||
self.weather_pending = set()
|
||||
self.state_cache = (0, {})
|
||||
self.state_lock = threading.Lock()
|
||||
self.previews = {}
|
||||
self.preview_requests = {}
|
||||
self.pair_codes = {}
|
||||
self.pair_attempts = {}
|
||||
|
||||
def initialize(self):
|
||||
with self.a.LOCK, self.a.DB:
|
||||
self.a.DB.execute('CREATE TABLE IF NOT EXISTS household_displays '
|
||||
'(id TEXT PRIMARY KEY, family_id TEXT NOT NULL, device_id TEXT NOT NULL, '
|
||||
'token_hash TEXT UNIQUE NOT NULL, created_at REAL, expires_at REAL, '
|
||||
'last_seen REAL DEFAULT 0, revoked INTEGER DEFAULT 0, weather TEXT NOT NULL)')
|
||||
self.a.DB.execute('CREATE TABLE IF NOT EXISTS display_telemetry (id TEXT PRIMARY KEY, at REAL, body TEXT NOT NULL)')
|
||||
self.a.DB.execute('CREATE TABLE IF NOT EXISTS display_alerts (id INTEGER PRIMARY KEY, display_id TEXT, '
|
||||
'code TEXT, message TEXT, severity TEXT, opened REAL, cleared REAL DEFAULT 0)')
|
||||
self.a.DB.execute('CREATE TABLE IF NOT EXISTS display_native_keys (id TEXT PRIMARY KEY, token_hash TEXT UNIQUE NOT NULL)')
|
||||
|
||||
def device(self, user, device_id):
|
||||
if not self.a.HOUSEHOLDS.manager(user):
|
||||
raise self.a.Problem('需要家庭管理员权限', 403)
|
||||
device = self.a.HOUSEHOLDS.owns(user, self.a.get_object('devices', device_id))
|
||||
if not re.search('电视|显示|大屏', device.get('deviceType', '')):
|
||||
raise self.a.Problem('请先登记电视或显示屏设备')
|
||||
return device
|
||||
|
||||
def listing(self, user, device_id):
|
||||
self.device(user, device_id)
|
||||
with self.a.LOCK:
|
||||
rows = self.a.DB.execute('SELECT id,created_at,expires_at,last_seen,revoked FROM household_displays '
|
||||
'WHERE device_id=? AND family_id=? ORDER BY created_at DESC LIMIT 20',
|
||||
(device_id, self.a.HOUSEHOLDS.scope(user))).fetchall()
|
||||
return {'items': [dict(r) for r in rows]}
|
||||
|
||||
def manage(self, user, data):
|
||||
a = self.a
|
||||
device = self.device(user, data.get('deviceId'))
|
||||
family = a.HOUSEHOLDS.scope(user)
|
||||
if data.get('action') == 'preview':
|
||||
with a.LOCK:
|
||||
row = a.DB.execute('SELECT id FROM household_displays WHERE device_id=? AND family_id=? AND revoked=0 AND expires_at>?',
|
||||
(device['id'], family, time.time())).fetchone()
|
||||
if not row: raise a.Problem('电视尚未授权', 404)
|
||||
self.preview_requests[row['id']] = time.time()+65
|
||||
return {'ok': True, 'expiresIn': 65}
|
||||
if data.get('action') == 'revoke':
|
||||
with a.LOCK, a.DB:
|
||||
result = a.DB.execute('UPDATE household_displays SET revoked=1 WHERE id=? AND device_id=? AND family_id=?',
|
||||
(data.get('id'), device['id'], family))
|
||||
if not result.rowcount: raise a.Problem('展示授权不存在', 404)
|
||||
a.audit('停用电视展示', device['name'])
|
||||
return {'ok': True}
|
||||
if data.get('action') != 'create': raise a.Problem('展示操作不正确')
|
||||
city = a.clean_text(data.get('city', ''), 60)
|
||||
weather = {'city': city}
|
||||
if data.get('latitude') not in ('', None) or data.get('longitude') not in ('', None):
|
||||
try:
|
||||
lat, lon = float(data['latitude']), float(data['longitude'])
|
||||
if not math.isfinite(lat+lon) or not -90 <= lat <= 90 or not -180 <= lon <= 180: raise ValueError()
|
||||
except (ValueError, TypeError, KeyError): raise a.Problem('天气经纬度不正确')
|
||||
weather.update(latitude=round(lat, 4), longitude=round(lon, 4))
|
||||
token, key, now = secrets.token_urlsafe(32), secrets.token_hex(8), time.time()
|
||||
with a.LOCK, a.DB:
|
||||
# Replacing the grant invalidates the old TV link immediately.
|
||||
a.DB.execute('UPDATE household_displays SET revoked=1 WHERE device_id=? AND family_id=?', (device['id'], family))
|
||||
a.DB.execute('INSERT INTO household_displays VALUES (?,?,?,?,?,?,0,0,?)',
|
||||
(key, family, device['id'], hashlib.sha256(token.encode()).hexdigest(), now,
|
||||
now+365*86400, json.dumps(weather)))
|
||||
a.audit('授权家庭电视展示', device['name'])
|
||||
code = f'{secrets.randbelow(100000000):08d}'
|
||||
with a.LOCK:
|
||||
self.pair_codes = {k:v for k,v in self.pair_codes.items() if v['expires']>now}
|
||||
if len(self.pair_codes)>=128: self.pair_codes.pop(next(iter(self.pair_codes)))
|
||||
self.pair_codes[hashlib.sha256(code.encode()).hexdigest()] = dict(id=key,token=token,expires=now+600)
|
||||
return {'id': key, 'token': token, 'expiresAt': now+365*86400, 'path': '/tv#display='+token,
|
||||
'pairingCode':code,'pairingExpiresAt':now+600}
|
||||
|
||||
def pair(self, body, ip):
|
||||
now = time.time()
|
||||
code = body.get('code','')
|
||||
with self.a.LOCK:
|
||||
self.pair_attempts = {k:v for k,v in self.pair_attempts.items() if v[1]>now}
|
||||
count, until = self.pair_attempts.get(ip,(0,now+600))
|
||||
if count>=5: raise self.a.Problem('配对尝试过多,请 10 分钟后再试',429)
|
||||
self.pair_attempts[ip]=(count+1,until)
|
||||
if not isinstance(code,str) or not re.fullmatch('[0-9]{8}',code): raise self.a.Problem('请输入 8 位配对码')
|
||||
key=hashlib.sha256(code.encode()).hexdigest()
|
||||
item=self.pair_codes.get(key)
|
||||
if not item or item['expires']<now: raise self.a.Problem('配对码已失效,请重新生成',401)
|
||||
grant=self.authorize(item['token'])
|
||||
native=secrets.token_urlsafe(32)
|
||||
with self.a.DB:
|
||||
self.a.DB.execute('INSERT OR REPLACE INTO display_native_keys VALUES (?,?)',
|
||||
(grant['id'],hashlib.sha256(native.encode()).hexdigest()))
|
||||
del self.pair_codes[key]
|
||||
self.pair_attempts.pop(ip,None)
|
||||
return dict(token=item['token'],nativeToken=native,home=self.a.get_object('households',grant['family_id'])['name'])
|
||||
|
||||
def authorize_native(self, token):
|
||||
if not isinstance(token,str) or not re.fullmatch('[A-Za-z0-9_-]{43}',token): raise self.a.Problem('需要 App 配对授权',401)
|
||||
with self.a.LOCK:
|
||||
row=self.a.DB.execute('SELECT d.* FROM household_displays d JOIN display_native_keys n ON d.id=n.id '
|
||||
'WHERE n.token_hash=? AND d.revoked=0 AND d.expires_at>?',
|
||||
(hashlib.sha256(token.encode()).hexdigest(),time.time())).fetchone()
|
||||
if not row: raise self.a.Problem('App 授权已失效',401)
|
||||
grant=dict(row)
|
||||
device=self.a.get_object('devices',grant['device_id'])
|
||||
if not device or self.a.HOUSEHOLDS.family_of(device)!=grant['family_id']: raise self.a.Problem('设备归属已更改',403)
|
||||
return grant
|
||||
|
||||
def cameras(self, grant):
|
||||
# Scoped credentials travel only over TLS to the paired native player, never to the WebView.
|
||||
items=[]
|
||||
nets=[ipaddress.ip_network(n) for n in ('10.0.0.0/8','172.16.0.0/12','192.168.0.0/16','100.64.0.0/10')]
|
||||
for c in self.a.objects('cameras'):
|
||||
if self.a.HOUSEHOLDS.family_of(c)!=grant['family_id'] or not c.get('enabled',True): continue
|
||||
endpoint=self.a.get_object('recorders',c.get('recorderId')) if c.get('sourceKind')=='recorder' else c
|
||||
if not endpoint or self.a.HOUSEHOLDS.family_of(endpoint)!=grant['family_id']: continue
|
||||
try: address=ipaddress.ip_address(endpoint.get('host',''))
|
||||
except ValueError: continue
|
||||
if not any(address in net for net in nets): continue
|
||||
items.append(dict(id=c['id'],name=c['name'],host=str(address),url=self.a.source(c,'sub')))
|
||||
return dict(items=items,transport='direct',leaseSeconds=300)
|
||||
|
||||
def heartbeat(self, grant, body):
|
||||
"""Only typed, bounded telemetry; never accept a caller-selected device or household."""
|
||||
a, key, now = self.a, grant['id'], time.time()
|
||||
allowed_numbers = {'memoryTotalMB':(1,1048576), 'memoryAvailableMB':(0,1048576),
|
||||
'storageTotalGB':(0,1048576), 'storageAvailableGB':(0,1048576),
|
||||
'uptimeSeconds':(0,1e10), 'temperatureC':(-30,150), 'powerW':(0,10000),
|
||||
'screenWidth':(1,16384), 'screenHeight':(1,16384), 'rotation':(0,3)}
|
||||
clean = {}
|
||||
for name,(lo,hi) in allowed_numbers.items():
|
||||
value = body.get(name)
|
||||
if value is None: clean[name] = None
|
||||
elif type(value) not in (int,float) or not math.isfinite(value) or not lo <= value <= hi:
|
||||
raise a.Problem('硬件数据格式不正确:'+name)
|
||||
else: clean[name] = value
|
||||
for name in ('model','osVersion','appVersion','temperatureSource','powerSource','ip'):
|
||||
clean[name] = a.clean_text(body.get(name,''),120)
|
||||
clean['foreground'] = body.get('foreground') is True
|
||||
clean['screenOn'] = body.get('screenOn') is True
|
||||
clean['cameraStates'] = []
|
||||
if body.get('cameraStates') is not None and not isinstance(body['cameraStates'],list): raise a.Problem('镜头状态格式不正确')
|
||||
for item in (body.get('cameraStates') or [])[:32]:
|
||||
if isinstance(item,dict) and re.fullmatch('[a-f0-9]{16}',str(item.get('id',''))) and item.get('state') in ('online','connecting','offline','outside_lan','unsupported'):
|
||||
clean['cameraStates'].append(dict(id=item['id'],state=item['state']))
|
||||
with a.LOCK, a.DB:
|
||||
old = a.DB.execute('SELECT at FROM display_telemetry WHERE id=?', (key,)).fetchone()
|
||||
if old and now-old['at'] < 5: raise a.Problem('心跳过于频繁',429)
|
||||
a.DB.execute('INSERT OR REPLACE INTO display_telemetry VALUES (?,?,?)',(key,now,json.dumps(clean)))
|
||||
self.alerts_for(key, now, clean, now)
|
||||
return {'ok':True, 'capturePreview': self.preview_requests.get(key,0) > now}
|
||||
|
||||
def accept_preview(self, grant, body):
|
||||
key, now = grant['id'], time.time()
|
||||
if self.preview_requests.get(key,0) < now: raise self.a.Problem('未请求屏幕预览',403)
|
||||
encoded = body.get('jpeg','')
|
||||
if not isinstance(encoded,str) or len(encoded)>240000: raise self.a.Problem('预览图片过大')
|
||||
try: raw = base64.b64decode(encoded,validate=True)
|
||||
except Exception: raise self.a.Problem('预览图片不正确')
|
||||
if not raw.startswith(b'\xff\xd8\xff') or not raw.endswith(b'\xff\xd9'): raise self.a.Problem('需要 JPEG 预览')
|
||||
with self.a.LOCK:
|
||||
self.previews = {k:v for k,v in self.previews.items() if now-v[0]<90}
|
||||
if len(self.previews)>=32: self.previews.pop(next(iter(self.previews)))
|
||||
self.previews[key] = (now,raw)
|
||||
return {'ok':True}
|
||||
|
||||
def preview(self,user,device_id):
|
||||
self.device(user,device_id)
|
||||
with self.a.LOCK:
|
||||
row=self.a.DB.execute('SELECT id FROM household_displays WHERE device_id=? AND family_id=? AND revoked=0 AND expires_at>?',
|
||||
(device_id,self.a.HOUSEHOLDS.scope(user),time.time())).fetchone()
|
||||
value=self.previews.get(row['id']) if row else None
|
||||
if not value or time.time()-value[0]>90: raise self.a.Problem('等待电视回传当前应用画面',404)
|
||||
return value
|
||||
|
||||
def alerts_for(self,key,at,body,now):
|
||||
wanted = {}
|
||||
if now-at > 100: wanted['offline'] = ('电视心跳中断','warning')
|
||||
else:
|
||||
temp=body.get('temperatureC')
|
||||
if temp is not None and temp >= 75: wanted['temperature'] = ('处理器温度偏高(阈值 75°C)','critical' if temp>=85 else 'warning')
|
||||
total, available=body.get('memoryTotalMB'),body.get('memoryAvailableMB')
|
||||
if total and available is not None and available/total<.05: wanted['memory']=('可用内存不足 5%','warning')
|
||||
free=body.get('storageAvailableGB')
|
||||
if free is not None and free < .5: wanted['storage']=('可用存储不足 0.5 GB','warning')
|
||||
if not body.get('foreground'): wanted['background']=('家庭看板当前不在前台','warning')
|
||||
current={r['code']:r for r in self.a.DB.execute('SELECT * FROM display_alerts WHERE display_id=? AND cleared=0',(key,))}
|
||||
for code,(message,severity) in wanted.items():
|
||||
if code not in current:
|
||||
self.a.DB.execute('INSERT INTO display_alerts(display_id,code,message,severity,opened) VALUES (?,?,?,?,?)',
|
||||
(key,code,message,severity,now))
|
||||
else: self.a.DB.execute('UPDATE display_alerts SET severity=? WHERE id=?',(severity,current[code]['id']))
|
||||
for code,row in current.items():
|
||||
if code not in wanted: self.a.DB.execute('UPDATE display_alerts SET cleared=? WHERE id=?',(now,row['id']))
|
||||
self.a.DB.execute('DELETE FROM display_alerts WHERE display_id=? AND cleared>0 AND id NOT IN '
|
||||
'(SELECT id FROM display_alerts WHERE display_id=? ORDER BY id DESC LIMIT 200)',(key,key))
|
||||
|
||||
def watch(self):
|
||||
while True:
|
||||
try:
|
||||
with self.a.LOCK,self.a.DB:
|
||||
rows=self.a.DB.execute('SELECT t.* FROM display_telemetry t JOIN household_displays d ON d.id=t.id '
|
||||
'WHERE d.revoked=0 AND d.expires_at>?',(time.time(),)).fetchall()
|
||||
for row in rows:self.alerts_for(row['id'],row['at'],json.loads(row['body']),time.time())
|
||||
except Exception: pass
|
||||
time.sleep(20)
|
||||
|
||||
def hardware(self,user,device_id):
|
||||
self.device(user,device_id)
|
||||
with self.a.LOCK:
|
||||
row=self.a.DB.execute('SELECT d.id,t.at,t.body FROM household_displays d LEFT JOIN display_telemetry t ON d.id=t.id '
|
||||
'WHERE d.device_id=? AND d.family_id=? AND d.revoked=0 AND d.expires_at>? ORDER BY d.created_at DESC LIMIT 1',
|
||||
(device_id,self.a.HOUSEHOLDS.scope(user),time.time())).fetchone()
|
||||
if not row:return {'paired':False,'online':False,'alerts':[]}
|
||||
alerts=[dict(r) for r in self.a.DB.execute('SELECT code,message,severity,opened,cleared FROM display_alerts WHERE display_id=? ORDER BY id DESC LIMIT 30',(row['id'],))]
|
||||
preview=self.previews.get(row['id'])
|
||||
return dict(paired=True,online=bool(row['at'] and time.time()-row['at']<100),lastSeen=row['at'],
|
||||
hardware=json.loads(row['body']) if row['body'] else {},alerts=alerts,
|
||||
previewAt=preview[0] if preview and time.time()-preview[0]<90 else None)
|
||||
|
||||
def authorize(self, token):
|
||||
if not isinstance(token, str) or not re.fullmatch('[A-Za-z0-9_-]{43}', token):
|
||||
raise self.a.Problem('请在设备页生成电视展示链接', 401)
|
||||
a, now = self.a, time.time()
|
||||
with a.LOCK:
|
||||
row = a.DB.execute('SELECT * FROM household_displays WHERE token_hash=? AND revoked=0 AND expires_at>?',
|
||||
(hashlib.sha256(token.encode()).hexdigest(), now)).fetchone()
|
||||
if not row: raise a.Problem('展示授权已失效,请联系家庭管理员重新连接', 401)
|
||||
grant = dict(row)
|
||||
device = a.get_object('devices', grant['device_id'])
|
||||
if not device or a.HOUSEHOLDS.family_of(device) != grant['family_id']:
|
||||
raise a.Problem('电视已移出原家庭,请重新授权', 403)
|
||||
if now-grant['last_seen'] > 60:
|
||||
a.DB.execute('UPDATE household_displays SET last_seen=? WHERE id=?', (now, grant['id']))
|
||||
a.DB.commit()
|
||||
return grant
|
||||
|
||||
def weather(self, location):
|
||||
if 'latitude' not in location:
|
||||
return {'available': False, 'city': location.get('city', ''), 'message': '天气位置未设置'}
|
||||
key = (location['latitude'], location['longitude'])
|
||||
now = time.time()
|
||||
with self.weather_lock:
|
||||
cached = self.weather_cache.get(key, {})
|
||||
if now-cached.get('attemptAt', 0) > 900 and key not in self.weather_pending:
|
||||
self.weather_pending.add(key)
|
||||
threading.Thread(target=self.fetch_weather, args=(key,), daemon=True).start()
|
||||
if cached.get('data') and now-cached.get('at', 0) < 6*3600:
|
||||
return dict(cached['data'], available=True, stale=now-cached['at'] > 1800,
|
||||
updatedAt=cached['at'], city=location.get('city', ''), source='Open-Meteo')
|
||||
return {'available': False, 'city': location.get('city', ''), 'message': '天气正在更新' if not cached else '天气暂时不可用'}
|
||||
|
||||
def fetch_weather(self, key):
|
||||
now = time.time()
|
||||
try:
|
||||
query = urllib.parse.urlencode(dict(latitude=key[0], longitude=key[1], timezone='Asia/Shanghai',
|
||||
current='temperature_2m,relative_humidity_2m,apparent_temperature,weather_code,wind_speed_10m,is_day',
|
||||
daily='temperature_2m_max,temperature_2m_min,weather_code', forecast_days=3))
|
||||
with urllib.request.urlopen('https://api.open-meteo.com/v1/forecast?'+query, timeout=8) as response:
|
||||
value = json.loads(response.read(100000))
|
||||
current, daily = value['current'], value['daily']
|
||||
if not isinstance(current.get('temperature_2m'), (int, float)): raise ValueError()
|
||||
data = dict(current={k: current.get(k) for k in ('time','temperature_2m','relative_humidity_2m',
|
||||
'apparent_temperature','weather_code','wind_speed_10m','is_day')},
|
||||
days=[dict(date=d, high=daily['temperature_2m_max'][i], low=daily['temperature_2m_min'][i],
|
||||
code=daily['weather_code'][i]) for i,d in enumerate(daily['time'][:3])])
|
||||
with self.weather_lock:
|
||||
if len(self.weather_cache) >= 128: self.weather_cache.pop(next(iter(self.weather_cache)))
|
||||
self.weather_cache[key] = {'data': data, 'at': now, 'attemptAt': now}
|
||||
except Exception:
|
||||
with self.weather_lock:
|
||||
self.weather_cache[key] = {**self.weather_cache.get(key, {}), 'attemptAt': now}
|
||||
finally:
|
||||
with self.weather_lock: self.weather_pending.discard(key)
|
||||
|
||||
def media_state(self):
|
||||
with self.state_lock:
|
||||
if time.monotonic()-self.state_cache[0] > 20:
|
||||
self.state_cache = (time.monotonic(), self.a.status())
|
||||
return self.state_cache[1]
|
||||
|
||||
def snapshot(self, grant):
|
||||
a, family = self.a, grant['family_id']
|
||||
home = a.get_object('households', family)
|
||||
if not home: raise a.Problem('家庭已不可用', 404)
|
||||
def scoped(table): return [x for x in a.objects(table) if a.HOUSEHOLDS.family_of(x) == family]
|
||||
sites = {x['id']: x['name'] for x in scoped('sites')}
|
||||
state = self.media_state()
|
||||
channels = [c for c in state.get('cameras', []) if a.HOUSEHOLDS.family_of(c) == family]
|
||||
devices = []
|
||||
with a.LOCK:
|
||||
displays = {r['device_id']: r['last_seen'] for r in a.DB.execute(
|
||||
'SELECT device_id,last_seen FROM household_displays WHERE family_id=? AND revoked=0 AND expires_at>?', (family,time.time()))}
|
||||
for table, kind in (('assets','摄像机'), ('devices','设备'), ('recorders','录像机')):
|
||||
for item in scoped(table):
|
||||
label, condition = '状态未接入', 'unknown'
|
||||
matched = [c for c in channels if c.get('assetId') == item['id'] or c.get('recorderId') == item['id']]
|
||||
if matched:
|
||||
if not state.get('mediaOnline'): label = '视频服务未连接'
|
||||
elif any(c.get('ready') for c in matched): label, condition = '画面已连接', 'online'
|
||||
else: label, condition = '画面未连接', 'offline'
|
||||
elif item['id'] in displays:
|
||||
condition = 'online' if time.time()-displays[item['id']] < 100 else 'offline'
|
||||
label = '正在展示' if condition == 'online' else '展示未连接'
|
||||
devices.append(dict(id=item['id'],name=item['name'],type=item.get('deviceType',kind),
|
||||
location=sites.get(item.get('siteId'), '位置待设置'),status=condition,statusLabel=label))
|
||||
today = dt.datetime.now(TZ).date()
|
||||
until = (today+dt.timedelta(days=60)).isoformat()
|
||||
events = sorted([dict(id=e['id'],title=e['title'],date=e['eventDate']) for e in scoped('family_events')
|
||||
if e.get('status') == 'published' and not e.get('archived')
|
||||
and today.isoformat() <= e.get('eventDate','') <= until], key=lambda e:(e['date'],e['id']))
|
||||
return dict(serverTime=dt.datetime.now(dt.timezone.utc).isoformat(), timezone='Asia/Shanghai',
|
||||
home=dict(name=home['name'],city=home.get('city',''),district=home.get('district',''),
|
||||
spaces=len(sites),deviceCount=len(devices)),
|
||||
display=dict(id=grant['id'],deviceId=grant['device_id']),devices=devices,
|
||||
events=events[:12],eventCount=len(events),weather=self.weather(json.loads(grant['weather'])))
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "zhao-steward-ui",
|
||||
"private": true,
|
||||
"version": "0.1.43",
|
||||
"version": "0.1.44",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "vite build",
|
||||
|
||||
@@ -15,6 +15,6 @@ export function enhance(root){
|
||||
export async function loadControllers(){
|
||||
enhance(document.getElementById('app'))
|
||||
new MutationObserver(records=>{for(const record of records)for(const node of record.addedNodes)enhance(node)}).observe(document.getElementById('app'),{childList:true,subtree:true})
|
||||
for(const path of [...scripts,'/vue-bridge.js'])await new Promise((resolve,reject)=>{const script=document.createElement('script');script.src=path+'?ui=0.1.43';script.onload=resolve;script.onerror=()=>reject(new Error('Could not load '+path));document.head.append(script)})
|
||||
for(const path of [...scripts,'/vue-bridge.js'])await new Promise((resolve,reject)=>{const script=document.createElement('script');script.src=path+'?ui=0.1.44';script.onload=resolve;script.onerror=()=>reject(new Error('Could not load '+path));document.head.append(script)})
|
||||
await window.ZhaoVue.boot()
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
} from "../composables/bridge.js";
|
||||
import AppIcon from "./AppIcon.vue";
|
||||
import NetworkStatus from "./NetworkStatus.vue";
|
||||
import DisplayManager from './DisplayManager.vue';
|
||||
import DeviceTransfer from './DeviceTransfer.vue';
|
||||
const channels = (d) =>
|
||||
(snapshot.value.state.cameras || []).filter((c) =>
|
||||
d.source === "camera"
|
||||
@@ -118,6 +120,8 @@ const monitored = (d) =>
|
||||
snapshot.page === 'objects' && deviceView.mode === 'cards'
|
||||
"
|
||||
/>
|
||||
<DisplayManager v-if="d.source==='device' && /电视|显示|大屏/.test(d.deviceType)" :device="d"/>
|
||||
<DeviceTransfer :device="d"/>
|
||||
</div>
|
||||
<div class="card-footer device-card-actions">
|
||||
<button
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
<script setup>
|
||||
import {snapshot} from '../composables/bridge.js'
|
||||
import NetworkStatus from './NetworkStatus.vue'
|
||||
import DisplayManager from './DisplayManager.vue'
|
||||
import DeviceTransfer from './DeviceTransfer.vue'
|
||||
</script>
|
||||
<template><section v-if="snapshot.admin&&snapshot.device&&snapshot.page==='device'" class="panel"><h3>网络状态与管理入口</h3><NetworkStatus :device="snapshot.device"/><p class="description mb-0">只检查已登记的设备地址。常用端口未响应不一定表示断电;Tailscale 节点在线也不代表下级网段可达。</p></section></template>
|
||||
<template><section v-if="snapshot.admin&&snapshot.device&&snapshot.page==='device'" class="panel"><h3>网络状态与管理入口</h3><DisplayManager v-if="snapshot.device.source==='device' && /电视|显示|大屏/.test(snapshot.device.deviceType)" :device="snapshot.device"/><NetworkStatus v-else :device="snapshot.device"/><DeviceTransfer :device="snapshot.device"/></section></template>
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
<script setup>
|
||||
import {ref,computed,watch} from 'vue'
|
||||
import {snapshot,bridge} from '../composables/bridge.js'
|
||||
const props=defineProps({device:Object})
|
||||
const open=ref(false),target=ref(''),confirm=ref(false),busy=ref(false),message=ref('')
|
||||
const targets=computed(()=>(snapshot.value.state.households||[]).filter(h=>h.id!==snapshot.value.state.familyId))
|
||||
watch(()=>snapshot.value.state.familyId,()=>{open.value=false;target.value='';confirm.value=false;message.value=''})
|
||||
async function transfer(){if(!confirm.value||!target.value)return;busy.value=true;message.value=''
|
||||
try{await bridge().api('/api/devices/transfer',{source:props.device.source,id:props.device.id,targetFamilyId:target.value});bridge().notify('设备已转移,电视需在新家庭重新授权。');open.value=false;await bridge().refresh()}catch(e){message.value=e.message}finally{busy.value=false}}
|
||||
</script>
|
||||
<template><div v-if="snapshot.user?.role==='admin'" class="mt-3"><button class="btn btn-sm btn-outline-secondary" @click="open=!open">转移到其他家庭</button><div v-if="open" class="border rounded p-3 mt-2"><label class="w-100">目标家庭 / 公司 / 工厂<select v-model="target" class="form-select mt-2"><option value="">请选择</option><option v-for="h in targets" :key="h.id" :value="h.id">{{h.name}}</option></select></label><p class="small text-secondary mt-2">保留设备编号与基本档案。所属区域、负责人和上级设备需重新设置;电视旧展示授权会停用。关联录像机的摄像头需先解除关联。</p><label class="d-flex gap-2 small mb-2"><input v-model="confirm" type="checkbox">确认将这台设备转移给目标家庭管理</label><button class="btn btn-primary btn-sm" :disabled="busy||!confirm||!target" @click="transfer">确认转移</button></div><p v-if="message" class="small mt-2" role="status">{{message}}</p></div></template>
|
||||
@@ -0,0 +1,45 @@
|
||||
<script setup>
|
||||
import {ref,watch,onUnmounted,computed} from 'vue'
|
||||
import {snapshot,bridge} from '../composables/bridge.js'
|
||||
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)
|
||||
let timer,epoch=0,blob=''
|
||||
const home=computed(()=>snapshot.value.state.households?.find(h=>h.id===snapshot.value.state.familyId))
|
||||
const city=ref(''),latitude=ref(''),longitude=ref('')
|
||||
const pairingCode=ref('')
|
||||
const endpoint=path=>path+'?deviceId='+encodeURIComponent(props.device.id)
|
||||
const hardware=computed(()=>result.value?.hardware||{})
|
||||
const number=(value,digits=1)=>typeof value==='number'?value.toFixed(digits):'未提供'
|
||||
const formatTime=value=>value?new Date(value*1000).toLocaleString('zh-CN'):'尚未上报'
|
||||
async function reload(){const e=epoch;if(!open.value)return
|
||||
try{const value=await bridge().api(endpoint('/api/displays/hardware'));if(e!==epoch)return;result.value=value
|
||||
if(Date.now()<previewUntil.value&&value.previewAt){const response=await fetch(endpoint('/api/displays/preview'),{headers:{'X-Household-Id':snapshot.value.state.familyId},cache:'no-store'});if(response.ok){const image=await response.blob();if(e!==epoch)return;if(blob)URL.revokeObjectURL(blob);blob=URL.createObjectURL(image);preview.value=blob}}
|
||||
}catch(e2){if(e===epoch)error.value=e2.message}finally{if(e===epoch&&open.value)timer=setTimeout(reload,5000)}
|
||||
}
|
||||
async function change(action,id){busy.value=true;error.value='';const e=epoch
|
||||
try{const value=await bridge().api('/api/displays',{action,deviceId:props.device.id,id,city:city.value,latitude:latitude.value,longitude:longitude.value});if(e!==epoch)return
|
||||
if(value.path)link.value=location.origin+value.path
|
||||
if(value.pairingCode)pairingCode.value=value.pairingCode
|
||||
if(action==='preview')previewUntil.value=Date.now()+60000
|
||||
if(action==='revoke'){link.value='';pairingCode.value='';preview.value='';previewUntil.value=0}
|
||||
grants.value=(await bridge().api(endpoint('/api/displays'))).items;clearTimeout(timer);reload()
|
||||
}catch(e2){if(e===epoch)error.value=e2.message}finally{if(e===epoch)busy.value=false}
|
||||
}
|
||||
watch(open,async value=>{epoch++;clearTimeout(timer);link.value='';error.value='';preview.value='';previewUntil.value=0;if(blob){URL.revokeObjectURL(blob);blob=''}if(value){city.value=home.value?.city||'';latitude.value=city.value==='济南市'?'36.67':'';longitude.value=city.value==='济南市'?'116.99':'';reload();try{grants.value=(await bridge().api(endpoint('/api/displays'))).items}catch(e){error.value=e.message}}})
|
||||
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)})
|
||||
</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>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<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')">生成新的电视展示链接</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>
|
||||
<p v-if="error" class="text-danger mt-2" role="alert">{{error}}</p>
|
||||
</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>
|
||||
@@ -0,0 +1,57 @@
|
||||
<script setup>
|
||||
import {ref,computed,onMounted,onBeforeUnmount} from 'vue'
|
||||
import {chinaParts,weatherLabel} from './time.mjs'
|
||||
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
|
||||
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{}
|
||||
const time=computed(()=>chinaParts(new Date(clock.value+offset.value)))
|
||||
const lunar=computed(()=>{try{return new Intl.DateTimeFormat('zh-CN-u-ca-chinese',{timeZone:'Asia/Shanghai',month:'long',day:'numeric'}).format(new Date(clock.value+offset.value))}catch{return ''}})
|
||||
const greeting=computed(()=>+time.value.hour<6?'夜深了,愿你好梦':+time.value.hour<11?'早安,新的一天':+time.value.hour<14?'午安,慢慢生活':+time.value.hour<18?'午后,家有暖意':'晚安时光,灯火可亲')
|
||||
const angles=computed(()=>({hour:(+time.value.hour%12)*30+(+time.value.minute)/2,minute:(+time.value.minute)*6,second:(+time.value.second)*6}))
|
||||
const devices=computed(()=>{const all=data.value?.devices||[];return all.slice((paging.value%Math.max(1,Math.ceil(all.length/4)))*4,(paging.value%Math.max(1,Math.ceil(all.length/4)))*4+4)})
|
||||
const weather=computed(()=>data.value?.weather)
|
||||
const syncLabel=computed(()=>!lastSync.value?'正在连接家庭':clock.value-lastSync.value>90000?'网络暂时中断 · 显示上次资料':'家庭资料已同步')
|
||||
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{}}
|
||||
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)})
|
||||
onBeforeUnmount(()=>{clearTimeout(poll);clearInterval(tick);clearInterval(cycle);controller?.abort();wake?.release();document.removeEventListener('visibilitychange',visibility)})
|
||||
</script>
|
||||
<template>
|
||||
<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>
|
||||
<div class="tv-upper">
|
||||
<section class="square-clock" aria-label="北京时间时钟">
|
||||
<svg viewBox="0 0 440 440" role="img" :aria-label="`${time.hour}:${time.minute}:${time.second}`">
|
||||
<g v-for="n in 60" :key="n" :transform="`rotate(${n*6} 220 220)`"><line x1="220" :y1="n%5===0?29:32" x2="220" :y2="n%5===0?46:39" :class="n%5===0?'hour-mark':'minute-mark'"/></g>
|
||||
<text v-for="n in 12" :key="'n'+n" :x="220+148*Math.sin(n*Math.PI/6)" :y="220-148*Math.cos(n*Math.PI/6)+10" class="clock-number">{{n}}</text>
|
||||
<text x="220" y="140" class="clock-word">家 · 在 此 刻</text>
|
||||
<line x1="220" y1="231" x2="220" y2="127" class="clock-hour" :transform="`rotate(${angles.hour} 220 220)`"/>
|
||||
<line x1="220" y1="234" x2="220" y2="91" class="clock-minute" :transform="`rotate(${angles.minute} 220 220)`"/>
|
||||
<line x1="220" y1="247" x2="220" y2="65" class="clock-second" :transform="`rotate(${angles.second} 220 220)`"/>
|
||||
<circle cx="220" cy="220" r="8" fill="#a66645"/><circle cx="220" cy="220" r="3" fill="#fffaf0"/>
|
||||
<text x="220" y="303" class="digital-time">{{time.hour}}:{{time.minute}}</text><text x="220" y="329" class="clock-zone">北京时间</text>
|
||||
</svg>
|
||||
</section>
|
||||
<section class="tv-home"><div class="tv-greeting">{{greeting}}</div><h1>{{data?.home.name||'欢迎回家'}}</h1><div class="tv-date">{{time.year}} 年 {{+time.month}} 月 {{+time.day}} 日 <b>{{time.weekday}}</b></div><div class="tv-date-extra"><span v-if="lunar">农历 {{lunar}}</span><span>{{time.weekYear}} 年 · 第 {{time.week}} 周</span></div></section>
|
||||
</div>
|
||||
<section class="tv-weather tv-card" aria-label="天气">
|
||||
<div class="weather-current"><div class="section-label">{{weather?.city||data?.home.city||'本地'}} · 天气</div><div class="weather-big"><span class="weather-symbol">{{weather?.available?(weather.current.weather_code<3?'☀':'☁'):'☁'}}</span><strong>{{weather?.available?fmt(weather.current.temperature_2m):'—'}}<small>°</small></strong><div><b>{{weather?.available?weatherLabel(weather.current.weather_code):'天气更新中'}}</b><span v-if="weather?.available">体感 {{fmt(weather.current.apparent_temperature)}}° · 湿度 {{fmt(weather.current.relative_humidity_2m)}}%</span></div></div><div class="weather-note">{{weather?.stale?'上次天气 · 待更新':weather?.available?'室外天气 · '+(weather.current.time||'').slice(11,16)+' 更新':weather?.message||'正在连接天气服务'}}</div></div>
|
||||
<div class="weather-forecast" v-if="weather?.available"><div v-for="(day,i) in weather.days" :key="day.date"><span>{{['今天','明天','后天'][i]}}</span><b>{{weatherLabel(day.code)}}</b><span>{{fmt(day.low)}}° / {{fmt(day.high)}}°</span></div></div>
|
||||
</section>
|
||||
<div class="tv-bottom">
|
||||
<section class="tv-card tv-devices"><div class="tv-section-heading"><h2>家中设备</h2><span>{{data?.home.deviceCount??'—'}} 台 · {{data?.home.spaces??'—'}} 处区域</span></div><div class="tv-device-grid"><article v-for="d in devices" :key="d.id" class="tv-device"><div class="device-emblem">{{/电视|显示/.test(d.type)?'▣':/摄像/.test(d.type)?'◉':/路由|网关/.test(d.type)?'⌁':'◇'}}</div><div><h3>{{d.name}}</h3><p>{{d.location}}</p><span :class="['tv-status',d.status]"><i></i>{{d.statusLabel}}</span></div></article><div class="tv-empty" v-if="!devices.length">设备接入后,会在这里与你见面。</div></div><div class="tv-page-count" v-if="(data?.devices.length||0)>4">设备分组自动轮换 · 每 15 秒</div></section>
|
||||
<section class="tv-card tv-agenda"><div class="tv-section-heading"><h2>近期日程</h2><span>未来 60 天</span></div><div v-if="!data?.events.length" class="agenda-empty"><span class="agenda-line">日子从容,家有余闲。</span><p>暂没有已发布的家庭安排</p></div><article v-for="e in data?.events.slice(0,3)" :key="e.id" class="tv-event"><time>{{e.date.slice(5).replace('-',' / ')}}</time><h3>{{e.title}}</h3></article><div class="agenda-source">来自本家庭已发布的重大记事</div></section>
|
||||
</div>
|
||||
<section class="tv-family-presence tv-card"><div><h2>家人位置</h2><p>等待家人主动开启位置共享</p></div><span>共享关闭</span></section>
|
||||
<footer class="tv-footer"><span :class="{warning:!!error}"><i></i>{{syncLabel}}</span><span v-if="error" class="sync-error">{{error}}</span><span>愿每个平常日,都有家的温度</span><a href="https://open-meteo.com/" target="_blank" rel="noreferrer">天气 Open-Meteo</a></footer>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,5 @@
|
||||
import {createApp} from 'vue'
|
||||
import 'bootstrap/dist/css/bootstrap.min.css'
|
||||
import './tv.css'
|
||||
import Television from './Television.vue'
|
||||
createApp(Television).mount('#app')
|
||||
@@ -0,0 +1,8 @@
|
||||
export function chinaParts(date) {
|
||||
const values=Object.fromEntries(new Intl.DateTimeFormat('en-GB',{timeZone:'Asia/Shanghai',year:'numeric',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',second:'2-digit',hourCycle:'h23'}).formatToParts(date).map(p=>[p.type,p.value]));
|
||||
const day=new Date(Date.UTC(+values.year,+values.month-1,+values.day)), weekday=day.getUTCDay();
|
||||
const thursday=new Date(day);thursday.setUTCDate(day.getUTCDate()+4-(weekday||7));
|
||||
const start=new Date(Date.UTC(thursday.getUTCFullYear(),0,1));
|
||||
return {...values,weekday:'星期'+'日一二三四五六'[weekday],week:Math.ceil((((thursday-start)/86400000)+1)/7),weekYear:thursday.getUTCFullYear(),date:`${values.year}-${values.month}-${values.day}`};
|
||||
}
|
||||
export const weatherLabel=code=>code===0?'晴':code<=3?'多云':code<=48?'有雾':code<=67?'有雨':code<=77?'有雪':code<=82?'阵雨':code<=86?'阵雪':code>=95?'雷雨':'天气更新中';
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
<!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></head><body><div id="app"></div><script type="module" src="/src/tv/main.js"></script></body></html>
|
||||
@@ -1,3 +1,3 @@
|
||||
import {defineConfig} from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
export default defineConfig({plugins:[vue({template:{transformAssetUrls:false}})],base:'/ui/',build:{outDir:'../web/ui',emptyOutDir:true,assetsDir:'assets'}})
|
||||
export default defineConfig({plugins:[vue({template:{transformAssetUrls:false}})],base:'/ui/',build:{target:'es2018',outDir:'../web/ui',emptyOutDir:true,assetsDir:'assets',rollupOptions:{input:{index:'index.html',tv:'tv.html'}}}})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Common device responsibility fields and non-video device records."""
|
||||
import ipaddress
|
||||
import re
|
||||
import json
|
||||
class Inventory:
|
||||
def __init__(self, app):
|
||||
self.a = app
|
||||
@@ -92,3 +93,40 @@ class Inventory:
|
||||
a.save_object('devices', item)
|
||||
a.audit('保存设备档案', item['name'])
|
||||
return item
|
||||
|
||||
def transfer(self, data, user):
|
||||
a = self.a
|
||||
if user.get('role') != 'admin':
|
||||
raise a.Problem('跨家庭转移需要超级管理员同时管理双方家庭',403)
|
||||
table = {'device':'devices','camera':'assets','recorder':'recorders'}.get(data.get('source'))
|
||||
if not table: raise a.Problem('请选择设备类型')
|
||||
with a.LOCK:
|
||||
item = a.HOUSEHOLDS.owns(user, a.get_object(table,data.get('id')))
|
||||
target = a.get_object('households',data.get('targetFamilyId'))
|
||||
if not target: raise a.Problem('目标家庭不存在',404)
|
||||
if target['id'] == a.HOUSEHOLDS.family_of(item): raise a.Problem('设备已经属于这个家庭')
|
||||
site = a.get_object('sites',data.get('targetSiteId')) if data.get('targetSiteId') else None
|
||||
if data.get('targetSiteId') and (not site or a.HOUSEHOLDS.family_of(site)!=target['id']):
|
||||
raise a.Problem('目标区域不属于所选家庭')
|
||||
channels = [c for c in a.objects('cameras') if table=='assets' and c.get('assetId')==item['id']
|
||||
or table=='recorders' and (c.get('recorderId')==item['id'] or c.get('archiveRecorderId')==item['id'])]
|
||||
if table=='recorders' and channels:
|
||||
raise a.Problem('录像机仍关联摄像头,请先在镜头设置解除取流及录像来源关联,再转移')
|
||||
if table=='assets' and any(c.get('recorderId') or c.get('archiveRecorderId') for c in channels):
|
||||
raise a.Problem('摄像头仍关联原家庭录像机,请先解除录像机关联,再转移')
|
||||
old_family = a.HOUSEHOLDS.family_of(item)
|
||||
with a.DB:
|
||||
for row_table, row in [(table,item)]+[('cameras',c) for c in channels]:
|
||||
updated = dict(row,familyId=target['id'],siteId=site['id'] if site else '',
|
||||
uplinkId='',ownerRef='',ownerName='',managerRef='',managerName='')
|
||||
a.DB.execute('UPDATE '+row_table+' SET body=? WHERE id=?',(json.dumps(updated),row['id']))
|
||||
# Do not leave topology links crossing family boundaries.
|
||||
for other_table in ('devices','assets','recorders'):
|
||||
for child in a.objects(other_table):
|
||||
if child.get('uplinkId') == item['id']:
|
||||
child['uplinkId']=''
|
||||
a.DB.execute('UPDATE '+other_table+' SET body=? WHERE id=?',(json.dumps(child),child['id']))
|
||||
a.DB.execute('UPDATE household_displays SET revoked=1 WHERE device_id=?',(item['id'],))
|
||||
a.audit('转移设备家庭',item['name']+':'+old_family+' → '+target['name'])
|
||||
if channels: a.write_media_config()
|
||||
return {'ok':True,'id':item['id'],'familyId':target['id']}
|
||||
|
||||
+4
-2
@@ -110,9 +110,11 @@ class WebTests(unittest.TestCase):
|
||||
self.assertEqual(headers['Cache-Control'], 'no-store')
|
||||
self.assertNotIn(b'__ASSET_VERSION__', body)
|
||||
assets = re.findall(r'(?:src|href)="(/ui/assets/[^"?]+\.(?:js|css))"', body.decode())
|
||||
self.assertEqual(len(assets), 2)
|
||||
self.assertGreaterEqual(len(assets), 2)
|
||||
self.assertTrue(any('/index-' in asset and asset.endswith('.js') for asset in assets))
|
||||
self.assertTrue(any('/index-' in asset and asset.endswith('.css') for asset in assets))
|
||||
for asset in assets:
|
||||
self.assertRegex(asset,r'/ui/assets/index-[A-Za-z0-9_-]+\.(js|css)$')
|
||||
self.assertRegex(asset,r'/ui/assets/[A-Za-z0-9_.-]+-[A-Za-z0-9_-]+\.(js|css)$')
|
||||
self.assertEqual(self.request(asset, False)[0], 200)
|
||||
for path in ['/ui/assets/../../vision.db','/ui/assets/missing.js','/ui/index.html']:
|
||||
self.assertEqual(self.request(path,False)[0],404)
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import json
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import test_households as fixtures
|
||||
app=fixtures.app
|
||||
|
||||
|
||||
class DisplayTests(unittest.TestCase):
|
||||
setUp = fixtures.HouseholdTests.setUp
|
||||
stop_server = fixtures.HouseholdTests.stop_server
|
||||
|
||||
def tv(self, family=None):
|
||||
return app.INVENTORY.save(dict(name='Fixture TV',deviceType='安卓电视',managementHost='192.168.8.223'),self.roots[family or self.aid])
|
||||
|
||||
def pair(self, device):
|
||||
app.DISPLAYS.state_cache=(0,{})
|
||||
return app.DISPLAYS.manage(self.roots[self.aid],dict(action='create',deviceId=device['id'],city='Fixture'))
|
||||
|
||||
def test_token_hash_only_and_revocation(self):
|
||||
tv=self.tv();first=self.pair(tv)
|
||||
row=dict(app.DB.execute('SELECT * FROM household_displays').fetchone())
|
||||
self.assertNotIn(first['token'],json.dumps(row))
|
||||
self.assertEqual(app.DISPLAYS.authorize(first['token'])['family_id'],self.aid)
|
||||
self.pair(tv)
|
||||
with self.assertRaises(app.Problem):app.DISPLAYS.authorize(first['token'])
|
||||
|
||||
def test_scoped_projection_does_not_expose_secrets(self):
|
||||
tv=self.tv();other=self.tv(self.bid);grant=app.DISPLAYS.authorize(self.pair(tv)['token'])
|
||||
with patch.object(app.DISPLAYS,'weather',return_value={'available':False}):snap=app.DISPLAYS.snapshot(grant)
|
||||
raw=json.dumps(snap)
|
||||
self.assertNotIn(other['id'],raw)
|
||||
for key in ('password','username','managementHost','host','token','ownerName','serial'):
|
||||
self.assertNotIn('"'+key+'"',raw)
|
||||
self.assertEqual(snap['home']['deviceCount'],2)
|
||||
|
||||
def test_cross_household_admin_context_is_enforced(self):
|
||||
tv=self.tv()
|
||||
for actor in (self.other,self.members[self.aid],self.roots[self.bid]):
|
||||
with self.assertRaises(app.Problem):app.DISPLAYS.listing(actor,tv['id'])
|
||||
|
||||
def test_expired_token_is_denied(self):
|
||||
token=self.pair(self.tv())['token']
|
||||
app.DB.execute('UPDATE household_displays SET expires_at=?',(time.time()-1,));app.DB.commit()
|
||||
with self.assertRaises(app.Problem):app.DISPLAYS.authorize(token)
|
||||
|
||||
def test_pair_code_is_single_use_and_native_camera_access_is_separate(self):
|
||||
grant=self.pair(self.tv())
|
||||
with self.assertRaises(app.Problem):app.DISPLAYS.authorize_native(grant['token'])
|
||||
paired=app.DISPLAYS.pair({'code':grant['pairingCode']},'fixture-pair')
|
||||
native=app.DISPLAYS.authorize_native(paired['nativeToken'])
|
||||
items=app.DISPLAYS.cameras(native)['items']
|
||||
self.assertEqual([c['id'] for c in items],[self.cameras[self.aid]['id']])
|
||||
self.assertTrue(items[0]['url'].startswith('rtsp://192.168.3.10:554/'))
|
||||
with self.assertRaises(app.Problem):app.DISPLAYS.pair({'code':grant['pairingCode']},'fixture-pair')
|
||||
self.pair(app.get_object('devices',native['device_id']))
|
||||
with self.assertRaises(app.Problem):app.DISPLAYS.authorize_native(paired['nativeToken'])
|
||||
|
||||
def test_pair_attempt_limit_and_expiry(self):
|
||||
grant=self.pair(self.tv())
|
||||
for item in app.DISPLAYS.pair_codes.values():item['expires']=0
|
||||
with self.assertRaises(app.Problem):app.DISPLAYS.pair({'code':grant['pairingCode']},'expired-fixture')
|
||||
for _ in range(5):
|
||||
with self.assertRaises(app.Problem):app.DISPLAYS.pair({'code':'wrong'},'blocked-fixture')
|
||||
with self.assertRaises(app.Problem) as caught:app.DISPLAYS.pair({'code':'00000000'},'blocked-fixture')
|
||||
self.assertEqual(caught.exception.status,429)
|
||||
|
||||
def test_telemetry_alert_opens_and_recovers(self):
|
||||
tv=self.tv();grant=app.DISPLAYS.authorize(self.pair(tv)['token'])
|
||||
app.DISPLAYS.heartbeat(grant,{'temperatureC':86,'temperatureSource':'soc-thermal','foreground':True})
|
||||
status=app.DISPLAYS.hardware(self.root,tv['id'])
|
||||
self.assertTrue(status['online']);self.assertEqual(status['alerts'][0]['severity'],'critical')
|
||||
app.DB.execute('UPDATE display_telemetry SET at=at-10');app.DB.commit()
|
||||
app.DISPLAYS.heartbeat(grant,{'temperatureC':55,'foreground':True})
|
||||
self.assertTrue(app.DISPLAYS.hardware(self.root,tv['id'])['alerts'][0]['cleared'])
|
||||
|
||||
def test_invalid_telemetry_rejected(self):
|
||||
grant=app.DISPLAYS.authorize(self.pair(self.tv())['token'])
|
||||
for value in (float('nan'),151,True,'86'):
|
||||
with self.assertRaises(app.Problem):app.DISPLAYS.heartbeat(grant,{'temperatureC':value})
|
||||
|
||||
def test_transfer_revokes_previous_family_access(self):
|
||||
tv=self.tv();token=self.pair(tv)['token']
|
||||
with self.assertRaises(app.Problem):app.INVENTORY.transfer(dict(source='device',id=tv['id'],targetFamilyId=self.bid),self.owner)
|
||||
app.INVENTORY.transfer(dict(source='device',id=tv['id'],targetFamilyId=self.bid),self.root)
|
||||
self.assertEqual(app.get_object('devices',tv['id'])['familyId'],self.bid)
|
||||
with self.assertRaises(app.Problem):app.DISPLAYS.authorize(token)
|
||||
with self.assertRaises(app.Problem):app.DISPLAYS.hardware(self.owner,tv['id'])
|
||||
self.assertFalse(app.DISPLAYS.hardware(self.roots[self.bid],tv['id'])['paired'])
|
||||
|
||||
def test_preview_is_requested_scoped_and_ephemeral(self):
|
||||
tv=self.tv();grant=app.DISPLAYS.authorize(self.pair(tv)['token'])
|
||||
with self.assertRaises(app.Problem):app.DISPLAYS.accept_preview(grant,{'jpeg':''})
|
||||
app.DISPLAYS.manage(self.root,dict(action='preview',deviceId=tv['id']))
|
||||
self.assertTrue(app.DISPLAYS.heartbeat(grant,{'foreground':True})['capturePreview'])
|
||||
with self.assertRaises(app.Problem):app.DISPLAYS.accept_preview(grant,{'jpeg':'PHN2Zz4='})
|
||||
app.DISPLAYS.previews[grant['id']]=(time.time()-91,b'old')
|
||||
with self.assertRaises(app.Problem):app.DISPLAYS.preview(self.root,tv['id'])
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,6 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {chinaParts,weatherLabel} from './frontend/src/tv/time.mjs'
|
||||
test('Beijing midnight and Thursday ISO week',()=>{const v=chinaParts(new Date('2026-10-14T16:00:00Z'));assert.equal(v.date,'2026-10-15');assert.equal(v.hour,'00');assert.equal(v.weekday,'星期四');assert.equal(v.week,42)})
|
||||
test('ISO week year across January boundary',()=>{const v=chinaParts(new Date('2021-01-01T00:00:00Z'));assert.equal(v.week,53);assert.equal(v.weekYear,2020)})
|
||||
test('weather types',()=>{assert.equal(weatherLabel(0),'晴');assert.equal(weatherLabel(95),'雷雨');assert.equal(weatherLabel(65),'有雨')})
|
||||
Vendored
+1
File diff suppressed because one or more lines are too long
+2
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
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
+4
-2
@@ -1,3 +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-OX4XEEVF.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/index-BOIfNXlB.css">
|
||||
<!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-CBo81CLd.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/bootstrap.min-z2h-5aUQ.js">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/bootstrap-DBkz-poX.css">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/index-B8TRemWE.css">
|
||||
</head><body><div id="app"></div></body></html>
|
||||
|
||||
@@ -0,0 +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-BwowoKxJ.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/bootstrap.min-z2h-5aUQ.js">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/bootstrap-DBkz-poX.css">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/tv-Bv_s0xCW.css">
|
||||
</head><body><div id="app"></div></body></html>
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
Object.assign(window.ZhaoVue,{
|
||||
boot:bootApplication,
|
||||
publish(){this.accept({state,user:currentUser,admin:isAdmin(),platformAdmin:isPlatformAdmin(),loggedIn,page:activePage,session:sessionGeneration,device:selectedDevice(),brandName:branding.name});},
|
||||
api,notify:toast,address:ZhaoGeography.describe,
|
||||
api,refresh,notify:toast,address:ZhaoGeography.describe,
|
||||
async saveLayout(value){const saved=await api('/api/households/layout',value);state.householdLayout=saved;this.publish();return saved;},
|
||||
async enterHome(id,network=false){try{if(id!==state.familyId&&!await switchHousehold(id))return;if(network){devicePresentation='topology';showPage('objects');}else showPage('overview');}catch(e){if(!e.stale)toast(e.message);}},
|
||||
enterDevice,
|
||||
|
||||
Reference in New Issue
Block a user