feat(android): warm voice interface and custom sampling up to one day v0.1.51
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
# V0.1.51 — 自定义采集间隔与家人喊话界面
|
||||
|
||||
## 位置采集
|
||||
|
||||
- 定位采集独立支持 10 秒、1/5/15/30 分钟、1/2/3/4/5/6/12 小时、每天一次;自定义可填秒、分钟、小时或天,范围 10 秒至 24 小时,拒绝一周等更长采集间隔。
|
||||
- 读取设置时完整恢复所选周期和自定义数值。上传周期仍独立设置,沿用 V0.1.50 的离线加密缓存、恢复补传、网盘回读校验及确认后清理。
|
||||
- 即使多个定位来源同时回调,当前点与历史点也共同遵守采集间隔。一天采集一次只能留下每天的位置点,不能还原当天完整路线;系统定位回调仍受手机权限和省电策略约束。
|
||||
- 平台、手机与显示终端区分等待采集和等待上传。长间隔未到期不误报定位中断,已过期坐标不当作实时位置展示。持久化最后采集时间以保留重启后的排期,不额外持久化实时坐标。
|
||||
|
||||
## 家人喊话
|
||||
|
||||
- 按暖白、青绿色设计图实现原生界面:底部保留简洁入口,展开后全屏选择家人。姓名首字头像卡片明确区分已打开 / 未打开 App,选中对象有边框和勾选提示。
|
||||
- 大号按住说话按钮,录音时显示实际麦克风音量波形和时长。上滑 48 dp 或移出左右边界后进入取消状态,回到按钮区域可恢复发送;离开页面、多指干扰或手势中断均取消。
|
||||
- 最长 30 秒。达到上限时若处于取消状态则丢弃,不会误发送;过短语音、权限不足、对方离线和网络失败均明确提示。
|
||||
- “已发送”“对方正在接收”“对方已播放”等来自服务端和对方播放回执;播放完毕不等同于确认家人听见。接收名单与共享授权不因界面升级改变,接收语音不会打开麦克风。
|
||||
- 支持遥控器 / 键盘按住回车,以及读屏模式点按开始、再次点按发送。录音临时文件在发送完成、取消或失败后清理。
|
||||
|
||||
## 验证
|
||||
|
||||
- 全量 Python 回归 331 项、JavaScript 回归 191 项通过;桌面与 390 像素手机页面的等待采集提示、无误报与无横向溢出检查通过。
|
||||
- 原生周期边界检查 178 条断言、取消手势 9 条断言通过。
|
||||
- Android 原生界面用隔离测试包检查普通、录音、取消、夜间四种状态,使用模拟姓名和模拟波形,不申请定位、麦克风或网络权限。测试结束卸载测试包并恢复原前台应用。
|
||||
- 尚未在用户手机上验证真实双端录音和播放。安装需从配套 App 下载页覆盖更新,不能声称已更新未连接的手机。
|
||||
@@ -1,4 +1,4 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="6" android:versionName="0.1.50">
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="7" android:versionName="0.1.51">
|
||||
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="6" android:versionName="0.1.50">
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="7" android:versionName="0.1.51">
|
||||
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30"/>
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
|
||||
|
||||
@@ -15,8 +15,10 @@ import java.util.*;
|
||||
public class LocationActivity extends Activity {
|
||||
static volatile boolean pairing=false;
|
||||
TextView identity,status,viewStatus,permissionStatus;EditText code;Button pair,reload;
|
||||
CheckBox consent,historyConsent;Switch sharing;Spinner cadence,sampleCadence,customUnit;EditText customAmount;LinearLayout customPeriod,settings,recipients,familyList,homeContent,shareControls;
|
||||
CheckBox consent,historyConsent;Switch sharing;Spinner cadence,sampleCadence,customUnit,sampleUnit;EditText customAmount,sampleAmount;LinearLayout customPeriod,samplePeriod,settings,recipients,familyList,homeContent,shareControls;
|
||||
TextView queueStatus;LocationQueue outbox;String queueOwner="";
|
||||
final int[] sampleIntervals={10,60,300,900,1800,3600,7200,10800,14400,18000,21600,43200,86400,0};
|
||||
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;
|
||||
@@ -52,7 +54,10 @@ public class LocationActivity extends Activity {
|
||||
shareControls=new LinearLayout(this);shareControls.setOrientation(1);settings.addView(shareControls);
|
||||
text("我的位置共享",22,shareControls);text("选择谁能看我的位置",16,shareControls);
|
||||
recipients=new LinearLayout(this);recipients.setOrientation(1);shareControls.addView(recipients);
|
||||
text("定位采集频率",16,shareControls);sampleCadence=new Spinner(this);sampleCadence.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"每 10 秒(较耗电)","每 1 分钟(默认)","每 5 分钟(省电)"}));sampleCadence.setSelection(1);shareControls.addView(sampleCadence);
|
||||
text("定位采集频率",16,shareControls);sampleCadence=new Spinner(this);sampleCadence.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"每 10 秒(较耗电)","每 1 分钟(默认)","每 5 分钟","每 15 分钟","每 30 分钟","每 1 小时","每 2 小时","每 3 小时","每 4 小时","每 5 小时","每 6 小时","每 12 小时","每 1 天","自定义采集间隔"}));sampleCadence.setSelection(1);shareControls.addView(sampleCadence);
|
||||
samplePeriod=new LinearLayout(this);samplePeriod.setOrientation(LinearLayout.HORIZONTAL);sampleAmount=new EditText(this);sampleAmount.setInputType(InputType.TYPE_CLASS_NUMBER);sampleAmount.setHint("正整数");sampleAmount.setText("2");sampleAmount.setFilters(new android.text.InputFilter[]{new android.text.InputFilter.LengthFilter(5)});samplePeriod.addView(sampleAmount,new LinearLayout.LayoutParams(0,-2,1));sampleUnit=new Spinner(this);sampleUnit.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"秒","分钟","小时","天"}));sampleUnit.setSelection(2);samplePeriod.addView(sampleUnit);shareControls.addView(samplePeriod);samplePeriod.setVisibility(View.GONE);
|
||||
sampleCadence.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){public void onItemSelected(AdapterView<?> p,View v,int position,long id){samplePeriod.setVisibility(position==sampleIntervals.length-1?View.VISIBLE:View.GONE);}public void onNothingSelected(AdapterView<?> p){}});
|
||||
text("每次采集留下一个定位点。可自定义 10 秒至 24 小时,最长每天一次,不设一周。采集越稀疏越省电,但无法还原期间的完整路线。",14,shareControls);
|
||||
text("集中上传周期",16,shareControls);cadence=new Spinner(this);cadence.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"实时(约 10 秒)","每 1 分钟","每 5 分钟(默认)","每 1 小时","每 2 小时","每 3 小时","每 4 小时","每 5 小时","每 1 天","每 2 天","每 3 天","自定义小时 / 天"}));cadence.setSelection(2);shareControls.addView(cadence);
|
||||
customPeriod=new LinearLayout(this);customPeriod.setOrientation(0);customAmount=new EditText(this);customAmount.setInputType(InputType.TYPE_CLASS_NUMBER);customAmount.setHint("正整数");customAmount.setText("6");customAmount.setFilters(new android.text.InputFilter[]{new android.text.InputFilter.LengthFilter(3)});customPeriod.addView(customAmount,new LinearLayout.LayoutParams(0,-2,1));customUnit=new Spinner(this);customUnit.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"小时","天"}));customPeriod.addView(customUnit);shareControls.addView(customPeriod);customPeriod.setVisibility(View.GONE);
|
||||
cadence.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){public void onItemSelected(AdapterView<?> p,View v,int position,long id){customPeriod.setVisibility(position==uploadIntervals.length-1?View.VISIBLE:View.GONE);}public void onNothingSelected(AdapterView<?> p){}});
|
||||
@@ -94,7 +99,7 @@ public class LocationActivity extends Activity {
|
||||
rendering=true;sharing.setChecked(active);rendering=false;
|
||||
sharing.setEnabled(paired&&!pairing&&(active||!busy&&settingsReady));
|
||||
pair.setEnabled(!active&&!busy);cadence.setEnabled(!active&&!busy);consent.setEnabled(!active&&!busy);historyConsent.setEnabled(!active&&!busy&&settingsReady);
|
||||
sampleCadence.setEnabled(!active&&!busy);customAmount.setEnabled(!active&&!busy);customUnit.setEnabled(!active&&!busy);
|
||||
sampleCadence.setEnabled(!active&&!busy);sampleAmount.setEnabled(!active&&!busy);sampleUnit.setEnabled(!active&&!busy);customAmount.setEnabled(!active&&!busy);customUnit.setEnabled(!active&&!busy);
|
||||
for(List<CheckBox> list:choices.values())for(CheckBox c:list)c.setEnabled(!active&&!busy);
|
||||
reload.setEnabled(paired&&!loading&&!pairing);
|
||||
}
|
||||
@@ -119,7 +124,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=response.optJSONArray("items");map.setItems(list);familyList.removeAllViews();viewStatus.setText(list==null||list.length()==0?"尚无家人授权给这台手机的位置。请对方在自己的位置设置里勾选你的手机,并开启共享。":"只显示仍在授权有效期内的最新位置。");
|
||||
if(list!=null)for(int i=0;i<list.length();i++){JSONObject row=list.optJSONObject(i);if(row==null)continue;JSONObject pos=row.optJSONObject("position");String detail=pos==null?("scheduled".equals(row.optString("status"))?"按设定周期上传中,当前没有实时坐标":("stale".equals(row.optString("status"))?"更新中断,旧坐标已隐藏":"等待定位")) : String.format(Locale.CHINA,"纬度 %.5f · 经度 %.5f\n精度约 %.0f 米 · %s",pos.optDouble("latitude"),pos.optDouble("longitude"),pos.optDouble("accuracy"),java.text.DateFormat.getTimeInstance().format(new Date((long)(pos.optDouble("at")*1000))));Button item=button(row.optString("name")+"\n"+detail,familyList);item.setAllCaps(false);item.setOnClickListener(v->{if(pos!=null)map.focus(pos);});button("查看 "+row.optString("name")+" 的已授权历史",familyList).setOnClickListener(v->history(row.optString("id")));}
|
||||
if(list!=null)for(int i=0;i<list.length();i++){JSONObject row=list.optJSONObject(i);if(row==null)continue;JSONObject pos=row.optJSONObject("position");String detail=pos==null?("scheduled".equals(row.optString("status"))?("sampling".equals(row.optString("scheduleReason"))?"等待下次采集,当前没有实时坐标":"等待下次上传,当前没有实时坐标"):("stale".equals(row.optString("status"))?"更新中断,旧坐标已隐藏":"等待定位")) : String.format(Locale.CHINA,"纬度 %.5f · 经度 %.5f\n精度约 %.0f 米 · %s",pos.optDouble("latitude"),pos.optDouble("longitude"),pos.optDouble("accuracy"),java.text.DateFormat.getTimeInstance().format(new Date((long)(pos.optDouble("at")*1000))));Button item=button(row.optString("name")+"\n"+detail,familyList);item.setAllCaps(false);item.setOnClickListener(v->{if(pos!=null)map.focus(pos);});button("查看 "+row.optString("name")+" 的已授权历史",familyList).setOnClickListener(v->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)){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();settings.setVisibility(View.VISIBLE);}viewStatus.setText(e instanceof DisplayApi.ApiError&&((DisplayApi.ApiError)e).status==401?"手机配对已过期或解除,请重新配对。":"位置未能刷新,已隐藏旧画面,请检查网络。");});}finally{runOnUiThread(()->{if(g==generation){loading=false;render();}});}},"family-positions").start();
|
||||
}
|
||||
@@ -129,7 +134,7 @@ public class LocationActivity extends Activity {
|
||||
JSONObject result=DisplayApi.call("/api/location/update",token,new JSONObject().put("action","settings"));
|
||||
runOnUiThread(()->{if(!visible||g!=generation||request!=settingsRequest)return;settingsReceipt=result.optString("receipt");recipients.removeAllViews();choices.clear();
|
||||
for(String type:new String[]{"viewers","phones","displays"}){String key=type.equals("viewers")?"viewerIds":type.equals("phones")?"phoneIds":"displayIds";text(type.equals("viewers")?"平台查看账号":type.equals("phones")?"已配对的家人手机":"公共显示终端",16,recipients);JSONArray options=result.optJSONArray(type),selected=result.optJSONArray(key);Set<String> ids=new HashSet<>();if(selected!=null)for(int i=0;i<selected.length();i++)ids.add(selected.optString(i));List<CheckBox> list=new ArrayList<>();choices.put(key,list);if(options!=null)for(int i=0;i<options.length();i++){JSONObject item=options.optJSONObject(i);CheckBox c=new CheckBox(this);c.setText(item.optString("name"));c.setTag(item.optString("id"));c.setChecked(ids.contains(item.optString("id")));recipients.addView(c);list.add(c);}if(list.isEmpty())text("暂无可选对象",14,recipients);}
|
||||
int seconds=result.optInt("intervalSeconds",300);setUploadPeriod(seconds);int sample=result.optInt("sampleIntervalSeconds",60);sampleCadence.setSelection(sample==10?0:sample==300?2:1);historyAcknowledged=result.optBoolean("historyEnabled",false);historyConsent.setChecked(historyAcknowledged||result.optBoolean("historyDefault",false));JSONObject h=result.optJSONObject("history");if(h!=null)historyStatus.setText("待归档 "+h.optInt("pending")+" 个定位点 · 已归档 "+h.optInt("archived")+" 段 · 待删除 "+h.optInt("deleting")+" 段\n"+h.optString("error")+"\n长期保留,由本人手动删除。修改设置前先关闭共享。");settingsReady=true;render();});
|
||||
int seconds=result.optInt("intervalSeconds",300);setUploadPeriod(seconds);setSamplePeriod(result.optInt("sampleIntervalSeconds",60));historyAcknowledged=result.optBoolean("historyEnabled",false);historyConsent.setChecked(historyAcknowledged||result.optBoolean("historyDefault",false));JSONObject h=result.optJSONObject("history");if(h!=null)historyStatus.setText("待归档 "+h.optInt("pending")+" 个定位点 · 已归档 "+h.optInt("archived")+" 段 · 待删除 "+h.optInt("deleting")+" 段\n"+h.optString("error")+"\n长期保留,由本人手动删除。修改设置前先关闭共享。");settingsReady=true;render();});
|
||||
}catch(Exception e){runOnUiThread(()->{if(visible&&g==generation&&request==settingsRequest){settingsReady=false;settingsError="无法读取我的位置设置,请检查网络或配对有效期,重新打开设置重试。";render();}});}},"location-settings").start();
|
||||
}
|
||||
void start(){
|
||||
@@ -138,12 +143,14 @@ public class LocationActivity extends Activity {
|
||||
if(historyConsent.isChecked()&&!historyAcknowledged){new AlertDialog.Builder(this).setTitle("同意长期保存我的轨迹").setMessage("定位点将加密上传家庭百度网盘,按天、周、月、年或全部历史查看,长期保留直到你手动删除。共享时所选查看人能读取其获授权期间的历史。关闭实时共享不会删除历史。是否同意?").setNegativeButton("暂不启用",null).setPositiveButton("本人同意并开启",(d,w)->{historyAcknowledged=true;start();}).show();return;}
|
||||
if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED&&checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},45);return;}
|
||||
if(!LocationService.locationEnabled((android.location.LocationManager)getSystemService(LOCATION_SERVICE))){Toast.makeText(this,"请先打开手机系统定位开关",1).show();return;}
|
||||
final JSONObject body=new JSONObject();try{int total=0;for(Map.Entry<String,List<CheckBox>> e:choices.entrySet()){JSONArray ids=new JSONArray();for(CheckBox c:e.getValue())if(c.isChecked()){ids.put((String)c.getTag());total++;}body.put(e.getKey(),ids);}if(total==0){Toast.makeText(this,"请选择至少一位查看人;只看家人无需开启此开关",1).show();return;}int upload=uploadPeriod();if(upload>=3600&&!historyConsent.isChecked()){Toast.makeText(this,"按小时或天集中上传需要本人启用历史保存,才能保留期间的轨迹",1).show();return;}body.put("action","configure").put("consent",true).put("receipt",settingsReceipt).put("intervalSeconds",upload).put("sampleIntervalSeconds",new int[]{10,60,300}[sampleCadence.getSelectedItemPosition()]).put("historyEnabled",historyConsent.isChecked()).put("historyConsent",historyConsent.isChecked());}catch(Exception e){Toast.makeText(this,"请填写 1—720 小时或 1—30 天的整数周期",1).show();return;}
|
||||
final JSONObject body=new JSONObject();try{int total=0;for(Map.Entry<String,List<CheckBox>> e:choices.entrySet()){JSONArray ids=new JSONArray();for(CheckBox c:e.getValue())if(c.isChecked()){ids.put((String)c.getTag());total++;}body.put(e.getKey(),ids);}if(total==0){Toast.makeText(this,"请选择至少一位查看人;只看家人无需开启此开关",1).show();return;}int upload=uploadPeriod();if(upload>=3600&&!historyConsent.isChecked()){Toast.makeText(this,"按小时或天集中上传需要本人启用历史保存,才能保留期间的轨迹",1).show();return;}body.put("action","configure").put("consent",true).put("receipt",settingsReceipt).put("intervalSeconds",upload).put("sampleIntervalSeconds",samplePeriodSeconds()).put("historyEnabled",historyConsent.isChecked()).put("historyConsent",historyConsent.isChecked());}catch(Exception e){Toast.makeText(this,"采集间隔需为 10 秒至 1 天;上传周期为 1—720 小时或 1—30 天,均填正整数",1).show();return;}
|
||||
final int g=generation;final String token=prefs.getString("token","");pairing=true;settingsReady=false;settingsError="";render();
|
||||
new Thread(()->{try{JSONObject result=DisplayApi.call("/api/location/update",token,body);remember(result);runOnUiThread(()->{if(!visible||g!=generation)return;settingsReceipt=result.optString("receipt");settingsReady=true;LocationService.busy=true;try{startForegroundService(new Intent(this,LocationService.class).setAction("START"));}catch(Exception e){LocationService.busy=false;Toast.makeText(this,"未能启动定位,请保持页面在前台再试",1).show();}render();});}
|
||||
catch(Exception e){runOnUiThread(()->{if(visible&&g==generation)Toast.makeText(this,"开启未成功,请重新读取设置并核对名单",1).show();});}
|
||||
finally{pairing=false;runOnUiThread(()->{if(!isDestroyed()){if(visible&&!settingsReady)loadSettings();render();}});}},"location-configure").start();
|
||||
}
|
||||
int samplePeriodSeconds(){int index=sampleCadence.getSelectedItemPosition();return sampleIntervals[index]>0?sampleIntervals[index]:LocationCadence.customSample(Integer.parseInt(sampleAmount.getText().toString().trim()),sampleUnits[sampleUnit.getSelectedItemPosition()]);}
|
||||
void setSamplePeriod(int seconds){seconds=LocationCadence.sample(seconds);for(int i=0;i<sampleIntervals.length-1;i++)if(sampleIntervals[i]==seconds){sampleCadence.setSelection(i);return;}sampleCadence.setSelection(sampleIntervals.length-1);int unit=seconds%86400==0?3:seconds%3600==0?2:seconds%60==0?1:0;sampleUnit.setSelection(unit);sampleAmount.setText(Integer.toString(seconds/sampleUnits[unit]));}
|
||||
int uploadPeriod(){int index=cadence.getSelectedItemPosition();return uploadIntervals[index]>0?uploadIntervals[index]:LocationCadence.custom(Integer.parseInt(customAmount.getText().toString().trim()),customUnit.getSelectedItemPosition()==1);}
|
||||
void setUploadPeriod(int seconds){for(int i=0;i<uploadIntervals.length-1;i++)if(uploadIntervals[i]==seconds){cadence.setSelection(i);return;}cadence.setSelection(uploadIntervals.length-1);boolean days=seconds%86400==0;customUnit.setSelection(days?1:0);customAmount.setText(Integer.toString(seconds/(days?86400:3600)));}
|
||||
void refreshQueueStats(){try{queueOwner=LocationQueue.digest(prefs.getString("token",""));long[] values=outbox.stats(queueOwner);prefs.edit().putLong("pendingPoints",values[0]).putLong("pendingBytes",values[1]).putLong("uploadedPoints",values[2]).putLong("freedBytes",values[3]).apply();}catch(Exception e){prefs.edit().putString("syncStatus","本机轨迹暂不能读取,数据没有删除").apply();}}
|
||||
|
||||
@@ -5,7 +5,10 @@ final class LocationCadence {
|
||||
static final int MAX_SECONDS=30*86400;
|
||||
static boolean valid(int value){return value==10||value==60||value==300||value>=3600&&value<=MAX_SECONDS&&value%3600==0;}
|
||||
static int seconds(int value){return valid(value)?value:300;}
|
||||
static int sample(int value){return value==10||value==60||value==300?value:60;}
|
||||
static boolean sampleValid(int value){return value>=10&&value<=86400;}
|
||||
static int sample(int value){return sampleValid(value)?value:60;}
|
||||
static int customSample(int value,int unit){long seconds=value*(long)unit;if(value<1||(unit!=1&&unit!=60&&unit!=3600&&unit!=86400)||seconds<10||seconds>86400)throw new IllegalArgumentException("采集间隔需在 10 秒至 1 天内");return (int)seconds;}
|
||||
static boolean sampleDue(long now,long previous,int seconds){return previous==0||now-previous>=sample(seconds)*1000L;}
|
||||
static int custom(int value,boolean days){long seconds=value*(days?86400L:3600L);if(value<1||seconds>MAX_SECONDS)throw new IllegalArgumentException("周期需在 1 小时至 30 天内");return (int)seconds;}
|
||||
static boolean due(long now,long lastAttempt,int interval,boolean firstFix){
|
||||
return lastAttempt==0||now-lastAttempt>=1000L*(firstFix?10:seconds(interval));
|
||||
|
||||
@@ -121,13 +121,14 @@ public class LocationService extends Service implements LocationListener {
|
||||
prefs.edit().putBoolean("active",false).putString("status","本机已停止采集,联网后通知平台清除当前位置;关闭前轨迹仍会补传").apply();notification("已停止定位 · 联网后完成同步");nextAttempt=0;
|
||||
}
|
||||
public void onLocationChanged(Location value){
|
||||
if(!active||stopping)return;latest=new Location(value);if(!historyEnabled)return;
|
||||
Location fix=new Location(value);String session=collection;long epoch=prefs.getLong("queueEpoch",0),started=collectionStarted;
|
||||
if(!active||stopping)return;
|
||||
Location fix=new Location(value);long elapsed=fix.getElapsedRealtimeNanos()/1000000;
|
||||
if(!LocationCadence.sampleDue(elapsed,lastSample,sampleSeconds)||fix.getTime()<collectionStarted-5000||fix.getTime()>System.currentTimeMillis()+60000||System.currentTimeMillis()-fix.getTime()>900000)return;
|
||||
lastSample=elapsed;latest=fix;if(!historyEnabled)return;
|
||||
String session=collection;long epoch=prefs.getLong("queueEpoch",0);
|
||||
recorder.execute(()->{try{
|
||||
if(epoch!=prefs.getLong("queueEpoch",0))return;
|
||||
long elapsed=fix.getElapsedRealtimeNanos()/1000000;
|
||||
if(lastSample!=0&&elapsed-lastSample<sampleSeconds*1000L||fix.getTime()<started-5000||fix.getTime()>System.currentTimeMillis()+60000||System.currentTimeMillis()-fix.getTime()>900000)return;
|
||||
if(queue.append(owner,session,position(fix))){lastSample=elapsed;cacheFull=false;}
|
||||
if(queue.append(owner,session,position(fix))){cacheFull=false;}
|
||||
else{cacheFull=true;prefs.edit().putString("syncStatus","本地缓存已达上限,暂停新增历史;未上传记录没有覆盖,请联网补传").apply();notification("轨迹缓存已满 · 请联网补传");}
|
||||
updateQueueStatus();
|
||||
}catch(Exception error){cacheFull=true;prefs.edit().putString("syncStatus","本地轨迹未能写入,请检查手机存储空间;已有记录保留").apply();}});
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package cn.ucvl.zhaodisplay;
|
||||
|
||||
/** Same cancel rule for touch and the recording deadline; no audio or network dependency. */
|
||||
final class VoiceGesture {
|
||||
static boolean cancel(float deltaY,float x,float width,float threshold){return deltaY<=-threshold||x<0||x>width;}
|
||||
static boolean sendAtLimit(boolean cancelled){return !cancelled;}
|
||||
}
|
||||
@@ -19,63 +19,87 @@ import java.util.function.Supplier;
|
||||
final class VoicePanel extends LinearLayout {
|
||||
final Activity app;final String kind;final Supplier<String> token;
|
||||
final Handler ui=new Handler();final ExecutorService worker=Executors.newSingleThreadExecutor();
|
||||
final TextView status;final Spinner targets;final Button speak,settings,stop;
|
||||
final TextView status;final Button speak,settings,stop;final VoiceSurface dock;VoiceSurface expanded;Dialog sheet;
|
||||
String selectedId="";boolean networkReady=false;long feedbackAt=0;
|
||||
final AudioManager audio;final AudioAttributes attributes=new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build();
|
||||
AudioFocusRequest focus;MediaRecorder recorder;MediaPlayer player;File recording,playing;
|
||||
JSONArray choices=new JSONArray(),allowed=new JSONArray(),destinations=new JSONArray();
|
||||
boolean enabled=false,cancelled=false,sending=false,night=false,polling=false;volatile boolean visible=false,closed=false;volatile int epoch=0;
|
||||
long started;String recordTarget="",recordToken="",playingId="",playingToken="",lastMessage="";
|
||||
final Runnable refresh=new Runnable(){public void run(){if(!visible||closed)return;poll();ui.postDelayed(this,5000);}};
|
||||
final Runnable limit=()->finish(true);
|
||||
final Runnable limit=()->finish(VoiceGesture.sendAtLimit(cancelled));
|
||||
final Runnable visual=new Runnable(){public void run(){if(!visible||closed)return;renderSurfaces();ui.postDelayed(this,recorder!=null?100:500);}};
|
||||
VoicePanel(Activity activity,String type,Supplier<String> credentials){
|
||||
super(activity);app=activity;kind=type;token=credentials;audio=(AudioManager)app.getSystemService(Context.AUDIO_SERVICE);
|
||||
setOrientation(VERTICAL);int p=(int)(8*getResources().getDisplayMetrics().density);setPadding(p,p,p,p);setBackgroundColor(0xffe5ebe5);
|
||||
status=new TextView(app);status.setTextSize(14);status.setTextColor(0xff254b3f);status.setText("家人喊话 · 先配对,再选择接收人");addView(status);
|
||||
LinearLayout row=new LinearLayout(app);row.setGravity(Gravity.CENTER_VERTICAL);addView(row);
|
||||
targets=new Spinner(app);row.addView(targets,new LayoutParams(0,-2,1));
|
||||
speak=new Button(app);speak.setText("🎙 按住说话");speak.setEnabled(false);row.addView(speak);
|
||||
speak.setOnTouchListener((v,event)->{
|
||||
setOrientation(VERTICAL);dock=new VoiceSurface(app,false);addView(dock,new LayoutParams(-1,-2));
|
||||
status=dock.status;speak=dock.speak;settings=dock.settings;stop=dock.stop;wire(dock);speak.setEnabled(false);stop.setEnabled(false);
|
||||
for(File file:Optional.ofNullable(app.getCacheDir().listFiles()).orElse(new File[0]))if(file.getName().startsWith("voice-"))file.delete();
|
||||
}
|
||||
void showStatus(String text){VoiceSurface.text(status,text);feedbackAt=SystemClock.elapsedRealtime();if(expanded!=null)VoiceSurface.text(expanded.status,text);}
|
||||
void wire(VoiceSurface view){
|
||||
view.settings.setOnClickListener(v->configure());view.stop.setOnClickListener(v->stopPlayer("rejected"));
|
||||
view.expand.setOnClickListener(v->{if(view.full&&sheet!=null)sheet.dismiss();else openSheet();});view.recipient.setOnClickListener(v->{if(!view.full)openSheet();});
|
||||
final float[] down={0};view.speak.setOnTouchListener((v,event)->{
|
||||
switch(event.getActionMasked()){
|
||||
case MotionEvent.ACTION_DOWN:begin();return true;
|
||||
case MotionEvent.ACTION_MOVE:cancelled=event.getX()<0||event.getY()<0||event.getX()>v.getWidth()||event.getY()>v.getHeight();if(recorder!=null)speak.setText(cancelled?"松开取消":"松开发送");return true;
|
||||
case MotionEvent.ACTION_UP:finish(!cancelled);v.performClick();return true;
|
||||
case MotionEvent.ACTION_DOWN:down[0]=event.getRawY();v.getParent().requestDisallowInterceptTouchEvent(true);begin();return true;
|
||||
case MotionEvent.ACTION_MOVE:cancelled=VoiceGesture.cancel(event.getRawY()-down[0],event.getX(),v.getWidth(),view.dp(48));renderSurfaces();return true;
|
||||
case MotionEvent.ACTION_UP:v.getParent().requestDisallowInterceptTouchEvent(false);finish(!cancelled);return true;
|
||||
case MotionEvent.ACTION_POINTER_DOWN:finish(false);return true;
|
||||
case MotionEvent.ACTION_CANCEL:finish(false);return true;
|
||||
}return false;
|
||||
});
|
||||
speak.setOnKeyListener((v,key,event)->{if(key!=KeyEvent.KEYCODE_DPAD_CENTER&&key!=KeyEvent.KEYCODE_ENTER)return false;if(event.getAction()==KeyEvent.ACTION_DOWN){if(event.getRepeatCount()==0)begin();}else finish(true);return true;});
|
||||
LinearLayout tools=new LinearLayout(app);addView(tools);
|
||||
settings=new Button(app);settings.setText("接收设置");settings.setOnClickListener(v->configure());tools.addView(settings,new LayoutParams(0,-2,1));
|
||||
stop=new Button(app);stop.setText("停止播放");stop.setEnabled(false);stop.setOnClickListener(v->stopPlayer("rejected"));tools.addView(stop,new LayoutParams(0,-2,1));
|
||||
for(File file:Optional.ofNullable(app.getCacheDir().listFiles()).orElse(new File[0]))if(file.getName().startsWith("voice-"))file.delete();
|
||||
view.speak.setOnKeyListener((v,key,event)->{if(key!=KeyEvent.KEYCODE_DPAD_CENTER&&key!=KeyEvent.KEYCODE_ENTER)return false;if(event.getAction()==KeyEvent.ACTION_DOWN){if(event.getRepeatCount()==0)begin();}else finish(true);return true;});
|
||||
view.speak.setOnClickListener(v->{android.view.accessibility.AccessibilityManager a=(android.view.accessibility.AccessibilityManager)app.getSystemService(Context.ACCESSIBILITY_SERVICE);if(a!=null&&a.isTouchExplorationEnabled()){if(recorder==null)begin();else finish(true);}});
|
||||
}
|
||||
void openSheet(){
|
||||
if(closed||sheet!=null&&sheet.isShowing())return;
|
||||
expanded=new VoiceSurface(app,true);wire(expanded);expanded.applyTheme(night);
|
||||
ScrollView scroll=new ScrollView(app);scroll.setFillViewport(true);scroll.addView(expanded);
|
||||
sheet=new Dialog(app,android.R.style.Theme_Material_Light_NoActionBar);sheet.setContentView(scroll);
|
||||
sheet.setOnDismissListener(d->{finish(false);expanded=null;sheet=null;});sheet.show();
|
||||
sheet.getWindow().setLayout(-1,-1);sheet.getWindow().setStatusBarColor(night?0xff172820:0xfff8f5ed);sheet.getWindow().setNavigationBarColor(night?0xff172820:0xfff8f5ed);
|
||||
sheet.getWindow().getDecorView().setSystemUiVisibility(night?0:View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR|View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
|
||||
renderSurfaces();
|
||||
}
|
||||
JSONObject destination(){if(destinations!=null)for(int i=0;i<destinations.length();i++){JSONObject d=destinations.optJSONObject(i);if(d!=null&&d.optString("id").equals(selectedId))return d;}return null;}
|
||||
void choose(String id){if(recorder!=null||sending)return;selectedId=id;lastMessage="";JSONObject d=destination();showStatus(d!=null&&d.optBoolean("online")?"按住说话,松开发送给 "+d.optString("name"):"请先让对方打开 App,再向其喊话");renderSurfaces();}
|
||||
void renderSurfaces(){
|
||||
JSONObject selected=destination();String name=selected==null?"":selected.optString("name");boolean available=selected!=null&&selected.optBoolean("online");
|
||||
boolean can=networkReady&&available&&!sending&µphone();int amplitude=0;if(recorder!=null)try{amplitude=recorder.getMaxAmplitude();}catch(Exception ignored){}
|
||||
for(VoiceSurface view:new VoiceSurface[]{dock,expanded}){if(view==null)continue;
|
||||
view.targets(destinations,selectedId,this::choose);if(recorder==null||view.full)VoiceSurface.text(view.recipient,name.isEmpty()?"选择一位家人":view.full?"对"+name+"说句话":name+" · "+(available?"已打开 App":"未打开 App")+" ›");
|
||||
VoiceSurface.text(view.receive,enabled?"● 接收已开启 · 仅限你允许的家人":"○ 接收已关闭 · 可在接收设置中开启");
|
||||
view.settings.setEnabled(networkReady&&recorder==null&&!sending);view.stop.setVisibility(player!=null?View.VISIBLE:View.GONE);view.stop.setEnabled(player!=null);
|
||||
view.recording(recorder!=null,cancelled,recorder==null?0:SystemClock.elapsedRealtime()-started,amplitude,sending,can);
|
||||
if(view!=dock)VoiceSurface.text(view.status,status.getText());
|
||||
if(!microphone()&&recorder==null&&!sending)view.speak.setText("待接入话筒");
|
||||
}
|
||||
}
|
||||
JSONObject body(String action)throws Exception{return new JSONObject().put("kind",kind).put("action",action);}
|
||||
boolean current(int e,String t){return visible&&!closed&&e==epoch&&t.equals(token.get());}
|
||||
void active(boolean value){
|
||||
if(closed)return;visible=value;epoch++;ui.removeCallbacks(refresh);
|
||||
if(value){ui.post(refresh);}else{finish(false);stopPlayer("rejected");String t=token.get();if(!t.isEmpty())worker.execute(()->{try{DisplayApi.call("/api/voice",t,body("offline"));}catch(Exception ignored){}});}
|
||||
if(closed)return;visible=value;epoch++;ui.removeCallbacks(refresh);ui.removeCallbacks(visual);
|
||||
if(value){ui.post(refresh);ui.post(visual);}else{if(sheet!=null)sheet.dismiss();finish(false);stopPlayer("rejected");String t=token.get();if(!t.isEmpty())worker.execute(()->{try{DisplayApi.call("/api/voice",t,body("offline"));}catch(Exception ignored){}});}
|
||||
}
|
||||
void rebound(){active(false);choices=new JSONArray();allowed=new JSONArray();destinations=new JSONArray();enabled=false;lastMessage="";active(true);}
|
||||
void rebound(){active(false);choices=new JSONArray();allowed=new JSONArray();destinations=new JSONArray();enabled=false;networkReady=false;selectedId="";lastMessage="";active(true);}
|
||||
void close(){active(false);closed=true;ui.removeCallbacksAndMessages(null);worker.shutdown();}
|
||||
void poll(){
|
||||
if(polling||closed||!visible)return;
|
||||
String t=token.get();if(t.isEmpty()){speak.setEnabled(false);settings.setEnabled(false);return;}final int e=epoch;polling=true;
|
||||
worker.execute(()->{try{
|
||||
JSONObject value=DisplayApi.call("/api/voice",t,body("status"));
|
||||
ui.post(()->{if(!current(e,t))return;choices=value.optJSONArray("candidates");allowed=value.optJSONArray("allowed");enabled=value.optBoolean("enabled");settings.setEnabled(true);
|
||||
ui.post(()->{if(!current(e,t))return;choices=value.optJSONArray("candidates");allowed=value.optJSONArray("allowed");enabled=value.optBoolean("enabled");networkReady=true;settings.setEnabled(true);
|
||||
if(!enabled&&player!=null)stopPlayer("rejected");
|
||||
if(recorder==null&&!sending){String selected=selectedTarget();destinations=value.optJSONArray("targets");List<String> names=new ArrayList<>();int index=0;
|
||||
if(destinations!=null)for(int i=0;i<destinations.length();i++){JSONObject d=destinations.optJSONObject(i);names.add(d.optString("name")+(d.optBoolean("online")?" · 在线":" · 未打开 App"));if(d.optString("id").equals(selected))index=i;}
|
||||
if(names.isEmpty())names.add("暂无允许接收的对象");targets.setAdapter(new ArrayAdapter<String>(app,android.R.layout.simple_spinner_dropdown_item,names){public View getView(int position,View convert,ViewGroup parent){TextView view=(TextView)super.getView(position,convert,parent);view.setTextColor(night?0xffa6b5ac:0xff254b3f);return view;}});targets.setSelection(index);
|
||||
speak.setEnabled(destinations!=null&&destinations.length()>0&µphone());speak.setText(microphone()?"🎙 按住说话":"待接入话筒");
|
||||
}
|
||||
JSONArray sent=value.optJSONArray("sent");if(sent!=null&&!lastMessage.isEmpty())for(int i=0;i<sent.length();i++){JSONObject r=sent.optJSONObject(i);if(lastMessage.equals(r.optString("id"))){String s=r.optString("status");status.setText(s.equals("played")?"对方已播放":s.equals("rejected")?"对方已停止或未播放":s.equals("expired")?"喊话已过期,未播放":s.equals("received")?"对方正在接收":"已发送,等待对方播放");}}
|
||||
if(lastMessage.isEmpty()&&player==null&&recorder==null)status.setText("家人喊话 · "+(enabled?"接收已开启":"接收已关闭")+" · 最长 30 秒");
|
||||
if(recorder==null&&!sending){destinations=value.optJSONArray("targets");if(destination()==null){selectedId="";if(destinations!=null&&destinations.length()>0){selectedId=destinations.optJSONObject(0).optString("id");for(int i=0;i<destinations.length();i++){JSONObject d=destinations.optJSONObject(i);if(d.optBoolean("online")){selectedId=d.optString("id");break;}}}}}
|
||||
JSONArray sent=value.optJSONArray("sent");if(sent!=null&&!lastMessage.isEmpty()&&recorder==null&&player==null&&!sending)for(int i=0;i<sent.length();i++){JSONObject r=sent.optJSONObject(i);if(lastMessage.equals(r.optString("id"))){String s=r.optString("status");showStatus(s.equals("played")?"对方已播放":s.equals("rejected")?"对方已停止或未播放":s.equals("expired")?"喊话已过期,未播放":s.equals("received")?"对方正在接收":"已发送,等待对方播放");}}
|
||||
if(lastMessage.isEmpty()&&player==null&&recorder==null&&!sending&&SystemClock.elapsedRealtime()-feedbackAt>12000)showStatus(destination()==null?"暂无允许接收的家人,请对方开启接收":!destination().optBoolean("online")?"请对方打开 App 后再说话":"按住说话,松开发送 · 上滑取消");
|
||||
renderSurfaces();
|
||||
JSONArray inbox=value.optJSONArray("inbox");if(enabled&&player==null&&recorder==null&&!sending&&inbox!=null&&inbox.length()>0)take(inbox.optJSONObject(0).optString("id"));
|
||||
});
|
||||
}catch(Exception error){ui.post(()->{if(current(e,t)){speak.setEnabled(false);settings.setEnabled(false);if(error instanceof DisplayApi.ApiError&&(((DisplayApi.ApiError)error).status==401||((DisplayApi.ApiError)error).status==403)){finish(false);stopPlayer("rejected");enabled=false;destinations=new JSONArray();}status.setText("喊话连接暂不可用,请检查网络和配对");}});}finally{ui.post(()->polling=false);}});
|
||||
}catch(Exception error){ui.post(()->{if(current(e,t)){networkReady=false;speak.setEnabled(false);settings.setEnabled(false);if(error instanceof DisplayApi.ApiError&&(((DisplayApi.ApiError)error).status==401||((DisplayApi.ApiError)error).status==403)){finish(false);stopPlayer("rejected");enabled=false;destinations=new JSONArray();}showStatus("喊话连接暂不可用,请检查网络和配对");}});}finally{ui.post(()->polling=false);}});
|
||||
}
|
||||
String selectedTarget(){JSONObject d=destinations==null?null:destinations.optJSONObject(targets.getSelectedItemPosition());return d==null?"":d.optString("id");}
|
||||
void night(boolean value){night=value;setBackgroundColor(value?0xff17231e:0xffe5ebe5);status.setTextColor(value?0xffa6b5ac:0xff254b3f);for(Button b:new Button[]{speak,settings,stop}){b.setTextColor(value?0xffa6b5ac:0xff254b3f);b.setBackgroundTintList(android.content.res.ColorStateList.valueOf(value?0xff25362d:0xffd0dfd6));}View selected=targets.getSelectedView();if(selected instanceof TextView)((TextView)selected).setTextColor(value?0xffa6b5ac:0xff254b3f);}
|
||||
String selectedTarget(){return destination()==null?"":selectedId;}
|
||||
void night(boolean value){night=value;dock.applyTheme(value);if(expanded!=null)expanded.applyTheme(value);renderSurfaces();}
|
||||
boolean microphone(){try{return audio.getDevices(AudioManager.GET_DEVICES_INPUTS).length>0;}catch(Exception e){return false;}}
|
||||
void configure(){
|
||||
if(choices==null)return;final JSONArray options=choices;String[] names=new String[options.length()];boolean[] checked=new boolean[names.length];
|
||||
@@ -85,33 +109,33 @@ final class VoicePanel extends LinearLayout {
|
||||
.setPositiveButton("允许所选对象",(d,w)->{JSONArray selected=new JSONArray();for(int i=0;i<checked.length;i++)if(checked[i])selected.put(options.optJSONObject(i).optString("id"));saveSettings(true,selected);}).show();
|
||||
}
|
||||
void saveSettings(boolean receive,JSONArray ids){
|
||||
if(receive&&ids.length()==0){status.setText("请先选择允许的家人或终端");return;}
|
||||
if(receive&&ids.length()==0){showStatus("请先选择允许的家人或终端");return;}
|
||||
if(!receive){enabled=false;stopPlayer("rejected");}String t=token.get();int e=epoch;
|
||||
worker.execute(()->{try{DisplayApi.call("/api/voice",t,body("configure").put("enabled",receive).put("allowed",ids).put("consent",true));ui.post(()->{if(current(e,t)){lastMessage="";poll();}});}catch(Exception error){ui.post(()->{if(current(e,t))status.setText("接收设置保存失败,请检查网络后重试");});}});
|
||||
worker.execute(()->{try{DisplayApi.call("/api/voice",t,body("configure").put("enabled",receive).put("allowed",ids).put("consent",true));ui.post(()->{if(current(e,t)){lastMessage="";poll();}});}catch(Exception error){ui.post(()->{if(current(e,t))showStatus("接收设置保存失败,请检查网络后重试");});}});
|
||||
}
|
||||
void begin(){
|
||||
if(!visible||recorder!=null||sending||selectedTarget().isEmpty())return;
|
||||
JSONObject target=destinations.optJSONObject(targets.getSelectedItemPosition());if(target==null||!target.optBoolean("online")){status.setText("请先让对方打开 App");return;}
|
||||
if(!microphone()){status.setText("请先连接麦克风;仍可接收家人喊话");return;}
|
||||
if(app.checkSelfPermission(Manifest.permission.RECORD_AUDIO)!=0){app.requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO},46);status.setText("授权麦克风后,再次按住说话");return;}
|
||||
JSONObject target=destination();if(target==null||!target.optBoolean("online")){showStatus("请先让对方打开 App");return;}
|
||||
if(!microphone()){showStatus("请先连接麦克风;仍可接收家人喊话");return;}
|
||||
if(app.checkSelfPermission(Manifest.permission.RECORD_AUDIO)!=0){app.requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO},46);showStatus("授权麦克风后,再次按住说话");return;}
|
||||
stopPlayer("rejected");cancelled=false;recordTarget=selectedTarget();recordToken=token.get();lastMessage="";
|
||||
try{
|
||||
recording=File.createTempFile("voice-record-",".aac",app.getCacheDir());recorder=new MediaRecorder();recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
|
||||
recorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS);recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);recorder.setAudioSamplingRate(16000);recorder.setAudioChannels(1);recorder.setAudioEncodingBitRate(32000);recorder.setOutputFile(recording.getAbsolutePath());recorder.prepare();recorder.start();started=SystemClock.elapsedRealtime();
|
||||
speak.setText("松开发送");targets.setEnabled(false);settings.setEnabled(false);status.setText("正在录音 · 移出按钮后松开取消");ui.postDelayed(limit,30000);
|
||||
}catch(Exception error){finish(false);status.setText("无法录音,请检查话筒和权限");}
|
||||
settings.setEnabled(false);showStatus("正在对"+target.optString("name")+"说话");ui.postDelayed(limit,30000);renderSurfaces();
|
||||
}catch(Exception error){finish(false);showStatus("无法录音,请检查话筒和权限");}
|
||||
}
|
||||
void finish(boolean send){
|
||||
ui.removeCallbacks(limit);if(recorder==null)return;MediaRecorder r=recorder;recorder=null;
|
||||
try{r.stop();}catch(Exception error){send=false;}finally{r.release();}
|
||||
File file=recording;recording=null;speak.setText("🎙 按住说话");targets.setEnabled(true);settings.setEnabled(true);
|
||||
if(!send||SystemClock.elapsedRealtime()-started<350||file==null){if(file!=null)file.delete();status.setText("录音已取消");return;}
|
||||
final String t=recordToken,destination=recordTarget;final int e=epoch;sending=true;speak.setEnabled(false);status.setText("正在发送喊话…");
|
||||
File file=recording;recording=null;settings.setEnabled(true);renderSurfaces();
|
||||
if(!send||SystemClock.elapsedRealtime()-started<350||file==null){if(file!=null)file.delete();showStatus(send?"说话时间太短,请按住后再说一句":"已取消,这条语音没有发送");renderSurfaces();return;}
|
||||
final String t=recordToken,destination=recordTarget;final int e=epoch;sending=true;speak.setEnabled(false);showStatus("正在发送喊话…");
|
||||
worker.execute(()->{try{
|
||||
if(!current(e,t))return;byte[] bytes=Files.readAllBytes(file.toPath());if(bytes.length>150000)throw new IOException("Too large");
|
||||
JSONObject result=DisplayApi.call("/api/voice",t,body("send").put("target",destination).put("id",UUID.randomUUID().toString().replace("-","")).put("audio",Base64.encodeToString(bytes,Base64.NO_WRAP)));
|
||||
ui.post(()->{if(current(e,t)){lastMessage=result.optString("id");status.setText("已发送,等待对方播放");}});
|
||||
}catch(Exception error){ui.post(()->{if(current(e,t))status.setText("发送未成功,请检查对方的接收权限和在线状态");});}
|
||||
ui.post(()->{if(current(e,t)){lastMessage=result.optString("id");showStatus("已发送,等待对方播放");}});
|
||||
}catch(Exception error){ui.post(()->{if(current(e,t))showStatus("未发送,请检查网络或对方的接收权限后重新录制");});}
|
||||
finally{file.delete();ui.post(()->{sending=false;if(current(e,t))poll();});}});
|
||||
}
|
||||
void take(String id){
|
||||
@@ -127,16 +151,16 @@ final class VoicePanel extends LinearLayout {
|
||||
playingToken=t;focus=new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT).setAudioAttributes(attributes).setOnAudioFocusChangeListener(change->{if(change<0)stopPlayer("rejected");}).build();
|
||||
if(audio.requestAudioFocus(focus)!=AudioManager.AUDIOFOCUS_REQUEST_GRANTED)throw new IOException("Audio busy");
|
||||
playing=File.createTempFile("voice-play-",".aac",app.getCacheDir());Files.write(playing.toPath(),bytes);player=new MediaPlayer();player.setAudioAttributes(attributes);player.setDataSource(playing.getAbsolutePath());
|
||||
player.setOnPreparedListener(p->{if(visible&&enabled&&p==player){p.start();stop.setEnabled(true);status.setText(clip.optString("senderName")+"正在喊话 · "+clip.optDouble("seconds")+" 秒");}else stopPlayer("rejected");});
|
||||
player.setOnPreparedListener(p->{if(visible&&enabled&&p==player){p.start();stop.setEnabled(true);showStatus(clip.optString("senderName")+"正在喊话 · "+clip.optDouble("seconds")+" 秒");}else stopPlayer("rejected");});
|
||||
player.setOnCompletionListener(p->stopPlayer("played"));player.setOnErrorListener((p,what,extra)->{stopPlayer("rejected");return true;});player.prepareAsync();
|
||||
}catch(Exception error){stopPlayer("rejected");status.setText("语音未能播放,请检查扬声器");}
|
||||
}catch(Exception error){stopPlayer("rejected");showStatus("语音未能播放,请检查扬声器");}
|
||||
}
|
||||
void stopPlayer(String outcome){
|
||||
if(player!=null){try{player.release();}catch(Exception ignored){}player=null;}
|
||||
if(focus!=null){audio.abandonAudioFocusRequest(focus);focus=null;}
|
||||
if(playing!=null){playing.delete();playing=null;}
|
||||
if(!playingId.isEmpty()&&!playingToken.isEmpty())ack(playingToken,playingId,outcome);
|
||||
playingId="";playingToken="";stop.setEnabled(false);
|
||||
playingId="";playingToken="";stop.setEnabled(false);renderSurfaces();
|
||||
}
|
||||
void ack(String t,String id,String state){if(!worker.isShutdown())worker.execute(()->{try{DisplayApi.call("/api/voice",t,body("ack").put("id",id).put("status",state));}catch(Exception ignored){}});}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package cn.ucvl.zhaodisplay;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.res.ColorStateList;
|
||||
import android.graphics.*;
|
||||
import android.graphics.drawable.*;
|
||||
import android.view.*;
|
||||
import android.widget.*;
|
||||
import org.json.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** Native warm, large-target view shared by the compact dock and full voice sheet. */
|
||||
final class VoiceSurface extends LinearLayout {
|
||||
final boolean full;final TextView title,subtitle,recipient,status,hint,clock,receive;
|
||||
final Button speak,settings,stop,expand;final LinearLayout people,compose;final HorizontalScrollView strip;
|
||||
final VoiceArt art;boolean night=false;String targetSignature="",controlSignature="";
|
||||
int ink(){return night?0xffc8d5cd:0xff29443c;}int muted(){return night?0xff96aaa0:0xff65766d;}
|
||||
int accent(){return night?0xff456b5e:0xff17695e;}int paper(){return night?0xff172820:0xfff8f5ed;}
|
||||
int card(){return night?0xff21372d:0xfffffefa;}
|
||||
int dp(float n){return Math.round(n*getResources().getDisplayMetrics().density);}
|
||||
VoiceSurface(Activity activity,boolean expanded){
|
||||
super(activity);full=expanded;setOrientation(VERTICAL);setPadding(dp(full?20:12),dp(full?20:8),dp(full?20:12),dp(full?22:8));
|
||||
LinearLayout header=new LinearLayout(activity);header.setGravity(Gravity.CENTER_VERTICAL);addView(header);
|
||||
title=label(full?"家人喊话":"家人喊话",full?30:19);title.setTypeface(null,Typeface.BOLD);header.addView(title,new LayoutParams(0,-2,1));
|
||||
settings=button("接收设置",14);header.addView(settings);expand=button(full?"收起":"展开",14);header.addView(expand);
|
||||
subtitle=label("一句问候,家就在身边",17);if(full){addView(subtitle);space(16);}
|
||||
strip=new HorizontalScrollView(activity);strip.setHorizontalScrollBarEnabled(false);strip.setClipToPadding(false);
|
||||
people=new LinearLayout(activity);people.setOrientation(HORIZONTAL);strip.addView(people);if(full)addView(strip,new LayoutParams(-1,-2));
|
||||
receive=label("",13);if(full){space(8);addView(receive);space(16);}
|
||||
recipient=label("选择一位家人",full?23:15);recipient.setTypeface(null,full?Typeface.BOLD:Typeface.NORMAL);recipient.setMaxLines(full?2:1);recipient.setEllipsize(android.text.TextUtils.TruncateAt.END);addView(recipient);if(full)space(14);
|
||||
compose=new LinearLayout(activity);compose.setOrientation(VERTICAL);compose.setGravity(Gravity.CENTER_HORIZONTAL);compose.setPadding(dp(full?20:0),dp(full?18:0),dp(full?20:0),dp(full?18:0));addView(compose,new LayoutParams(-1,-2));
|
||||
art=new VoiceArt(activity);art.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);if(full)compose.addView(art,new LayoutParams(-1,dp(88)));
|
||||
clock=label("按住说话,松开发送",16);clock.setGravity(Gravity.CENTER);if(full)compose.addView(clock,new LayoutParams(-1,dp(56)));
|
||||
status=label("先配对,再选择家人",full?16:13);status.setGravity(Gravity.CENTER);status.setAccessibilityLiveRegion(ACCESSIBILITY_LIVE_REGION_POLITE);
|
||||
speak=button("按住说话",full?24:21);speak.setTypeface(null,Typeface.BOLD);speak.setCompoundDrawablePadding(dp(12));speak.setContentDescription("按住说话,松开发送,上滑取消");
|
||||
LayoutParams talkParams=new LayoutParams(-1,dp(full?80:64));talkParams.topMargin=dp(full?14:6);compose.addView(speak,talkParams);
|
||||
hint=label("上滑取消 · 最长 30 秒",13);hint.setGravity(Gravity.CENTER);if(full){spaceIn(compose,10);compose.addView(hint);spaceIn(compose,16);}else spaceIn(compose,4);
|
||||
compose.addView(status,new LayoutParams(-1,-2));
|
||||
stop=button("停止播放",16);stop.setVisibility(GONE);compose.addView(stop);
|
||||
applyTheme(false);
|
||||
}
|
||||
TextView label(String text,int size){TextView v=new TextView(getContext());v.setText(text);v.setTextSize(size);v.setPadding(0,dp(3),0,dp(3));return v;}
|
||||
static void text(TextView view,CharSequence value){if(!android.text.TextUtils.equals(view.getText(),value))view.setText(value);}
|
||||
Button button(String text,int size){Button b=new Button(getContext());b.setText(text);b.setTextSize(size);b.setAllCaps(false);b.setMinHeight(dp(44));b.setMinimumHeight(dp(44));b.setMinWidth(0);b.setMinimumWidth(0);b.setPadding(dp(12),dp(8),dp(12),dp(8));b.setStateListAnimator(null);return b;}
|
||||
void space(int amount){spaceIn(this,amount);}void spaceIn(LinearLayout parent,int amount){parent.addView(new View(getContext()),new LayoutParams(1,dp(amount)));}
|
||||
GradientDrawable shape(int color,int border,int radius){GradientDrawable d=new GradientDrawable();d.setColor(color);d.setCornerRadius(dp(radius));if(border!=0)d.setStroke(dp(1),border);return d;}
|
||||
void applyTheme(boolean value){
|
||||
night=value;setBackgroundColor(paper());for(TextView t:new TextView[]{title,recipient,clock})t.setTextColor(ink());for(TextView t:new TextView[]{subtitle,status,hint,receive})t.setTextColor(muted());
|
||||
compose.setBackground(full?shape(card(),night?0xff345043:0xffe4e8df,26):null);
|
||||
for(Button b:new Button[]{settings,stop,expand}){b.setTextColor(ink());b.setBackground(shape(night?0xff2d4439:0xffefeee6,0,18));}
|
||||
art.night=value;art.invalidate();targetSignature="";controlSignature="";
|
||||
}
|
||||
void targets(JSONArray values,String selected,Consumer<String> choose){
|
||||
String signature=String.valueOf(values)+selected+night;if(signature.equals(targetSignature))return;targetSignature=signature;people.removeAllViews();
|
||||
if(values==null||values.length()==0){TextView empty=label("暂无允许接收的家人\n请对方打开 App,在接收设置中允许你",16);empty.setTextColor(muted());people.addView(empty,new LayoutParams(dp(285),-2));return;}
|
||||
for(int i=0;i<values.length();i++){
|
||||
JSONObject item=values.optJSONObject(i);if(item==null)continue;String id=item.optString("id"),name=item.optString("name","家人");boolean chosen=id.equals(selected),online=item.optBoolean("online");
|
||||
LinearLayout tile=new LinearLayout(getContext());tile.setOrientation(VERTICAL);tile.setGravity(Gravity.CENTER);tile.setPadding(dp(8),dp(12),dp(8),dp(10));
|
||||
tile.setBackground(shape(chosen?(night?0xff304f40:0xffeaf3ec):card(),chosen?accent():night?0xff345043:0xffe5e6dc,20));tile.setFocusable(true);tile.setClickable(true);tile.setSelected(chosen);tile.setContentDescription(name+","+(online?"已打开 App":"未打开 App")+(chosen?",已选中":",点按选择"));tile.setOnClickListener(v->choose.accept(id));
|
||||
TextView avatar=label(name.isEmpty()?"家":name.substring(0,name.offsetByCodePoints(0,1)),28);avatar.setGravity(Gravity.CENTER);avatar.setTypeface(null,Typeface.BOLD);avatar.setTextColor(chosen?Color.WHITE:ink());avatar.setBackground(shape(chosen?accent():night?0xff375547:0xffe2e9dc,0,30));tile.addView(avatar,new LayoutParams(dp(54),dp(54)));
|
||||
TextView caption=label(name+(chosen?" ✓":""),17);caption.setGravity(Gravity.CENTER);caption.setTypeface(null,Typeface.BOLD);caption.setMaxLines(2);caption.setTextColor(ink());tile.addView(caption);
|
||||
TextView availability=label(online?"● 已打开 App":"○ 未打开 App",12);availability.setGravity(Gravity.CENTER);availability.setTextColor(online?(night?0xff9bbfab:accent()):muted());tile.addView(availability);
|
||||
LayoutParams layout=new LayoutParams(dp(122),dp(146));layout.rightMargin=dp(10);people.addView(tile,layout);
|
||||
}
|
||||
}
|
||||
void recording(boolean recording,boolean cancel,long duration,int amplitude,boolean uploading,boolean canSpeak){
|
||||
int color=cancel?(night?0xff69433b:0xffa84b37):accent();speak.setEnabled(canSpeak||recording);speak.setAlpha(canSpeak||recording?1f:.52f);
|
||||
String label=recording?(cancel?"松开取消":"松开发送"):uploading?"正在发送…":"按住说话";
|
||||
MicIcon inline=new MicIcon(night?0xffc8d5cd:Color.WHITE,dp(24));inline.setBounds(0,0,dp(24),dp(24));
|
||||
android.text.SpannableString text=new android.text.SpannableString(" "+label);text.setSpan(new android.text.style.ImageSpan(inline,android.text.style.ImageSpan.ALIGN_BOTTOM),0,1,android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);if(!android.text.TextUtils.equals(speak.getText(),text)||!controlSignature.equals(color+":"+night))speak.setText(text);speak.setTextColor(night?0xffd1dfd5:Color.WHITE);
|
||||
String signature=color+":"+night;if(!signature.equals(controlSignature)){controlSignature=signature;
|
||||
speak.setBackground(new RippleDrawable(ColorStateList.valueOf(0x337fffff),shape(color,0,32),null));}
|
||||
clock.setTextSize(recording?38:16);clock.setTypeface(null,recording?Typeface.BOLD:Typeface.NORMAL);text(clock,recording?String.format(java.util.Locale.ROOT,"00:%02d",Math.min(30,duration/1000)):"按住说话,松开发送");clock.setTextColor(cancel?color:ink());
|
||||
text(hint,recording?(cancel?"松开手指,取消这条语音":"上滑取消 · 松开发送 · 30 秒自动发送"):"上滑取消 · 最长 30 秒");hint.setTextColor(cancel?color:muted());
|
||||
art.level(recording,cancel,amplitude);if(!full&&recording)text(recipient,String.format(java.util.Locale.CHINA,"%s · %02d 秒",cancel?"松开即取消":"正在录音,上滑可取消",Math.min(30,duration/1000)));
|
||||
}
|
||||
static final class MicIcon extends Drawable {
|
||||
final Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);final int size;
|
||||
MicIcon(int color,int size){paint.setColor(color);this.size=size;}
|
||||
public int getIntrinsicWidth(){return size;}public int getIntrinsicHeight(){return size;}
|
||||
public void draw(Canvas canvas){Rect b=getBounds();canvas.save();canvas.translate(b.left,b.top);canvas.scale(b.width()/24f,b.height()/24f);paint.setStyle(Paint.Style.STROKE);paint.setStrokeWidth(1.8f);paint.setStrokeCap(Paint.Cap.ROUND);canvas.drawRoundRect(8,2,16,15,4,4,paint);canvas.drawArc(5,5,19,20,0,180,false,paint);canvas.drawLine(5,12,5,13,paint);canvas.drawLine(19,12,19,13,paint);canvas.drawLine(12,20,12,23,paint);canvas.drawLine(8,23,16,23,paint);canvas.restore();}
|
||||
public void setAlpha(int alpha){paint.setAlpha(alpha);}public void setColorFilter(ColorFilter f){paint.setColorFilter(f);}public int getOpacity(){return PixelFormat.TRANSLUCENT;}
|
||||
}
|
||||
static final class VoiceArt extends View {
|
||||
final Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);final float[] bars=new float[31];boolean recording=false,cancel=false,night=false;
|
||||
VoiceArt(Activity app){super(app);}
|
||||
void level(boolean active,boolean cancelled,int amplitude){if(active){System.arraycopy(bars,1,bars,0,bars.length-1);bars[bars.length-1]=(float)Math.min(1,Math.sqrt(Math.max(0,amplitude)/32768d));}else java.util.Arrays.fill(bars,0);recording=active;cancel=cancelled;invalidate();}
|
||||
protected void onDraw(Canvas c){super.onDraw(c);int w=getWidth(),h=getHeight();paint.setStyle(Paint.Style.FILL);int color=cancel?0xffa84b37:night?0xff91ac9d:0xff267266;
|
||||
if(recording){paint.setColor(color);float step=w/35f;for(int i=0;i<bars.length;i++){float height=Math.max(4,bars[i]*(h-14));float x=step*(i+2);c.drawRoundRect(x-step*.22f,(h-height)/2,x+step*.22f,(h+height)/2,4,4,paint);}}
|
||||
else{paint.setColor(night?0xff2d4439:0xfff0f1e8);c.drawCircle(w/2f,h/2f,Math.min(h*.43f,48),paint);MicIcon icon=new MicIcon(color,44);int size=(int)(h*.48f);icon.setBounds((w-size)/2,(h-size)/2,(w+size)/2,(h+size)/2);icon.draw(c);}}
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,15 @@ public class LocationCadenceTest {
|
||||
require(LocationCadence.custom(3,true)==259200);assertions++;
|
||||
require(LocationCadence.custom(5,false)==18000);assertions++;
|
||||
for(int invalid:new int[]{-1,0,721,Integer.MAX_VALUE}){try{LocationCadence.custom(invalid,false);throw new AssertionError();}catch(IllegalArgumentException expected){assertions++;}}
|
||||
for(int seconds:new int[]{10,11,30,60,120,300,900,1800,3600,7200,10800,14400,18000,21600,43200,86399,86400}){
|
||||
require(LocationCadence.sample(seconds)==seconds);assertions++;
|
||||
require(LocationCadence.sampleDue(10000,0,seconds));assertions++;
|
||||
require(!LocationCadence.sampleDue(1000+seconds*1000L-1,1000,seconds));assertions++;
|
||||
require(LocationCadence.sampleDue(1000+seconds*1000L,1000,seconds));assertions++;
|
||||
}
|
||||
for(int invalid:new int[]{-1,0,9,86401,604800,Integer.MAX_VALUE}){require(!LocationCadence.sampleValid(invalid));assertions++;}
|
||||
for(int[] period:new int[][]{{30,1,30},{7,60,420},{7,3600,25200},{24,3600,86400},{1,86400,86400}}){require(LocationCadence.customSample(period[0],period[1])==period[2]);assertions++;}
|
||||
for(int[] period:new int[][]{{0,60},{9,1},{25,3600},{2,86400},{7,86400},{1,17},{Integer.MAX_VALUE,86400}}){try{LocationCadence.customSample(period[0],period[1]);throw new AssertionError();}catch(IllegalArgumentException expected){assertions++;}}
|
||||
System.out.println("Location cadence: "+assertions+" assertions passed");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package cn.ucvl.zhaodisplay;
|
||||
public class VoiceGestureTest {
|
||||
static void check(boolean value){if(!value)throw new AssertionError();}
|
||||
public static void main(String[] args){
|
||||
check(!VoiceGesture.cancel(0,120,320,48));check(!VoiceGesture.cancel(-47,120,320,48));
|
||||
check(VoiceGesture.cancel(-48,120,320,48));check(VoiceGesture.cancel(-100,120,320,48));
|
||||
check(VoiceGesture.cancel(0,-1,320,48));check(VoiceGesture.cancel(0,321,320,48));
|
||||
check(!VoiceGesture.cancel(-10,120,320,48));check(!VoiceGesture.sendAtLimit(true));check(VoiceGesture.sendAtLimit(false));
|
||||
System.out.println("Voice gesture: 9 assertions passed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package cn.ucvl.zhaodisplay;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.os.Bundle;
|
||||
import android.view.*;
|
||||
import android.widget.*;
|
||||
import org.json.*;
|
||||
|
||||
/** Isolated visual fixture: no microphone/network/location permissions, no real identities. */
|
||||
public class VoicePreviewActivity extends Activity {
|
||||
VoiceSurface surface;JSONArray people;
|
||||
protected void attachBaseContext(android.content.Context base){android.content.res.Configuration config=new android.content.res.Configuration(base.getResources().getConfiguration());config.densityDpi=420;super.attachBaseContext(base.createConfigurationContext(config));}
|
||||
public void onCreate(Bundle state){super.onCreate(state);
|
||||
getWindow().setStatusBarColor(0xfff8f5ed);getWindow().setNavigationBarColor(0xfff8f5ed);getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR|View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
|
||||
ScrollView scroller=new ScrollView(this);scroller.setFillViewport(true);surface=new VoiceSurface(this,true);scroller.addView(surface);
|
||||
FrameLayout frame=new FrameLayout(this);frame.setBackgroundColor(0xfff8f5ed);frame.addView(scroller,new FrameLayout.LayoutParams(surface.dp(390),surface.dp(844),Gravity.TOP|Gravity.CENTER_HORIZONTAL));setContentView(frame);
|
||||
try{people=new JSONArray("[{\"id\":\"mom\",\"name\":\"妈妈\",\"online\":true},{\"id\":\"dad\",\"name\":\"爸爸\",\"online\":false},{\"id\":\"home\",\"name\":\"家庭屏\",\"online\":true}]");}catch(Exception e){throw new RuntimeException(e);}
|
||||
surface.subtitle.setText("一句问候,家就在身边");surface.receive.setText("界面验收 · 模拟家人,不发送语音");surface.recipient.setText("对妈妈说句话");
|
||||
surface.status.setText("只向已允许接收的家人发送");surface.stop.setVisibility(View.GONE);surface.expand.setOnClickListener(v->finish());
|
||||
String mode=getIntent().getStringExtra("mode");boolean recording="recording".equals(mode)||"cancel".equals(mode),cancel="cancel".equals(mode);
|
||||
surface.applyTheme("night".equals(mode));surface.targets(people,"mom",id->surface.targets(people,id,x->{}));
|
||||
for(int i=0;i<31;i++)surface.recording(recording,cancel,8000,recording?(int)(4000+12000*Math.abs(Math.sin(i*.41))):0,false,true);
|
||||
if(recording)surface.status.setText(cancel?"松开手指,这条语音不会发送":"正在对妈妈说话 · 演示波形");
|
||||
scroller.postDelayed(()->{try{android.graphics.Bitmap bitmap=android.graphics.Bitmap.createBitmap(scroller.getWidth(),scroller.getHeight(),android.graphics.Bitmap.Config.ARGB_8888);scroller.draw(new android.graphics.Canvas(bitmap));try(java.io.FileOutputStream out=new java.io.FileOutputStream(new java.io.File(getExternalFilesDir(null),"preview.png"))){bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG,100,out);}bitmap.recycle();}catch(Exception e){throw new RuntimeException(e);}},500);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
param([string]$ToolRoot='C:\Users\Administrator\Documents\ChatGPT\优创未来\services\toplc-vpn-android\.tools')
|
||||
$ErrorActionPreference='Stop'
|
||||
$tests=Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
$source=Split-Path -Parent $tests
|
||||
$stage=Join-Path 'C:\CodexBuild' ('ZhaoVoiceCheck-'+[guid]::NewGuid().ToString('N'))
|
||||
New-Item -ItemType Directory -Path $stage,"$stage\classes","$stage\dex" | Out-Null
|
||||
$jdk=Join-Path $ToolRoot 'jdk-staging\jdk-21.0.12.1+1'
|
||||
$sdk=Join-Path $ToolRoot 'android-sdk'
|
||||
$bt=Join-Path $sdk 'build-tools\36.0.0'
|
||||
$android=Join-Path $sdk 'platforms\android-37.0\android.jar'
|
||||
$env:JAVA_HOME=$jdk
|
||||
$env:Path="$jdk\bin;$env:Path"
|
||||
@'
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay.voicecheck" android:versionCode="1" android:versionName="1">
|
||||
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30"/>
|
||||
<application android:label="喊话界面隔离测试" android:allowBackup="false" android:theme="@android:style/Theme.Material.Light.NoActionBar"><activity android:name="cn.ucvl.zhaodisplay.VoicePreviewActivity" android:exported="true" android:screenOrientation="portrait"/></application>
|
||||
|
||||
</manifest>
|
||||
'@ | Set-Content -LiteralPath "$stage\AndroidManifest.xml" -Encoding utf8
|
||||
& "$bt\aapt2.exe" link -o "$stage\unsigned.apk" -I $android --manifest "$stage\AndroidManifest.xml"
|
||||
if($LASTEXITCODE){throw 'Test resource linking failed'}
|
||||
& "$jdk\bin\javac.exe" -encoding UTF-8 -source 8 -target 8 -cp $android -d "$stage\classes" "$source\src\cn\ucvl\zhaodisplay\VoiceSurface.java" "$tests\VoicePreviewActivity.java"
|
||||
if($LASTEXITCODE){throw 'Test Java compile failed'}
|
||||
& "$jdk\bin\jar.exe" cf "$stage\classes.jar" -C "$stage\classes" .
|
||||
& "$bt\d8.bat" --lib $android --min-api 26 --output "$stage\dex" "$stage\classes.jar"
|
||||
if($LASTEXITCODE){throw 'Test Dex compile failed'}
|
||||
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||
$zip=[IO.Compression.ZipFile]::Open("$stage\unsigned.apk",[IO.Compression.ZipArchiveMode]::Update)
|
||||
try{[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,"$stage\dex\classes.dex",'classes.dex',[IO.Compression.CompressionLevel]::Optimal) | Out-Null}finally{$zip.Dispose()}
|
||||
& "$bt\zipalign.exe" -f 4 "$stage\unsigned.apk" "$stage\aligned.apk"
|
||||
$keystore=Join-Path $env:LOCALAPPDATA 'ZhaoDisplay\display-signing.jks'
|
||||
& "$bt\apksigner.bat" sign --ks $keystore --ks-pass pass:android --key-pass pass:android --ks-key-alias zhaodisplay --out "$source\build\VoiceCheck.apk" "$stage\aligned.apk"
|
||||
if($LASTEXITCODE){throw 'Test APK signing failed'}
|
||||
& "$bt\apksigner.bat" verify "$source\build\VoiceCheck.apk"
|
||||
if($LASTEXITCODE){throw 'Test APK verification failed'}
|
||||
Write-Output "$source\build\VoiceCheck.apk"
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "zhao-steward-ui",
|
||||
"private": true,
|
||||
"version": "0.1.50",
|
||||
"version": "0.1.51",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "vite build",
|
||||
|
||||
@@ -11,7 +11,7 @@ const home=computed(()=>snapshot.value.state.households?.find(x=>x.id===snapshot
|
||||
let timer,epoch=0,requestId=0
|
||||
const items=computed(()=>result.value?.items||[])
|
||||
const time=n=>n?new Date(n*1000).toLocaleString('zh-CN'):'尚未收到'
|
||||
const status=d=>d.status==='scheduled'?'等待下次定时上传':d.status==='stale'?'位置更新中断':d.status==='live'?'位置已更新':'等待手机定位'
|
||||
const status=d=>d.status==='scheduled'?(d.scheduleReason==='sampling'?'等待下次采集':'等待下次定时上传'):d.status==='stale'?'位置更新中断':d.status==='live'?'位置已更新':'等待手机定位'
|
||||
const location=d=>d.position?`${d.position.latitude.toFixed(4)}°, ${d.position.longitude.toFixed(4)}° · 精度约 ${Math.round(d.position.accuracy)} 米`:'尚无有效位置'
|
||||
async function load(){const e=epoch,r=++requestId;if(!active.value)return
|
||||
try{const value=await bridge().api('/api/locations');if(e===epoch&&r===requestId){result.value=value;error.value=''}}
|
||||
@@ -30,7 +30,7 @@ onBeforeUnmount(()=>{epoch++;clearTimeout(timer)})
|
||||
<div class="d-flex flex-wrap justify-content-between gap-2"><div><h2>家人位置</h2><p class="text-secondary small">{{home?.name}} · {{items.length}} 位家人正在共享 · 只显示本人同意分享的最新位置</p></div><button class="btn btn-sm btn-outline-secondary align-self-start" @click="selected=''">查看全部位置</button></div>
|
||||
<div v-if="items.some(d=>d.status==='stale')" class="alert alert-warning" role="status">{{items.filter(d=>d.status==='stale').map(d=>d.name).join('、')}}的位置超过约定上传周期仍未更新。请检查手机网络、定位权限或省电设置;这不代表人员失联。</div>
|
||||
<div class="row g-3"><div class="col-12 col-lg-8"><FamilyMap :items="items" :selected="selected" :height="420" @select="selected=$event"/><p class="small text-secondary mb-0">点击家人卡片定位,圆圈表示定位精度范围。底图由智家提供,位置仅对获授权的人显示。</p></div>
|
||||
<div class="col-12 col-lg-4"><div v-if="!items.length" class="location-empty"><span>⌖</span><h3 class="fs-5">等待家人主动分享</h3><p>家人无需注册账号。手机配对、本人同意并开启共享后,获准的查看人才能看到位置。</p></div><button v-for="d in items" :key="d.id" class="location-person w-100 text-start" :class="{'location-selected':selected===d.id}" @click="selected=d.id"><strong>{{d.name}}</strong><span :class="d.status==='stale'?'text-warning-emphasis':'text-success'">{{status(d)}}</span><small>{{location(d)}}</small><small>定位时间:{{time(d.position?.at)}}</small><small v-if="d.status==='scheduled'">下次预计上传:{{time(d.nextUploadAt)}} · 期间轨迹保留在手机</small><small v-if="d.signal==='permission_denied'||d.signal==='location_disabled'">手机定位或权限未开启</small></button></div></div>
|
||||
<div class="col-12 col-lg-4"><div v-if="!items.length" class="location-empty"><span>⌖</span><h3 class="fs-5">等待家人主动分享</h3><p>家人无需注册账号。手机配对、本人同意并开启共享后,获准的查看人才能看到位置。</p></div><button v-for="d in items" :key="d.id" class="location-person w-100 text-start" :class="{'location-selected':selected===d.id}" @click="selected=d.id"><strong>{{d.name}}</strong><span :class="d.status==='stale'?'text-warning-emphasis':'text-success'">{{status(d)}}</span><small>{{location(d)}}</small><small>定位时间:{{time(d.position?.at)}}</small><small v-if="d.status==='scheduled'"><template v-if="d.scheduleReason==='sampling'">下次预计采集:{{time(d.nextSampleAt)}} · 按本人设定的间隔记录</template><template v-else>下次预计上传:{{time(d.nextUploadAt)}} · 期间轨迹保留在手机</template></small><small v-if="d.signal==='permission_denied'||d.signal==='location_disabled'">手机定位或权限未开启</small></button></div></div>
|
||||
<LocationHistory :members="[...items,...(result?.members||[]).filter(m=>!items.some(i=>i.id===m.id))]"/>
|
||||
<details class="mt-3 border-top pt-3"><summary>为家庭成员配对手机</summary>
|
||||
<p class="small text-secondary mt-2">老人和孩子无需登录。先选择真实成员及具体查看人,再将配对码输入本人的手机。本人核对授权内容、允许定位并打开共享后才上传;管理员生成配对码不能代替本人同意。家庭屏需单独勾选。</p>
|
||||
@@ -41,7 +41,7 @@ onBeforeUnmount(()=>{epoch++;clearTimeout(timer)})
|
||||
<p v-if="binding">{{binding.enabled?'手机已开启共享':'手机已绑定,共享关闭'}} · {{time(binding.expires)}} 到期</p>
|
||||
<div class="d-flex flex-wrap gap-2 mt-3"><button class="btn btn-primary" :disabled="busy||!memberId||(!viewOnly&&!viewerIds.length&&!displayIds.length&&!phoneIds.length)">生成配对码</button><button v-if="binding||code" type="button" class="btn btn-outline-danger" :disabled="busy" @click="action('stop')">解除该手机授权</button><a class="btn btn-outline-secondary" href="/downloads" target="_blank" rel="noreferrer">下载配套 App</a></div>
|
||||
<div v-if="code" class="alert alert-success mt-3" role="status">配对码 <strong class="font-monospace fs-3">{{code}}</strong> · 10 分钟内使用一次<br>请在成员本人的手机核对姓名与查看名单,手机授权有效至 {{time(expires)}}。重新配对会替换旧手机授权。</div>
|
||||
</form><p class="small text-secondary mt-3">手机可分别设置采集频率与上传周期:实时、1/5 分钟、1—5 小时、1—3 天,或自定义至 30 天。启用历史保存后,断网轨迹加密暂存在手机,联网后补传;百度网盘完整校验后清理对应本机记录。超过 15 分钟的旧坐标隐藏;长周期未到期显示等待上传,超过约定周期才提示更新中断,不表示人员失联。</p></details>
|
||||
</form><p class="small text-secondary mt-3">采集间隔可自定义 10 秒至 1 天;上传周期另行设置:实时、1/5 分钟、1—5 小时、1—3 天,或自定义至 30 天。启用历史保存后,断网轨迹加密暂存在手机,联网后补传;百度网盘完整校验后清理对应本机记录。超过 15 分钟的旧坐标隐藏;长周期未到期显示等待上传,超过约定周期才提示更新中断,不表示人员失联。</p></details>
|
||||
<p v-if="error" class="text-danger mt-2" role="alert">{{error}}</p>
|
||||
</section></template>
|
||||
<style scoped>.family-locations h2{font-size:1.3rem}.location-empty{display:grid;align-content:center;min-height:270px;text-align:center;color:var(--ui-muted,#64776f);padding:1rem}.location-empty>span{font-size:3rem;color:#6c9685}.location-person{display:flex;flex-direction:column;gap:.35rem;background:var(--panel,#fff);border:1px solid var(--ui-line,#d9e3dd);border-radius:12px;padding:14px;margin-bottom:10px;color:var(--ink,#243c32)}.location-person>span,.location-person small{font-size:.85rem}.location-selected{border-color:#257a68;box-shadow:inset 3px 0 #257a68}.family-locations summary{cursor:pointer}.family-locations input[type=checkbox]{min-width:18px;width:18px;min-height:18px}</style>
|
||||
|
||||
@@ -20,7 +20,7 @@ const angles=computed(()=>({hour:(+time.value.hour%12)*30+(+time.value.minute)/2
|
||||
const devices=computed(()=>{const all=data.value?.devices||[],start=(paging.value%Math.max(1,Math.ceil(all.length/3)))*3;return all.slice(start,start+3)})
|
||||
const positions=computed(()=>{if(clock.value-lastSync.value>90000||error.value)return [];const all=data.value?.locations||[];return all.slice((paging.value%Math.max(1,Math.ceil(all.length/3)))*3,(paging.value%Math.max(1,Math.ceil(all.length/3)))*3+3)})
|
||||
const mapPositions=computed(()=>clock.value-lastSync.value>90000||error.value?[]:data.value?.locations||[])
|
||||
const locationText=d=>d.status==='scheduled'?'按设定周期上传 · 等待下次更新':d.status==='stale'?'位置更新中断 · 请检查手机':d.position?`${d.position.latitude.toFixed(3)}°, ${d.position.longitude.toFixed(3)}°`:'等待手机定位'
|
||||
const locationText=d=>d.status==='scheduled'?(d.scheduleReason==='sampling'?'按设定间隔采集 · 等待下次定位':'按设定周期上传 · 等待下次更新'):d.status==='stale'?'位置更新中断 · 请检查手机':d.position?`${d.position.latitude.toFixed(3)}°, ${d.position.longitude.toFixed(3)}°`:'等待手机定位'
|
||||
|
||||
const weather=computed(()=>data.value?.weather)
|
||||
const syncLabel=computed(()=>authRequired.value?'等待重新连接':!lastSync.value?'正在连接家庭':error.value||clock.value-lastSync.value>90000?'网络暂时中断 · 显示上次资料':'家庭资料已同步')
|
||||
|
||||
+7
-5
@@ -27,13 +27,15 @@ class Sync:
|
||||
'(id TEXT PRIMARY KEY,share_id TEXT,family TEXT,member TEXT,started REAL,ended REAL,expires REAL,grant_json TEXT)')
|
||||
self.a.DB.execute('CREATE INDEX IF NOT EXISTS collection_share ON location_collection_sessions(share_id)')
|
||||
self.a.DB.execute('CREATE TABLE IF NOT EXISTS location_upload_timing (share_id TEXT PRIMARY KEY,started REAL,last_received REAL)')
|
||||
if 'last_sample' not in {r[1] for r in self.a.DB.execute('PRAGMA table_info(location_upload_timing)')}:
|
||||
self.a.DB.execute('ALTER TABLE location_upload_timing ADD COLUMN last_sample REAL NOT NULL DEFAULT 0')
|
||||
|
||||
def close(self, sid):
|
||||
self.a.DB.execute('UPDATE location_collection_sessions SET ended=? WHERE share_id=? AND ended IS NULL', (time.time(), sid))
|
||||
|
||||
def start(self, row, grant):
|
||||
self.close(row['id'])
|
||||
self.a.DB.execute('INSERT OR REPLACE INTO location_upload_timing VALUES (?,?,0)', (row['id'], time.time()))
|
||||
self.a.DB.execute('INSERT OR REPLACE INTO location_upload_timing VALUES (?,?,0,0)', (row['id'], time.time()))
|
||||
if not grant.get('historyEnabled'):
|
||||
return dict(historyEnabled=False, collectionId='')
|
||||
key = secrets.token_hex(16)
|
||||
@@ -42,12 +44,12 @@ class Sync:
|
||||
(key, row['id'], row['family_id'], row['member_id'], now, row['expires'], json.dumps(grant)))
|
||||
return dict(historyEnabled=True, collectionId=key, collectionStartedAt=now)
|
||||
|
||||
def seen(self, sid, started, now):
|
||||
self.a.DB.execute('INSERT OR REPLACE INTO location_upload_timing VALUES (?,?,?)', (sid, started, now))
|
||||
def seen(self, sid, started, now, sample_at=0):
|
||||
self.a.DB.execute('INSERT OR REPLACE INTO location_upload_timing VALUES (?,?,?,?)', (sid, started, now, sample_at))
|
||||
|
||||
def timing(self, sid):
|
||||
row=self.a.DB.execute('SELECT started,last_received FROM location_upload_timing WHERE share_id=?', (sid,)).fetchone()
|
||||
return dict(started=row['started'],seen=row['last_received']) if row else {}
|
||||
row=self.a.DB.execute('SELECT started,last_received,last_sample FROM location_upload_timing WHERE share_id=?', (sid,)).fetchone()
|
||||
return dict(started=row['started'],seen=row['last_received'],sampleAt=row['last_sample']) if row else {}
|
||||
|
||||
def batch(self, token, body):
|
||||
a = self.a
|
||||
|
||||
+9
-4
@@ -167,7 +167,7 @@ class Locations:
|
||||
interval=body.get('intervalSeconds',300)
|
||||
if not interval_valid(interval):raise a.Problem('上传周期可选 10 秒、1/5 分钟,或 1 至 720 小时(最多 30 天)')
|
||||
sample=body.get('sampleIntervalSeconds',60)
|
||||
if type(sample) is not int or sample not in (10,60,300):raise a.Problem('采集周期可选 10 秒、1 分钟或 5 分钟')
|
||||
if type(sample) is not int or not 10 <= sample <= 86400:raise a.Problem('采集间隔可自定义 10 秒至 1 天,不支持一周等更长间隔')
|
||||
if not any(chosen.values()):raise a.Problem('至少选择一位查看人;只查看家人无需开启自己的共享')
|
||||
history=body.get('historyEnabled',False)
|
||||
if type(history) is not bool or history and body.get('historyConsent') is not True:raise a.Problem('长期保存轨迹需要本人单独同意',403)
|
||||
@@ -198,7 +198,7 @@ class Locations:
|
||||
if not fix or pos['at']>fix['at']:fix={k:pos[k] for k in ('latitude','longitude','accuracy','at')}
|
||||
if signal in ('permission_denied','location_disabled'):fix=None
|
||||
self.latest[sid]=dict(started=old['started'],seen=now,fix=fix,signal=signal)
|
||||
self.sync.seen(sid,old['started'],now)
|
||||
self.sync.seen(sid,old['started'],now,fix['at'] if fix else 0)
|
||||
return dict(ok=True,expires=row['expires'])
|
||||
|
||||
def listing(self, family, user=None, display_id=None, phone_id=None):
|
||||
@@ -225,13 +225,18 @@ class Locations:
|
||||
if phone_id and phone_id!=row['id'] and phone_id not in {v['id'] for v in grant.get('phones',[])}:continue
|
||||
recent=self.latest.get(row['id']) or self.sync.timing(row['id']);fix=recent.get('fix');seen=recent.get('seen',0)
|
||||
age=now-(fix['at'] if fix else recent.get('started',row['created']))
|
||||
scheduled=grant.get('intervalSeconds',300)>900 and now-(seen or recent.get('started',row['created']))<=grant['intervalSeconds']+900
|
||||
upload=grant.get('intervalSeconds',300);sample=grant.get('sampleIntervalSeconds',60)
|
||||
next_upload=(seen or recent.get('started',row['created']))+upload
|
||||
next_sample=(fix['at'] if fix else recent.get('sampleAt') or recent.get('started',row['created']))+sample
|
||||
sampling=sample>900 and now<=next_sample+900
|
||||
scheduled=sampling or upload>900 and now<=next_upload+900
|
||||
stale=age>900 or seen and now-seen>900
|
||||
state='scheduled' if stale and scheduled else 'stale' if stale else 'live' if fix else 'waiting'
|
||||
position=fix if fix and state=='live' else None
|
||||
items.append(dict(id=row['member_id'],personId=valid[1]['id'],name=valid[1]['name'],status=state,
|
||||
signal=recent.get('signal','waiting'),lastSeen=seen or None,position=position,expires=row['expires'],
|
||||
intervalSeconds=grant.get('intervalSeconds',300),nextUploadAt=(seen or recent.get('started',row['created']))+grant.get('intervalSeconds',300)))
|
||||
intervalSeconds=upload,sampleIntervalSeconds=sample,scheduleReason='sampling' if sampling and sample>upload else 'upload',
|
||||
nextSampleAt=next_sample,nextUploadAt=next_upload))
|
||||
return items
|
||||
|
||||
def snapshot(self,user):
|
||||
|
||||
@@ -51,7 +51,9 @@ class AndroidLocationContractTests(unittest.TestCase):
|
||||
ui = (ANDROID/'src/cn/ucvl/zhaodisplay/LocationActivity.java').read_text(encoding='utf-8')
|
||||
self.assertNotIn('WebView', ui)
|
||||
self.assertIn('共享我的位置', ui)
|
||||
self.assertIn('new int[]{10,60,300}', ui)
|
||||
self.assertIn('自定义采集间隔', ui)
|
||||
self.assertIn('LocationCadence.customSample', ui)
|
||||
self.assertIn('setSamplePeriod(result.optInt', ui)
|
||||
self.assertIn('自定义小时 / 天',ui)
|
||||
self.assertIn('LocationCadence.custom',ui)
|
||||
queue=(ANDROID/'src/cn/ucvl/zhaodisplay/LocationQueue.java').read_text(encoding='utf-8')
|
||||
@@ -59,6 +61,14 @@ class AndroidLocationContractTests(unittest.TestCase):
|
||||
self.assertIn(contract,queue)
|
||||
self.assertIn('consent.isChecked()', ui)
|
||||
|
||||
def test_voice_has_full_screen_large_controls_and_real_amplitude(self):
|
||||
panel=(ANDROID/'src/cn/ucvl/zhaodisplay/VoicePanel.java').read_text(encoding='utf-8')
|
||||
surface=(ANDROID/'src/cn/ucvl/zhaodisplay/VoiceSurface.java').read_text(encoding='utf-8')
|
||||
for text in ('setLayout(-1,-1)','getMaxAmplitude()','VoiceGesture.sendAtLimit(cancelled)','ACTION_CANCEL:finish(false)','view.full','stopPlayer("rejected")'):
|
||||
self.assertIn(text,panel)
|
||||
for text in ('上滑取消','已打开 App','setContentDescription'):
|
||||
self.assertIn(text,surface)
|
||||
|
||||
def test_map_uses_first_party_tiles_and_never_exposes_pairing_token(self):
|
||||
source = (ANDROID/'src/cn/ucvl/zhaodisplay/LocationMapView.java').read_text(encoding='utf-8')
|
||||
for text in ('https://zhao.ucvl.cn/maps/phone','shouldInterceptRequest','setGeolocationEnabled(false)','setAllowFileAccess(false)','JSONObject.quote','setItems(new JSONArray())'):
|
||||
|
||||
@@ -143,5 +143,43 @@ class LocationSyncTests(unittest.TestCase):
|
||||
phone=self.enabled(intervalSeconds=3*86400);started=phone['collectionStartedAt'];app.LOCATIONS.latest.clear()
|
||||
with patch('member_locations.time.time',return_value=started+86400):self.assertEqual(app.LOCATIONS.listing(self.aid,user=self.owner)[0]['status'],'scheduled')
|
||||
|
||||
def test_custom_sampling_roundtrips_independently_and_limits_one_day(self):
|
||||
phone=self.phone('自定义采集')
|
||||
for sample in (10,30,120,420,900,1800,3600,7200,10800,14400,18000,25200,43200,86400):
|
||||
response=self.configure(phone,viewerIds=[self.owner['id']],intervalSeconds=300,sampleIntervalSeconds=sample)
|
||||
self.assertEqual(response['sampleIntervalSeconds'],sample)
|
||||
self.assertEqual(response['intervalSeconds'],300)
|
||||
settings=app.LOCATIONS.native(phone['token'],dict(action='settings'))
|
||||
self.assertEqual(settings['sampleIntervalSeconds'],sample)
|
||||
for invalid in (True,0,9,86401,7*86400,3600.0,'3600',None):
|
||||
with self.assertRaises(app.Problem):self.configure(phone,viewerIds=[self.owner['id']],sampleIntervalSeconds=invalid)
|
||||
|
||||
def test_daily_sampling_wait_and_overdue_are_distinct_from_upload(self):
|
||||
phone=self.enabled(intervalSeconds=300,sampleIntervalSeconds=86400);started=phone['collectionStartedAt']
|
||||
with patch('member_locations.time.time',return_value=started+3600):
|
||||
row=app.LOCATIONS.listing(self.aid,user=self.owner)[0]
|
||||
self.assertEqual(row['status'],'scheduled');self.assertEqual(row['scheduleReason'],'sampling')
|
||||
self.assertEqual(row['nextSampleAt'],started+86400);self.assertIsNone(row['position'])
|
||||
# Heartbeats must not postpone the next scheduled collection indefinitely.
|
||||
app.LOCATIONS.latest[phone['sid']]['seen']=started+86400+901
|
||||
with patch('member_locations.time.time',return_value=started+86400+901):
|
||||
self.assertEqual(app.LOCATIONS.listing(self.aid,user=self.owner)[0]['status'],'stale')
|
||||
|
||||
def test_last_sample_schedule_survives_restart_without_persisting_coordinates(self):
|
||||
phone=self.enabled(intervalSeconds=300,sampleIntervalSeconds=86400);started=phone['collectionStartedAt']
|
||||
with app.DB:app.LOCATIONS.sync.seen(phone['sid'],started,started+86400,started+86400)
|
||||
app.LOCATIONS.latest.clear()
|
||||
with patch('member_locations.time.time',return_value=started+86400+3600):
|
||||
row=app.LOCATIONS.listing(self.aid,user=self.owner)[0];self.assertEqual(row['status'],'scheduled')
|
||||
self.assertEqual(row['nextSampleAt'],started+2*86400);self.assertIsNone(row['position'])
|
||||
|
||||
def test_upload_timing_migration_preserves_existing_schedule(self):
|
||||
with app.DB:
|
||||
app.DB.execute('DROP TABLE location_upload_timing')
|
||||
app.DB.execute('CREATE TABLE location_upload_timing (share_id TEXT PRIMARY KEY,started REAL,last_received REAL)')
|
||||
app.DB.execute('INSERT INTO location_upload_timing VALUES (?,?,?)',('old-phone',100,200))
|
||||
app.LOCATIONS.sync.initialize();app.LOCATIONS.sync.initialize()
|
||||
self.assertEqual(app.LOCATIONS.sync.timing('old-phone'),dict(started=100,seen=200,sampleAt=0))
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>配套 App · 赵府智家</title><link rel="icon" href="/brand-icon.png"><link rel="stylesheet" href="/vendor/bootstrap.min.css"><link rel="stylesheet" href="/downloads.css"><script src="/downloads.js" defer></script></head>
|
||||
<body><main class="container py-4 py-md-5"><a href="/" class="back">← 返回赵府智家</a><section class="card border-0 shadow-sm p-4 p-md-5 mt-4"><div class="d-flex gap-3 align-items-center"><img src="/brand-icon.png" width="60" height="60" alt="赵府"><div><span class="text-secondary small">家庭成员均可下载</span><h1 class="h3 mb-0 mt-1">赵府智家 · 配套 App</h1></div></div><p class="mt-4 text-secondary">按设备选择手机或显示终端安装包。使用平台账号登录下载;安装后凭配对码使用,无需在 App 注册。两种版本使用同一个应用身份,请按实际用途选择。</p>
|
||||
<div class="row g-3 my-2"><div class="col-md-6"><article class="p-3 rounded bg-light h-100"><h2 class="h5">家庭显示终端</h2><p class="mb-0">用于显示时间、天气、家人位置及家庭设备。安装后使用管理员提供的配对码,绑定指定家庭。</p></article></div><div class="col-md-6"><article class="p-3 rounded bg-light h-100"><h2 class="h5">手机家人位置</h2><p class="mb-0">手机打开“赵府家人位置”,输入绑定本人档案的手机配对码,无需注册或登录。可查看获授权的家人;“我的位置设置”可选择查看人,分别设置定位采集频率和上传周期:实时、分钟、小时或天(最多 30 天)。启用历史保存后,断网轨迹在手机加密暂存,恢复网络自动补传,网盘完整校验后清理本机副本。由本人打开共享开关。查看家人无需开启自己的定位。</p></article></div></div>
|
||||
<div class="row g-3 my-2"><div class="col-md-6"><article class="p-3 rounded bg-light h-100"><h2 class="h5">家庭显示终端</h2><p class="mb-0">用于显示时间、天气、家人位置及家庭设备。安装后使用管理员提供的配对码,绑定指定家庭。</p></article></div><div class="col-md-6"><article class="p-3 rounded bg-light h-100"><h2 class="h5">手机家人位置</h2><p class="mb-0">手机打开“赵府家人位置”,输入绑定本人档案的手机配对码,无需注册或登录。可查看获授权的家人;“我的位置设置”可选择查看人,采集间隔可自定义 10 秒至 1 天;上传周期独立设置,最多 30 天。家人喊话支持温暖简洁的全屏面板、大号家人卡片、按住说话、上滑取消及实际录音波形。启用历史保存后,断网轨迹在手机加密暂存,恢复网络自动补传,网盘完整校验后清理本机副本。由本人打开共享开关。查看家人无需开启自己的定位。</p></article></div></div>
|
||||
<form id="download-login" class="mt-4" hidden><h2 class="h5">登录后下载</h2><div class="row g-3"><label class="col-md-6">用户名<input class="form-control mt-1" name="username" autocomplete="username" required></label><label class="col-md-6">密码<input class="form-control mt-1" type="password" name="password" autocomplete="current-password" required></label></div><button class="btn btn-success mt-3" type="submit">登录并准备下载</button></form>
|
||||
<div id="download-ready" class="mt-4" hidden><a id="apk-link" class="btn btn-success btn-lg" href="/downloads/ZhaoDisplay.apk">下载手机家人位置版</a><a id="terminal-link" class="btn btn-outline-success btn-lg ms-2" href="/downloads/ZhaoTerminal.apk" hidden>下载显示终端版</a><p id="terminal-info" class="small text-secondary mt-3"></p><details class="small"><summary>显示终端版校验</summary><code id="terminal-hash"></code></details><p id="release-info" class="small text-secondary mt-3"></p><details class="small"><summary>校验安装包</summary><p class="mt-2">SHA-256</p><code id="apk-hash"></code></details></div><p id="download-status" class="mt-3" role="status">正在检查登录状态…</p><button id="download-retry" class="btn btn-outline-secondary" hidden>重新检查</button>
|
||||
<hr class="my-4"><p class="small text-secondary mb-0">支持 Android 8.0 及以上,ARM64 / ARMv7。下载后打开 APK,按系统提示完成安装。iPhone 可使用网页;此安装包不适用于 iOS。安装后仍按家庭授权访问资料。两端均提供“按住说话,松开发送”;接收方需先允许具体喊话人并打开 App。显示终端无需麦克风即可接收,接上话筒后可以发送。</p></section></main></body></html>
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+2
-2
@@ -1,6 +1,6 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#244d43"><link rel="icon" href="/zhao-icon.png"><link rel="apple-touch-icon" href="/zhao-icon.png"><title>赵府 · 智能数字管家</title> <script type="module" crossorigin src="/ui/assets/index-w9su1uwq.js"></script>
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#244d43"><link rel="icon" href="/zhao-icon.png"><link rel="apple-touch-icon" href="/zhao-icon.png"><title>赵府 · 智能数字管家</title> <script type="module" crossorigin src="/ui/assets/index-D1RrgHpo.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/modulepreload-polyfill-B5Qt9EMX.js">
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/FamilyMap-CiWCoS6Z.js">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/FamilyMap-DBkz-poX.css">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/index-gJyED1pB.css">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/index-BlhoXB1K.css">
|
||||
</head><body><div id="app"></div></body></html>
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f3eee4"><meta name="referrer" content="no-referrer"><link rel="icon" href="/zhao-icon.png"><title>赵府 · 家庭时光</title> <script type="module" crossorigin src="/ui/assets/tv-8KQFA1ao.js"></script>
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f3eee4"><meta name="referrer" content="no-referrer"><link rel="icon" href="/zhao-icon.png"><title>赵府 · 家庭时光</title> <script type="module" crossorigin src="/ui/assets/tv-CumBWqRi.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/modulepreload-polyfill-B5Qt9EMX.js">
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/FamilyMap-CiWCoS6Z.js">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/FamilyMap-DBkz-poX.css">
|
||||
|
||||
Reference in New Issue
Block a user