diff --git a/README.md b/README.md index 4f0cc17..43d15a6 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,11 @@ # 赵府智家 · 视觉系统 +## v0.1.56 · 数据、设备与视图 + +正式地址:[home.ucvl.cn](https://home.ucvl.cn)。新版手机与显示终端同步使用此域名。 + +新增数据类型与数据实例、设备类型(FB)与设备实例、视图类型与视图实例。先定义数据结构,再选择设备实现;视图只按数据类型匹配。手机增加「家庭 / 设备」入口,电脑接入独立授权的 RUN/OP 状态及唤醒、安全关机功能。[本版说明](RELEASE-v0.1.56.md) · [对象与接口](docs/device-types.md)。 + ## v0.1.55 · 手机 Bootstrap 视觉规范 「位置 / 沟通 / 我的」统一浅灰底、白色描边卡片、青绿色主按钮、分组列表与导航选中态。设置详情全屏打开,表单加入统一下拉框、输入框、焦点和禁用状态,适配窄屏及大字体。安卓使用本地原生组件实现 Bootstrap 风格,未引入远程样式或字体。[本版说明](RELEASE-v0.1.55.md)。 diff --git a/RELEASE-v0.1.56.md b/RELEASE-v0.1.56.md new file mode 100644 index 0000000..3a15e59 --- /dev/null +++ b/RELEASE-v0.1.56.md @@ -0,0 +1,33 @@ +# V0.1.56 · 数据、设备与视图 + +## 新域名 + +手机与显示终端的正式服务地址统一为 `https://home.ucvl.cn`,地图、配对与 API 使用同一地址并执行路径白名单校验。请从新版配套 App 下载页获取对应安装包。 + +百度网盘支持在保持同一开发者应用及网盘授权的情况下迁移回调域名,无须解除已有连接。迁移会使旧的待完成授权请求失效;新授权仍需在百度开发者后台登记 `https://home.ucvl.cn/api/baidu/callback`。发布软件不代表开发者后台已经更新。 + +## 六类对象 + +数据类型定义字段、单位、范围与默认值;设备类型(FB)关联数据类型和已注册的执行驱动。实例化后,每个设备拥有独立参数与运行数据。 + +视图类型仅依赖数据类型。视图实例引用兼容的数据实例,多个视图可以展示同一份数据。设备类型不决定可用视图。当前支持参数卡片和内置电脑电源数据视图;暂不提供任意脚本、布局编程或第三方自定义驱动。 + +家庭管理员可以在设备目录管理三种类型,在设备详情绑定类型、填写参数并新建具名视图。类型和实例遵守家庭、区域权限与修订校验。数据结构变更会校验现有实例,阻止不兼容修改;旧设备档案继续保留。 + +## 电脑与手机 + +手机导航为「位置 / 家庭 / 设备 / 沟通 / 我的」。家庭与设备按明确授权显示,已配对不自动获得设备控制权。位置共享、最近十条沟通记录及定时上传继续使用原有规则。 + +电脑显示 RUN 与 OP:RUN 为在线、已确认不可达或未知;OP 为 0 空闲、1 启动、2 安全关机。请求按编号去重,成功、失败、超时或服务重启后复位,不重放旧命令。未知状态禁止发送电源操作。 + +唤醒通过专用 SSH 密钥调用路由器固定脚本。Windows 服务只向固定平台地址发起签名请求,不监听端口,只接受安全关机。关机须二次确认,不强制关闭应用;安装后默认维护锁,工作期间保持锁定。服务端凭据不进入设备档案、网页或 APK。 + +## 安装与验证范围 + +从平台「配套 App 下载」覆盖安装手机版,保留原配对和待上传数据;显示终端使用独立安装包。网页使用本地 Vue、Bootstrap,安卓为本地原生 Bootstrap 风格控件。 + +35 个安卓原生测试场景在隔离模拟器中执行,包含窄屏、大字体、空授权、过期状态、处理中、令牌切换及导航生命周期。测试包使用合成数据,不连接真实硬件;结果不能代替用户手机的省电、锁屏及全屏实机验收。 + +代码验收:396 项 Python 测试、224 项 JavaScript 测试、292 项 Java 断言、38 项 Windows 服务自检通过。随后补充设备转移后释放原家庭视图名额的测试,相关的 70 项类型、家庭和电源回归再次通过。手机端与显示终端均为 `0.1.56 / 12`,已构建并验证签名。网页实测创建视图类型、绑定同一数据实例的两个视图,修改数据后两个视图均更新。 + +P15 是本次工作的运行主机,真实关机在维护期间不执行。固定唤醒桥已在主机在线时验证;Windows 服务安装、生产设备授权及真实关机/冷启动仍需部署验收。在线主机接收唤醒脚本不等同于断电开机测试。完整接入说明见 [Windows 电源服务](windows-power/README.md)。 diff --git a/VERSION b/VERSION index 8893a8e..c52af3e 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.1.55 +0.1.56 diff --git a/android-display/AndroidManifest-terminal.xml b/android-display/AndroidManifest-terminal.xml index c392c42..33a2b99 100644 --- a/android-display/AndroidManifest-terminal.xml +++ b/android-display/AndroidManifest-terminal.xml @@ -1,4 +1,4 @@ - + diff --git a/android-display/AndroidManifest.xml b/android-display/AndroidManifest.xml index a62b249..6941571 100644 --- a/android-display/AndroidManifest.xml +++ b/android-display/AndroidManifest.xml @@ -1,4 +1,4 @@ - + diff --git a/android-display/src/cn/ucvl/zhaodisplay/DisplayApi.java b/android-display/src/cn/ucvl/zhaodisplay/DisplayApi.java index fed8a23..2f7bbe0 100644 --- a/android-display/src/cn/ucvl/zhaodisplay/DisplayApi.java +++ b/android-display/src/cn/ucvl/zhaodisplay/DisplayApi.java @@ -8,7 +8,7 @@ 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(); + HttpsURLConnection c=(HttpsURLConnection)new URL(ServerEndpoint.api(path)).openConnection(); c.setInstanceFollowRedirects(false);c.setConnectTimeout(10000);c.setReadTimeout(10000); if(token!=null&&!token.isEmpty())c.setRequestProperty("Authorization","Bearer "+token); try{ diff --git a/android-display/src/cn/ucvl/zhaodisplay/LocationActivity.java b/android-display/src/cn/ucvl/zhaodisplay/LocationActivity.java index d424827..7d1c653 100644 --- a/android-display/src/cn/ucvl/zhaodisplay/LocationActivity.java +++ b/android-display/src/cn/ucvl/zhaodisplay/LocationActivity.java @@ -21,7 +21,7 @@ public class LocationActivity extends Activity { final int[] sampleUnits={1,60,3600,86400}; final int[] uploadIntervals={10,60,300,3600,7200,10800,14400,18000,86400,172800,259200,0}; TextView historyStatus,historyNotice;Dialog historyDialog;LocationMapView historyMap;Button historyMore;JSONArray historyPoints=new JSONArray();int historyRequest=0;boolean historyAcknowledged=false; - VoicePanel voice;Button settingsButton;PhoneLayout phone;PhoneStyle style;Dialog detailDialog; + VoicePanel voice;Button settingsButton;PhoneLayout phone;PhoneHomePanel phoneHome;PhoneStyle style;Dialog detailDialog; LinearLayout pairSection,recipientSection,sampleSection,uploadSection,historySection,permissionSection,consentSection; LocationMapView map;boolean rendering=false,visible=false,loading=false,settingsReady=false,pendingStart=false,bindingRejected=false; int generation=0,settingsRequest=0;long lastList=0;String settingsReceipt="",settingsError=""; @@ -83,24 +83,26 @@ public class LocationActivity extends Activity { button("打开手机系统定位设置",permissionSection).setOnClickListener(v->startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS))); sharing.setOnCheckedChangeListener((v,checked)->{if(rendering)return;if(checked)confirmSharing();else{startService(new Intent(this,LocationService.class).setAction("STOP"));consent.setChecked(false);}render();}); map=new LocationMapView(this);phone.mapSlot.addView(map,0,new FrameLayout.LayoutParams(-1,-1));phone.fit.setOnClickListener(v->map.reset());reload.setOnClickListener(v->loadFamily()); - voice=new VoicePanel(this,"phone",()->prefs.getString("token",""));phone.pages[1].addView(voice.page(),new LinearLayout.LayoutParams(-1,0,1));phone.voiceSettings.addView(voice.dock.receiverCard); + voice=new VoicePanel(this,"phone",()->prefs.getString("token",""));phone.pages[PhoneLayout.COMMUNICATION].addView(voice.page(),new LinearLayout.LayoutParams(-1,0,1));phone.voiceSettings.addView(voice.dock.receiverCard); phone.voiceSettings.addView(style.label("仅接收你允许的家人或设备。聊天记录长期保存在家庭网盘,关闭接收不会删除历史。",12,PhoneStyle.MUTED)); Button soundSettings=style.button("麦克风与声音权限",false);phone.voiceSettings.addView(soundSettings);soundSettings.setOnClickListener(v->startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,android.net.Uri.parse("package:"+getPackageName())))); - try{phone.pages[2].addView(style.label("赵府智家 · "+getPackageManager().getPackageInfo(getPackageName(),0).versionName,12,PhoneStyle.MUTED));}catch(Exception ignored){} - phone.onTab=i->{voice.finish(false);voice.communication(i==1);if(i==2&&!settingsReady)loadSettings();}; - settingsButton.setOnClickListener(v->selectTab(2));phone.check.setOnClickListener(v->{selectTab(2);if(pairingRequired())showDetail("配对我的手机",pairSection);else showDetail("定位权限",permissionSection);}); - phone.pairNow.setOnClickListener(v->{selectTab(2);showDetail("配对我的手机",pairSection);}); + try{phone.pages[PhoneLayout.MINE].addView(style.label("赵府智家 · "+getPackageManager().getPackageInfo(getPackageName(),0).versionName,12,PhoneStyle.MUTED));}catch(Exception ignored){} + phoneHome=new PhoneHomePanel(this,phone,()->prefs.getString("token",""),()->!pairingRequired(),this::selectTab); + phone.onTab=this::tabChanged; + settingsButton.setOnClickListener(v->selectTab(PhoneLayout.MINE));phone.check.setOnClickListener(v->{selectTab(PhoneLayout.MINE);if(pairingRequired())showDetail("配对我的手机",pairSection);else showDetail("定位权限",permissionSection);}); + phone.pairNow.setOnClickListener(v->{selectTab(PhoneLayout.MINE);showDetail("配对我的手机",pairSection);}); phone.profile.setOnClickListener(v->showDetail("配对与设备",pairSection));phone.pairing.setOnClickListener(v->showDetail("配对与设备",pairSection)); phone.myCheck.setOnClickListener(v->{if(pairingRequired())showDetail("配对我的手机",pairSection);else showDetail("定位权限",permissionSection);});phone.permissions.setOnClickListener(v->showDetail("定位权限与系统设置",permissionSection)); phone.viewers.setOnClickListener(v->{if(!settingsReady)loadSettings();showDetail("允许谁查看",recipientSection);}); phone.expiry.setOnClickListener(v->new AlertDialog.Builder(this).setTitle("共享有效期").setMessage(prefs.getLong("expires",0)>0?"本手机配对有效至 "+java.text.DateFormat.getDateTimeInstance().format(new Date(prefs.getLong("expires",0)))+"。到期后停止新位置共享;可随时手动关闭。续期或重新配对请联系家庭管理员。":"配对后显示有效期。").setPositiveButton("知道了",null).show()); phone.sampling.setOnClickListener(v->showDetail("共享模式与采集频率",sampleSection));phone.upload.setOnClickListener(v->showDetail("集中上传与离线暂存",uploadSection));phone.history.setOnClickListener(v->showDetail("我的历史轨迹",historySection)); - selectTab(paired()?0:2);render(); + selectTab(paired()?PhoneLayout.LOCATION:PhoneLayout.MINE);render(); } boolean paired(){return !prefs.getString("token","").isEmpty();} boolean pairingRequired(){long expires=prefs.getLong("expires",0);return !paired()||bindingRejected||expires>0&&expires<=System.currentTimeMillis();} LinearLayout section(){LinearLayout v=style.column();settings.addView(v);return v;} - void selectTab(int tab){voice.finish(false);phone.select(tab);voice.communication(tab==1);if(tab==2&&!settingsReady)loadSettings();} + void selectTab(int tab){phone.select(tab);tabChanged(tab);} + void tabChanged(int tab){voice.finish(false);voice.communication(tab==PhoneLayout.COMMUNICATION);if(phoneHome!=null)phoneHome.contextChanged();if(tab==PhoneLayout.MINE&&!settingsReady)loadSettings();} void showDetail(String title,LinearLayout content){ if(detailDialog!=null)detailDialog.dismiss();voice.finish(false);if(content.getParent()!=null)((android.view.ViewGroup)content.getParent()).removeView(content); LinearLayout frame=style.column();frame.setBackgroundColor(PhoneStyle.PAPER); @@ -118,9 +120,10 @@ public class LocationActivity extends Activity { new AlertDialog.Builder(this).setTitle("开启我的位置共享").setMessage((realtimeMode()?"实时共享:持续定位与汇报。\n":"定时共享:采集完即释放定位。\n")+"允许 "+total+" 个对象查看 · 采集"+periodLabel(samplePeriodSeconds())+" · 上传"+periodLabel(uploadPeriod())+"。\n可随时关闭。频率与名单将在此次开启时生效。").setView(consentSection).setNegativeButton("暂不开启",null).setPositiveButton("开启共享",(d,w)->start()).setOnDismissListener(d->{if(consentSection.getParent()!=null)((android.view.ViewGroup)consentSection.getParent()).removeView(consentSection);settings.addView(consentSection);render();}).show(); } String periodLabel(int seconds){return "每 "+(seconds%86400==0?seconds/86400+" 天":seconds%3600==0?seconds/3600+" 小时":seconds%60==0?seconds/60+" 分钟":seconds+" 秒");} - public void onBackPressed(){if(phone.tab!=0){selectTab(0);return;}super.onBackPressed();} + public void onBackPressed(){if(phone.tab!=PhoneLayout.LOCATION){selectTab(PhoneLayout.LOCATION);return;}super.onBackPressed();} void render(){ + if(phoneHome!=null)phoneHome.contextChanged(); permissionStatus.setText(locationPermissionText()); 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);voice.setVisibility(paired?View.VISIBLE:View.GONE);phone.pairIntro.setVisibility(paired?View.GONE:View.VISIBLE); @@ -156,7 +159,7 @@ public class LocationActivity extends Activity { new Thread(()->{try{ JSONObject response=DisplayApi.call("/api/location/pair",null,new JSONObject().put("code",value).put("consentProtocol",3));remember(response); LocationSchedule.cancel(this);stopService(new Intent(this,LocationService.class));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();refreshQueueStats(); - runOnUiThread(()->{if(isDestroyed())return;pairing=false;bindingRejected=false;generation++;loading=false;familyList.removeAllViews();map.setItems(new JSONArray());code.setText("");consent.setChecked(false);settingsReady=false;if(detailDialog!=null)detailDialog.dismiss();selectTab(0);voice.rebound();loadSettings();loadFamily();}); + runOnUiThread(()->{if(isDestroyed())return;pairing=false;bindingRejected=false;generation++;loading=false;familyList.removeAllViews();map.setItems(new JSONArray());code.setText("");consent.setChecked(false);settingsReady=false;if(detailDialog!=null)detailDialog.dismiss();selectTab(PhoneLayout.LOCATION);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(); } void loadFamily(){ @@ -165,7 +168,7 @@ public class LocationActivity extends Activity { new Thread(()->{try{ JSONObject response=DisplayApi.call("/api/location/update",token,new JSONObject().put("action","list")); runOnUiThread(()->{if(!visible||g!=generation)return;JSONArray list=sortPositions(response.optJSONArray("items"));map.setItems(list);familyList.removeAllViews();viewStatus.setText(list.length()==0?"尚无家人授权给这台手机的位置。请对方在自己的位置设置里勾选你的手机,并开启共享。":"按采集时间从新到旧 · 点击在地图上闪烁定位"); - for(int i=0;i{if(pos!=null){phone.scrolls[0].smoothScrollTo(0,0);map.focus(pos);}else Toast.makeText(this,"当前没有可显示的位置",0).show();},()->history(row.optString("id")));} + for(int i=0;i{if(pos!=null){phone.scrolls[PhoneLayout.LOCATION].smoothScrollTo(0,0);map.focus(pos);}else Toast.makeText(this,"当前没有可显示的位置",0).show();},()->history(row.optString("id")));} }); }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)){bindingRejected=true;boolean wasSharing=prefs.getBoolean("active",false);prefs.edit().putBoolean("active",false).apply();if(wasSharing||LocationService.busy)startService(new Intent(this,LocationService.class).setAction("STOP"));voice.rebound();settingsReady=false;settingsError="手机配对已失效,请在「我的」重新配对";}viewStatus.setText(e instanceof DisplayApi.ApiError&&((DisplayApi.ApiError)e).status==401?"手机配对已过期或解除,请重新配对。":"位置未能刷新,已隐藏旧画面,请检查网络。");});}finally{runOnUiThread(()->{if(g==generation){loading=false;render();}});}},"family-positions").start(); @@ -251,7 +254,7 @@ public class LocationActivity extends Activity { }).show(); } public void onRequestPermissionsResult(int request,String[] permissions,int[] results){super.onRequestPermissionsResult(request,permissions,results);if(request==47||request==48){render();return;}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;map.resumeMap();voice.active(true);lastList=0;refreshQueueStats();if(!LocationService.busy&&(prefs.getBoolean("reportPending",false)||prefs.getBoolean("stopPending",false)))syncNow();if(!settingsReady)loadSettings();ui.post(refresh);if(pendingStart){pendingStart=false;start();}} - public void onPause(){visible=false;if(historyDialog!=null)historyDialog.dismiss();voice.active(false);generation++;loading=false;ui.removeCallbacksAndMessages(null);if(map!=null)map.pauseMap();if(familyList!=null)familyList.removeAllViews();super.onPause();} - public void onDestroy(){if(detailDialog!=null)detailDialog.dismiss();if(map!=null)map.close();if(voice!=null)voice.close();ui.removeCallbacksAndMessages(null);super.onDestroy();} + public void onResume(){super.onResume();visible=true;map.resumeMap();voice.active(true);phoneHome.active(true);lastList=0;refreshQueueStats();if(!LocationService.busy&&(prefs.getBoolean("reportPending",false)||prefs.getBoolean("stopPending",false)))syncNow();if(!settingsReady)loadSettings();ui.post(refresh);if(pendingStart){pendingStart=false;start();}} + public void onPause(){visible=false;if(phoneHome!=null)phoneHome.active(false);if(historyDialog!=null)historyDialog.dismiss();voice.active(false);generation++;loading=false;ui.removeCallbacksAndMessages(null);if(map!=null)map.pauseMap();if(familyList!=null)familyList.removeAllViews();super.onPause();} + public void onDestroy(){if(phoneHome!=null)phoneHome.close();if(detailDialog!=null)detailDialog.dismiss();if(map!=null)map.close();if(voice!=null)voice.close();ui.removeCallbacksAndMessages(null);super.onDestroy();} } diff --git a/android-display/src/cn/ucvl/zhaodisplay/LocationMapView.java b/android-display/src/cn/ucvl/zhaodisplay/LocationMapView.java index bbcbf1f..d5d8ba3 100644 --- a/android-display/src/cn/ucvl/zhaodisplay/LocationMapView.java +++ b/android-display/src/cn/ucvl/zhaodisplay/LocationMapView.java @@ -2,7 +2,6 @@ package cn.ucvl.zhaodisplay; import android.content.Context; import android.webkit.*; -import android.net.Uri; import android.view.MotionEvent; import org.json.*; import java.io.ByteArrayInputStream; @@ -19,14 +18,13 @@ final class LocationMapView extends WebView { setWebViewClient(new WebViewClient(){ public boolean shouldOverrideUrlLoading(WebView view,WebResourceRequest request){return true;} public WebResourceResponse shouldInterceptRequest(WebView view,WebResourceRequest request){ - Uri uri=request.getUrl();String path=uri.getPath(); - if(!"https".equals(uri.getScheme())||!"zhao.ucvl.cn".equals(uri.getHost())||(uri.getPort()!=-1&&uri.getPort()!=443)||path==null||!(path.startsWith("/maps/")||path.startsWith("/ui/assets/")))return new WebResourceResponse("text/plain","UTF-8",new ByteArrayInputStream(new byte[0])); + if(!ServerEndpoint.mapResource(request.getUrl().toString()))return new WebResourceResponse("text/plain","UTF-8",new ByteArrayInputStream(new byte[0])); return null; } - public void onPageFinished(WebView view,String url){if(!closed&&url.startsWith("https://zhao.ucvl.cn/maps/phone")){ready=true;push();}} + public void onPageFinished(WebView view,String url){if(!closed&&ServerEndpoint.mapPage(url)){ready=true;push();}} public void onReceivedError(WebView view,WebResourceRequest request,WebResourceError error){if(request.isForMainFrame())ready=false;} }); - loadUrl("https://zhao.ucvl.cn/maps/phone"); + loadUrl(ServerEndpoint.MAP_PHONE); } void run(String expression){if(ready&&!closed)evaluateJavascript("if(window.ZhaoMap){"+expression+"}",null);} void push(){run("window.ZhaoMap.setItems(JSON.parse("+JSONObject.quote(items.toString())+"));window.ZhaoMap.setTrack(JSON.parse("+JSONObject.quote(track.toString())+"));");} diff --git a/android-display/src/cn/ucvl/zhaodisplay/MainActivity.java b/android-display/src/cn/ucvl/zhaodisplay/MainActivity.java index 339c3a2..d821de2 100644 --- a/android-display/src/cn/ucvl/zhaodisplay/MainActivity.java +++ b/android-display/src/cn/ucvl/zhaodisplay/MainActivity.java @@ -42,7 +42,7 @@ public class MainActivity extends Activity { web.getSettings().setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_NEVER_ALLOW); 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"); + return !ServerEndpoint.tvNavigation(request.getUrl().toString()); } }); LinearLayout layout=new LinearLayout(this);layout.setOrientation(LinearLayout.VERTICAL); @@ -58,7 +58,7 @@ public class MainActivity extends Activity { if(code!=null&&code.matches("[0-9]{8}")){intent.removeExtra("pairing_code");pair(code);return;} String token=getSharedPreferences("display",MODE_PRIVATE).getString("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)); + web.loadUrl(ServerEndpoint.TV+"?client=android&load="+System.currentTimeMillis()+(token.isEmpty()?"":"#display="+token)); if(!token.isEmpty())startForegroundService(new Intent(this,MonitorService.class)); else pairDialog(); } diff --git a/android-display/src/cn/ucvl/zhaodisplay/MonitorService.java b/android-display/src/cn/ucvl/zhaodisplay/MonitorService.java index c291441..b2bfdd2 100644 --- a/android-display/src/cn/ucvl/zhaodisplay/MonitorService.java +++ b/android-display/src/cn/ucvl/zhaodisplay/MonitorService.java @@ -68,7 +68,7 @@ public class MonitorService extends Service { 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(); + HttpsURLConnection c=(HttpsURLConnection)new URL(ServerEndpoint.api(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); diff --git a/android-display/src/cn/ucvl/zhaodisplay/PhoneHomePanel.java b/android-display/src/cn/ucvl/zhaodisplay/PhoneHomePanel.java new file mode 100644 index 0000000..f7cedee --- /dev/null +++ b/android-display/src/cn/ucvl/zhaodisplay/PhoneHomePanel.java @@ -0,0 +1,144 @@ +package cn.ucvl.zhaodisplay; + +import android.app.*; +import android.os.*; +import android.view.View; +import android.widget.*; +import org.json.*; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.function.*; + +/** Native household/device pages. The server is the sole source of catalog and control grants. */ +final class PhoneHomePanel { + final Activity app;final PhoneLayout phone;final PhoneStyle s;final Supplier token;final BooleanSupplier pairingValid;final IntConsumer navigate; + final LinearLayout households,devices;final TextView householdStatus,deviceStatus,selection; + final Button householdRefresh,deviceRefresh;final Handler ui=new Handler();final PhoneHomeSession session=new PhoneHomeSession(); + final List cards=new ArrayList<>();JSONArray families=new JSONArray(),catalog=new JSONArray(); + String selectedFamily="",selectedName="",boundToken="",message="请先在「我的」配对本人的手机。"; + boolean foreground=false,busy=false;long lastCatalog=0,lastStatus=0;AlertDialog confirmation; + final Runnable tick=new Runnable(){public void run(){if(!foreground)return;contextChanged();if(homePage()&&valid()){ + for(DeviceCard card:cards)card.update(); + long elapsed=SystemClock.elapsedRealtime(); + if(!busy&&confirmation==null&&elapsed-lastCatalog>=30000)loadCatalog(); + else if(!busy&&confirmation==null&&phone.tab==PhoneLayout.DEVICES&&elapsed-lastStatus>=10000)loadStatus(); + }ui.postDelayed(this,1000);}}; + + PhoneHomePanel(Activity app,PhoneLayout phone,Supplier token,BooleanSupplier pairingValid,IntConsumer navigate){ + this.app=app;this.phone=phone;this.s=phone.s;this.token=token;this.pairingValid=pairingValid;this.navigate=navigate; + LinearLayout familyPage=phone.pages[PhoneLayout.HOUSEHOLDS],devicePage=phone.pages[PhoneLayout.DEVICES]; + householdRefresh=heading(familyPage,"家庭","刷新家庭与设备授权"); + familyPage.addView(s.label("选择家庭或办公地点,查看明确授权给你的设备。",14,PhoneStyle.MUTED));s.gap(familyPage,14); + householdStatus=s.label(message,14,PhoneStyle.MUTED);familyPage.addView(householdStatus);s.gap(familyPage,14);households=s.column();familyPage.addView(households); + deviceRefresh=heading(devicePage,"设备","刷新设备状态与授权"); + selection=s.label("尚未选择家庭",16,PhoneStyle.MUTED);devicePage.addView(selection);s.gap(devicePage,12); + Button choose=s.button("切换家庭",false);devicePage.addView(choose,new LinearLayout.LayoutParams(-1,-2));choose.setOnClickListener(v->navigate.accept(PhoneLayout.HOUSEHOLDS));s.gap(devicePage,14); + deviceStatus=s.label(message,14,PhoneStyle.MUTED);devicePage.addView(deviceStatus);s.gap(devicePage,14);devices=s.column();devicePage.addView(devices); + householdRefresh.setOnClickListener(v->loadCatalog());deviceRefresh.setOnClickListener(v->loadCatalog());render(); + } + Button heading(LinearLayout parent,String title,String description){LinearLayout line=s.line();line.addView(s.bold(title,28),new LinearLayout.LayoutParams(0,-2,1));Button refresh=s.iconButton("refresh",description);line.addView(refresh,new LinearLayout.LayoutParams(s.dp(48),s.dp(48)));parent.addView(line);s.gap(parent,12);return refresh;} + boolean homePage(){return phone.tab==PhoneLayout.HOUSEHOLDS||phone.tab==PhoneLayout.DEVICES;} + boolean valid(){return !app.isDestroyed()&&pairingValid.getAsBoolean()&&!token.get().isEmpty();} + boolean current(PhoneHomeSession.Ticket ticket){return !app.isDestroyed()&&pairingValid.getAsBoolean()&&session.accepts(ticket,token.get());} + void active(boolean active){foreground=active;ui.removeCallbacks(tick);contextChanged();if(active)ui.post(tick);} + void contextChanged(){ + boolean enabled=foreground&&homePage()&&valid(); + String identity=token.get();if(!boundToken.equals(identity)){boundToken=identity;selectedFamily="";selectedName="";} + if(session.bind(identity,enabled,phone.tab)){ + if(confirmation!=null){confirmation.dismiss();confirmation=null;} + busy=false;families=new JSONArray();catalog=new JSONArray();cards.clear();lastCatalog=0;lastStatus=0; + message=valid()?"正在读取设备授权…":"请先在「我的」配对本人的手机。";render(); + if(enabled)loadCatalog(); + } + } + void close(){foreground=false;ui.removeCallbacksAndMessages(null);session.bind("",false,-1);if(confirmation!=null){confirmation.dismiss();confirmation=null;}families=new JSONArray();catalog=new JSONArray();cards.clear();} + void loadCatalog(){ + if(busy||!foreground||!homePage()||!valid())return; + busy=true;message="正在刷新家庭与设备授权…";status();PhoneHomeSession.Ticket ticket=session.begin();lastCatalog=SystemClock.elapsedRealtime(); + new Thread(()->{try{ + if(!current(ticket))return; + JSONObject result=DisplayApi.call("/api/phone/home",ticket.token,new JSONObject().put("action","catalog")); + // Missing catalog arrays must not preserve cached permissions. + JSONArray receivedFamilies=result.getJSONArray("households"),receivedDevices=result.getJSONArray("devices"); + app.runOnUiThread(()->{if(!current(ticket))return;busy=false;families=receivedFamilies;catalog=receivedDevices; + if(!hasFamily(selectedFamily))selectedFamily=result.optString("activeId"); + if(!hasFamily(selectedFamily))selectedFamily=firstFamilyId(); + selectedName=familyName(selectedFamily);lastStatus=SystemClock.elapsedRealtime();message="只显示已授权给你的设备;查看和控制权限分别授予。";render(); + }); + }catch(Exception e){app.runOnUiThread(()->failed(ticket,e,false));}},"phone-home-catalog").start(); + } + void loadStatus(){ + if(busy||!foreground||!homePage()||!valid()||cards.isEmpty())return; + List ids=new ArrayList<>();for(DeviceCard c:cards)if(c.row.optJSONObject("power")!=null)ids.add(c.id);if(ids.isEmpty()){lastStatus=SystemClock.elapsedRealtime();return;} + busy=true;PhoneHomeSession.Ticket ticket=session.begin();lastStatus=SystemClock.elapsedRealtime();status(); + new Thread(()->{try{ + Map states=new HashMap<>();for(String id:ids){if(!current(ticket))return;JSONObject response=DisplayApi.call("/api/phone/home",ticket.token,new JSONObject().put("action","status").put("deviceId",id));states.put(id,response.getJSONObject("power"));} + app.runOnUiThread(()->{if(!current(ticket))return;busy=false;for(DeviceCard c:cards){JSONObject p=states.get(c.id);if(p!=null)c.apply(p);}status();}); + }catch(Exception e){app.runOnUiThread(()->failed(ticket,e,false));}},"phone-home-status").start(); + } + void failed(PhoneHomeSession.Ticket ticket,Exception error,boolean command){ + if(!current(ticket))return;busy=false;families=new JSONArray();catalog=new JSONArray();cards.clear();selectedName=""; + int status=error instanceof DisplayApi.ApiError?((DisplayApi.ApiError)error).status:0; + message=status==401?"手机配对已过期或解除,请到「我的」重新配对。":status==403?"设备授权已失效或无权访问,请联系家庭管理员。":command?"暂时无法确认操作结果。请刷新状态后再决定,勿重复提交。":"暂时无法读取设备状态,已隐藏旧授权。请检查网络并刷新。"; + lastCatalog=SystemClock.elapsedRealtime();render(); + } + boolean hasFamily(String id){for(int i=0;i{selectedFamily=id;selectedName=name;navigate.accept(PhoneLayout.DEVICES);}); + LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(-1,-2);lp.bottomMargin=s.dp(14);households.addView(card,lp); + } + for(int i=0;i0&&cards.isEmpty()?"本家庭暂无获授权设备。请联系管理员为本人授予设备查看或控制权限。":message); + boolean refresh=foreground&&homePage()&&valid()&&!busy;householdRefresh.setEnabled(refresh);deviceRefresh.setEnabled(refresh);for(DeviceCard card:cards)card.update(); + } + static PhonePowerModel model(JSONObject power){ + if(power==null)return new PhonePowerModel(-1,0,"unknown",0,false,false,false); + return new PhonePowerModel(power.isNull("run")?-1:power.optInt("run",-1),power.optInt("op",-1),power.optString("state","unknown"),power.optLong("checkedAt",0),power.optBoolean("canStart",false),power.optBoolean("canShutdown",false),power.optBoolean("managed",false)); + } + String time(long seconds){return seconds>0?new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA).format(new Date(seconds*1000)):"尚未检查";} + String resultLabel(String status){switch(status){case "pending":case "queued":return "等待处理";case "scheduled":return "已安排关机";case "succeeded":case "success":return "已完成";case "failed":return "失败";case "blocked":return "已阻止";case "timeout":case "timed_out":return "已超时";default:return status.isEmpty()?"无":status;}} + final class DeviceCard { + final JSONObject row;final String id,name;JSONObject power;PhonePowerModel state;final LinearLayout view;final TextView run,operation,checked,result;final Button start,shutdown; + DeviceCard(JSONObject row){ + this.row=row;id=row.optString("id");name=row.optString("name","设备");power=row.optJSONObject("power");state=model(power);view=s.column();s.card(view);view.addView(s.bold(name,21));s.gap(view,8); + String location=row.optString("familyName"),site=row.optString("siteName");if(!site.isEmpty())location+=(location.isEmpty()?"":" · ")+site;view.addView(s.label(location.isEmpty()?"位置未填写":location,14,PhoneStyle.MUTED));s.gap(view,14); + run=s.bold("",18);view.addView(run);s.gap(view,8);operation=s.label("",14,PhoneStyle.MUTED);view.addView(operation);s.gap(view,12); + start=s.button("开机",true);shutdown=s.button("关机",false);start.setContentDescription("开机 "+name);shutdown.setContentDescription("关机 "+name);view.addView(start,new LinearLayout.LayoutParams(-1,-2));s.gap(view,8);view.addView(shutdown,new LinearLayout.LayoutParams(-1,-2)); + start.setOnClickListener(v->request(this,1));shutdown.setOnClickListener(v->request(this,2));s.gap(view,14);checked=s.label("",12,PhoneStyle.MUTED);view.addView(checked);s.gap(view,8);result=s.label("",13,PhoneStyle.MUTED);view.addView(result);update(); + } + void apply(JSONObject p){power=p;state=model(p);try{row.put("power",p);}catch(JSONException ignored){}update();} + void update(){ + long now=System.currentTimeMillis()/1000;int observed=state.run(now);run.setText("RUN "+(observed<0?"— · 未知":observed==1?"1 · 在线":"0 · 不可达"));run.setTextColor(observed==1?PhoneStyle.GREEN:PhoneStyle.MUTED); + operation.setText("OP "+(state.op>=0&&state.op<=2?state.op:"—")+" · "+(!state.managed?"未提供电源管理":state.op==1?"正在开机":state.op==2?"正在关机":observed<0?"等待有效状态":busy?"正在刷新或提交":"空闲")); + boolean enabled=foreground&&homePage()&&valid();start.setEnabled(enabled&&state.may(1,now,busy));shutdown.setEnabled(enabled&&state.may(2,now,busy)); + checked.setText("检查时间:"+time(state.checkedAt)+(observed==0?"\n不可达不代表已物理关机。":""));JSONObject last=power==null?null:power.optJSONObject("last"); + result.setText(last==null?"最近结果:尚无操作记录":"最近结果:"+resultLabel(last.optString("status"))+" · "+last.optString("result","无详情")+"\n"+time(last.optLong("at"))); + } + } + void request(DeviceCard card,int operation){ + if(!foreground||phone.tab!=PhoneLayout.DEVICES||!valid()||!cards.contains(card)||!card.state.may(operation,System.currentTimeMillis()/1000,busy))return; + if(operation==1){send(card,operation);return;} + PhoneHomeSession.Ticket ticket=session.begin(); + confirmation=new AlertDialog.Builder(app).setTitle("关闭 "+card.name+"?").setMessage("将请求设备正常关机,不会强制关闭应用。请先保存工作;应用阻止关机时,设备可能保持在线。是否继续?").setNegativeButton("取消",null).setPositiveButton("确认关机",(d,w)->{if(current(ticket))send(card,2);}).create(); + confirmation.setOnDismissListener(d->confirmation=null);confirmation.show(); + } + void send(DeviceCard card,int operation){ + if(!foreground||phone.tab!=PhoneLayout.DEVICES||!valid()||!cards.contains(card)||!card.state.may(operation,System.currentTimeMillis()/1000,busy))return; + busy=true;message="正在提交操作,请等待结果…";status();PhoneHomeSession.Ticket ticket=session.begin();String requestId=UUID.randomUUID().toString().replace("-",""); + new Thread(()->{try{ + if(!current(ticket))return; + JSONObject response=DisplayApi.call("/api/phone/home",ticket.token,new JSONObject().put("action","command").put("deviceId",card.id).put("op",operation).put("requestId",requestId).put("confirm",true));JSONObject power=response.getJSONObject("power"); + app.runOnUiThread(()->{if(!current(ticket))return;busy=false;card.apply(power);lastStatus=SystemClock.elapsedRealtime();message="已收到操作结果;设备运行状态以实际检查为准。";status();}); + }catch(Exception e){app.runOnUiThread(()->failed(ticket,e,true));}},"phone-home-command").start(); + } +} diff --git a/android-display/src/cn/ucvl/zhaodisplay/PhoneHomeSession.java b/android-display/src/cn/ucvl/zhaodisplay/PhoneHomeSession.java new file mode 100644 index 0000000..d0743ed --- /dev/null +++ b/android-display/src/cn/ucvl/zhaodisplay/PhoneHomeSession.java @@ -0,0 +1,19 @@ +package cn.ucvl.zhaodisplay; + +/** Invalidates asynchronous home API results on identity, lifecycle, page and request changes. */ +final class PhoneHomeSession { + static final class Ticket {final String token;final long generation,request;Ticket(String token,long generation,long request){this.token=token;this.generation=generation;this.request=request;}} + private String token="";private boolean active;private int page=-1;private long generation,request; + synchronized boolean bind(String token,boolean active,int page){ + if(token==null)token=""; + if(this.token.equals(token)&&this.active==active&&this.page==page)return false; + this.token=token;this.active=active;this.page=page;generation++;return true; + } + synchronized Ticket begin(){ + if(!active||token.isEmpty())throw new IllegalStateException("No active phone pairing"); + return new Ticket(token,generation,++request); + } + synchronized boolean accepts(Ticket ticket,String currentToken){ + return ticket!=null&&active&&!token.isEmpty()&&token.equals(currentToken)&&token.equals(ticket.token)&&generation==ticket.generation&&request==ticket.request; + } +} diff --git a/android-display/src/cn/ucvl/zhaodisplay/PhoneLayout.java b/android-display/src/cn/ucvl/zhaodisplay/PhoneLayout.java index 7df6d88..4afb526 100644 --- a/android-display/src/cn/ucvl/zhaodisplay/PhoneLayout.java +++ b/android-display/src/cn/ucvl/zhaodisplay/PhoneLayout.java @@ -6,49 +6,51 @@ import android.view.*; import android.widget.*; import java.util.function.IntConsumer; -/** Three persistent phone pages. All members, permissions and statuses are supplied by the controller. */ +/** Five persistent phone pages. All members, permissions and statuses are supplied by the controller. */ final class PhoneLayout extends LinearLayout { - final PhoneStyle s;final ScrollView[] scrolls=new ScrollView[3];final LinearLayout[] pages=new LinearLayout[3]; + static final int LOCATION=0,HOUSEHOLDS=1,DEVICES=2,COMMUNICATION=3,MINE=4,PAGE_COUNT=5; + private static final String[] NAMES={"位置","家庭","设备","沟通","我的"},ICONS={"location","family","display","mic","person"}; + final PhoneStyle s;final ScrollView[] scrolls=new ScrollView[PAGE_COUNT];final LinearLayout[] pages=new LinearLayout[PAGE_COUNT]; final LinearLayout nav,homeContent,familyList,mineContent,pairIntro,shareCard,profile,voiceSettings; final FrameLayout mapSlot;final TextView homeName,identity,avatar,homeStatus,myStatus,viewStatus,pairSummary; final Button settingsButton,check,refresh,fit,pairNow,myCheck;final Switch sharing; final PhoneStyle.Row viewers,expiry,sampling,upload,history,pairing,permissions; - final TextView[] navLabels=new TextView[3];final ImageView[] navIcons=new ImageView[3];int tab=0;IntConsumer onTab; + final TextView[] navLabels=new TextView[PAGE_COUNT];final ImageView[] navIcons=new ImageView[PAGE_COUNT];int tab=0;IntConsumer onTab; PhoneLayout(Activity app){ super(app);s=new PhoneStyle(app);setOrientation(VERTICAL);setBackgroundColor(PhoneStyle.PAPER); FrameLayout content=new FrameLayout(app);addView(content,new LayoutParams(-1,0,1)); - for(int i=0;i<3;i++){scrolls[i]=new ScrollView(app);scrolls[i].setFillViewport(true);scrolls[i].setClipToPadding(false);pages[i]=s.column();pages[i].setPadding(s.dp(18),s.dp(18),s.dp(18),s.dp(16));scrolls[i].addView(pages[i]);content.addView(scrolls[i],new FrameLayout.LayoutParams(-1,-1));} + for(int i=0;i{select(index);if(onTab!=null)onTab.accept(index);});nav.addView(item,new LayoutParams(0,-2,1));} - select(0); + nav=s.line();nav.setBackground(s.bordered(PhoneStyle.CARD,PhoneStyle.LINE,0));nav.setPadding(s.dp(8),s.dp(6),s.dp(8),s.dp(6));addView(nav,new LayoutParams(-1,-2)); + for(int i=0;i{select(index);if(onTab!=null)onTab.accept(index);});nav.addView(item,new LayoutParams(0,-2,1));} + select(LOCATION); } void section(LinearLayout parent,String title){s.gap(parent,22);parent.addView(s.bold(title,17));s.gap(parent,10);} - void select(int next){tab=next;pages[1].setVisibility(next==1?VISIBLE:GONE);for(int i=0;i<3;i++){scrolls[i].setVisibility(i==next?VISIBLE:GONE);nav.getChildAt(i).setSelected(i==next);nav.getChildAt(i).setBackground(s.shape(i==next?PhoneStyle.PALE:PhoneStyle.CARD,6));navLabels[i].setTextColor(i==next?PhoneStyle.GREEN:PhoneStyle.MUTED);navLabels[i].setTypeface(null,i==next?Typeface.BOLD:Typeface.NORMAL);navIcons[i].setImageDrawable(new PhoneStyle.Icon(new String[]{"location","mic","person"}[i],i==next?PhoneStyle.GREEN:PhoneStyle.MUTED,s.dp(25)));}} + void select(int next){if(next<0||next>=PAGE_COUNT)throw new IllegalArgumentException("Invalid phone page");tab=next;pages[COMMUNICATION].setVisibility(next==COMMUNICATION?VISIBLE:GONE);for(int i=0;ifocus.run());words.setContentDescription(name+","+detail+(position?",在地图上查看":""));row.addView(words,new LayoutParams(0,-2,1));Button more=s.button("轨迹",false);more.setContentDescription("查看 "+name+" 的已授权历史轨迹");more.setOnClickListener(v->history.run());row.addView(more);familyList.addView(row); } diff --git a/android-display/src/cn/ucvl/zhaodisplay/PhonePowerModel.java b/android-display/src/cn/ucvl/zhaodisplay/PhonePowerModel.java new file mode 100644 index 0000000..725ac60 --- /dev/null +++ b/android-display/src/cn/ucvl/zhaodisplay/PhonePowerModel.java @@ -0,0 +1,18 @@ +package cn.ucvl.zhaodisplay; + +/** Observed RUN and explicit server capabilities; OP never predicts physical state. */ +final class PhonePowerModel { + final int measuredRun,op;final String state;final long checkedAt;final boolean canStart,canShutdown,managed; + PhonePowerModel(int run,int op,String state,long checkedAt,boolean canStart,boolean canShutdown,boolean managed){this.measuredRun=run;this.op=op;this.state=state;this.checkedAt=checkedAt;this.canStart=canStart;this.canShutdown=canShutdown;this.managed=managed;} + int run(long now){ + if(checkedAt<=0||now45||op<0||op>2)return -1; + if(measuredRun==1&&"online".equals(state))return 1; + if(measuredRun==0&&"offline".equals(state))return 0; + return -1; + } + boolean may(int operation,long now,boolean submitting){ + if(!managed||submitting||op!=0)return false; + int observed=run(now); + return operation==1?observed==0&&canStart:operation==2&&observed==1&&canShutdown; + } +} diff --git a/android-display/src/cn/ucvl/zhaodisplay/ServerEndpoint.java b/android-display/src/cn/ucvl/zhaodisplay/ServerEndpoint.java new file mode 100644 index 0000000..fdb906c --- /dev/null +++ b/android-display/src/cn/ucvl/zhaodisplay/ServerEndpoint.java @@ -0,0 +1,31 @@ +package cn.ucvl.zhaodisplay; + +import java.net.URI; +import java.net.URISyntaxException; + +/** One official HTTPS origin and purpose-specific route allowlists. */ +final class ServerEndpoint { + static final String HOST="home.ucvl.cn",BASE="https://"+HOST,MAP_PHONE=BASE+"/maps/phone",TV=BASE+"/tv"; + static String api(String path){ + if(path==null||!path.startsWith("/api/"))throw new IllegalArgumentException("Expected first-party API path"); + String url=BASE+path;URI uri=trusted(url); + if(uri==null||uri.getFragment()!=null)throw new IllegalArgumentException("Invalid API path"); + return url; + } + static boolean mapResource(String url){URI uri=trusted(url);return uri!=null&&(uri.getPath().startsWith("/maps/")||uri.getPath().startsWith("/ui/assets/"));} + static boolean mapPage(String url){URI uri=trusted(url);return uri!=null&&"/maps/phone".equals(uri.getPath());} + static boolean tvNavigation(String url){URI uri=trusted(url);return uri!=null&&("/tv".equals(uri.getPath())||uri.getPath().startsWith("/tv/"));} + private static URI trusted(String url){ + if(url==null)return null; + try{ + URI uri=new URI(url); + if(!"https".equalsIgnoreCase(uri.getScheme())||!HOST.equalsIgnoreCase(uri.getHost())||uri.getRawUserInfo()!=null||(uri.getPort()!=-1&&uri.getPort()!=443))return null; + String path=uri.getRawPath(); + // These registered routes use plain ASCII paths. Do not let encoded separators or + // dot segments be interpreted differently by WebView, proxies and the server. + if(path==null||!path.startsWith("/")||path.contains("%")||path.contains("\\")||path.contains("//"))return null; + for(String segment:path.split("/"))if(segment.equals(".")||segment.equals(".."))return null; + return uri; + }catch(URISyntaxException error){return null;} + } +} diff --git a/android-display/tests/PhonePowerModelTest.java b/android-display/tests/PhonePowerModelTest.java new file mode 100644 index 0000000..a5c2ad3 --- /dev/null +++ b/android-display/tests/PhonePowerModelTest.java @@ -0,0 +1,46 @@ +package cn.ucvl.zhaodisplay; + +/** Pure Java checks: no transport, credentials, Android runtime or physical power operations. */ +public class PhonePowerModelTest { + static int assertions; + static void check(boolean condition,String description){assertions++;if(!condition)throw new AssertionError(description);} + static PhonePowerModel power(int run,int op,String state,long at,boolean start,boolean shutdown,boolean managed){return new PhonePowerModel(run,op,state,at,start,shutdown,managed);} + public static void main(String[] args){ + PhonePowerModel online=power(1,0,"online",1000,false,true,true); + check(online.run(1045)==1,"fresh online RUN remains observed at TTL boundary"); + check(online.may(2,1045,false),"fresh explicitly allowed shutdown"); + check(!online.may(1,1000,false),"online cannot be started even when caller chooses OP1"); + check(online.run(1046)==-1,"stale RUN must become unknown"); + check(!online.may(2,1046,false),"stale permission cannot enable shutdown"); + PhonePowerModel offline=power(0,0,"offline",1000,true,false,true); + check(offline.run(1000)==0&&offline.may(1,1000,false),"fresh offline asset allows granted start"); + check(!offline.may(2,1000,false),"offline cannot be shut down"); + check(!power(0,0,"offline",1000,false,false,true).may(1,1000,false),"view grant is not control grant"); + check(!power(1,0,"online",1000,true,true,false).may(2,1000,false),"unmanaged assets cannot receive power commands"); + check(!online.may(2,1000,true),"in flight request blocks repeated taps"); + for(int op:new int[]{1,2}){ + PhonePowerModel pending=power(1,op,"online",1000,true,true,true); + check(pending.run(1000)==1,"OP must not infer RUN"); + check(!pending.may(1,1000,false)&&!pending.may(2,1000,false),"server pending OP blocks further commands"); + } + for(PhonePowerModel invalid:new PhonePowerModel[]{power(-1,0,"unknown",1000,true,true,true),power(0,0,"online",1000,true,true,true),power(1,0,"offline",1000,true,true,true),power(1,0,"online",0,true,true,true),power(1,0,"online",1100,true,true,true),power(1,7,"online",1000,true,true,true)}){ + check(invalid.run(1000)==-1,"unknown, inconsistent or invalid server state fails closed"); + check(!invalid.may(1,1000,false)&&!invalid.may(2,1000,false),"invalid state disables both actions"); + } + check(!online.may(0,1000,false)&&!online.may(3,1000,false),"only OP1 and OP2 are executable"); + + PhoneHomeSession session=new PhoneHomeSession(); + session.bind("paired-a",true,1);PhoneHomeSession.Ticket first=session.begin(); + check(session.accepts(first,"paired-a"),"current paired foreground request accepted"); + check(!session.accepts(first,"paired-b"),"token supplier change rejects callback before next render"); + session.bind("paired-a",true,1);check(session.accepts(first,"paired-a"),"same context refresh retains request"); + PhoneHomeSession.Ticket newer=session.begin();check(!session.accepts(first,"paired-a")&&session.accepts(newer,"paired-a"),"newer request supersedes old response"); + session.bind("paired-a",true,2);check(!session.accepts(newer,"paired-a"),"tab switch invalidates callbacks"); + PhoneHomeSession.Ticket tab=session.begin();session.bind("paired-a",false,2);check(!session.accepts(tab,"paired-a"),"pause invalidates callbacks"); + session.bind("paired-a",true,2);check(!session.accepts(tab,"paired-a"),"resume cannot revive pre-pause response"); + PhoneHomeSession.Ticket rebound=session.begin();session.bind("paired-b",true,2);check(!session.accepts(rebound,"paired-a")&&!session.accepts(rebound,"paired-b"),"re-pair invalidates old identity"); + session.bind("",true,2);try{session.begin();throw new AssertionError("unpaired request allowed");}catch(IllegalStateException expected){assertions++;} + session.bind("paired-b",false,2);try{session.begin();throw new AssertionError("background request allowed");}catch(IllegalStateException expected){assertions++;} + System.out.println("Phone power/session: "+assertions+" assertions passed"); + } +} diff --git a/android-display/tests/ServerEndpointTest.java b/android-display/tests/ServerEndpointTest.java new file mode 100644 index 0000000..19384a6 --- /dev/null +++ b/android-display/tests/ServerEndpointTest.java @@ -0,0 +1,28 @@ +package cn.ucvl.zhaodisplay; + +/** Executes real URL construction and WebView allowlists without network or Android runtime. */ +public class ServerEndpointTest { + static int assertions; + static void check(boolean condition,String message){assertions++;if(!condition)throw new AssertionError(message);} + public static void main(String[] args){ + check(ServerEndpoint.api("/api/phone/home").equals("https://home.ucvl.cn/api/phone/home"),"phone API uses the official domain"); + check(ServerEndpoint.api("/api/display/heartbeat").equals("https://home.ucvl.cn/api/display/heartbeat"),"display heartbeat shares the same endpoint"); + check(ServerEndpoint.MAP_PHONE.equals("https://home.ucvl.cn/maps/phone"),"first-party map entry uses official origin"); + check(ServerEndpoint.tvNavigation(ServerEndpoint.TV+"?client=android&load=42#display=fixture"),"display pairing fragment stays on official TV origin"); + check(ServerEndpoint.tvNavigation("https://home.ucvl.cn:443/tv/child"),"explicit HTTPS default port and TV child allowed"); + for(String url:new String[]{"https://home.ucvl.cn/maps/phone","https://home.ucvl.cn:443/maps/tile?z=1&x=1&y=0","https://home.ucvl.cn/ui/assets/map-abc.js"})check(ServerEndpoint.mapResource(url),"allow only first-party map resources: "+url); + check(ServerEndpoint.mapPage("https://home.ucvl.cn/maps/phone?theme=day"),"ready callback accepts exact map document with query"); + check(!ServerEndpoint.mapPage("https://home.ucvl.cn/maps/phone-evil"),"map ready is not a prefix match"); + check(!ServerEndpoint.mapPage("https://home.ucvl.cn/maps/tile"),"tile cannot mark map document ready"); + for(String url:new String[]{null,"","http://home.ucvl.cn/maps/phone","https://zhao.ucvl.cn/maps/phone","https://home.ucvl.cn.evil.invalid/maps/phone","https://evil.invalid@home.ucvl.cn/maps/phone","https://home.ucvl.cn@evil.invalid/maps/phone","https://home.ucvl.cn:444/maps/phone","https://home.ucvl.cn./maps/phone","//home.ucvl.cn/maps/phone","file:///maps/phone","javascript:alert(1)","https://home.ucvl.cn/maps/../api/private","https://home.ucvl.cn/maps/%2e%2e/api/private","https://home.ucvl.cn/maps/%252e%252e/api/private","https://home.ucvl.cn/maps/%2f..%2fapi/private","https://home.ucvl.cn/maps\\phone","https://home.ucvl.cn/maps//phone"}){ + check(!ServerEndpoint.mapResource(url),"reject unsafe map resource: "+url); + check(!ServerEndpoint.mapPage(url),"reject unsafe map completion URL: "+url); + } + for(String url:new String[]{"https://home.ucvl.cn/api/phone/home","https://home.ucvl.cn/maps","https://home.ucvl.cn/ui/assets-evil/map.js","https://home.ucvl.cn/ui/private"})check(!ServerEndpoint.mapResource(url),"reject unrelated first-party path: "+url); + for(String url:new String[]{"https://home.ucvl.cn/tv-evil","https://home.ucvl.cn/tv/../api","https://home.ucvl.cn:8443/tv","https://evil.invalid/tv","https://zhao.ucvl.cn/tv","https://home.ucvl.cn/maps/phone","https://user@home.ucvl.cn/tv","http://home.ucvl.cn/tv"})check(!ServerEndpoint.tvNavigation(url),"reject unsafe TV navigation: "+url); + for(String path:new String[]{null,"","api/voice","//evil.invalid/api/voice","https://evil.invalid/api/voice","/maps/phone","/api/../tv","/api/%2e%2e/tv","/api/voice#token"}){ + try{ServerEndpoint.api(path);throw new AssertionError("unsafe API path accepted: "+path);}catch(IllegalArgumentException expected){assertions++;} + } + System.out.println("Server endpoint allowlist: "+assertions+" assertions passed"); + } +} diff --git a/android-display/tests/build-phone-check.ps1 b/android-display/tests/build-phone-check.ps1 index 1fccbff..87c10f0 100644 --- a/android-display/tests/build-phone-check.ps1 +++ b/android-display/tests/build-phone-check.ps1 @@ -22,7 +22,7 @@ if($LASTEXITCODE){throw 'Test resource linking failed'} $queueSource=Get-Content -LiteralPath "$source\src\cn\ucvl\zhaodisplay\LocationQueue.java" -Raw -Encoding UTF8 $queueSource=$queueSource.Replace('LocationQueue','StoredLocationQueue').Replace('location-outbox.db','storage-check.db') [IO.File]::WriteAllText("$stage\StoredLocationQueue.java",$queueSource,(New-Object Text.UTF8Encoding($false))) -$sources=@("$stage\StoredLocationQueue.java","$source\src\cn\ucvl\zhaodisplay\LocationService.java","$source\src\cn\ucvl\zhaodisplay\LocationActivity.java","$source\src\cn\ucvl\zhaodisplay\PhoneLayout.java","$source\src\cn\ucvl\zhaodisplay\PhoneStyle.java","$source\src\cn\ucvl\zhaodisplay\VoicePanel.java","$source\src\cn\ucvl\zhaodisplay\VoiceSurface.java","$source\src\cn\ucvl\zhaodisplay\VoiceChat.java","$source\src\cn\ucvl\zhaodisplay\VoiceGesture.java","$source\src\cn\ucvl\zhaodisplay\LocationCadence.java") + @((Get-ChildItem "$tests\phone-preview" -Filter "*.java").FullName) +$sources=@("$stage\StoredLocationQueue.java","$source\src\cn\ucvl\zhaodisplay\LocationService.java","$source\src\cn\ucvl\zhaodisplay\LocationActivity.java","$source\src\cn\ucvl\zhaodisplay\PhoneLayout.java","$source\src\cn\ucvl\zhaodisplay\PhoneHomePanel.java","$source\src\cn\ucvl\zhaodisplay\PhonePowerModel.java","$source\src\cn\ucvl\zhaodisplay\PhoneHomeSession.java","$source\src\cn\ucvl\zhaodisplay\PhoneStyle.java","$source\src\cn\ucvl\zhaodisplay\VoicePanel.java","$source\src\cn\ucvl\zhaodisplay\VoiceSurface.java","$source\src\cn\ucvl\zhaodisplay\VoiceChat.java","$source\src\cn\ucvl\zhaodisplay\VoiceGesture.java","$source\src\cn\ucvl\zhaodisplay\LocationCadence.java") + @((Get-ChildItem "$tests\phone-preview" -Filter "*.java").FullName) & "$jdk\bin\javac.exe" -encoding UTF-8 -source 8 -target 8 -cp $android -d "$stage\classes" @sources if($LASTEXITCODE){throw 'Test Java compile failed'} & "$jdk\bin\jar.exe" cf "$stage\classes.jar" -C "$stage\classes" . diff --git a/android-display/tests/phone-preview/DisplayApi.java b/android-display/tests/phone-preview/DisplayApi.java index 572877b..b42c571 100644 --- a/android-display/tests/phone-preview/DisplayApi.java +++ b/android-display/tests/phone-preview/DisplayApi.java @@ -6,6 +6,7 @@ final class DisplayApi { static class ApiError extends Exception {final int status;ApiError(int status){this.status=status;}} static JSONObject call(String path,String token,JSONObject body)throws Exception{ if(expired)throw new ApiError(401);if(offline)throw new ApiError(503);String action=body.optString("action"); + if(path.equals("/api/phone/home"))return HomeFixture.call(token,body); if(path.equals("/api/voice")){ if(action.equals("history")){boolean old=body.optLong("before")>0;JSONArray items=new JSONArray();for(int i=0;i<3;i++)items.put(new JSONObject().put("id","chat-"+i).put("seq",i+1).put("mine",i%2==0).put("senderName",i%2==0?"示例成员的手机":"家庭显示终端").put("at",1792387200+i*60-(old?86400:0)).put("seconds",i+3.6).put("delivery",i==2?"queued":"played").put("archive",i==2?"pending":"cloud"));return new JSONObject().put("items",items).put("before",old?0:12);} return new JSONObject("{\"enabled\":false,\"allowed\":[],\"candidates\":[{\"id\":\"phone:demo\",\"name\":\"示例家人的手机\"}],\"targets\":[{\"id\":\"display:demo\",\"archiveKey\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"name\":\"家庭显示终端\",\"kind\":\"display\",\"online\":true}],\"conversations\":[],\"sent\":[],\"inbox\":[]}"); diff --git a/android-display/tests/phone-preview/HomeFixture.java b/android-display/tests/phone-preview/HomeFixture.java new file mode 100644 index 0000000..0ec431c --- /dev/null +++ b/android-display/tests/phone-preview/HomeFixture.java @@ -0,0 +1,36 @@ +package cn.ucvl.zhaodisplay; + +import org.json.*; + +/** Entirely synthetic grants and machines. Test APK has no Internet permission. */ +final class HomeFixture { + static volatile String mode="";static volatile int commands;static volatile JSONObject lastCommand; + static volatile boolean holdNextCatalog=false,held=false,release=false; + static JSONObject power(String id)throws Exception{ + long now=System.currentTimeMillis()/1000;boolean offline=id.equals("demo-offline"),unknown=mode.equals("devices-unknown"); + int op=mode.equals("devices-pending")?2:0; + JSONObject p=new JSONObject().put("run",unknown?JSONObject.NULL:offline?0:1).put("op",op).put("state",unknown?"unknown":offline?"offline":"online").put("checkedAt",now-(mode.equals("devices-stale")?90:0)).put("canStart",offline&&!unknown&&op==0).put("canShutdown",!offline&&!unknown&&op==0&&!mode.equals("devices-view-only")).put("managed",true); + p.put("last",op==0?JSONObject.NULL:new JSONObject().put("id","bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb").put("op",2).put("status","pending").put("result","等待设备确认").put("at",now));return p; + } + static JSONObject device(String id,String name,String family)throws Exception{return new JSONObject().put("id",id).put("source","managed").put("name",name).put("deviceType","computer").put("familyId",family).put("familyName",family.equals("demo-home")?"演示家庭":"演示工作室").put("siteName","演示书房").put("power",power(id));} + static JSONObject call(String token,JSONObject body)throws Exception{ + if(token==null||token.isEmpty())throw new AssertionError("phone home requires the pairing bearer token"); + if(mode.equals("devices-denied"))throw new DisplayApi.ApiError(403); + String action=body.getString("action"); + if(action.equals("catalog")){ + JSONArray families=new JSONArray().put(new JSONObject().put("id","demo-home").put("name","演示家庭").put("kind","family")); + JSONArray devices=new JSONArray(); + if(!mode.equals("devices-empty")&&!token.equals("rebound-token")){families.put(new JSONObject().put("id","demo-office").put("name","演示工作室").put("kind","office"));devices.put(device("demo-online","演示笔记本","demo-home")).put(device("demo-offline","演示工作电脑","demo-office"));} + JSONObject result=new JSONObject().put("households",families).put("devices",devices).put("activeId","demo-home"); + if(holdNextCatalog){holdNextCatalog=false;held=true;long until=System.currentTimeMillis()+5000;while(!release&&System.currentTimeMillis(){ + PhoneHomePanel panel=a.phoneHome; + if(a.mode.equals("devices-denied")){a.check(panel.devices.getChildCount()==0,"denied grant clears device cards");a.selectTab(PhoneLayout.DEVICES);later(()->{a.check(text(a.phone.pages[PhoneLayout.DEVICES],"授权"),"denied access is explicit");done.run();});return;} + a.check(text(panel.households,"演示家庭"),"paired household remains visible"); + if(a.mode.equals("devices-empty")){a.check(panel.devices.getChildCount()==0,"pairing alone grants no devices");a.selectTab(PhoneLayout.DEVICES);later(()->{a.check(text(a.phone.pages[PhoneLayout.DEVICES],"管理员"),"empty grant tells user to contact administrator");done.run();});return;} + a.check(panel.households.getChildCount()==2,"only API-authorized households shown"); + if(a.mode.startsWith("households")){done.run();return;} + button(panel.households,"查看设备").performClick(); + later(()->{ + a.check(a.phone.tab==PhoneLayout.DEVICES,"household selection opens device page"); + a.check(panel.devices.getChildCount()==1&&text(panel.devices,"演示笔记本")&&!text(panel.devices,"演示工作电脑"),"family selection scopes visible devices"); + a.check(text(panel.devices,"演示书房")&&text(panel.devices,"RUN")&&text(panel.devices,"OP")&&text(panel.devices,"检查时间")&&text(panel.devices,"最近结果"),"managed card exposes location and measured state details"); + Button start=button(panel.devices,"开机"),stop=button(panel.devices,"关机"); + a.check(!start.isEnabled(),"online device start disabled"); + boolean blocked=a.mode.equals("devices-stale")||a.mode.equals("devices-unknown")||a.mode.equals("devices-pending")||a.mode.equals("devices-view-only"); + a.check(stop.isEnabled()!=blocked,"shutdown follows freshness, pending OP and explicit grant"); + if(a.mode.equals("devices-stale")||a.mode.equals("devices-unknown"))a.check(text(panel.devices,"未知"),"stale/unknown RUN never presented as online"); + a.check(start.getHeight()>=a.style.dp(48)&&stop.getHeight()>=a.style.dp(48),"power controls preserve touch targets on narrow/large text views"); + a.check(stop.getWidth()>a.style.dp(150),"stacked controls retain usable width"); + if(a.mode.equals("devices-token")||a.mode.equals("devices-lifecycle")){ + HomeFixture.release=false;HomeFixture.holdNextCatalog=true;panel.deviceRefresh.performClick(); + later(()->{a.check(HomeFixture.held,"catalog response is delayed at the network boundary"); + if(a.mode.equals("devices-token")){a.prefs.edit().putString("token","rebound-token").commit();panel.contextChanged();}else panel.active(false); + HomeFixture.release=true;later(()->{a.check(panel.devices.getChildCount()==0,"old identity/lifecycle callback cannot restore device grants"); + if(a.mode.equals("devices-lifecycle")){panel.active(true);later(()->{a.check(panel.devices.getChildCount()==1,"resume reloads authorized current catalog");done.run();});}else done.run(); + }); + });return; + } + if(a.mode.equals("devices-revoked")){ + HomeFixture.mode="devices-denied";panel.deviceRefresh.performClick();later(()->{a.check(panel.devices.getChildCount()==0&&text(a.phone.pages[PhoneLayout.DEVICES],"授权"),"revocation clears previously visible controls");done.run();});return; + } + if(a.mode.equals("devices-command")){ + int before=HomeFixture.commands;stop.performClick();a.check(panel.confirmation!=null&&panel.confirmation.isShowing(),"shutdown has native confirmation");a.check(HomeFixture.commands==before,"opening confirmation never dispatches");panel.confirmation.getButton(AlertDialog.BUTTON_NEGATIVE).performClick();a.check(HomeFixture.commands==before,"cancel leaves machine untouched");stop.performClick();panel.confirmation.getButton(AlertDialog.BUTTON_POSITIVE).performClick(); + later(()->{a.check(HomeFixture.commands==before+1&&HomeFixture.lastCommand.optInt("op")==2,"confirmed shutdown dispatches exactly once");a.check(!button(panel.devices,"关机").isEnabled(),"pending command disables repeat");done.run();});return; + } + if(a.mode.equals("devices-offline")){ + a.selectTab(PhoneLayout.HOUSEHOLDS);later(()->{button((ViewGroup)panel.households.getChildAt(1),"查看设备").performClick();later(()->{a.check(text(panel.devices,"RUN 0")&&button(panel.devices,"开机").isEnabled()&&!button(panel.devices,"关机").isEnabled(),"offline explicit control grant enables only start");done.run();});});return; + } + done.run(); + }); + }); + } +} diff --git a/android-display/tests/phone-preview/PhonePreviewActivity.java b/android-display/tests/phone-preview/PhonePreviewActivity.java index 7f3c7e8..2160af8 100644 --- a/android-display/tests/phone-preview/PhonePreviewActivity.java +++ b/android-display/tests/phone-preview/PhonePreviewActivity.java @@ -11,14 +11,14 @@ public class PhonePreviewActivity extends LocationActivity { protected void attachBaseContext(android.content.Context base){android.content.res.Configuration c=new android.content.res.Configuration(base.getResources().getConfiguration());c.densityDpi=420;super.attachBaseContext(base.createConfigurationContext(c));} public void onCreate(Bundle state){ mode=getIntent().getStringExtra("mode");if(mode==null)mode="family"; - if(mode.equals("large")||mode.equals("settings-large")||mode.equals("voice-large")){android.content.res.Configuration cfg=new android.content.res.Configuration(getResources().getConfiguration());cfg.fontScale=1.35f;getResources().updateConfiguration(cfg,getResources().getDisplayMetrics());} - DisplayApi.offline="offline".equals(mode);DisplayApi.expired="expired".equals(mode); + if(mode.equals("large")||mode.equals("settings-large")||mode.equals("voice-large")||mode.equals("devices-large")){android.content.res.Configuration cfg=new android.content.res.Configuration(getResources().getConfiguration());cfg.fontScale=1.35f;getResources().updateConfiguration(cfg,getResources().getDisplayMetrics());} + HomeFixture.mode=mode;DisplayApi.offline="offline".equals(mode);DisplayApi.expired="expired".equals(mode); getSharedPreferences("location",0).edit().clear().putString("token","unpaired".equals(mode)?"":"synthetic-token").putString("memberName","示例成员").putString("home","我的家 · 演示家庭").putLong("expires",System.currentTimeMillis()+86400000L).putString("status","共享关闭 · 可以查看已授权的家人").apply(); super.onCreate(state); // Limit the actual Activity layout to a phone viewport without changing display configuration. ((android.view.ViewGroup)phone.getParent()).removeView(phone);FrameLayout outer=new FrameLayout(this);outer.setBackgroundColor(PhoneStyle.PAPER); - int width="narrow".equals(mode)||"large".equals(mode)||"voice-large".equals(mode)?320:390;outer.addView(phone,new FrameLayout.LayoutParams(style.dp(width),style.dp("narrow".equals(mode)?640:844),Gravity.TOP|Gravity.CENTER_HORIZONTAL));previewRoot=phone;setContentView(outer); - new Handler().postDelayed(()->{try{exercise();if(mode.equals("history"))exerciseHistory();else if(mode.equals("cycles"))LocationCycleChecks.run(this,this::save);else if(mode.equals("storage")){QueueStorageChecks.run(this);save();}else save();}catch(Exception e){throw new RuntimeException(e);}},1800); + int width="narrow".equals(mode)||"large".equals(mode)||"voice-large".equals(mode)||"devices-narrow".equals(mode)||"devices-large".equals(mode)?320:390;outer.addView(phone,new FrameLayout.LayoutParams(style.dp(width),style.dp("narrow".equals(mode)?640:844),Gravity.TOP|Gravity.CENTER_HORIZONTAL));previewRoot=phone;setContentView(outer); + new Handler().postDelayed(()->{try{exercise();if(mode.startsWith("devices")||mode.startsWith("households"))HomePanelChecks.run(this,this::save);else if(mode.equals("history"))exerciseHistory();else if(mode.equals("cycles"))LocationCycleChecks.run(this,this::save);else if(mode.equals("storage")){QueueStorageChecks.run(this);save();}else save();}catch(Exception e){throw new RuntimeException(e);}},1800); } void check(boolean condition,String message){if(!condition)throw new AssertionError(message);} void exercise()throws Exception{ @@ -28,32 +28,32 @@ public class PhonePreviewActivity extends LocationActivity { check(map.items.optJSONObject(0).optString("id").equals("c")&&map.items.optJSONObject(2).optString("id").equals("b"),"collection time descending, missing fixes last"); ((android.view.ViewGroup)familyList.getChildAt(0)).getChildAt(1).performClick();check(map.focused==map.items.optJSONObject(0).optJSONObject("position"),"row focuses the matching point"); check(voice.getParent()==null,"no voice dock on the position page");check(voice.dock.receiverCard.getParent()==phone.voiceSettings,"receiver controls belong to my settings"); - phone.nav.getChildAt(2).performClick();check(phone.tab==2,"mine tab click");phone.sampling.performClick();check(detailDialog!=null&&detailDialog.isShowing(),"sampling opens full screen");detailDialog.dismiss(); + phone.nav.getChildAt(PhoneLayout.MINE).performClick();check(phone.tab==PhoneLayout.MINE,"mine tab click");phone.sampling.performClick();check(detailDialog!=null&&detailDialog.isShowing(),"sampling opens full screen");detailDialog.dismiss(); check(sampleCadence.getParent()==sampleSection,"sample controls retain their owner"); phone.upload.performClick();check(detailDialog!=null,"upload detail");detailDialog.dismiss(); - phone.nav.getChildAt(0).performClick();check(phone.tab==0,"family navigation"); + phone.nav.getChildAt(PhoneLayout.LOCATION).performClick();check(phone.tab==PhoneLayout.LOCATION,"family navigation"); check(!prefs.getBoolean("active",false),"navigation never enables sharing"); } if(mode.equals("modes")){ - selectTab(2);sharingMode.setSelection(1);check(samplePeriodSeconds()==10&&uploadPeriod()==10,"realtime fixes both cadences to ten seconds"); + selectTab(PhoneLayout.MINE);sharingMode.setSelection(1);check(samplePeriodSeconds()==10&&uploadPeriod()==10,"realtime fixes both cadences to ten seconds"); sharingMode.setSelection(0);check(samplePeriodSeconds()==300&&uploadPeriod()==7200,"scheduled controls retain independent cadences"); check(!prefs.getBoolean("active",false),"choosing a mode never enables sharing"); } - if(mode.equals("mine")||mode.equals("large"))selectTab(2); + if(mode.equals("mine")||mode.equals("large"))selectTab(PhoneLayout.MINE); else if(mode.equals("voice")||mode.equals("voice-large")||mode.equals("recording")||mode.equals("cancel")||mode.equals("narrow")||mode.equals("history")){ - selectTab(1);voice.ui.removeCallbacks(voice.visual);VoiceSurface v=voice.page();v.expand.setVisibility(View.GONE);v.destination(new JSONObject("{\"name\":\"家庭显示终端\",\"kind\":\"display\",\"online\":true}"),true);v.recipient.setText("家庭显示终端");v.status.setText("界面验收 · 不录音、不发送语音"); + selectTab(PhoneLayout.COMMUNICATION);voice.ui.removeCallbacks(voice.visual);VoiceSurface v=voice.page();v.expand.setVisibility(View.GONE);v.destination(new JSONObject("{\"name\":\"家庭显示终端\",\"kind\":\"display\",\"online\":true}"),true);v.recipient.setText("家庭显示终端");v.status.setText("界面验收 · 不录音、不发送语音"); boolean recording=mode.equals("recording")||mode.equals("cancel");for(int i=0;i<31;i++)v.recording(recording,mode.equals("cancel"),8000,(int)(9000*Math.abs(Math.sin(i))),false,true); } - else if(mode.equals("unpaired")){check(shareControls.getVisibility()==View.GONE,"unpaired share controls hidden");check(phone.tab==2,"unpaired starts on my page");} - else selectTab(0); + else if(mode.equals("unpaired")){check(shareControls.getVisibility()==View.GONE,"unpaired share controls hidden");check(phone.tab==PhoneLayout.MINE,"unpaired starts on my page");} + else selectTab(PhoneLayout.LOCATION); if(mode.equals("expired")){check(pairingRequired(),"expired requires re-pairing");check(!sharing.isEnabled(),"expired cannot start sharing");phone.check.performClick();check(detailDialog!=null&&pairSection.getParent()!=settings,"status routes to pairing instead of OS permission settings");detailDialog.dismiss();} if(mode.equals("offline")){check(familyList.getChildCount()==0,"offline stale positions removed");check(!sharing.isEnabled(),"offline cannot start sharing");} - check(phone.nav.getChildCount()==3,"exactly three tabs");check(phone.navLabels[0].getText().toString().equals("位置")&&phone.navLabels[1].getText().toString().equals("沟通"),"requested navigation names"); + check(phone.nav.getChildCount()==5,"exactly five tabs");String[] names={"位置","家庭","设备","沟通","我的"};for(int i=0;i{check(voice.nextBefore==12,"history initial page");voice.page().chat.older.performClick();new Handler().postDelayed(()->{check(voice.historyBefore==12&&voice.nextBefore==0,"older page loaded");check(!voice.page().chat.older.isEnabled(),"end of history disables older");voice.page().chat.latest.performClick();new Handler().postDelayed(()->{check(voice.historyBefore==0&&voice.nextBefore==12,"return to latest page");check(!voice.enabled,"reading history does not enable reception");save();},250);},250);},250); } - void save(){previewRoot.postDelayed(()->{try{if(detailDialog==null)check(sampleSection.getParent()==settings&&uploadSection.getParent()==settings,"dismissed forms safely returned after queued dialog callbacks");else{EditText field=mode.equals("pair-settings")?code:mode.equals("upload-settings")?customAmount:sampleAmount;check(field.getHeight()>=style.dp(48),"form fields retain accessible touch height");check(field.getWidth()>style.dp(60),"custom amount retains usable width");if(!mode.equals("pair-settings")){LinearLayout period=mode.equals("upload-settings")?customPeriod:samplePeriod;View unit=mode.equals("upload-settings")?customUnit:sampleUnit;check(unit.getBottom()<=period.getHeight(),"unit selector is not clipped by baseline alignment");}}if(phone.tab==1){check(voice.page().chat.messages.getChildCount()==3,"real controller loads chat history");check(voice.nextBefore==12,"older history cursor available");check(voice.page().chat.scroll.getHeight()>=style.dp(90),"chat viewport="+voice.page().chat.scroll.getHeight()+", root="+voice.page().getHeight()+", chat="+voice.page().chat.getHeight()+", compose="+voice.page().compose.getHeight()+", compact="+voice.page().compact);check(voice.page().speak.getHeight()>=style.dp(110),"microphone remains a large target");}android.graphics.Bitmap b=android.graphics.Bitmap.createBitmap(previewRoot.getWidth(),previewRoot.getHeight(),android.graphics.Bitmap.Config.ARGB_8888);previewRoot.draw(new android.graphics.Canvas(b));try(java.io.FileOutputStream f=new java.io.FileOutputStream(new java.io.File(getExternalFilesDir(null),"preview.png"))){b.compress(android.graphics.Bitmap.CompressFormat.PNG,100,f);}b.recycle();try(java.io.FileWriter f=new java.io.FileWriter(new java.io.File(getExternalFilesDir(null),"checks.txt"))){f.write("PASS "+mode+" production navigation, chronological list, focus, chat visibility and settings ownership");}}catch(Exception e){throw new RuntimeException(e);}},600);} + void save(){previewRoot.postDelayed(()->{try{if(detailDialog==null)check(sampleSection.getParent()==settings&&uploadSection.getParent()==settings,"dismissed forms safely returned after queued dialog callbacks");else{EditText field=mode.equals("pair-settings")?code:mode.equals("upload-settings")?customAmount:sampleAmount;check(field.getHeight()>=style.dp(48),"form fields retain accessible touch height");check(field.getWidth()>style.dp(60),"custom amount retains usable width");if(!mode.equals("pair-settings")){LinearLayout period=mode.equals("upload-settings")?customPeriod:samplePeriod;View unit=mode.equals("upload-settings")?customUnit:sampleUnit;check(unit.getBottom()<=period.getHeight(),"unit selector is not clipped by baseline alignment");}}if(phone.tab==PhoneLayout.COMMUNICATION){check(voice.page().chat.messages.getChildCount()==3,"real controller loads chat history");check(voice.nextBefore==12,"older history cursor available");check(voice.page().chat.scroll.getHeight()>=style.dp(90),"chat viewport="+voice.page().chat.scroll.getHeight()+", root="+voice.page().getHeight()+", chat="+voice.page().chat.getHeight()+", compose="+voice.page().compose.getHeight()+", compact="+voice.page().compact);check(voice.page().speak.getHeight()>=style.dp(110),"microphone remains a large target");}android.graphics.Bitmap b=android.graphics.Bitmap.createBitmap(previewRoot.getWidth(),previewRoot.getHeight(),android.graphics.Bitmap.Config.ARGB_8888);previewRoot.draw(new android.graphics.Canvas(b));try(java.io.FileOutputStream f=new java.io.FileOutputStream(new java.io.File(getExternalFilesDir(null),"preview.png"))){b.compress(android.graphics.Bitmap.CompressFormat.PNG,100,f);}b.recycle();try(java.io.FileWriter f=new java.io.FileWriter(new java.io.File(getExternalFilesDir(null),"checks.txt"))){f.write("PASS "+mode+" production navigation, chronological list, focus, chat visibility and settings ownership");}}catch(Exception e){throw new RuntimeException(e);}},600);} } diff --git a/android-display/tests/run-model-checks.ps1 b/android-display/tests/run-model-checks.ps1 new file mode 100644 index 0000000..4e03638 --- /dev/null +++ b/android-display/tests/run-model-checks.ps1 @@ -0,0 +1,14 @@ +param([string]$ToolRoot='C:\Users\Administrator\Documents\ChatGPT\优创未来\services\toplc-vpn-android\.tools') +$ErrorActionPreference='Stop' +$source=Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path) +$stage=Join-Path $env:TEMP ('ZhaoPhoneModel-'+[guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $stage | Out-Null +$jdk=Join-Path $ToolRoot 'jdk-staging\jdk-21.0.12.1+1' +$files=@('PhonePowerModel','PhoneHomeSession','LocationCadence','VoiceGesture','ServerEndpoint') | ForEach-Object {Join-Path $source "src\cn\ucvl\zhaodisplay\$_.java"} +$tests=@('PhonePowerModelTest','LocationCadenceTest','VoiceGestureTest','ServerEndpointTest') | ForEach-Object {Join-Path $source "tests\$_.java"} +& "$jdk\bin\javac.exe" -encoding UTF-8 -d $stage @files @tests +if($LASTEXITCODE){throw 'Phone model Java compilation failed'} +foreach($test in @('PhonePowerModelTest','LocationCadenceTest','VoiceGestureTest','ServerEndpointTest')){ + & "$jdk\bin\java.exe" -cp $stage "cn.ucvl.zhaodisplay.$test" + if($LASTEXITCODE){throw "$test failed"} +} diff --git a/app.py b/app.py index 1d52b16..3220c13 100644 --- a/app.py +++ b/app.py @@ -50,6 +50,8 @@ import recording_archive import app_downloads import map_service import location_history +import device_power +import device_types ROOT = Path(__file__).resolve().parent os.umask(0o077) @@ -108,6 +110,8 @@ HISTORY = location_history.History(sys.modules[__name__]) VOICE = family_voice.Voice(sys.modules[__name__]) MEMBERS = family_members.Members(sys.modules[__name__]) ARCHIVE = recording_archive.Archive(sys.modules[__name__]) +POWER = device_power.Power(sys.modules[__name__]) +TYPES = device_types.DeviceTypes(sys.modules[__name__]) def setting(key, default=None): @@ -698,6 +702,11 @@ class Handler(BaseHTTPRequestHandler): def do_POST(self): try: path = url.urlsplit(self.path).path + if path == '/api/device-power/agent': + self.answer(POWER.agent(self.body(16384))); return + if path == '/api/phone/home': + authorization=self.headers.get('Authorization','') + self.answer(POWER.phone(authorization[7:] if authorization.startswith('Bearer ') else '',self.body(16384))); return if path == '/api/voice': authorization=self.headers.get('Authorization','') self.answer(VOICE.native(authorization[7:] if authorization.startswith('Bearer ') else '',self.body(220000))) @@ -736,7 +745,7 @@ class Handler(BaseHTTPRequestHandler): self.login(data, path == '/api/setup') return self.require_auth() - if path not in ('/api/locations', '/api/location-history', '/api/logout', '/api/account/password', '/api/preferences', '/api/households/layout', '/api/family/restore', + if path not in ('/api/device-power', '/api/locations', '/api/location-history', '/api/logout', '/api/account/password', '/api/preferences', '/api/households/layout', '/api/family/restore', '/api/family/person', '/api/family/link', '/api/family/event', '/api/heritage', '/api/ptz', '/api/ptz/presets', '/api/journal', '/api/journal/action', '/api/journal/upload', '/api/journal/finish', '/api/journal/pause', '/api/journal/draft', '/api/journal/abandon-draft', '/api/journal/remove-upload', '/api/journal/restore-upload'): self.require_manager() @@ -747,6 +756,16 @@ class Handler(BaseHTTPRequestHandler): self.answer({'ok': True}, cookie='vision=; Path=/; Max-Age=0; HttpOnly; SameSite=Strict') elif path == '/api/locations': self.answer(LOCATIONS.manage(self.user,data)) + elif path == '/api/device-power': + self.answer(POWER.web(self.user,data)) + elif path == '/api/device-types': + self.answer(TYPES.bind(self.user,data) if data.get('action')=='bind' else TYPES.manage(self.user,data)) + elif path == '/api/data-types': + self.answer(TYPES.save_data_type(self.user,data)) + elif path == '/api/view-types': + self.answer(TYPES.save_view_type(self.user,data)) + elif path == '/api/device-views': + self.answer(TYPES.save_view(self.user,data)) elif path == '/api/maps': self.require_admin() if data.get('action')!='retry':raise Problem('地图操作不正确') @@ -1065,6 +1084,19 @@ class Handler(BaseHTTPRequestHandler): self.answer(ACCOUNTS.state(self.user, status())) elif path == '/api/locations': self.answer(LOCATIONS.snapshot(self.user)) + elif path == '/api/device-power': + self.answer(POWER.read(self.user,query.get('id'))) + elif path == '/api/device-types': + self.answer(TYPES.listing(self.user)) + elif path == '/api/data-types': + self.answer(TYPES.data_listing(self.user)) + elif path == '/api/view-types': + self.answer(TYPES.view_listing(self.user)) + elif path == '/api/device-views': + self.answer(TYPES.views(self.user,query.get('dataInstanceId') or query.get('deviceId'))) + elif path == '/api/device-data': + item=POWER.web_device(self.user,query.get('id')) + self.answer({'instance':INVENTORY.display(item)['dataInstance']}) elif path == '/api/maps': self.require_admin();self.answer(MAPS.archive.status()) elif path == '/api/location-history': @@ -1301,6 +1333,7 @@ def initialize(): FAMILY.initialize() ACCOUNTS.initialize() HOUSEHOLDS.initialize() + TYPES.initialize() MEMBERS.initialize() DISPLAYS.initialize() LOCATIONS.initialize() @@ -1309,6 +1342,7 @@ def initialize(): ARCHIVE.initialize() HERITAGE.initialize() JOURNAL.initialize() + POWER.initialize() if not setting('storage'): set_setting('storage', DEFAULT_STORAGE) if not setting('mediaSecret'): @@ -1333,6 +1367,7 @@ if __name__ == '__main__': threading.Thread(target=JOURNAL.watch, daemon=True).start() threading.Thread(target=MAPS.archive.watch, daemon=True).start() threading.Thread(target=HISTORY.watch, daemon=True).start() + threading.Thread(target=POWER.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 = [] diff --git a/baidu.py b/baidu.py index b5bd2c2..b7a76d5 100644 --- a/baidu.py +++ b/baidu.py @@ -100,7 +100,11 @@ class Baidu: if p.scheme != 'https' or not p.hostname or p.username or p.password or p.query or p.fragment or p.path != CALLBACK: raise a.Problem('回调地址须为 HTTPS 站点地址加 '+CALLBACK) changed = any(old.get(k) != v for k, v in dict(appKey=key, secretKey=secret, appFolder=folder, redirectUri=callback).items()) - if changed and saved['connections']: + identity_changed = any(old.get(k) != v for k, v in dict(appKey=key, secretKey=secret, appFolder=folder).items()) + # Moving this platform to a new HTTPS hostname does not change the + # authorized Baidu application or account. Keep its existing tokens; + # revision and pending-state invalidation prevent old OAuth completion. + if identity_changed and saved['connections']: raise a.Problem('已有网盘授权,修改应用前须先解除共享网盘连接', 409) saved['config'] = dict(appKey=key, secretKey=secret, appFolder=folder, redirectUri=callback, revision=old.get('revision', 0)+1) diff --git a/device_power.py b/device_power.py new file mode 100644 index 0000000..b753189 --- /dev/null +++ b/device_power.py @@ -0,0 +1,271 @@ +"""Scoped RUN/OP control: fixed WOL bridge and outbound-only signed shutdown.""" +import base64 +import hashlib +import hmac +import json +import os +from pathlib import Path +import re +import socket +import subprocess +import time + +HEX = re.compile(r'^[a-f0-9]{32}$') +TTL = 45 + +class Power: + def __init__(self, app): self.a=app + + def initialize(self): + a=self.a + with a.LOCK,a.DB: + a.DB.executescript(''' + CREATE TABLE IF NOT EXISTS power_states(id TEXT PRIMARY KEY,body TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS power_commands(id TEXT PRIMARY KEY,device_id TEXT,created REAL,body TEXT NOT NULL); + CREATE INDEX IF NOT EXISTS power_commands_device ON power_commands(device_id,created); + CREATE TABLE IF NOT EXISTS power_grants(device_id TEXT,person_id TEXT,family_id TEXT,control INTEGER,PRIMARY KEY(device_id,person_id)); + CREATE TABLE IF NOT EXISTS power_nonces(device_id TEXT,nonce TEXT,expires REAL,PRIMARY KEY(device_id,nonce)); + ''') + for c in self.commands(): + if c['status']=='pending':self.finish(c,'cancelled','服务已重启,旧命令不再执行') + a.DB.execute('DELETE FROM power_states') + + def profiles(self): + try: + path=Path(os.environ.get('VISION_POWER_CONFIG','/etc/zhaovision-power.json')) + if path.stat().st_size>65536:return {} + value=json.loads(path.read_text(encoding='utf-8')) + return value.get('devices',{}) if isinstance(value,dict) else {} + except (OSError,ValueError):return {} + + def profile(self,key): + item=self.a.get_object('devices',key);value=self.profiles().get(key) + if not item or not isinstance(value,dict) or value.get('enabled') is False:return None + if self.a.TYPES.instance(item).get('fbType')!='computer.power.v1':return None + return value if value.get('familyId')==self.a.HOUSEHOLDS.family_of(item) else None + + def managed(self,item):return bool(self.profile(item['id'])) + + def state(self,key): + row=self.a.DB.execute('SELECT body FROM power_states WHERE id=?',(key,)).fetchone() + return json.loads(row[0]) if row else dict(run=None,checkedAt=0,agentAt=0,ready=False,bootId='') + + def save_state(self,key,state): + self.a.DB.execute('INSERT OR REPLACE INTO power_states VALUES (?,?)',(key,json.dumps(state)));self.a.DB.commit() + + def commands(self,key=None): + sql='SELECT body FROM power_commands'+(' WHERE device_id=?' if key else '')+' ORDER BY created DESC,rowid DESC' + return [json.loads(r[0]) for r in self.a.DB.execute(sql,(key,) if key else ())] + + def save_command(self,c): + self.a.DB.execute('INSERT OR REPLACE INTO power_commands VALUES (?,?,?,?)',(c['id'],c['deviceId'],c['created'],json.dumps(c)));self.a.DB.commit() + + def finish(self,c,status,result): + c.update(status=status,result=result,at=time.time());self.save_command(c) + + def pending(self,key): + for c in self.commands(key): + if c['status']!='pending':continue + if time.time()>=c['expires']:self.finish(c,'timeout','等待设备状态变化超时,请核对设备后重新操作') + elif not self.profile(key):self.finish(c,'cancelled','设备归属或控制配置已变更') + elif not self.actor_allowed(c):self.finish(c,'cancelled','控制授权已失效') + else:return c + return None + + def observe(self,key,run): + if run is not None and (type(run) is not int or run not in (0,1)):raise ValueError('RUN') + with self.a.LOCK: + state=self.state(key);state.update(run=run,checkedAt=time.time());self.save_state(key,state);c=self.pending(key) + if c and c['op']==1 and c.get('sent') and run==1:self.finish(c,'succeeded','设备已在线') + if c and c['op']==2 and c.get('ack')=='scheduled' and run==0:self.finish(c,'succeeded','安全关机已受理,设备已离线') + + def power(self,key,control=False): + with self.a.LOCK: + managed=bool(self.profile(key));c=self.pending(key);state=self.state(key);now=time.time() + run=state['run'] if managed and 0<=now-state['checkedAt']<=TTL else None + ready=state.get('ready') and 0<=now-state.get('agentAt',0)<=35 + commands=self.commands(key);last=commands[0] if commands else None + return dict(run=run,op=c['op'] if c else 0,state={0:'offline',1:'online',None:'unknown'}[run],checkedAt=state['checkedAt'],managed=managed, + canStart=bool(control and managed and run==0 and not c),canShutdown=bool(control and managed and run==1 and ready and not c), + last={k:last[k] for k in ('id','op','status','result','at')} if last else None) + + def web_device(self,user,key): + a=self.a;item=a.HOUSEHOLDS.owns(user,a.get_object('devices',key)) + if not a.HOUSEHOLDS.manager(user) and item.get('siteId') not in a.HOUSEHOLDS.site_ids(user):raise a.Problem('没有这个区域设备的访问权限',403) + return item + + def grant_row(self,key,person): + item=self.a.get_object('devices',key) + if not item:return None + return self.a.DB.execute('SELECT * FROM power_grants WHERE device_id=? AND person_id=? AND family_id=?',(key,person,self.a.HOUSEHOLDS.family_of(item))).fetchone() + + def web_control(self,user,key): + if self.a.HOUSEHOLDS.manager(user):return True + row=self.grant_row(key,user.get('personId',''));return bool(row and row['control']) + + def candidates(self,user): + a=self.a;result={} + for row in a.DB.execute('SELECT family_id,member_id FROM member_location_shares WHERE expires>?',(time.time(),)): + if user.get('role')!='admin' and row['family_id']!=a.HOUSEHOLDS.scope(user):continue + eligible=a.LOCATIONS.eligible(row['family_id'],row['member_id']) + if eligible: + _,person=eligible;result[person['id']]=dict(personId=person['id'],name=person['name']) + return list(result.values()) + + def read(self,user,key): + with self.a.LOCK: + item=self.web_device(user,key);manage=self.a.HOUSEHOLDS.manager(user) + grants=[dict(personId=r['person_id'],view=True,control=bool(r['control'])) for r in self.a.DB.execute('SELECT * FROM power_grants WHERE device_id=? AND family_id=?',(key,self.a.HOUSEHOLDS.family_of(item)))] if manage else [] + return dict(power=self.power(key,self.web_control(user,key)),canManage=manage,grants=grants,candidates=self.candidates(user) if manage else []) + + def phone_identity(self,token=None,sid=None): + a=self.a + if token is not None: + if not isinstance(token,str) or not 40<=len(token)<=128:raise a.Problem('请重新配对手机',401) + row=a.DB.execute('SELECT * FROM member_location_shares WHERE token_hash=?',(hashlib.sha256(token.encode()).hexdigest(),)).fetchone() + else:row=a.DB.execute('SELECT * FROM member_location_shares WHERE id=?',(sid,)).fetchone() + eligible=a.LOCATIONS.eligible(row['family_id'],row['member_id']) if row and row['expires']>time.time() else None + if not eligible:raise a.Problem('手机配对已失效,请重新配对',401) + return row,eligible[1] + + def actor_allowed(self,c): + a=self.a + try: + if c['actor'].startswith('phone:'): + _,person=self.phone_identity(sid=c['actor'][6:]);grant=self.grant_row(c['deviceId'],person['id']);return bool(grant and grant['control']) + user=a.get_object('users',c['actor'][4:]) + if not user or user.get('disabled'):return False + user=a.HOUSEHOLDS.context(user,c['familyId']);self.web_device(user,c['deviceId']);return self.web_control(user,c['deviceId']) + except a.Problem:return False + + def command(self,key,data,actor,control): + a=self.a + with a.LOCK: + if not control:raise a.Problem('没有设备控制权限',403) + op=data.get('op');rid=data.get('requestId','') + if type(op) is not int or op not in (1,2) or not isinstance(rid,str) or not HEX.fullmatch(rid) or data.get('confirm') is not True:raise a.Problem('请确认有效的启动或安全关机操作') + old=a.DB.execute('SELECT body FROM power_commands WHERE id=?',(rid,)).fetchone() + if old: + previous=json.loads(old[0]) + if previous['deviceId']!=key or previous['actor']!=actor or previous['op']!=op:raise a.Problem('请求编号已使用',409) + return dict(power=self.power(key,control)) + state=self.power(key,control) + if not state['canStart' if op==1 else 'canShutdown']:raise a.Problem('当前状态不允许此操作,请刷新设备状态',409) + now=time.time() + if a.DB.execute('SELECT count(*) FROM power_commands WHERE device_id=? AND created>?',(key,now-60)).fetchone()[0]>=10:raise a.Problem('操作过于频繁,请稍后重试',429) + c=dict(id=rid,deviceId=key,familyId=a.HOUSEHOLDS.family_of(a.get_object('devices',key)),actor=actor,op=op,created=now,at=now,expires=now+120,status='pending', + result='等待发送唤醒' if op==1 else '等待安全关机端接收',bootId=self.state(key).get('bootId'),sent=False,ack=None) + self.save_command(c);a.audit('设备电源操作',a.get_object('devices',key)['name']+(':启动' if op==1 else ':安全关机')) + return dict(power=self.power(key,control)) + + def web(self,user,data): + a=self.a;key=data.get('deviceId') + with a.LOCK: + item=self.web_device(user,key) + if data.get('action')=='command':return self.command(key,data,'web:'+user['id'],self.web_control(user,key)) + if data.get('action')!='grants':raise a.Problem('设备操作不正确') + if not a.HOUSEHOLDS.manager(user):raise a.Problem('仅场所管理员可以授权',403) + grants=data.get('grants');allowed={r['personId'] for r in self.candidates(user)} + if not isinstance(grants,list) or len(grants)>100:raise a.Problem('授权名单不正确') + valid={} + for g in grants: + if not isinstance(g,dict) or g.get('personId') not in allowed or g.get('view') is not True or type(g.get('control')) is not bool:raise a.Problem('请从有效的已配对成员中选择授权对象') + valid[g['personId']]=g['control'] + with a.DB: + a.DB.execute('DELETE FROM power_grants WHERE device_id=?',(key,)) + for person,control in valid.items():a.DB.execute('INSERT INTO power_grants VALUES (?,?,?,?)',(key,person,a.HOUSEHOLDS.family_of(item),int(control))) + self.pending(key);a.audit('设备控制授权',item['name']);return self.read(user,key) + + def phone(self,token,data): + a=self.a + with a.LOCK: + identity,person=self.phone_identity(token);key=data.get('deviceId');action=data.get('action') + if action=='catalog': + home=a.get_object('households',identity['family_id']);homes={home['id']:home} if home else {};devices=[] + for row in a.DB.execute('SELECT device_id FROM power_grants WHERE person_id=?',(person['id'],)): + key=row['device_id'];grant=self.grant_row(key,person['id']);item=a.get_object('devices',key) + if not grant or not item:continue + family=a.get_object('households',a.HOUSEHOLDS.family_of(item)) + if not family:continue + homes[family['id']]=family;site=a.get_object('sites',item.get('siteId')) + devices.append(dict(id=key,source='device',name=item['name'],deviceType=item['deviceType'],familyId=family['id'],familyName=family['name'],siteName=site['name'] if site else '',power=self.power(key,bool(grant['control'])) if self.profile(key) else None)) + return dict(households=[dict(id=h['id'],name=h['name'],kind=h.get('kind','home')) for h in homes.values()],devices=devices,activeId=identity['family_id']) + grant=self.grant_row(key,person['id']) + if not grant:raise a.Problem('没有此设备的授权',403) + if action=='status':return dict(power=self.power(key,bool(grant['control']))) + if action=='command':return self.command(key,data,'phone:'+identity['id'],bool(grant['control'])) + raise a.Problem('设备操作不正确') + + def agent(self,envelope): + a=self.a + try: + raw=envelope['payload'];signature=envelope['signature'] + if not isinstance(raw,str) or len(raw)>12000 or not isinstance(signature,str):raise ValueError() + payload=json.loads(base64.b64decode(raw,validate=True));key=payload['deviceId'];profile=self.profile(key) + if not profile:raise ValueError() + secret=base64.b64decode(profile['secret'],validate=True) + if len(secret)!=32 or not hmac.compare_digest(signature,hmac.new(secret,raw.encode('ascii'),hashlib.sha256).hexdigest()):raise ValueError() + nonce=payload['nonce'];boot=payload['bootId'];at=payload['at'] + if not HEX.fullmatch(nonce) or not HEX.fullmatch(boot) or type(at) not in (int,float) or not abs(time.time()-at)<=60 or type(payload['ready']) is not bool:raise ValueError() + except (KeyError,TypeError,ValueError,UnicodeError):raise a.Problem('设备认证未通过',401) + with a.LOCK: + now=time.time();a.DB.execute('DELETE FROM power_nonces WHERE expires device types (FBs) -> device/data instances -> view instances. + +Nothing in this module executes a function block or configures its server driver. +Instance properties are user parameters, never runtime signals or credentials. +""" +import copy +import math +import re +import secrets + + +BLOCKS = [ + dict(id='computer.power.v1', name='电脑电源执行驱动', + inputs=[dict(key='OP', name='操作命令', type='enum', values=[0, 1, 2], access='write', default=0)], + outputs=[dict(key='RUN', name='运行状态', type='boolean', nullable=True, access='read'), + dict(key='BUSY', name='操作处理中', type='boolean', access='read'), + dict(key='RESULT', name='最近操作结果', type='text', access='read')]), + dict(id='manual.v1', name='手动参数执行驱动', inputs=[], + outputs=[dict(key='properties', name='实例参数', type='object', access='read')]), +] +DATA_BUILTINS = [ + dict(id='computer-power',name='电脑电源数据类型',familyId='',fields=[],builtin=True,revision=1, + signals=[dict(key='RUN',name='运行状态',type='boolean',nullable=True,access='read',default=None), + dict(key='OP',name='操作命令',type='enum',values=[0,1,2],access='write',default=0), + dict(key='BUSY',name='操作处理中',type='boolean',access='read',default=False), + dict(key='RESULT',name='最近操作结果',type='text',access='read',default='')]), + dict(id='generic',name='通用参数数据类型',familyId='',fields=[],signals=[],builtin=True,revision=1), +] +BUILTINS = [ + dict(id='computer', name='电脑', familyId='', fbType='computer.power.v1', dataTypeId='computer-power', dataTypeRevision=1, fields=[], viewTemplate='power', builtin=True, revision=1), + dict(id='generic', name='通用设备', familyId='', fbType='manual.v1', dataTypeId='generic', dataTypeRevision=1, fields=[], viewTemplate='properties', builtin=True, revision=1), +] +VIEW_BUILTINS = [ + dict(id='properties',name='通用参数视图类型',familyId='',dataTypeId='generic',renderer='properties',builtin=True,revision=1), + dict(id='power',name='电脑电源视图类型',familyId='',dataTypeId='computer-power',renderer='power',builtin=True,revision=1), +] +RESERVED = {'run', 'op', 'busy', 'result', 'state', 'checkedat', 'canstart', 'canshutdown', 'managed', + 'powermanaged', 'last', 'id', 'familyid', 'deviceid', 'typeid', 'fbtype', 'viewtemplate', + 'properties', 'revision', 'bootid', 'nonce', 'signature', 'payload', 'sshkey', 'knownhosts', + 'datatypeid','datatype','datainstance'} +CREDENTIAL_PARTS = ('password', 'passphrase', 'secret', 'token', 'credential', 'privatekey', 'apikey', 'accesskey') +DEVICE_PUBLIC_FIELDS = {'id','name','deviceType','brand','model','serial','note','familyId','siteId','ownerName', + 'managerName','ownerRef','managerRef','managementHost','tailscaleHost','networkAccess', + 'connectionType','networkCidr','uplinkId','tags','powerManaged'} + + +class DeviceTypes: + def __init__(self, app): + self.a = app + + def initialize(self): + with self.a.LOCK, self.a.DB: + self.a.DB.execute('CREATE TABLE IF NOT EXISTS data_types (id TEXT PRIMARY KEY, body TEXT NOT NULL)') + self.a.DB.execute('CREATE TABLE IF NOT EXISTS device_types (id TEXT PRIMARY KEY, body TEXT NOT NULL)') + self.a.DB.execute('CREATE TABLE IF NOT EXISTS device_views (id TEXT PRIMARY KEY, body TEXT NOT NULL)') + self.a.DB.execute('CREATE TABLE IF NOT EXISTS view_types (id TEXT PRIMARY KEY, body TEXT NOT NULL)') + + def _family(self, user): + if not user or user.get('disabled'): + raise self.a.Problem('请使用当前家庭的有效账号', 403) + return self.a.HOUSEHOLDS.scope(user) + + def _manager(self, user): + family = self._family(user) + if not self.a.HOUSEHOLDS.manager(user): + raise self.a.Problem('只有当前家庭管理员可以管理设备类型与视图', 403) + return family + + def _object(self, data): + if not isinstance(data, dict): + raise self.a.Problem('请提交对象格式的参数') + return data + + def _shape(self, data, allowed): + self._object(data) + if set(data) - set(allowed): + raise self.a.Problem('包含不支持的参数;不能提交脚本或运行时配置') + if 'id' in data and data['id'] is not None and not isinstance(data['id'],str): + raise self.a.Problem('对象编号必须为文本') + + def _revision(self, value, expected): + if type(value) is not int or value != expected: + raise self.a.Problem('资料已更新,请刷新后重试', 409) + + def _number(self, value): + try: + valid = type(value) in (int, float) and math.isfinite(value) + except (OverflowError, TypeError): + valid = False + if not valid: + raise self.a.Problem('数值参数必须是有限数字,不能使用文本或布尔值') + return value + + def _value(self, field, value): + kind = field['type'] + if kind == 'text': + return self.a.clean_text(value, 500) + if kind == 'boolean': + if type(value) is not bool: + raise self.a.Problem('布尔参数只能为 true 或 false') + return value + value = self._number(value) + if 'min' in field and value < field['min'] or 'max' in field and value > field['max']: + raise self.a.Problem('参数“'+field['label']+'”超出类型允许范围') + return value + + def _fields(self, fields): + if not isinstance(fields, list) or len(fields) > 24: + raise self.a.Problem('每个类型最多定义 24 个实例参数') + result, used = [], set() + for raw in fields: + self._shape(raw, ('key','label','type','unit','default','min','max')) + key = raw.get('key') + if not isinstance(key, str) or not re.fullmatch(r'[A-Za-z][A-Za-z0-9_]{0,39}', key): + raise self.a.Problem('参数标识须为字母开头的 ASCII 字母、数字或下划线,最多 40 字符') + normalized = key.replace('_','').lower() + if key.lower() in used or normalized in RESERVED or any(part in normalized for part in CREDENTIAL_PARTS): + raise self.a.Problem('参数标识重复,或属于运行信号、身份或凭据保留名称') + used.add(key.lower()) + kind = raw.get('type') + if kind not in ('text','number','boolean'): + raise self.a.Problem('实例参数仅支持文本、数值和布尔类型') + field = dict(key=key, label=self.a.clean_text(raw.get('label',''),80,True), type=kind, + unit=self.a.clean_text(raw.get('unit',''),20)) + if kind != 'number' and ('min' in raw or 'max' in raw): + raise self.a.Problem('只有数值参数可以设置上下限') + for bound in ('min','max'): + if bound in raw:field[bound] = self._number(raw[bound]) + if 'min' in field and 'max' in field and field['min'] > field['max']: + raise self.a.Problem('参数下限不能大于上限') + field['default'] = self._value(field, raw.get('default', {'text':'','number':0,'boolean':False}[kind])) + result.append(field) + return result + + def _resolve(self, type_id, family): + if not isinstance(type_id, str):raise self.a.Problem('设备类型编号不正确') + for item in BUILTINS: + if item['id'] == type_id:return copy.deepcopy(item) + item = self.a.get_object('device_types', type_id) + if not item or item.get('familyId') != family: + raise self.a.Problem('设备类型不存在或不属于当前家庭', 404) + data_type = self._resolve_data(item.get('dataTypeId','generic'),family) + return dict(item,dataTypeId=data_type['id'],dataTypeRevision=data_type['revision'],fields=copy.deepcopy(data_type['fields'])) + + def _resolve_data(self, data_id, family): + if not isinstance(data_id,str):raise self.a.Problem('数据类型编号不正确') + for item in DATA_BUILTINS: + if item['id']==data_id:return copy.deepcopy(item) + item=self.a.get_object('data_types',data_id) + if not item or item.get('familyId')!=family:raise self.a.Problem('数据类型不存在或不属于当前家庭',404) + return item + + def data_listing(self,user): + with self.a.LOCK: + family=self._family(user) + rows=[item for item in self.a.objects('data_types') if item.get('familyId')==family] + return dict(types=copy.deepcopy(DATA_BUILTINS+rows),canManage=self.a.HOUSEHOLDS.manager(user)) + + def _compatible_instances(self,type_ids,definition,family): + for item in self.a.objects('devices'): + if item.get('typeId') not in type_ids or self.a.HOUSEHOLDS.family_of(item)!=family:continue + try:self._properties(definition,item.get('properties',{})) + except self.a.Problem: + raise self.a.Problem('数据结构变更会使已有设备实例参数失效,请先调整实例参数或使用新数据类型',409) + + def _save_data_definition(self,user,data): + family=self._manager(user) + self._shape(data,('action','id','name','familyId','fields','revision')) + if data.get('action')!='save':raise self.a.Problem('请选择保存数据类型') + if data.get('familyId',family)!=family:raise self.a.Problem('不能修改数据类型的家庭归属',403) + old=None + if data.get('id'): + old=self._resolve_data(data['id'],family) + if old.get('builtin'):raise self.a.Problem('内置数据类型及运行信号只读',403) + self._revision(data.get('revision'),old['revision']) + else:self._revision(data.get('revision',0),0) + item=dict(id=old['id'] if old else secrets.token_hex(8),name=self.a.clean_text(data.get('name',''),80,True), + familyId=family,fields=self._fields(data.get('fields',[])),signals=[],builtin=False,revision=old['revision']+1 if old else 1) + dependents=[row for row in self.a.objects('device_types') if row.get('familyId')==family and row.get('dataTypeId')==item['id']] + self._compatible_instances({row['id'] for row in dependents},item,family) + self.a.save_object('data_types',item) + for row in dependents: + self.a.save_object('device_types',dict(row,fields=copy.deepcopy(item['fields']),dataTypeRevision=item['revision'],revision=row['revision']+1)) + self.a.audit('保存数据类型',item['name']) + return item + + def save_data_type(self,user,data): + with self.a.LOCK: + self._save_data_definition(user,data) + return self.data_listing(user) + + def _resolve_view(self,view_id,family): + if not isinstance(view_id,str):raise self.a.Problem('视图类型编号不正确') + for row in VIEW_BUILTINS: + if row['id']==view_id:return copy.deepcopy(row) + row=self.a.get_object('view_types',view_id) + if not row or row.get('familyId')!=family:raise self.a.Problem('视图类型不存在或不属于当前家庭',404) + self._resolve_data(row['dataTypeId'],family) + return row + + def view_listing(self,user): + with self.a.LOCK: + family=self._family(user) + rows=[self._resolve_view(row['id'],family) for row in self.a.objects('view_types') if row.get('familyId')==family] + return dict(types=copy.deepcopy(VIEW_BUILTINS+rows),canManage=self.a.HOUSEHOLDS.manager(user)) + + def save_view_type(self,user,data): + with self.a.LOCK: + family=self._manager(user) + self._shape(data,('action','id','familyId','name','dataTypeId','dataTypeRevision','renderer','revision')) + if data.get('action')!='save':raise self.a.Problem('请选择保存视图类型') + if data.get('familyId',family)!=family:raise self.a.Problem('不能修改视图类型的家庭归属',403) + old=None + if data.get('id'): + old=self._resolve_view(data['id'],family) + if old.get('builtin'):raise self.a.Problem('内置视图类型只读',403) + self._revision(data.get('revision'),old['revision']) + else:self._revision(data.get('revision',0),0) + definition=self._resolve_data(data.get('dataTypeId'),family) + if 'dataTypeRevision' in data:self._revision(data['dataTypeRevision'],definition['revision']) + if data.get('renderer')!='properties':raise self.a.Problem('自定义视图类型只支持安全的参数卡片渲染器') + row=dict(id=old['id'] if old else secrets.token_hex(8),name=self.a.clean_text(data.get('name',''),80,True),familyId=family, + dataTypeId=definition['id'],renderer='properties',builtin=False,revision=old['revision']+1 if old else 1) + if old and old['dataTypeId']!=row['dataTypeId']: + for view in self.a.objects('device_views'): + if view.get('familyId')!=family or view.get('viewTypeId',view.get('templateId'))!=old['id']:continue + item=self.a.get_object('devices',view.get('dataInstanceId',view.get('deviceId'))) + if item and self.a.HOUSEHOLDS.family_of(item)==family and self.instance(item)['dataInstance']['dataTypeId']!=row['dataTypeId']: + raise self.a.Problem('已有视图实例的数据类型不匹配,请新建视图类型或先调整视图实例',409) + self.a.save_object('view_types',row) + self.a.audit('保存视图类型',row['name']) + return self.view_listing(user) + + def _properties(self, definition, values, strict=True): + if not isinstance(values, dict): + if strict:raise self.a.Problem('实例参数必须是对象') + values = {} + fields = definition['fields'] + if strict and set(values) - {field['key'] for field in fields}: + raise self.a.Problem('实例参数必须先在设备类型中声明;不能写入运行信号') + result = {} + for field in fields: + try:result[field['key']] = self._value(field, values.get(field['key'],field['default'])) + except self.a.Problem: + if strict:raise + result[field['key']] = field['default'] + return result + + def listing(self, user): + with self.a.LOCK: + family = self._family(user) + custom = [self._resolve(item['id'],family) for item in self.a.objects('device_types') if item.get('familyId') == family] + return dict(types=copy.deepcopy(BUILTINS+custom), blocks=copy.deepcopy(BLOCKS), canManage=self.a.HOUSEHOLDS.manager(user)) + + def manage(self, user, data): + self._object(data) + if data.get('action') == 'bind':return self.bind(user,data) + with self.a.LOCK: + family = self._manager(user) + self._shape(data, ('action','id','name','familyId','fbType','fields','viewTemplate','revision','dataTypeId','dataTypeRevision')) + if 'dataTypeRevision' in data and 'dataTypeId' not in data: + raise self.a.Problem('校验数据类型修订号时必须明确指定数据类型') + if data.get('action') != 'save':raise self.a.Problem('请选择保存设备类型') + if data.get('familyId',family) != family:raise self.a.Problem('不能修改类型的家庭归属',403) + key = data.get('id');old=None + if key: + old = self._resolve(key,family) + if old.get('builtin'):raise self.a.Problem('内置类型只读,请另建自定义类型',403) + self._revision(data.get('revision'),old['revision']) + revision = old['revision']+1 + else: + self._revision(data.get('revision',0),0) + key, revision = secrets.token_hex(8), 1 + fb_type = data.get('fbType','manual.v1') + block = next((b for b in BLOCKS if b['id']==fb_type),None) + if not block:raise self.a.Problem('设备类型只能选择已注册的执行驱动') + # Accept the old display hint for wire compatibility only. A driver has no + # view dependency; actual view bindings are validated against data types. + if 'viewTemplate' in data and data['viewTemplate'] not in ('power','properties'): + raise self.a.Problem('旧版显示提示不正确;请通过视图类型管理显示') + name=self.a.clean_text(data.get('name',''),80,True) + if 'dataTypeId' in data: + data_type=self._resolve_data(data['dataTypeId'],family) + if 'fields' in data and self._fields(data['fields'])!=data_type['fields']:raise self.a.Problem('请在数据类型中修改参数结构') + elif old and 'fields' not in data: + data_type=self._resolve_data(old['dataTypeId'],family) + elif fb_type=='computer.power.v1': + if data.get('fields'):raise self.a.Problem('电脑驱动必须使用内置电脑电源数据类型') + data_type=self._resolve_data('computer-power',family) + else: + # Transitional flat fields become a real reusable data type, not a second schema. + legacy=dict(action='save',name=name[:78]+'参数',fields=data.get('fields',[]),revision=0) + if old and old.get('dataTypeId') not in ('generic','computer-power'): + previous=self._resolve_data(old['dataTypeId'],family) + legacy.update(id=previous['id'],revision=previous['revision'],name=previous['name']) + data_type=self._save_data_definition(user,legacy) + if 'dataTypeRevision' in data:self._revision(data['dataTypeRevision'],data_type['revision']) + if (fb_type=='computer.power.v1')!=(data_type['id']=='computer-power'): + raise self.a.Problem('数据类型与设备执行驱动不兼容') + template = 'power' if data_type['id']=='computer-power' else 'properties' + self._compatible_instances({key},data_type,family) + item = dict(id=key,name=name,familyId=family,fbType=fb_type,dataTypeId=data_type['id'],dataTypeRevision=data_type['revision'], + fields=copy.deepcopy(data_type['fields']),viewTemplate=template,builtin=False,revision=revision) + self.a.save_object('device_types',item) + self.a.audit('保存设备类型',item['name']) + return self.listing(user) + + def preserve(self, data, old, user): + with self.a.LOCK: + self._object(data) + family = self._manager(user) + if old:self.a.HOUSEHOLDS.owns(user,old) + if data.get('familyId',family) != family:raise self.a.Problem('不能修改设备的家庭归属',403) + old = old or {} + type_id = data.get('typeId',old.get('typeId') or 'generic') + definition = self._resolve(type_id,family) + if 'typeRevision' in data:self._revision(data['typeRevision'],definition['revision']) + if 'dataTypeRevision' in data:self._revision(data['dataTypeRevision'],definition['dataTypeRevision']) + previous = old.get('properties',{}) if old.get('typeId') == type_id else {} + values = data.get('properties',previous) + return dict(typeId=type_id, properties=self._properties(definition,values)) + + def instance(self, item): + with self.a.LOCK: + item = item or {} + try:definition = self._resolve(item.get('typeId') or 'generic',self.a.HOUSEHOLDS.family_of(item)) + except self.a.Problem:definition = copy.deepcopy(BUILTINS[1]) + properties = self._properties(definition,item.get('properties',{}),False) + return dict(typeId=definition['id'],fbType=definition['fbType'],viewTemplate=definition['viewTemplate'], + properties=properties,typeName=definition['name'],dataInstance=dict(id=item.get('id',''),deviceId=item.get('id',''), + dataTypeId=definition['dataTypeId'],values=copy.deepcopy(properties))) + + def _device(self, user, device_id): + item = self.a.HOUSEHOLDS.owns(user,self.a.get_object('devices',device_id)) + if not self.a.HOUSEHOLDS.manager(user) and item.get('siteId') not in self.a.HOUSEHOLDS.site_ids(user): + raise self.a.Problem('没有这个区域设备的访问权限',403) + return item + + def _public_device(self, item): + displayed = self.a.INVENTORY.display(item) + projection=self.instance(item) + # The inventory provider may enrich this same data instance with live adapter signals. + for key in projection: + if key in displayed:projection[key]=copy.deepcopy(displayed[key]) + return dict({key:copy.deepcopy(value) for key,value in displayed.items() if key in DEVICE_PUBLIC_FIELDS}, **projection) + + def bind(self, user, data): + with self.a.LOCK: + self._manager(user) + self._shape(data, ('action','deviceId','typeId','properties','typeRevision','dataTypeRevision')) + if data.get('action','bind') != 'bind':raise self.a.Problem('请选择绑定设备类型') + if not data.get('typeId'):raise self.a.Problem('请选择设备类型') + item = self._device(user,data.get('deviceId')) + # Binding is an explicit parameter replacement; omitted values take type defaults. + update = self.preserve(dict(data,properties=data.get('properties',{})),item,user) + item = dict(item,**update) + self.a.save_object('devices',item) + self.a.audit('绑定设备类型',item.get('name','')) + return dict(device=self._public_device(item)) + + def _view_item(self, row): + data_id=row.get('dataInstanceId',row.get('deviceId')) + view_id=row.get('viewTypeId',row.get('templateId')) + return dict({key:copy.deepcopy(row[key]) for key in ('id','familyId','title','revision')}, + dataInstanceId=data_id,viewTypeId=view_id,deviceId=data_id,templateId=view_id) + + def _view_matches(self,row,item,family): + try:definition=self._resolve_view(row.get('viewTypeId',row.get('templateId')),family) + except self.a.Problem:return False + return definition['dataTypeId']==self.instance(item)['dataInstance']['dataTypeId'] + + def views(self, user, device_id=None): + with self.a.LOCK: + family = self._family(user) + if device_id is not None:self._device(user,device_id) + manager = self.a.HOUSEHOLDS.manager(user) + allowed_sites = None if manager else self.a.HOUSEHOLDS.site_ids(user) + devices = {item['id']:item for item in self.a.objects('devices') + if self.a.HOUSEHOLDS.family_of(item)==family and (manager or item.get('siteId') in allowed_sites)} + result = [] + for row in self.a.objects('device_views'): + item = devices.get(row.get('dataInstanceId',row.get('deviceId'))) + if row.get('familyId') != family or not item or device_id is not None and item['id'] != device_id:continue + if not self._view_matches(row,item,family):continue + result.append(self._view_item(row)) + return dict(items=result,canManage=manager) + + def save_view(self, user, data): + with self.a.LOCK: + family = self._manager(user) + self._shape(data, ('action','id','familyId','deviceId','templateId','dataInstanceId','viewTypeId','title','revision')) + action = data.get('action') + if action not in ('save','delete'):raise self.a.Problem('请选择保存或删除视图实例') + if data.get('familyId',family) != family:raise self.a.Problem('不能修改视图的家庭归属',403) + for canonical,alias in (('dataInstanceId','deviceId'),('viewTypeId','templateId')): + if canonical in data and alias in data and data[canonical]!=data[alias]:raise self.a.Problem('视图引用编号存在冲突') + old = None + if data.get('id'): + old = self.a.HOUSEHOLDS.owns(user,self.a.get_object('device_views',data['id'])) + self._revision(data.get('revision'),old['revision']) + self._device(user,old.get('dataInstanceId',old.get('deviceId'))) + else: + if action == 'delete':raise self.a.Problem('请选择要删除的视图实例') + self._revision(data.get('revision',0),0) + if action == 'delete': + with self.a.DB:self.a.DB.execute('DELETE FROM device_views WHERE id=?',(old['id'],)) + self.a.audit('删除设备视图',old['title']) + return dict(ok=True,**self.views(user,old.get('dataInstanceId',old.get('deviceId')))) + if not old and sum(row.get('familyId')==family for row in self.a.objects('device_views')) >= 100: + raise self.a.Problem('每个家庭最多 100 个设备视图实例') + device_id = data.get('dataInstanceId',data.get('deviceId',old.get('dataInstanceId',old.get('deviceId')) if old else None)) + item = self._device(user,device_id) + template = data.get('viewTypeId',data.get('templateId',old.get('viewTypeId',old.get('templateId')) if old else None)) + definition=self._resolve_view(template,family) + if definition['dataTypeId']!=self.instance(item)['dataInstance']['dataTypeId']: + raise self.a.Problem('视图类型必须匹配所选数据实例的数据类型') + row = dict(id=old['id'] if old else secrets.token_hex(8),familyId=family,dataInstanceId=device_id,viewTypeId=template,deviceId=device_id,templateId=template, + title=self.a.clean_text(data.get('title',''),80,True),revision=old['revision']+1 if old else 1) + self.a.save_object('device_views',row) + self.a.audit('保存设备视图',row['title']) + return dict(view=self._view_item(row),**self.views(user,device_id)) diff --git a/docs/device-types.md b/docs/device-types.md new file mode 100644 index 0000000..9aa11a9 --- /dev/null +++ b/docs/device-types.md @@ -0,0 +1,105 @@ +# 数据、设备与视图对象 + +本次提供可运行的对象基础和第一种电脑电源实现。六个正式名称为:**数据类型、数据实例、设备类型、设备实例、视图类型、视图实例**。 + +| 对象 | 含义 | 当前实现 | +| --- | --- | --- | +| 数据类型 | 可复用的数据结构、参数约束与运行信号契约 | `data_types`,内置 `computer-power`、`generic`,家庭自定义类型 | +| 数据实例 | 某台设备自己的参数值与运行状态 | `dataInstance`,稳定编号与所属设备编号相同 | +| 设备类型 | FB,组合关联的数据类型和功能实现 | `device_types`,`dataTypeId` 与已注册执行驱动 `fbType` | +| 设备实例 | 某个家庭内的一台实际设备 | 既有 `devices`,保存 `typeId` 和参数 `properties` | +| 视图类型 | 只依赖数据类型的呈现规则 | `view_types`;内置 `properties`、`power` 和自定义参数卡片 | +| 视图实例 | 绑定数据实例的具名呈现对象 | `device_views`,独立编号、标题和修订号,同一数据实例可有多个 | + +视图类型只依赖数据类型,与设备和设备类型完全独立。视图实例绑定 `dataInstanceId`。当前实现只接入设备提供的数据实例,尚未开放独立外部数据提供者;视图接口本身不依赖设备类型。绑定兼容性仅比较数据类型编号,不比较设备类型、执行驱动或设备的默认视图。 + +FB 就是设备类型。`computer.power.v1`、`manual.v1` 是设备类型所选择的**执行驱动**,不会再形成一个与设备类型并列的 FB 对象层。此版本不提供任意脚本、在线编程或任意布局代码。 + +## 数据结构与参数 + +数据类型公开结构: + +```json +{ + "id": "<16 位小写十六进制>", + "name": "温度设备参数", + "familyId": "<家庭编号>", + "fields": [{"key":"TargetValue","label":"目标温度","type":"number","unit":"℃","default":20,"min":0,"max":100}], + "signals": [], + "builtin": false, + "revision": 1 +} +``` + +`fields` 只定义用户可编辑的实例参数。最多 24 项,标识匹配 `[A-Za-z][A-Za-z0-9_]{0,39}`;允许 PLC 风格大小写,但重名检查忽略大小写。参数标识、显示标签、单位分别最多 40、80、20 字符。类型名和视图标题最多 80 字符。 + +参数支持 `text`、`number`、`boolean`。文本最多 500 字符;布尔值必须为 JSON 布尔值;数字必须有限,拒绝字符串、布尔值、NaN、无穷和范围外值,不会静默截断工程数值。数字才允许 `min/max`。默认值缺省时分别是空文本、0、false,因此下限大于 0 的数值参数必须显式提供有效默认值。文本沿用平台文本校验,不接受控制字符。 + +内置 `computer-power` 的 `fields` 为空,`signals` 定义不可由用户改写的运行契约: + +| 信号 | 数据类型 | 访问 | +| --- | --- | --- | +| RUN | 可空布尔 | 读取实测运行状态;未知不等于停止 | +| OP | 枚举 0/1/2 | 经独立电源命令 API 写入,分别为空闲/开机/关机 | +| BUSY | 布尔 | 读取操作处理中状态 | +| RESULT | 文本 | 读取最近操作结果 | + +RUN、OP、BUSY、RESULT,以及身份、运行时控制和凭据相关名称被保留,不能伪装成自定义参数。运行信号不写入 `properties`。`computer.power.v1` 仅兼容 `computer-power`;`manual.v1` 使用通用或家庭自定义数据类型。自定义电脑设备类型不会自动配置执行驱动、连接设备或取得电源权限,仍需独立服务器适配器配置和明确授权。 + +## 数据实例与修订 + +`DeviceTypes.instance(item)` 返回公开的类型信息和数据实例: + +```json +{ + "typeId":"<设备类型编号>", + "fbType":"manual.v1", + "viewTemplate":"properties", + "typeName":"温度设备", + "properties":{"TargetValue":20}, + "dataInstance":{ + "id":"<设备编号>", + "deviceId":"<设备编号>", + "dataTypeId":"<数据类型编号>", + "values":{"TargetValue":20} + } +} +``` + +每台设备只有一个稳定的数据实例身份。更改设备名、设备类型或视图不会复制它。此模块投影参数值;电脑运行信号由电源适配器按权限补入同一 `values`,保持电源模块为唯一运行状态来源。没有第二份运行状态数据库。 + +数据类型更新会先校验所有依赖设备实例。删除已用参数、缩小范围等操作如导致既有值失效,会返回 409;先调整实例值,或创建新的数据类型并显式重新绑定。兼容更新增加数据类型修订号,同时增加所有依赖设备类型修订号,避免旧绑定表单覆盖新结构。新增字段可使用已验证的默认值。设备类型改变数据类型时也检查已有实例的兼容性。 + +普通设备档案编辑通过 `preserve(data,old,user)` 保留类型和有效实例参数。显式绑定默认值会替换旧参数。旧记录没有类型时使用 `generic`;丢失或跨家庭的类型引用在公开显示时退回通用类型和空参数,编辑时须显式重新绑定。 + +## 接口契约 + +所有接口使用既有网页登录身份与当前家庭范围。内置定义只读。管理操作仅限当前家庭管理员;普通成员可以读取本家庭类型定义,视图和设备仍受区域权限限制。 + +| 接口 | 请求或响应 | +| --- | --- | +| `GET /api/data-types` | `{types,canManage}` | +| `POST /api/data-types` | 扁平 `{action:"save",id?,name,fields,revision?}`;返回数据类型列表 | +| `GET /api/device-types` | `{types,blocks,canManage}`;`blocks` 为兼容的执行驱动目录,类型含 `dataTypeId/dataTypeRevision` 和派生 `fields` | +| `POST /api/device-types` 保存 | 扁平 `{action:"save",id?,name,dataTypeId,dataTypeRevision?,fbType,revision?}`;返回类型列表 | +| `POST /api/device-types` 绑定 | `{action:"bind",deviceId,typeId,properties,typeRevision?,dataTypeRevision?}`;返回 `{device}` | +| `GET /api/view-types` | `{types,canManage}`;视图类型结构 `{id,name,familyId,dataTypeId,renderer,builtin,revision}` | +| `POST /api/view-types` | `{action:"save",id?,name,dataTypeId,dataTypeRevision?,renderer:"properties",revision?}`;返回视图类型列表 | +| `GET /api/device-data?id=...` | `{instance:{id,dataTypeId,values,...}}`;按数据实例编号读取,执行家庭及区域授权检查 | +| `GET /api/device-views?dataInstanceId=...` | `{items,canManage}`;省略数据实例过滤时返回当前可读取的视图 | +| `POST /api/device-views` 保存 | `{action:"save",id?,dataInstanceId,viewTypeId,title,revision?}`;返回 `{view,items,canManage}` | +| `POST /api/device-views` 删除 | `{action:"delete",id,revision}`;返回该设备的 `{ok:true,items,canManage}` | + +新建修订号省略或为 0,保存后为 1。编辑和删除必须提供精确的当前修订号,冲突返回 409。类型绑定的修订字段提供额外的结构一致性检查。兼容旧客户端的设备类型 `fields` 请求会转为真实的数据类型,不建立第二份独立参数结构;新客户端应使用独立数据类型接口。 + +设备类型响应中的 `viewTemplate` 仅为旧客户端保留的派生显示提示,不参与视图注册或绑定。新客户端不提交该字段。视图组件通过数据实例读取实际值;同一数据实例的多个视图共享页面数据更新,不分别启动轮询。当前保存的视图只读,电脑控制操作由独立授权的电源面板执行。 + +跨家庭转移设备时,在同一数据库事务中删除原家庭对应的视图绑定,释放原家庭的视图名额。视图属于家庭的展示配置,不随设备迁移;新家庭可自行建立视图,其他设备和家庭的视图不受影响。 + +视图实例结构为 `{id,familyId,dataInstanceId,viewTypeId,title,revision}`。兼容输出 `deviceId` / `templateId` 指向相同编号;同时提交别名时必须一致。`viewTypeId` 指向视图类型,其 `dataTypeId` 必须匹配数据实例的数据类型。内置 `properties` 消费 `generic`,内置 `power` 消费 `computer-power`;自定义视图类型可消费任意可见数据类型,但只能使用安全的 `properties` 渲染器。电源渲染器仅供内置类型,不提供 HTML 或脚本。每个家庭最多 100 个视图实例。删除视图不删除设备、不改变数据实例、不授予控制权限。设备转移后旧家庭的视图无法读取;数据实例改绑为不同数据类型后,类型不匹配的旧视图不再展示。仅更换设备类型而保持数据类型不变,不影响视图。修改视图类型的数据类型引用时,也会校验所有已有视图实例,禁止使它们失配的变更。 + +## 集成和验证 + +`DeviceTypes(app).initialize()` 在 `HOUSEHOLDS.initialize()` 后调用,创建 `data_types`、`device_types`、`view_types`、`device_views` 四张 `id/body` 表。使用既有 SQLite 和可重入锁。库存保存调用 `preserve`;库存展示合入 `instance`;路由分别调用上表方法。此模块不修改设备名称、原有 `deviceType` 文本、网络配置、联系人或现有权限。 + +运行 `py -m unittest -v test_device_types`。测试复用真实内存 SQLite 和家庭角色,覆盖数据类型复用、默认值、数值范围、大小写命名、保留信号、凭据名称、结构修订、绑定/重新绑定、跨家庭拒绝、稳定数据实例、独立视图与区域读取;不连接真实设备,不执行电源操作。 diff --git a/docs/superpowers/plans/2026-10-25-p15-power.md b/docs/superpowers/plans/2026-10-25-p15-power.md new file mode 100644 index 0000000..2cbafa2 --- /dev/null +++ b/docs/superpowers/plans/2026-10-25-p15-power.md @@ -0,0 +1,42 @@ +# P15 managed asset implementation plan + +Goal: existing household/device catalog gains a managed laptop with RUN/OP and phone tabs 位置 / 家庭 / 设备 / 沟通 / 我的. No generic remote shell. + +Architecture: existing `devices` JSON objects hold the asset and metadata. New `device_power.py` holds runtime state, commands and explicit phone grants. A least-privilege Windows service polls HTTPS, accepts only signed shutdown commands, persists consumed IDs before execution and never listens on a network port. Server calls a fixed, forced-command SSH bridge on MT2500 for WOL. No credentials in catalog/UI. + +User specification: delegated task from 日常操作, 2026-10-25. User approved existing smart-home integration and autonomous implementation. Retain existing pairing and consent; no automatic grants from a location-sharing token. P15 is the active development host, so real shutdown is deferred until work has ended. + +## Interfaces (binding for all components) + +### Phone API + +POST `/api/phone/home` with existing phone pairing Bearer token. Actions: +- `catalog`: response `{households:[{id,name,kind}],devices:[{id,source,name,deviceType,familyId,familyName,siteName,power:null|PowerState}],activeId:pairedFamilyId}`. Only explicitly granted devices; paired household name remains visible. Empty device list directs user to administrator; no implied control permission. +- `command`: `{action,deviceId,op:1|2,requestId:32 lowercase hex,confirm:true}`; response `{power:PowerState}`. Shutdown requires explicit UI confirmation. UUID without hyphens creates requestId. +- `status`: `{action,deviceId}` returns `{power:PowerState}`. + +PowerState = `{run:0|1|null,op:0|1|2,state:'online'|'offline'|'unknown',checkedAt:unixSeconds,canStart:boolean,canShutdown:boolean,managed:boolean,last:{id,op,status,result,at}|null}`. +`run=0` means confirmed unreachable through an available relay, not proof of physical shutdown. Unknown disables both actions. Command buttons follow `canStart/canShutdown`; status also validates server-side. OP always resets on terminal outcome/restart. RUN is sampled, never inferred from an OP request. + +### Web API + +GET `/api/device-power?id=...` authenticated in current household returns `{power:PowerState,grants:[{personId,view,control}],candidates:[{personId,name}],canManage:boolean}`. Only admins/managers get grants/candidates; ordinary authorized site readers see state only. +POST `/api/device-power` current household, `{action:'command',deviceId,op,requestId,confirm:true}` or `{action:'grants',deviceId,grants:[{personId,view:true,control:boolean}]}`. Commands only manager or explicit per-person grant. Grant save only current household manager, admin may select active paired people across households; family managers only own-family members. Existing paired token alone grants no device access. Grants follow stable person identity but require valid current member pairing and expiry on every request. + +### Windows agent protocol + +POST `/api/device-power/agent` HTTPS `https://home.ucvl.cn`, <=16KiB. +Envelope `{payload:base64(UTF8 JSON),signature:hex HMAC-SHA256(secretBytes,payload ASCII)}`. Config secret is base64 random32 bytes. Payload `{deviceId,bootId:32hex,nonce:32hex,at:unixSeconds,ready:boolean,ack:null|{id,status:'scheduled'|'failed'|'blocked',result:string}}`. At within60sec. Server nonce cache rejects duplicates. Poll every10sec. BootId fresh each process start. +Response same envelope, payload `{nonce:,at:unixSeconds,command:null|{id:32hex,op:2,bootId,expires:unixSeconds}}`. Verify HMAC in constant time, matching nonce/bootId, timestamp window60sec and command expiry before action. No arbitrary command/path/args accepted. Server delivers only once per command; no reissue after timeout/restart. Agent persists consumed ID before shutdown. Acknowledge 'scheduled' before calling graceful shutdown (no forced application termination). Failed ACK prevents shutdown. Agent retains seen IDs bounded, never replays on restart. Agent service can run `--check`/`--self-test` without shutdown; installation must be explicit. `ready=false` while maintenance/installation safety lock exists. LocalService or dedicated service identity granted only shutdown privilege; no admin shell. Do not change RDP/Tailscale. + +## Tasks and ownership + +- [x] Backend (root): failing tests for RUN unknown/stale/online/offline, OP success/failure/timeouts/restart, duplicate requests, boot changes, replay/HMAC, household and phone grants. Implement module, routes, worker, metadata preservation. Existing tables reused. Bridge script only fixed status/wake operations. +- [x] Android: update native layout/controller to five pages, old behavior keyed constants; new PhoneHomePanel calls API above. Bootstrap native look, household selection -> matching devices, explicit shutdown confirmation, no stale callbacks across pair/tab changes. Add isolated native fixture tests/preview modes; no real device calls in tests. +- [x] Web: `DevicePowerPanel.vue` + pure model .mjs tests, integrate existing DeviceCollection and device details. Show only name/location/state/buttons/time/result for managed computer card. API authorization errors explicit, no cached permission fallback. Grant editor uses candidates from API. No credential fields. +- [x] Windows: dedicated agent under `windows-power/`, .NET Framework compilation supported, self-tests for signatures/nonces/boot/expiry/duplicate journal/only OP2, install/uninstall docs/scripts; no machine mutations until root reviews. +- [x] Integrate/review: all tests, signed APKs, preview 320dp and135% font, existing location/voice regression. Resolve test fixture old three-tab assumptions. +- [ ] Production: inspect existing records first, online DB backup, idempotently create 优创青岛办 and P15, relay topology is parallel under172.16.1.1, not under MT2500 LAN. P15 LAN172.16.1.44/24 gateway172.16.1.1, TS100.82.249.65, MACs8C:3B:4A:17:BC:C4/9C:2D:CD:03:D9:24. MT2500 WAN172.16.1.163 TS100.66.203.38. Grant only verified requested owner identity, otherwise leave explicit admin grant UI. Restricted SSH key and pinned host key server-side. Agent installation on P15 with maintenance lock; dry-run validates chain without shutdown during work. +- [ ] Release: V0.1.56/code12, existing signing/backup/deploy workflow, metadata/hash/download checks. State exactly what was physically tested. Real shutdown deferred because active host. + +Review focus: stale state must be unknown; revoked or moved-device grants fail closed; timeout before delivery cannot execute later; service restart cannot replay; new permissions must not attach to everyone holding a location token. No formal production objects hardcoded into fixture data. diff --git a/frontend/package.json b/frontend/package.json index 43d90fb..d748240 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "zhao-steward-ui", "private": true, - "version": "0.1.55", + "version": "0.1.56", "type": "module", "scripts": { "build": "vite build", diff --git a/frontend/src/components/DataView.vue b/frontend/src/components/DataView.vue new file mode 100644 index 0000000..1b8e5c8 --- /dev/null +++ b/frontend/src/components/DataView.vue @@ -0,0 +1,51 @@ + + + + + diff --git a/frontend/src/components/DeviceCollection.vue b/frontend/src/components/DeviceCollection.vue index ea381cd..d3b9abf 100644 --- a/frontend/src/components/DeviceCollection.vue +++ b/frontend/src/components/DeviceCollection.vue @@ -9,6 +9,9 @@ import AppIcon from "./AppIcon.vue"; import NetworkStatus from "./NetworkStatus.vue"; import DisplayManager from './DisplayManager.vue'; import DeviceTransfer from './DeviceTransfer.vue'; +import DevicePowerPanel from './DevicePowerPanel.vue'; +import DeviceTypeLibrary from './DeviceTypeLibrary.vue'; +const powerManaged = (d) => d.source === 'device' && d.powerManaged === true; const channels = (d) => (snapshot.value.state.cameras || []).filter((c) => d.source === "camera" @@ -28,6 +31,7 @@ const monitored = (d) =>