From 4dc3e2fb9f2967a323fb99da87b43ba8419a940a Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 19 Oct 2026 07:55:36 +0800 Subject: [PATCH] Release v0.1.54: scheduled location sessions and paged voice delivery history --- README.md | 4 + RELEASE-v0.1.54.md | 35 +++ VERSION | 2 +- android-display/AndroidManifest-terminal.xml | 2 +- android-display/AndroidManifest.xml | 3 +- .../src/cn/ucvl/zhaodisplay/BootReceiver.java | 5 + .../cn/ucvl/zhaodisplay/LocationActivity.java | 42 ++-- .../cn/ucvl/zhaodisplay/LocationQueue.java | 12 +- .../cn/ucvl/zhaodisplay/LocationSchedule.java | 32 +++ .../cn/ucvl/zhaodisplay/LocationService.java | 215 +++++++++++------- .../cn/ucvl/zhaodisplay/LocationSyncJob.java | 12 + .../src/cn/ucvl/zhaodisplay/PhoneLayout.java | 2 +- .../src/cn/ucvl/zhaodisplay/VoiceChat.java | 17 +- .../src/cn/ucvl/zhaodisplay/VoicePanel.java | 44 ++-- android-display/tests/build-phone-check.ps1 | 5 +- .../tests/phone-preview/DisplayApi.java | 1 + .../tests/phone-preview/LocationQueue.java | 14 +- .../tests/phone-preview/LocationSchedule.java | 7 + .../tests/phone-preview/LocationService.java | 61 ++++- .../phone-preview/PhonePreviewActivity.java | 7 +- .../phone-preview/QueueStorageChecks.java | 28 +++ family_voice.py | 11 +- frontend/package.json | 2 +- member_locations.py | 13 +- test_family_voice.py | 12 + test_phone_locations.py | 15 ++ test_voice_history.py | 10 +- voice_history.py | 21 +- 28 files changed, 481 insertions(+), 153 deletions(-) create mode 100644 RELEASE-v0.1.54.md create mode 100644 android-display/src/cn/ucvl/zhaodisplay/LocationSchedule.java create mode 100644 android-display/src/cn/ucvl/zhaodisplay/LocationSyncJob.java create mode 100644 android-display/tests/phone-preview/LocationSchedule.java create mode 100644 android-display/tests/phone-preview/QueueStorageChecks.java diff --git a/README.md b/README.md index 8f441f8..fda25ba 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,9 @@ # 赵府智家 · 视觉系统 +## v0.1.54 · 定时定位与沟通状态 + +手机新增「定时采集 / 实时共享」。定时模式每次取得新位置或 30 秒超时后释放定位,上传周期单独配置;后台由系统调度,省电限制可能延迟。沟通列表首次加载最近 10 条,分开显示传输、送达、播放和网盘保存状态。[本版说明](RELEASE-v0.1.54.md)。 + ## v0.1.53 · 位置、沟通与长期语音记录 底部统一为「位置 / 沟通 / 我的」。位置按采集时间排序,点击在地图上脉冲定位;沟通页固定接收对象和说话按钮,中间查看和回听长期聊天记录。语音加密归档百度网盘,回读校验后清理服务器暂存,记录按家庭内的成员手机或显示终端档案归属。接收和共享设置统一到「我的」。[本版说明](RELEASE-v0.1.53.md)。 diff --git a/RELEASE-v0.1.54.md b/RELEASE-v0.1.54.md new file mode 100644 index 0000000..4c8aa4a --- /dev/null +++ b/RELEASE-v0.1.54.md @@ -0,0 +1,35 @@ +# V0.1.54 · 定时定位、最近十条与语音送达状态 + +## 使用 + +更新「家人位置手机版」后,进入「我的 → 共享模式与采集频率」选择: + +- 定时采集与汇报:采集间隔与集中上传周期独立;每轮取得新位置或 30 秒超时即释放定位。两轮之间没有常驻定位监听或计时服务。 +- 实时共享:持续定位,约每 10 秒上传;保留运行通知,可随时停止。 +- 修改模式或周期前先关闭共享,再由本人确认开启。查看家人不需要开启自己的位置共享。 +- 定时模式需要本人授予“始终允许”定位权限;系统省电、锁屏、网络与厂商限制可能延迟任务,不能承诺秒级定时。重启后需本人重新开启共享。 + +沟通页按双方语音显示列表,初次及每页最多十条;点击“更早”翻页,“最近”返回最新。只查询文字索引,点击播放才读取音频。 + +- 正在传输:手机向平台发送,或平台正在向接收设备传输。 +- 已发送、等待送达:平台已接收,接收设备尚未确认。 +- 已送达:接收设备已确认拿到语音。 +- 已播放:接收设备确认完整播放。 +- 等待存入 / 正在传输到网盘 / 归档待重试 / 已存网盘:独立的保存进度。“已存网盘”必须经过完整回读校验。 +- 发送未确认可在当前 App 会话内重试或放弃;重试复用消息编号,不重复发送。未确认副本只暂存在内存,退出 App 后不保留;平台已接收的记录继续保留。 + +## 实现与边界 + +- 定时唤醒使用 Android AlarmManager 非精确调度;联网补传使用带网络条件的 JobScheduler。每轮定位与同步最多运行 90 秒,完成后结束服务;只同步时不会开启 GPS。 +- 离线定位点仍加密保存本机,原有容量上限不变。只有百度网盘完整回读校验的批次才从本机删除。 +- 停止、过期、换绑取消采集;关闭时离线也立即停止新采集,平台关闭通知等待联网补送。 +- 手机数据库从版本 1 增至 2,增加最多一条当前成员的加密待汇报位置;原待上传队列保留。服务器聊天索引新增家庭、双方设备及序号索引,两路各查最多十一条,合并后返回十条。 +- 历史记录继续沿用家庭内成员手机或显示终端的稳定身份,长期保存,访问仍检查参与双方和家庭权限。 +- 本轮验证使用隔离假数据;真实手机锁屏、厂商后台限制与双端话筒效果仍需设备安装后验证。 + +## 验收 + +- Python 全量 345 项、JavaScript 全量 192 项通过。 +- 安卓隔离测试覆盖 14 种界面/流程,包括普通与窄屏、分页、模式切换、单次采集、离线停止、同步不唤醒 GPS,以及真实 SQLite/Keystore 的版本 1→2 迁移与上传回执清理。 +- 手机与显示终端安装包构建、签名验证通过。手机尚未连接,本轮没有远程安装到用户手机。 +- 真实百度网盘合成语音已验证加密上传、完整回读、本地清理、重启回听;测试文件及空测试目录已清理。 diff --git a/VERSION b/VERSION index a4c528c..7b30067 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.1.53 +0.1.54 diff --git a/android-display/AndroidManifest-terminal.xml b/android-display/AndroidManifest-terminal.xml index ab091a4..e7e2986 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 d66d4bc..9a9ed92 100644 --- a/android-display/AndroidManifest.xml +++ b/android-display/AndroidManifest.xml @@ -1,4 +1,4 @@ - + @@ -16,6 +16,7 @@ + diff --git a/android-display/src/cn/ucvl/zhaodisplay/BootReceiver.java b/android-display/src/cn/ucvl/zhaodisplay/BootReceiver.java index f553b97..4326a7e 100644 --- a/android-display/src/cn/ucvl/zhaodisplay/BootReceiver.java +++ b/android-display/src/cn/ucvl/zhaodisplay/BootReceiver.java @@ -2,6 +2,11 @@ package cn.ucvl.zhaodisplay; import android.content.*; public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context,Intent intent){ + if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())&&context.getSharedPreferences("display",0).getBoolean("phoneMode",false)){ + android.content.SharedPreferences p=context.getSharedPreferences("location",0);boolean was=p.getBoolean("active",false); + LocationSchedule.cancel(context);p.edit().putBoolean("active",false).putBoolean("stopPending",was||p.getBoolean("stopPending",false)).putString("status","手机已重启,请本人重新开启共享").apply(); + if(was||p.getLong("pendingPoints",0)>0)LocationSchedule.retry(context,30000); + } if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()) && !context.getSharedPreferences("display",0).getBoolean("phoneMode",false) && !context.getSharedPreferences("display",0).getString("token","").isEmpty()) context.startForegroundService(new Intent(context,MonitorService.class)); } diff --git a/android-display/src/cn/ucvl/zhaodisplay/LocationActivity.java b/android-display/src/cn/ucvl/zhaodisplay/LocationActivity.java index 5bd0ff3..1b901ca 100644 --- a/android-display/src/cn/ucvl/zhaodisplay/LocationActivity.java +++ b/android-display/src/cn/ucvl/zhaodisplay/LocationActivity.java @@ -15,7 +15,7 @@ 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,sampleUnit;EditText customAmount,sampleAmount;LinearLayout customPeriod,samplePeriod,settings,recipients,familyList,homeContent,shareControls; + CheckBox consent,historyConsent;Switch sharing;Spinner sharingMode,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}; @@ -37,10 +37,11 @@ public class LocationActivity extends Activity { getSharedPreferences("display",0).edit().putBoolean("phoneMode",true).apply(); stopService(new Intent(this,MonitorService.class)); // Process death/reboot cannot leave a stale switch claiming collection is active. - if(prefs.getBoolean("active",false)&&!LocationService.busy){ + if(prefs.getBoolean("active",false)&&!LocationService.busy&&!LocationSchedule.enabled(prefs)){ prefs.edit().putBoolean("active",false).putString("status","共享已中断,请本人重新开启").apply(); startService(new Intent(this,LocationService.class).setAction("STOP")); } + LocationSchedule.resume(this); style=new PhoneStyle(this);phone=new PhoneLayout(this);setContentView(phone); getWindow().setStatusBarColor(PhoneStyle.PAPER);getWindow().setNavigationBarColor(PhoneStyle.CARD); getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR|View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR); @@ -54,11 +55,16 @@ public class LocationActivity extends Activity { text("只允许勾选的对象查看我的位置",19,recipientSection); text("修改名单前先关闭共享。完成设置后,重新开启共享才会应用新的授权名单。",14,recipientSection); recipients=style.column();recipientSection.addView(recipients); - text("定位采集频率",16,sampleSection);sampleCadence=new Spinner(this);sampleCadence.setAdapter(new ArrayAdapter(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);sampleSection.addView(sampleCadence); + text("位置共享模式",20,sampleSection); + sharingMode=new Spinner(this);sharingMode.setAdapter(new ArrayAdapter(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"定时采集与汇报(省电)","实时共享(持续在线)"}));sampleSection.addView(sharingMode); + text("定时:到点短暂定位,取得位置或 30 秒超时后释放定位;采集和上传分开设置。实时:持续定位,约每 10 秒汇报,保留运行通知。",14,sampleSection); + text("锁屏、省电或系统限制可能延后定时任务,不能保证精确到秒。手机重启后需要本人重新开启共享。",14,sampleSection); + sharingMode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){public void onItemSelected(AdapterView p,View v,int i,long id){if(sampleCadence!=null&&cadence!=null)render();}public void onNothingSelected(AdapterView p){}}); + text("定时采集频率",16,sampleSection);sampleCadence=new Spinner(this);sampleCadence.setAdapter(new ArrayAdapter(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);sampleSection.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(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"秒","分钟","小时","天"}));sampleUnit.setSelection(2);samplePeriod.addView(sampleUnit);sampleSection.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,sampleSection); - text("集中上传周期",16,uploadSection);cadence=new Spinner(this);cadence.setAdapter(new ArrayAdapter(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"实时(约 10 秒)","每 1 分钟","每 5 分钟(默认)","每 1 小时","每 2 小时","每 3 小时","每 4 小时","每 5 小时","每 1 天","每 2 天","每 3 天","自定义小时 / 天"}));cadence.setSelection(2);uploadSection.addView(cadence); + text("集中上传周期",16,uploadSection);cadence=new Spinner(this);cadence.setAdapter(new ArrayAdapter(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"每 10 秒","每 1 分钟","每 5 分钟(默认)","每 1 小时","每 2 小时","每 3 小时","每 4 小时","每 5 小时","每 1 天","每 2 天","每 3 天","自定义小时 / 天"}));cadence.setSelection(2);uploadSection.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(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"小时","天"}));customPeriod.addView(customUnit);uploadSection.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){}}); text("采集与上传分开:例如每分钟采集、每天集中上传。自定义 1—720 小时或 1—30 天。断网时本地暂存,恢复后自动补传;长周期期间家人无法看到实时移动。调整名单或频率前,先关闭共享。",14,uploadSection); @@ -88,7 +94,7 @@ public class LocationActivity extends Activity { 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)); + phone.sampling.setOnClickListener(v->showDetail("共享模式与采集频率",sampleSection));phone.upload.setOnClickListener(v->showDetail("集中上传与离线暂存",uploadSection));phone.history.setOnClickListener(v->showDetail("我的历史轨迹",historySection)); selectTab(paired()?0:2);render(); } boolean paired(){return !prefs.getString("token","").isEmpty();} @@ -109,7 +115,7 @@ public class LocationActivity extends Activity { if(total==0){showDetail("先选择查看人",recipientSection);Toast.makeText(this,"请先选择允许查看你位置的家人或显示终端",1).show();return;} try{samplePeriodSeconds();uploadPeriod();}catch(Exception e){Toast.makeText(this,"请先检查定位频率和上传周期",1).show();return;} if(consentSection.getParent()!=null)((android.view.ViewGroup)consentSection.getParent()).removeView(consentSection);consent.setChecked(false); - new AlertDialog.Builder(this).setTitle("开启我的位置共享").setMessage("允许 "+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(); + 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();} @@ -127,20 +133,20 @@ public class LocationActivity extends Activity { VoiceSurface.text(phone.check,pairingRequired()?"去配对":"检查");VoiceSurface.text(phone.myCheck,pairingRequired()?"重新配对":"检查权限"); phone.expiry.value(expires>0?java.text.DateFormat.getDateInstance().format(new Date(expires))+" 到期":"尚未配对"); int viewers=0;for(List list:choices.values())for(CheckBox c:list)if(c.isChecked())viewers++;phone.viewers.value(settingsReady?viewers+" 个已选对象 · "+(active?"共享期间生效":"开启共享后生效"):"点击读取授权名单"); - try{phone.sampling.value(periodLabel(samplePeriodSeconds()));phone.upload.value(periodLabel(uploadPeriod())+" · 断网时加密暂存");}catch(Exception e){phone.sampling.value("请检查自定义间隔");} + try{phone.sampling.value(realtimeMode()?"实时共享 · 持续定位":"定时采集 · "+periodLabel(samplePeriodSeconds()));phone.upload.value(realtimeMode()?"约每 10 秒 · 持续在线":periodLabel(uploadPeriod())+" · 断网时加密暂存");}catch(Exception e){phone.sampling.value("请检查自定义间隔");} phone.history.value((historyConsent.isChecked()?"已选择保存轨迹":"未选择保存轨迹")+" · "+prefs.getLong("pendingPoints",0)+" 个点待同步"); phone.permissions.value(locationPermissionText()); queueStatus.setText(String.format(Locale.CHINA,"本机待同步:%d 个点 · %.1f KB\n累计校验清理:%d 个点 · %.1f KB\n%s%s",prefs.getLong("pendingPoints",0),prefs.getLong("pendingBytes",0)/1024d,prefs.getLong("uploadedPoints",0),prefs.getLong("freedBytes",0)/1024d,prefs.getBoolean("cacheFull",false)?"缓存已满,暂停新增历史。\n":"",prefs.getString("syncStatus","尚无待同步轨迹"))); rendering=true;sharing.setChecked(active);rendering=false; sharing.setEnabled(paired&&!pairing&&(active||!pairingRequired()&&!busy&&settingsReady)); pair.setEnabled(!active&&!busy);cadence.setEnabled(!active&&!busy);consent.setEnabled(!active&&!busy);historyConsent.setEnabled(!active&&!busy&&settingsReady); - sampleCadence.setEnabled(!active&&!busy);sampleAmount.setEnabled(!active&&!busy);sampleUnit.setEnabled(!active&&!busy);customAmount.setEnabled(!active&&!busy);customUnit.setEnabled(!active&&!busy); + sharingMode.setEnabled(!active&&!busy);cadence.setEnabled(!active&&!busy&&!realtimeMode());sampleCadence.setEnabled(!active&&!busy&&!realtimeMode());sampleAmount.setEnabled(!active&&!busy&&!realtimeMode());sampleUnit.setEnabled(!active&&!busy&&!realtimeMode());customAmount.setEnabled(!active&&!busy&&!realtimeMode());customUnit.setEnabled(!active&&!busy&&!realtimeMode()); for(List list:choices.values())for(CheckBox c:list)c.setEnabled(!active&&!busy); reload.setEnabled(paired&&!loading&&!pairing); } void remember(JSONObject response)throws Exception{ StringBuilder names=new StringBuilder();for(String type:new String[]{"viewers","phones","displays"}){JSONArray list=response.optJSONArray(type);if(list==null)continue;for(int i=0;i0)names.append("、");names.append(list.getJSONObject(i).getString("name"));if(type.equals("displays"))names.append("(显示终端)");}} - prefs.edit().putString("receipt",response.getString("receipt")).putString("recipients",names.toString()).putInt("intervalSeconds",response.optInt("intervalSeconds",300)).putInt("sampleIntervalSeconds",response.optInt("sampleIntervalSeconds",60)).apply(); + prefs.edit().putString("receipt",response.getString("receipt")).putString("recipients",names.toString()).putString("sharingMode",response.optString("sharingMode","scheduled")).putInt("intervalSeconds",response.optInt("intervalSeconds",300)).putInt("sampleIntervalSeconds",response.optInt("sampleIntervalSeconds",60)).apply(); } void pair(){ if(pairing||LocationService.busy||prefs.getBoolean("active",false))return; @@ -149,7 +155,7 @@ public class LocationActivity extends Activity { pairing=true;render(); new Thread(()->{try{ JSONObject response=DisplayApi.call("/api/location/pair",null,new JSONObject().put("code",value).put("consentProtocol",3));remember(response); - 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(); + 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();}); }catch(Exception e){runOnUiThread(()->{if(!isDestroyed())Toast.makeText(this,"配对未成功,请检查手机配对码或安装新版 App",1).show();});}finally{pairing=false;runOnUiThread(()->{if(!isDestroyed())render();});}},"location-pair").start(); } @@ -176,7 +182,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 ids=new HashSet<>();if(selected!=null)for(int i=0;i list=new ArrayList<>();choices.put(key,list);if(options!=null)for(int i=0;i{if(visible&&g==generation&&request==settingsRequest){settingsReady=false;if(e instanceof DisplayApi.ApiError&&(((DisplayApi.ApiError)e).status==401||((DisplayApi.ApiError)e).status==403))bindingRejected=true;settingsError="无法读取我的位置设置,请检查网络或配对有效期,重新打开设置重试。";render();}});}},"location-settings").start(); } void start(){ @@ -184,20 +190,22 @@ public class LocationActivity extends Activity { if(!consent.isChecked()){Toast.makeText(this,"请本人核对并勾选共享说明",1).show();return;} 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(!realtimeMode()&&Build.VERSION.SDK_INT>=29&&checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)!=PackageManager.PERMISSION_GRANTED){backgroundPermission();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> 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 JSONObject body=new JSONObject();try{int total=0;for(Map.Entry> 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("sharingMode",realtimeMode()?"realtime":"scheduled").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()]);} + boolean realtimeMode(){return sharingMode!=null&&sharingMode.getSelectedItemPosition()==1;} + int samplePeriodSeconds(){if(realtimeMode())return 10;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;i0?uploadIntervals[index]:LocationCadence.custom(Integer.parseInt(customAmount.getText().toString().trim()),customUnit.getSelectedItemPosition()==1);} + int uploadPeriod(){if(realtimeMode())return 10;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{ String period=new String[]{"day","week","month","year","life"}[choice];Calendar c=Calendar.getInstance(); @@ -223,7 +231,7 @@ public class LocationActivity extends Activity { final Dialog shown=historyDialog;ui.postDelayed(()->{if(shown.isShowing())shown.dismiss();},60000); });}catch(Exception e){runOnUiThread(()->{if(visible&&g==generation&&request==historyRequest){if(historyDialog!=null)historyDialog.dismiss();Toast.makeText(this,"未能读取:请检查本人授权、日期和网盘连接",1).show();}});}},"location-history").start(); } - void deleteHistory(){int g=generation;prefs.edit().putLong("queueEpoch",System.currentTimeMillis()).commit();stopService(new Intent(this,LocationService.class));prefs.edit().putBoolean("active",false).apply();new Thread(()->{try{String token=prefs.getString("token","");DisplayApi.call("/api/location/update",token,new JSONObject().put("action","stop"));DisplayApi.call("/api/location/update",token,new JSONObject().put("action","history-delete").put("confirm",true));outbox.discard(queueOwner);refreshQueueStats();runOnUiThread(()->{if(visible&&g==generation){Toast.makeText(this,"本机待同步已清理,历史已隐藏,云端删除会持续重试",1).show();loadSettings();}});}catch(Exception e){runOnUiThread(()->Toast.makeText(this,"删除未完成,本机待同步记录保留,请检查连接后重试",1).show());}},"delete-history").start();} + void deleteHistory(){int g=generation;prefs.edit().putLong("queueEpoch",System.currentTimeMillis()).commit();LocationSchedule.cancel(this);stopService(new Intent(this,LocationService.class));prefs.edit().putBoolean("active",false).apply();new Thread(()->{try{String token=prefs.getString("token","");DisplayApi.call("/api/location/update",token,new JSONObject().put("action","stop"));DisplayApi.call("/api/location/update",token,new JSONObject().put("action","history-delete").put("confirm",true));outbox.discard(queueOwner);refreshQueueStats();runOnUiThread(()->{if(visible&&g==generation){Toast.makeText(this,"本机待同步已清理,历史已隐藏,云端删除会持续重试",1).show();loadSettings();}});}catch(Exception e){runOnUiThread(()->Toast.makeText(this,"删除未完成,本机待同步记录保留,请检查连接后重试",1).show());}},"delete-history").start();} String locationPermissionText(){ boolean foreground=checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)==0||checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)==0; if(!foreground)return "定位权限:未允许。查看家人不需要开启自己的定位。"; @@ -243,7 +251,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.getLong("pendingPoints",0)>0)syncNow();if(!settingsReady)loadSettings();ui.post(refresh);if(pendingStart){pendingStart=false;start();}} + 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();} } diff --git a/android-display/src/cn/ucvl/zhaodisplay/LocationQueue.java b/android-display/src/cn/ucvl/zhaodisplay/LocationQueue.java index dc4533b..f84b1c5 100644 --- a/android-display/src/cn/ucvl/zhaodisplay/LocationQueue.java +++ b/android-display/src/cn/ucvl/zhaodisplay/LocationQueue.java @@ -16,14 +16,20 @@ final class LocationQueue extends SQLiteOpenHelper { static final int MAX_POINTS=50000, BATCH_POINTS=128, MAX_INFLIGHT=4; static final long MAX_BYTES=12L*1024*1024, MAX_DATABASE_BYTES=32L*1024*1024; static final String KEY="zhao-location-outbox-v1"; - LocationQueue(Context context){super(context,"location-outbox.db",null,1);} + LocationQueue(Context context){super(context,"location-outbox.db",null,2);} public void onCreate(SQLiteDatabase db){ db.execSQL("CREATE TABLE points(id TEXT PRIMARY KEY,owner TEXT NOT NULL,session TEXT NOT NULL,at INTEGER,payload BLOB NOT NULL,batch TEXT)"); db.execSQL("CREATE INDEX queue_owner ON points(owner,at)"); db.execSQL("CREATE TABLE batches(id TEXT PRIMARY KEY,owner TEXT,session TEXT,payload BLOB,digest TEXT,count INTEGER,next_try INTEGER)"); db.execSQL("CREATE TABLE totals(owner TEXT PRIMARY KEY,uploaded INTEGER NOT NULL,freed INTEGER NOT NULL)"); + db.execSQL("CREATE TABLE latest(owner TEXT PRIMARY KEY,payload BLOB NOT NULL)"); } - public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){throw new IllegalStateException("Unsupported location outbox migration");} + public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){if(oldVersion==1&&newVersion==2)db.execSQL("CREATE TABLE latest(owner TEXT PRIMARY KEY,payload BLOB NOT NULL)");else throw new IllegalStateException("Unsupported location outbox migration");} + synchronized void latest(String owner,JSONObject fix)throws Exception{ContentValues row=new ContentValues();row.put("owner",owner);row.put("payload",encrypt(fix.toString(),owner+"latest"));getWritableDatabase().insertWithOnConflict("latest",null,row,SQLiteDatabase.CONFLICT_REPLACE);} + synchronized JSONObject latest(String owner)throws Exception{try(Cursor c=getReadableDatabase().rawQuery("SELECT payload FROM latest WHERE owner=?",new String[]{owner})){return c.moveToFirst()?new JSONObject(decrypt(c.getBlob(0),owner+"latest")):null;}} + synchronized void clearLatest(String owner){getWritableDatabase().delete("latest","owner=?",new String[]{owner});} + synchronized boolean hasBatches(String owner){try(Cursor c=getReadableDatabase().rawQuery("SELECT 1 FROM batches WHERE owner=? LIMIT 1",new String[]{owner})){return c.moveToFirst();}} + synchronized boolean ready(String owner,long cutoff){try(Cursor c=getReadableDatabase().rawQuery("SELECT 1 FROM points WHERE owner=? AND (batch IS NOT NULL OR at<=?) LIMIT 1",new String[]{owner,Long.toString(cutoff)})){return c.moveToFirst();}} public void onOpen(SQLiteDatabase db){super.onOpen(db);db.setMaximumSize(MAX_DATABASE_BYTES);try(Cursor c=db.rawQuery("PRAGMA secure_delete=ON",null)){c.moveToFirst();}} static String id(){return UUID.randomUUID().toString().replace("-","");} static String digest(String value)throws Exception{ @@ -91,5 +97,5 @@ final class LocationQueue extends SQLiteOpenHelper { return values; } synchronized long total(){try(Cursor c=getReadableDatabase().rawQuery("SELECT count(*) FROM points",null)){c.moveToFirst();return c.getLong(0);}} - synchronized void discard(String owner){SQLiteDatabase db=getWritableDatabase();db.beginTransaction();try{db.delete("points","owner=?",new String[]{owner});db.delete("batches","owner=?",new String[]{owner});db.setTransactionSuccessful();}finally{db.endTransaction();}} + synchronized void discard(String owner){SQLiteDatabase db=getWritableDatabase();db.beginTransaction();try{db.delete("points","owner=?",new String[]{owner});db.delete("batches","owner=?",new String[]{owner});db.delete("latest","owner=?",new String[]{owner});db.setTransactionSuccessful();}finally{db.endTransaction();}} } diff --git a/android-display/src/cn/ucvl/zhaodisplay/LocationSchedule.java b/android-display/src/cn/ucvl/zhaodisplay/LocationSchedule.java new file mode 100644 index 0000000..33fbe65 --- /dev/null +++ b/android-display/src/cn/ucvl/zhaodisplay/LocationSchedule.java @@ -0,0 +1,32 @@ +package cn.ucvl.zhaodisplay; + +import android.app.*; +import android.app.job.*; +import android.content.*; +import android.os.*; + +/** OS-owned, inexact wakeups. No timer thread, GPS listener or process between samples. */ +final class LocationSchedule { + static final int SAMPLE=4501,REPORT=4502,RETRY=4503; + static boolean scheduled(SharedPreferences p){return "scheduled".equals(p.getString("sharingMode","scheduled"));} + static boolean enabled(SharedPreferences p){return p.getBoolean("active",false)&&scheduled(p)&&p.getLong("expires",0)>System.currentTimeMillis()&&!p.getString("sessionToken","").isEmpty()&&p.getString("sessionToken","").equals(p.getString("token",""));} + static PendingIntent intent(Context c,int id){ + Intent i=new Intent(c,LocationService.class).setAction(id==SAMPLE?"SAMPLE":"REPORT"); + i.putExtra("session",c.getSharedPreferences("location",0).getString("sessionNonce","")); + return PendingIntent.getForegroundService(c,id,i,PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_IMMUTABLE); + } + static void arm(Context c,int id,long at){((AlarmManager)c.getSystemService(Context.ALARM_SERVICE)).setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,Math.max(System.currentTimeMillis()+1000,at),intent(c,id));} + static void resume(Context c){ + SharedPreferences p=c.getSharedPreferences("location",0);if(!enabled(p))return; + arm(c,SAMPLE,p.getLong("nextSampleAt",System.currentTimeMillis())); + arm(c,REPORT,p.getLong("nextReportAt",System.currentTimeMillis())); + } + static void retry(Context c,long delay){ + SharedPreferences p=c.getSharedPreferences("location",0);if(p.getString("token","").isEmpty())return; + PersistableBundle extras=new PersistableBundle();extras.putString("token",p.getString("token","")); + ((JobScheduler)c.getSystemService(Context.JOB_SCHEDULER_SERVICE)).schedule(new JobInfo.Builder(RETRY,new ComponentName(c,LocationSyncJob.class)) + .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).setMinimumLatency(Math.max(10000,delay)).setExtras(extras).build()); + } + static void cancelSampling(Context c){AlarmManager a=(AlarmManager)c.getSystemService(Context.ALARM_SERVICE);for(int id:new int[]{SAMPLE,REPORT})a.cancel(intent(c,id));} + static void cancel(Context c){cancelSampling(c);((JobScheduler)c.getSystemService(Context.JOB_SCHEDULER_SERVICE)).cancel(RETRY);} +} diff --git a/android-display/src/cn/ucvl/zhaodisplay/LocationService.java b/android-display/src/cn/ucvl/zhaodisplay/LocationService.java index ba20b6c..5142b36 100644 --- a/android-display/src/cn/ucvl/zhaodisplay/LocationService.java +++ b/android-display/src/cn/ucvl/zhaodisplay/LocationService.java @@ -10,135 +10,176 @@ import android.Manifest; import org.json.JSONObject; import java.util.concurrent.*; -/** Visible sharing plus an encrypted outbox. No boot receiver starts GPS collection. */ +/** Continuous GPS only for explicit realtime mode. Scheduled sessions sleep between bounded work. */ public class LocationService extends Service implements LocationListener { static volatile boolean busy=false; String sessionToken="",owner="",collection=""; - volatile boolean destroyed=false,active=false,stopping=false,starting=false,forceSync=false,failedNetwork=false,networkBlocked=false; - boolean historyEnabled=false,sentFix=false,cacheFull=false,ticking=false; - ScheduledExecutorService worker;ExecutorService recorder;LocationManager manager;LocationQueue queue;ConnectivityManager connectivity; - android.content.SharedPreferences prefs;volatile Location latest; - long lastUpload=0,lastSample=0,flushCutoff=0,collectionStarted=0;volatile long nextAttempt=0; - int failures=0,intervalSeconds=300,sampleSeconds=60;String lastSignal=""; + volatile boolean destroyed=false,active=false,stopping=false,starting=false,forceSync=false,networkBlocked=false; + volatile boolean realtime=false,capturing=false;boolean historyEnabled=false,cacheFull=false,finishing=false; + ScheduledExecutorService worker;LocationManager manager;LocationQueue queue;ConnectivityManager connectivity; + SharedPreferences prefs;PowerManager.WakeLock wake; + long collectionStarted=0,captureStarted=0,lastSample=0,deadline=0; + int intervalSeconds=300,sampleSeconds=60; final Handler ui=new Handler(); + final Runnable captureTimeout=()->finishCapture("本次未取得新位置,等待下次采集"); + final Runnable workTimeout=()->{if(!realtime){try{LocationSchedule.retry(this,60000);}catch(Exception ignored){}finishWork();}}; final ConnectivityManager.NetworkCallback networkCallback=new ConnectivityManager.NetworkCallback(){ - public void onAvailable(Network network){nextAttempt=0;} - public void onLost(Network network){failedNetwork=true;} - public void onBlockedStatusChanged(Network network,boolean blocked){networkBlocked=blocked;if(blocked)failedNetwork=true;else if(failedNetwork){forceSync=true;nextAttempt=0;}} - public void onCapabilitiesChanged(Network network,NetworkCapabilities caps){if(failedNetwork&&caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED))nextAttempt=0;} + public void onBlockedStatusChanged(Network n,boolean blocked){networkBlocked=blocked;} }; public void onCreate(){ super.onCreate();prefs=getSharedPreferences("location",0);manager=(LocationManager)getSystemService(LOCATION_SERVICE);queue=new LocationQueue(this); - sessionToken=prefs.getString("token","");try{owner=LocationQueue.digest(sessionToken);}catch(Exception e){stopSelf();return;} + sessionToken=prefs.getString("token","");try{owner=LocationQueue.digest(sessionToken);}catch(Exception ignored){} NotificationManager nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);nm.createNotificationChannel(new NotificationChannel("location","本人位置与轨迹同步",NotificationManager.IMPORTANCE_LOW)); - connectivity=(ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);worker=Executors.newSingleThreadScheduledExecutor();recorder=Executors.newSingleThreadExecutor(); + connectivity=(ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);worker=Executors.newSingleThreadScheduledExecutor(); try{connectivity.registerDefaultNetworkCallback(networkCallback);}catch(Exception ignored){} } + boolean validIdentity(){return !destroyed&&sessionToken.equals(prefs.getString("token",""));} void notification(String text){ PendingIntent stop=PendingIntent.getService(this,1,new Intent(this,LocationService.class).setAction("STOP"),PendingIntent.FLAG_IMMUTABLE|PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent open=PendingIntent.getActivity(this,1,new Intent(this,LocationActivity.class),PendingIntent.FLAG_IMMUTABLE|PendingIntent.FLAG_UPDATE_CURRENT); - Notification.Builder notice=new Notification.Builder(this,"location").setContentTitle(active||starting?"赵府 · 位置共享":"赵府 · 轨迹同步").setContentText(text).setSmallIcon(android.R.drawable.ic_menu_mylocation).setContentIntent(open).setOngoing(true); - if(active||starting)notice.addAction(new Notification.Action.Builder(null,"停止共享",stop).build()); - if(Build.VERSION.SDK_INT>=29)startForeground(45,notice.build(),active||starting?android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION:android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC);else startForeground(45,notice.build()); + Notification.Builder n=new Notification.Builder(this,"location").setContentTitle(realtime?"赵府 · 实时共享":"赵府 · 本次定位与同步").setContentText(text).setSmallIcon(android.R.drawable.ic_menu_mylocation).setContentIntent(open).setOngoing(true); + if(active||starting)n.addAction(new Notification.Action.Builder(null,"停止共享",stop).build()); + if(Build.VERSION.SDK_INT>=29)startForeground(45,n.build(),capturing||realtime?android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION:android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC);else startForeground(45,n.build()); + } + void bounded(){ + deadline=SystemClock.elapsedRealtime()+90000;ui.removeCallbacks(workTimeout);ui.postDelayed(workTimeout,90000); + if(wake==null){wake=((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"zhao:location-cycle");wake.setReferenceCounted(false);}wake.acquire(95000); } public int onStartCommand(Intent intent,int flags,int id){ - if(intent==null||sessionToken.isEmpty()){stopSelf();return START_NOT_STICKY;} - if(!ticking){ticking=true;worker.scheduleWithFixedDelay(this::tick,1,10,TimeUnit.SECONDS);} + notification("正在处理本次定位或同步"); + if(intent==null||sessionToken.isEmpty()||!validIdentity()){stopSelf();return START_NOT_STICKY;} String action=intent.getAction(); if("STOP".equals(action)){stopSharing();return START_NOT_STICKY;} - if("SYNC".equals(action)){forceSync=true;nextAttempt=0;notification(active?"位置共享中 · 正在补传轨迹":"只同步已采集轨迹,不开启定位");return START_NOT_STICKY;} + if("SYNC".equals(action)||"RETRY".equals(action)){ + if("SYNC".equals(action))forceSync=true; + if(busy)return START_NOT_STICKY; + restore();bounded();worker.execute(this::cycle);return START_NOT_STICKY; + } + if("SAMPLE".equals(action)||"REPORT".equals(action)){ + if(prefs.getLong("expires",0)<=System.currentTimeMillis()){prefs.edit().putBoolean("active",false).putBoolean("stopPending",true).apply();LocationSchedule.cancelSampling(this);LocationSchedule.retry(this,10000);if(!busy)stopSelf();return START_NOT_STICKY;} + if(!LocationSchedule.enabled(prefs)||!prefs.getString("sessionNonce","").equals(intent.getStringExtra("session"))){if(!busy)stopSelf();return START_NOT_STICKY;} + if(busy)return START_NOT_STICKY; + restore();bounded(); + if("SAMPLE".equals(action))listen();else worker.execute(this::cycle); + return START_NOT_STICKY; + } if(active||stopping||starting)return START_NOT_STICKY; - starting=true;busy=true;notification("正在确认本人的共享授权"); + starting=true;busy=true;bounded(); worker.execute(()->{try{ JSONObject result=DisplayApi.call("/api/location/update",sessionToken,new JSONObject().put("action","start").put("consent",true).put("receipt",prefs.getString("receipt","")).put("bufferedHistory",true)); - if(stopping||destroyed)return; + if(stopping||!validIdentity())return; intervalSeconds=LocationCadence.seconds(result.optInt("intervalSeconds",300));sampleSeconds=LocationCadence.sample(result.optInt("sampleIntervalSeconds",60)); - collection=result.optString("collectionId");historyEnabled=result.optBoolean("historyEnabled",false)&&!collection.isEmpty(); + realtime="realtime".equals(result.optString("sharingMode","scheduled"));collection=result.optString("collectionId");historyEnabled=result.optBoolean("historyEnabled",false)&&!collection.isEmpty(); collectionStarted=(long)(result.optDouble("collectionStartedAt",System.currentTimeMillis()/1000d)*1000); - active=true;starting=false;sentFix=false;lastUpload=0;lastSample=0;forceSync=true; - prefs.edit().putBoolean("active",true).putLong("lastFlushAt",System.currentTimeMillis()).putLong("expires",(long)(result.getDouble("expires")*1000)).putString("status","共享中,等待定位").apply(); - ui.post(()->{if(!stopping&&!destroyed){listen();notification("共享给 "+prefs.getString("recipients","")+" · 可随时停止");}}); - }catch(Exception e){starting=false;busy=false;if(!destroyed){prefs.edit().putBoolean("active",false).putString("status","未开启:请检查网络、配对有效期").apply();stopSelf();}}}); + active=true;starting=false;long now=System.currentTimeMillis();queue.clearLatest(owner); + prefs.edit().putBoolean("active",true).putBoolean("stopPending",false).putString("sharingMode",realtime?"realtime":"scheduled") + .putString("sessionToken",sessionToken).putString("sessionNonce",LocationQueue.id()).putString("collectionId",collection).putBoolean("collectHistory",historyEnabled).putLong("collectionStarted",collectionStarted) + .putLong("nextSampleAt",now).putLong("nextReportAt",now).putLong("lastLiveAt",0).putLong("flushCutoff",0).putLong("expires",(long)(result.getDouble("expires")*1000)).putString("status","共享已开启,等待本次定位").apply(); + ui.post(()->{if(stopping||!validIdentity())return;if(realtime){ui.removeCallbacks(workTimeout);if(wake!=null&&wake.isHeld())wake.release();worker.scheduleWithFixedDelay(this::cycle,10,10,TimeUnit.SECONDS);}listen();}); + }catch(Exception e){starting=false;busy=false;if(validIdentity()){prefs.edit().putBoolean("active",false).putString("status","未开启:请检查网络、配对有效期").apply();ui.post(this::finishWork);}}}); return START_NOT_STICKY; } - void listen(){ - if(!active||stopping)return; - try{for(String provider:new String[]{LocationManager.GPS_PROVIDER,LocationManager.NETWORK_PROVIDER})if(manager.getAllProviders().contains(provider))manager.requestLocationUpdates(provider,sampleSeconds*1000L,0,this);} - catch(SecurityException e){prefs.edit().putString("status","定位权限未开启").apply();} + void restore(){ + active=LocationSchedule.enabled(prefs);realtime=false;busy=true; + intervalSeconds=LocationCadence.seconds(prefs.getInt("intervalSeconds",300));sampleSeconds=LocationCadence.sample(prefs.getInt("sampleIntervalSeconds",60)); + collection=prefs.getString("collectionId","");collectionStarted=prefs.getLong("collectionStarted",0);historyEnabled=prefs.getBoolean("collectHistory",false)&&!collection.isEmpty(); + stopping=prefs.getBoolean("stopPending",false); } - boolean connected(){try{Network network=connectivity.getActiveNetwork();NetworkCapabilities caps=connectivity.getNetworkCapabilities(network);return !networkBlocked&&caps!=null&&caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);}catch(Exception e){return false;}} - void tick(){ + void listen(){ + if(!active||stopping||!validIdentity())return; + if(!realtime&&Build.VERSION.SDK_INT>=29&&checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)!=PackageManager.PERMISSION_GRANTED){prefs.edit().putString("status","定时采集需要始终允许定位,请在我的设置中检查").apply();finishCapture(null);return;} + capturing=true;captureStarted=System.currentTimeMillis();notification(realtime?"实时定位与共享中 · 可随时停止":"短暂采集当前位置 · 完成后释放定位"); + try{for(String provider:new String[]{LocationManager.GPS_PROVIDER,LocationManager.NETWORK_PROVIDER})if(manager.getAllProviders().contains(provider))manager.requestLocationUpdates(provider,realtime?10000L:0,0,this);} + catch(SecurityException e){finishCapture("定位权限未开启");return;} + if(!realtime)ui.postDelayed(captureTimeout,30000); + } + void detach(){capturing=false;ui.removeCallbacks(captureTimeout);try{manager.removeUpdates(this);}catch(Exception ignored){}} + void finishCapture(String message){ + detach();if(message!=null)prefs.edit().putString("status",message).apply(); + if(!realtime&&active){long next=System.currentTimeMillis()+sampleSeconds*1000L;prefs.edit().putLong("nextSampleAt",next).apply();LocationSchedule.arm(this,LocationSchedule.SAMPLE,next);} + if(!destroyed)worker.execute(this::cycle); + } + boolean connected(){try{NetworkCapabilities c=connectivity.getNetworkCapabilities(connectivity.getActiveNetwork());return !networkBlocked&&c!=null&&c.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);}catch(Exception e){return false;}} + void cycle(){ if(destroyed||starting)return; + boolean reportRequested=false; try{ + if(!validIdentity())return; if(active&&System.currentTimeMillis()>prefs.getLong("expires",0)){ui.post(this::stopSharing);return;} - updateQueueStatus(); - if(!active&&!stopping&&queue.stats(owner)[0]==0){stopSelf();return;} - if(!connected()){failedNetwork=true;prefs.edit().putString("syncStatus","网络不可用,已采集轨迹加密保留在本机,恢复后自动补传").apply();return;} - if(SystemClock.elapsedRealtime()=prefs.getLong("nextReportAt",0); + reportRequested=active&&(due||forceSync||prefs.getBoolean("reportPending",false)); + if(!connected()){ + prefs.edit().putString("syncStatus","网络不可用,已采集轨迹加密保留;联网后补传").apply(); + if(due||forceSync||stopping||queue.hasBatches(owner)){prefs.edit().putBoolean("reportPending",true).apply();LocationSchedule.retry(this,10000);}return; + } if(stopping){ try{DisplayApi.call("/api/location/update",sessionToken,new JSONObject().put("action","stop"));}catch(DisplayApi.ApiError e){if(e.status!=401&&e.status!=403)throw e;} - stopping=false;busy=false;prefs.edit().putString("status","共享关闭,平台已清除当前位置").apply();notification("正在补传关闭前已采集的轨迹");forceSync=true; + stopping=false;prefs.edit().putBoolean("stopPending",false).putString("status","共享已关闭,平台已清除当前位置").apply();forceSync=true; } - if(active)uploadLive(); - long now=System.currentTimeMillis(); - if(forceSync||failedNetwork||active&&now-prefs.getLong("lastFlushAt",0)>=intervalSeconds*1000L){ - flushCutoff=now;prefs.edit().putLong("lastFlushAt",now).apply();forceSync=false; + if(reportRequested){uploadLive();if(!validIdentity()||stopping)return;} + if(due||forceSync||prefs.getBoolean("reportPending",false)){ + prefs.edit().putLong("flushCutoff",now).putLong("nextReportAt",now+intervalSeconds*1000L).putBoolean("reportPending",false).apply();forceSync=false; } - for(int i=0;ideadline-20000)break; + LocationQueue.Batch batch=queue.next(owner,prefs.getLong("flushCutoff",0),now);if(batch==null)break; + JSONObject reply=DisplayApi.call("/api/location/update",sessionToken,batch.request());if(!validIdentity())return; boolean removed=queue.acknowledge(owner,batch,reply); - prefs.edit().putString("syncStatus",removed?"网盘完整校验通过,已清理对应手机记录":"平台已接收,等待网盘回读校验;本机副本继续保留").apply(); - if(removed)cacheFull=false; + prefs.edit().putString("syncStatus",removed?"网盘完整校验通过,已清理对应手机记录":"平台已接收,等待网盘回读校验;本机副本保留").apply();if(removed)cacheFull=false; } - failures=0;nextAttempt=0;failedNetwork=false;updateQueueStatus(); - }catch(DisplayApi.ApiError error){ - if(error.status==401||error.status==403){ - if(active)ui.post(this::stopSharing); - prefs.edit().putString("syncStatus","采集或配对授权已结束,未上传记录仍保留;请核对授权或手动清理").apply();nextAttempt=SystemClock.elapsedRealtime()+300000; - }else if(error.status==400||error.status==409){prefs.edit().putString("syncStatus","批次或授权校验未通过,本机记录保留,可手动重试或清理").apply();nextAttempt=SystemClock.elapsedRealtime()+300000;} - else retry("上传尚未完成,本机记录保留,稍后自动重试"); - }catch(SecurityException error){prefs.edit().putString("syncStatus","回执校验未通过,手机轨迹没有删除").apply();nextAttempt=SystemClock.elapsedRealtime()+300000;} - catch(Exception error){retry("网络或同步暂未完成,手机轨迹已保留,恢复后自动补传");} + updateQueueStatus();if(queue.ready(owner,prefs.getLong("flushCutoff",0)))LocationSchedule.retry(this,30000); + }catch(DisplayApi.ApiError e){ + if(reportRequested)prefs.edit().putBoolean("reportPending",true).apply(); + if(e.status==401||e.status==403){active=false;realtime=false;LocationSchedule.cancelSampling(this);prefs.edit().putBoolean("active",false).putString("status","共享授权已结束,请检查配对与授权").apply();ui.post(this::detach);} + prefs.edit().putString("syncStatus","同步未完成,本机记录保留,可检查网络或授权后重试").apply();if(e.status!=401&&e.status!=403)LocationSchedule.retry(this,60000); + }catch(Exception e){if(reportRequested)prefs.edit().putBoolean("reportPending",true).apply();prefs.edit().putString("syncStatus","同步或回执校验未完成,本机记录保留,稍后重试").apply();LocationSchedule.retry(this,60000);} + finally{if(!realtime&&!capturing&&!starting)ui.post(this::finishWork);} } - void retry(String message){failedNetwork=true;failures=Math.min(failures+1,5);nextAttempt=SystemClock.elapsedRealtime()+Math.min(300000,10000L*(1L<=28?manager.isLocationEnabled():manager.isProviderEnabled(LocationManager.GPS_PROVIDER)||manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);} - void stopSharing(){ - if(stopping)return;stopping=true;starting=false;busy=true;active=false;latest=null; - try{manager.removeUpdates(this);}catch(Exception ignored){} - prefs.edit().putBoolean("active",false).putString("status","本机已停止采集,联网后通知平台清除当前位置;关闭前轨迹仍会补传").apply();notification("已停止定位 · 联网后完成同步");nextAttempt=0; + JSONObject body=new JSONObject().put("action","update").put("bufferedHistory",true),fix=queue.latest(owner); + if(fix!=null&&"waiting".equals(signal)&&now-fix.optDouble("at")*1000<900000){body.put("position",fix);signal="available";} + body.put("signal",signal);DisplayApi.call("/api/location/update",sessionToken,body); + if(validIdentity()&&!stopping)prefs.edit().putLong("lastLiveAt",now).putString("status",(realtime?"实时共享中":"定时共享中")+" · 最近汇报 "+java.text.DateFormat.getTimeInstance().format(new java.util.Date(now))).apply(); } public void onLocationChanged(Location value){ - if(!active||stopping)return; - Location fix=new Location(value);long elapsed=fix.getElapsedRealtimeNanos()/1000000; - if(!LocationCadence.sampleDue(elapsed,lastSample,sampleSeconds)||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; - if(queue.append(owner,session,position(fix))){cacheFull=false;} - else{cacheFull=true;prefs.edit().putString("syncStatus","本地缓存已达上限,暂停新增历史;未上传记录没有覆盖,请联网补传").apply();notification("轨迹缓存已满 · 请联网补传");} + if(!active||!capturing||stopping||!validIdentity())return; + Location fix=new Location(value);long elapsed=fix.getElapsedRealtimeNanos()/1000000,now=System.currentTimeMillis(); + if(!LocationCadence.sampleDue(elapsed,lastSample,realtime?10:sampleSeconds)||fix.getTime()now+60000||now-fix.getTime()>900000)return; + lastSample=elapsed;if(!realtime)detach();long epoch=prefs.getLong("queueEpoch",0); + worker.execute(()->{try{ + if(!validIdentity()||epoch!=prefs.getLong("queueEpoch",0)||!prefs.getBoolean("active",false))return; + queue.latest(owner,position(fix)); + if(historyEnabled){cacheFull=!queue.append(owner,collection,position(fix));if(cacheFull)prefs.edit().putString("syncStatus","缓存已达上限,暂停新增历史;未上传记录保留").apply();} updateQueueStatus(); - }catch(Exception error){cacheFull=true;prefs.edit().putString("syncStatus","本地轨迹未能写入,请检查手机存储空间;已有记录保留").apply();}}); + }catch(Exception e){prefs.edit().putString("syncStatus","本次定位未能写入,请检查手机空间;已有记录保留").apply();} + finally{if(!realtime&&!destroyed&&!stopping&&active)ui.post(()->finishCapture("定时共享中 · 本次采集结束,定位已释放"));}}); } - public void onStatusChanged(String provider,int status,Bundle extras){} - public void onProviderEnabled(String provider){} - public void onProviderDisabled(String provider){} - public IBinder onBind(Intent intent){return null;} + void stopSharing(){ + LocationSchedule.cancelSampling(this);active=false;realtime=false;stopping=true;starting=false;busy=true;detach(); + prefs.edit().putBoolean("active",false).putBoolean("stopPending",true).putString("sessionNonce",LocationQueue.id()).putString("status","本机已停止采集;联网后清除平台当前位置").apply(); + bounded();notification("已停止定位 · 正在同步关闭状态");worker.execute(()->{queue.clearLatest(owner);cycle();}); + } + void finishWork(){ + if(finishing||destroyed)return;finishing=true;detach();ui.removeCallbacks(workTimeout); + if(LocationSchedule.enabled(prefs)){ + long now=System.currentTimeMillis();if(prefs.getLong("nextSampleAt",0)<=now)prefs.edit().putLong("nextSampleAt",now+sampleSeconds*1000L).apply();if(prefs.getLong("nextReportAt",0)<=now)prefs.edit().putLong("nextReportAt",now+intervalSeconds*1000L).apply(); + LocationSchedule.resume(this); + } + if(wake!=null&&wake.isHeld())wake.release();stopForeground(true);stopSelf(); + } + static JSONObject position(Location f)throws Exception{return new JSONObject().put("latitude",f.getLatitude()).put("longitude",f.getLongitude()).put("accuracy",f.getAccuracy()).put("at",f.getTime()/1000d);} + void updateQueueStatus(){long[] v=queue.stats(owner);prefs.edit().putLong("pendingPoints",v[0]).putLong("pendingBytes",v[1]).putLong("uploadedPoints",v[2]).putLong("freedBytes",v[3]).putBoolean("cacheFull",cacheFull).apply();} + static boolean locationEnabled(LocationManager m){return Build.VERSION.SDK_INT>=28?m.isLocationEnabled():m.isProviderEnabled(LocationManager.GPS_PROVIDER)||m.isProviderEnabled(LocationManager.NETWORK_PROVIDER);} + public void onStatusChanged(String p,int s,Bundle b){}public void onProviderEnabled(String p){}public void onProviderDisabled(String p){} + public IBinder onBind(Intent i){return null;} public void onDestroy(){ - destroyed=true;active=false;latest=null;try{manager.removeUpdates(this);}catch(Exception ignored){}try{connectivity.unregisterNetworkCallback(networkCallback);}catch(Exception ignored){} - if(worker!=null)worker.shutdownNow();if(recorder!=null)recorder.shutdown();prefs.edit().putBoolean("active",false).apply();busy=false;stopForeground(true);super.onDestroy(); + destroyed=true;detach();ui.removeCallbacksAndMessages(null);try{connectivity.unregisterNetworkCallback(networkCallback);}catch(Exception ignored){} + if(worker!=null)worker.shutdownNow();if(wake!=null&&wake.isHeld())wake.release(); + if(realtime)prefs.edit().putBoolean("active",false).putBoolean("stopPending",true).putString("status","实时共享已中断,请本人重新开启").apply(); + busy=false;stopForeground(true);super.onDestroy(); } } diff --git a/android-display/src/cn/ucvl/zhaodisplay/LocationSyncJob.java b/android-display/src/cn/ucvl/zhaodisplay/LocationSyncJob.java new file mode 100644 index 0000000..9f7f3e1 --- /dev/null +++ b/android-display/src/cn/ucvl/zhaodisplay/LocationSyncJob.java @@ -0,0 +1,12 @@ +package cn.ucvl.zhaodisplay; +import android.app.job.*; +import android.content.*; +/** A network-constrained retry starts bounded data sync only; never enables GPS. */ +public class LocationSyncJob extends JobService { + public boolean onStartJob(JobParameters params){ + if(!params.getExtras().getString("token","").equals(getSharedPreferences("location",0).getString("token","")))return false; + try{startForegroundService(new Intent(this,LocationService.class).setAction("RETRY"));}catch(Exception e){LocationSchedule.retry(this,300000);} + return false; + } + public boolean onStopJob(JobParameters params){return true;} +} diff --git a/android-display/src/cn/ucvl/zhaodisplay/PhoneLayout.java b/android-display/src/cn/ucvl/zhaodisplay/PhoneLayout.java index ed59028..a29c4d8 100644 --- a/android-display/src/cn/ucvl/zhaodisplay/PhoneLayout.java +++ b/android-display/src/cn/ucvl/zhaodisplay/PhoneLayout.java @@ -39,7 +39,7 @@ final class PhoneLayout extends LinearLayout { shareCard=s.column();s.card(shareCard);mineContent.addView(shareCard);sharing=new Switch(app);sharing.setText("共享我的位置");sharing.setTextSize(19);sharing.setTypeface(null,Typeface.BOLD);sharing.setTextColor(PhoneStyle.INK);sharing.setMinHeight(s.dp(50));sharing.setThumbTintList(new android.content.res.ColorStateList(new int[][]{new int[]{android.R.attr.state_checked},new int[]{}},new int[]{PhoneStyle.GREEN,0xffb5bcb6}));shareCard.addView(sharing); LinearLayout state=s.line();state.setPadding(s.dp(10),s.dp(6),s.dp(4),s.dp(6));state.setBackground(s.shape(0xfffff4de,12));myStatus=s.label("共享关闭",13,0xff805c23);state.addView(myStatus,new LayoutParams(0,-2,1));myCheck=s.button("检查权限",false);state.addView(myCheck);shareCard.addView(state);s.gap(shareCard,10);shareCard.addView(s.label("查看家人位置,无需开启自己的共享。",12,PhoneStyle.MUTED)); section(mineContent,"允许谁查看");LinearLayout access=s.column();s.card(access);mineContent.addView(access);viewers=s.row("family","查看人名单","读取中");access.addView(viewers);expiry=s.row("clock","共享有效期","跟随本机配对有效期");access.addView(expiry); - section(mineContent,"定位与轨迹");LinearLayout location=s.column();s.card(location);mineContent.addView(location);sampling=s.row("location","定位采集频率","每 1 分钟");upload=s.row("cloud","集中上传周期","每 5 分钟");history=s.row("track","我的历史轨迹","每天、每周、每月、每年、一生");permissions=s.row("shield","定位权限与系统设置","本人开启共享后才采集");for(View row:new View[]{sampling,upload,history,permissions})location.addView(row); + section(mineContent,"定位与轨迹");LinearLayout location=s.column();s.card(location);mineContent.addView(location);sampling=s.row("location","共享模式与采集频率","定时采集 · 每 1 分钟");upload=s.row("cloud","集中上传周期","每 5 分钟");history=s.row("track","我的历史轨迹","每天、每周、每月、每年、一生");permissions=s.row("shield","定位权限与系统设置","本人开启共享后才采集");for(View row:new View[]{sampling,upload,history,permissions})location.addView(row); section(mineContent,"沟通与声音");voiceSettings=s.column();s.card(voiceSettings);mineContent.addView(voiceSettings); section(pages[2],"设备与系统");LinearLayout device=s.column();s.card(device);pages[2].addView(device);pairing=s.row("phone","配对与设备","查看或更换手机配对");device.addView(pairing); nav=s.line();nav.setBackgroundColor(PhoneStyle.CARD);nav.setPadding(s.dp(8),s.dp(4),s.dp(8),s.dp(6));addView(nav,new LayoutParams(-1,-2));String[] names={"位置","沟通","我的"},icons={"location","mic","person"}; diff --git a/android-display/src/cn/ucvl/zhaodisplay/VoiceChat.java b/android-display/src/cn/ucvl/zhaodisplay/VoiceChat.java index ad764c2..3499ba4 100644 --- a/android-display/src/cn/ucvl/zhaodisplay/VoiceChat.java +++ b/android-display/src/cn/ucvl/zhaodisplay/VoiceChat.java @@ -11,7 +11,14 @@ import java.util.function.Consumer; final class VoiceChat extends LinearLayout { final PhoneStyle s;final LinearLayout messages;final TextView notice,heading;final Button older,latest;final ScrollView scroll; boolean night=false,savedMore=false,savedPast=false;JSONArray saved=new JSONArray(); - String signature="";Consumer replay=id->{}; + String signature="";Consumer replay=id->{};LinearLayout transfer; + void transfer(String description,boolean failed,Runnable retry,Runnable discard){ + if(transfer!=null){messages.removeView(transfer);transfer=null;}if(description.isEmpty())return; + transfer=s.column();transfer.setPadding(s.dp(12),s.dp(10),s.dp(12),s.dp(10));transfer.setBackground(s.shape(PhoneStyle.PALE,14)); + transfer.addView(s.label(description,13,PhoneStyle.INK)); + if(failed){LinearLayout actions=s.line();Button again=s.button("重试发送",true),cancel=s.button("放弃本次",false);actions.addView(again);actions.addView(cancel);again.setOnClickListener(v->retry.run());cancel.setOnClickListener(v->discard.run());transfer.addView(actions);} + messages.addView(transfer);scroll.post(()->scroll.fullScroll(FOCUS_DOWN)); + } VoiceChat(Activity app){ super(app);s=new PhoneStyle(app);setOrientation(VERTICAL);s.card(this); LinearLayout head=s.line();heading=s.bold("聊天记录",18);head.addView(heading,new LayoutParams(0,-2,1));older=s.button("更早",false);latest=s.button("最近",false);head.addView(older);head.addView(latest);addView(head); @@ -23,7 +30,7 @@ final class VoiceChat extends LinearLayout { void clear(String text){signature="";saved=new JSONArray();messages.removeAllViews();notice.setText(text);older.setEnabled(false);} void theme(boolean value){if(night==value)return;night=value;setBackground(s.shape(night?0xff21372d:PhoneStyle.CARD,20));heading.setTextColor(night?0xffc8d5cd:PhoneStyle.INK);notice.setTextColor(night?0xff96aaa0:PhoneStyle.MUTED);for(Button b:new Button[]{older,latest}){b.setTextColor(night?0xffc8d5cd:PhoneStyle.GREEN);b.setBackground(s.shape(night?0xff2d4439:PhoneStyle.PALE,14));}if(saved.length()>0){signature="";show(saved,savedMore,savedPast,replay);}} void show(JSONArray items,boolean hasMore,boolean past,Consumer play){ - replay=play;saved=items;savedMore=hasMore;savedPast=past;older.setEnabled(hasMore);notice.setText(past?"较早的记录 · 可继续向前翻阅":"长期保留 · 点击语音回听"); + replay=play;saved=items;savedMore=hasMore;savedPast=past;older.setEnabled(hasMore);notice.setText(past?"较早的 10 条 · 可继续向前翻阅":"最近 10 条 · 点语音回听 · 更早记录按需加载"); String next=items.toString();if(next.equals(signature))return;boolean follow=signature.isEmpty()||scroll.getScrollY()+scroll.getHeight()>=messages.getHeight()-s.dp(32);int oldScroll=scroll.getScrollY();signature=next;messages.removeAllViews(); if(items.length()==0){TextView empty=s.label("还没有聊天记录\n按住下方按钮,给家人说句话吧",15,PhoneStyle.MUTED);empty.setGravity(Gravity.CENTER);empty.setPadding(0,s.dp(42),0,s.dp(30));messages.addView(empty);return;} for(int i=0;ireplay.accept(item.optString("id")));row.addView(voice,new LayoutParams(-1,-2)); String delivery=item.optString("delivery"),archive=item.optString("archive"); - String state=delivery.equals("played")?"已播放":delivery.equals("received")?"已送达":delivery.equals("queued")?"等待播放":"未自动播放 · 可以回听"; - row.addView(s.label(state+" · "+(archive.equals("cloud")?"已存网盘":archive.equals("retry")?"网盘归档重试中":"网盘归档中"),11,muted)); + String state=delivery.equals("played")?"已送达 · 已播放":delivery.equals("received")?"已送达 · 尚未完整播放":delivery.equals("queued")?"已发送 · 等待送达":delivery.equals("rejected")?"未完整播放 · 可回听":"自动播放已过期 · 可回听"; + if(delivery.equals("transferring"))state="传输中 · 等待对方确认接收"; + row.addView(s.label(state,12,muted)); + row.addView(s.label(archive.equals("cloud")?"✓ 已存网盘 · 校验完成":archive.equals("retry")?"网盘归档待重试 · 临时副本保留":archive.equals("uploading")?"↑ 正在传输到网盘":"等待存入网盘",11,muted)); } if(!past&&follow)scroll.post(()->scroll.fullScroll(FOCUS_DOWN));else scroll.post(()->scroll.scrollTo(0,past?0:oldScroll)); } diff --git a/android-display/src/cn/ucvl/zhaodisplay/VoicePanel.java b/android-display/src/cn/ucvl/zhaodisplay/VoicePanel.java index eb049bf..4f9409e 100644 --- a/android-display/src/cn/ucvl/zhaodisplay/VoicePanel.java +++ b/android-display/src/cn/ucvl/zhaodisplay/VoicePanel.java @@ -20,6 +20,7 @@ final class VoicePanel extends LinearLayout { final Activity app;final String kind;final Supplier token; final Handler ui=new Handler();final ExecutorService worker=Executors.newSingleThreadExecutor(); final TextView status;final Button speak,settings,stop;final VoiceSurface dock;VoiceSurface expanded,page;Dialog sheet; + byte[] pendingAudio;String pendingToken="",pendingTarget="",pendingId="",pendingPeer="",pendingName="";long pendingAt=0;double pendingSeconds=0;boolean pendingFailed=false; String selectedId="";boolean networkReady=false;long feedbackAt=0; boolean communicationVisible=false,historyLoading=false,historyPlayback=false;long historyBefore=0,nextBefore=0;int historyEpoch=0,playbackRequest=0;String historyPeer=""; final AudioManager audio;final AudioAttributes attributes=new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build(); @@ -38,8 +39,8 @@ final class VoicePanel extends LinearLayout { } void showStatus(String text){VoiceSurface.text(status,text);feedbackAt=SystemClock.elapsedRealtime();if(expanded!=null)VoiceSurface.text(expanded.status,text);if(page!=null)VoiceSurface.text(page.status,text);} VoiceSurface page(){if(page==null){page=new VoiceSurface(app,true);page.communicationPage();wire(page);page.expand.setVisibility(GONE);page.applyTheme(night);}renderSurfaces();return page;} - void communication(boolean value){communicationVisible=value;if(value)loadConversation(false);} - void chooseTarget(){if(recorder!=null||sending)return;if(destinations==null||destinations.length()==0){new AlertDialog.Builder(app).setTitle("暂无可接收的家人").setMessage("请对方打开 App,在接收设置中允许你向其喊话。显示终端也需要先授权。").setPositiveButton("知道了",null).show();return;}String[] names=new String[destinations.length()];int selected=-1;for(int i=0;i{choose(snapshot.optJSONObject(i).optString("id"));d.dismiss();}).setNegativeButton("取消",null).show();} + void communication(boolean value){communicationVisible=value;if(value){loadConversation(false);renderTransfer();}} + void chooseTarget(){if(recorder!=null||sending||pendingAudio!=null){if(pendingAudio!=null)showStatus("请先重试或放弃本次待发送语音");return;}if(destinations==null||destinations.length()==0){new AlertDialog.Builder(app).setTitle("暂无可接收的家人").setMessage("请对方打开 App,在接收设置中允许你向其喊话。显示终端也需要先授权。").setPositiveButton("知道了",null).show();return;}String[] names=new String[destinations.length()];int selected=-1;for(int i=0;i{choose(snapshot.optJSONObject(i).optString("id"));d.dismiss();}).setNegativeButton("取消",null).show();} void wire(VoiceSurface view){ view.chat.older.setOnClickListener(v->{if(!historyLoading&&nextBefore>0){historyBefore=nextBefore;loadConversation(true);}}); view.chat.latest.setOnClickListener(v->{if(!historyLoading){historyBefore=0;loadConversation(true);}}); @@ -73,7 +74,7 @@ final class VoicePanel extends LinearLayout { void choose(String id){if(recorder!=null||sending)return;stopPlayer("rejected");selectedId=id;lastMessage="";clearHistory("正在读取聊天记录…");JSONObject d=destination();showStatus(d!=null&&d.optBoolean("online")?"按住说话,松开发送给 "+d.optString("name"):"可以回听历史;发送需要对方授权并在线");renderSurfaces();loadConversation(true);} void renderSurfaces(){ JSONObject selected=destination();String name=selected==null?"":selected.optString("name");boolean available=selected!=null&&selected.optBoolean("online"); - boolean can=networkReady&&available&&selected.optBoolean("canSend",true)&&!sending&µphone();int amplitude=0;if(recorder!=null)try{amplitude=recorder.getMaxAmplitude();}catch(Exception ignored){} + boolean can=networkReady&&available&&selected.optBoolean("canSend",true)&&!sending&&pendingAudio==null&µphone();int amplitude=0;if(recorder!=null)try{amplitude=recorder.getMaxAmplitude();}catch(Exception ignored){} for(VoiceSurface view:new VoiceSurface[]{dock,expanded,page}){if(view==null)continue; if(recorder==null||view.full)VoiceSurface.text(view.recipient,name.isEmpty()?"选择一位家人":view.full?name:name+" · "+(available?"已打开 App":"未打开 App")+" ›");view.destination(selected,networkReady);view.receiving(enabled,networkReady&&recorder==null&&!sending); VoiceSurface.text(view.receive,enabled?"● 接收已开启 · 仅限你允许的家人":"○ 接收已关闭 · 可在接收设置中开启"); @@ -89,8 +90,8 @@ final class VoicePanel extends LinearLayout { if(closed)return;visible=value;epoch++;ui.removeCallbacks(refresh);ui.removeCallbacks(visual); if(value){ui.post(refresh);ui.post(visual);}else{clearHistory("打开沟通后读取记录");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;networkReady=false;selectedId="";lastMessage="";active(true);} - void close(){active(false);closed=true;ui.removeCallbacksAndMessages(null);worker.shutdown();} + void rebound(){active(false);pendingAudio=null;choices=new JSONArray();allowed=new JSONArray();destinations=new JSONArray();enabled=false;networkReady=false;selectedId="";lastMessage="";active(true);} + void close(){active(false);pendingAudio=null;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; @@ -124,7 +125,9 @@ final class VoicePanel extends LinearLayout { for(VoiceSurface view:new VoiceSurface[]{page,expanded})if(view!=null){view.chat.older.setEnabled(false);view.chat.latest.setEnabled(false);} worker.execute(()->{try{ JSONObject result=DisplayApi.call("/api/voice",t,body("history").put("peer",peer).put("before",before)); - ui.post(()->{if(!current(e,t)||request!=historyEpoch||!peer.equals(historyPeer))return;nextBefore=result.optLong("before");JSONArray items=result.optJSONArray("items");for(VoiceSurface view:new VoiceSurface[]{page,expanded})if(view!=null)view.chat.show(items==null?new JSONArray():items,nextBefore>0,before>0,this::replay);}); + ui.post(()->{if(!current(e,t)||request!=historyEpoch||!peer.equals(historyPeer))return;nextBefore=result.optLong("before");JSONArray items=result.optJSONArray("items"); + if(items!=null&&pendingAudio!=null&&pendingToken.equals(t)&&pendingPeer.equals(peer))for(int i=0;i0,before>0,this::replay);renderTransfer();}); }catch(Exception error){ui.post(()->{if(current(e,t)&&request==historyEpoch)for(VoiceSurface view:new VoiceSurface[]{page,expanded})if(view!=null)view.chat.notice.setText("聊天记录未能刷新,点“最近”重试");});} finally{ui.post(()->{if(request==historyEpoch){historyLoading=false;for(VoiceSurface view:new VoiceSurface[]{page,expanded})if(view!=null){view.chat.latest.setEnabled(true);view.chat.older.setEnabled(nextBefore>0);}}});}}); } @@ -149,7 +152,7 @@ final class VoicePanel extends LinearLayout { 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||!networkReady||recorder!=null||sending||selectedTarget().isEmpty())return; + if(!visible||!networkReady||recorder!=null||sending||pendingAudio!=null||selectedTarget().isEmpty())return; JSONObject target=destination();if(target==null||!target.optBoolean("online")||!target.optBoolean("canSend",true)){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;} @@ -165,13 +168,27 @@ final class VoicePanel extends LinearLayout { try{r.stop();}catch(Exception error){send=false;}finally{r.release();} 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("正在发送喊话…"); + try{pendingAudio=Files.readAllBytes(file.toPath());if(pendingAudio.length>150000)throw new IOException("Too large"); + pendingToken=recordToken;pendingTarget=recordTarget;pendingId=UUID.randomUUID().toString().replace("-","");pendingAt=System.currentTimeMillis();pendingSeconds=(SystemClock.elapsedRealtime()-started)/1000d; + JSONObject target=destination();pendingPeer=target==null?"":target.optString("archiveKey");pendingName=target==null?"对方":target.optString("name");pendingFailed=false; + }catch(Exception error){pendingAudio=null;showStatus("录音未能读取,请重新录制");}finally{file.delete();} + if(pendingAudio!=null)sendPending(); + } + void renderTransfer(){ + String text=pendingAudio==null||historyBefore>0||!pendingPeer.equals(historyPeer)?"":"我 → "+pendingName+" · "+String.format(Locale.CHINA,"%.1f 秒",pendingSeconds)+"\\n"+new java.text.SimpleDateFormat("HH:mm:ss",Locale.CHINA).format(new Date(pendingAt))+" · "+(pendingFailed?"发送未确认 · 可重试,不会重复发送\n本次临时保留,退出 App 后需重新录制":"↑ 正在传输 · 尚未确认送达"); + for(VoiceSurface v:new VoiceSurface[]{page,expanded})if(v!=null)v.chat.transfer(text,pendingFailed,this::sendPending,()->{if(sending)return;pendingAudio=null;showStatus("已放弃本机待发送副本;如果服务器已收到,记录仍保留");renderTransfer();renderSurfaces();}); + } + void sendPending(){ + if(pendingAudio==null||sending||closed||!visible)return; + if(!pendingToken.equals(token.get())){pendingAudio=null;renderTransfer();return;} + final String t=pendingToken,target=pendingTarget,id=pendingId;final byte[] bytes=pendingAudio;final int e=epoch; + sending=true;pendingFailed=false;historyBefore=0;showStatus("正在传输语音…");renderTransfer();renderSurfaces(); 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");showStatus("已发送,等待对方播放");}}); - }catch(Exception error){ui.post(()->{if(current(e,t))showStatus("未发送,请检查网络或对方的接收权限后重新录制");});} - finally{file.delete();ui.post(()->{sending=false;if(current(e,t))poll();});}}); + JSONObject result=DisplayApi.call("/api/voice",t,body("send").put("target",target).put("id",id).put("audio",Base64.encodeToString(bytes,Base64.NO_WRAP))); + ui.post(()->{if(t.equals(token.get())&&id.equals(pendingId)){pendingAudio=null;lastMessage=result.optString("id");if(current(e,t))showStatus("已发送,等待对方接收;网盘归档单独显示");}}); + }catch(Exception error){ui.post(()->{if(t.equals(token.get())&&id.equals(pendingId)){pendingFailed=true;if(current(e,t))showStatus("发送结果未确认,请检查连接或权限后重试");}});} + finally{ui.post(()->{sending=false;if(!closed){renderTransfer();renderSurfaces();if(visible)poll();}});} + }); } void take(String id){ // Reserve the playback slot while the download is in flight. @@ -183,6 +200,7 @@ final class VoicePanel extends LinearLayout { } void play(JSONObject clip,String t,byte[] bytes){ try{ + if(!historyPlayback)ack(t,clip.getString("id"),"received"); 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()); diff --git a/android-display/tests/build-phone-check.ps1 b/android-display/tests/build-phone-check.ps1 index 9eaae15..1fccbff 100644 --- a/android-display/tests/build-phone-check.ps1 +++ b/android-display/tests/build-phone-check.ps1 @@ -19,7 +19,10 @@ $env:Path="$jdk\bin;$env:Path" '@ | 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'} -$sources=@("$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) +$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) & "$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 a29ba89..572877b 100644 --- a/android-display/tests/phone-preview/DisplayApi.java +++ b/android-display/tests/phone-preview/DisplayApi.java @@ -10,6 +10,7 @@ final class DisplayApi { 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\":[]}"); } + if(action.equals("update")||action.equals("stop"))return new JSONObject().put("ok",true); if(action.equals("list")){JSONObject a=new JSONObject("{\"id\":\"a\",\"name\":\"家人甲(示例)\",\"status\":\"live\"}");a.put("position",new JSONObject().put("latitude",0).put("longitude",0).put("accuracy",25).put("at",System.currentTimeMillis()/1000-120));JSONObject b=new JSONObject("{\"id\":\"b\",\"name\":\"家人乙(示例)\",\"status\":\"scheduled\",\"scheduleReason\":\"sampling\"}");JSONObject c=new JSONObject().put("id","c").put("name","家人丙(示例)").put("position",new JSONObject().put("latitude",0).put("longitude",0).put("accuracy",10).put("at",System.currentTimeMillis()/1000));return new JSONObject().put("items",new JSONArray().put(b).put(a).put(c));} if(action.equals("settings"))return new JSONObject("{\"receipt\":\"fixture\",\"intervalSeconds\":7200,\"sampleIntervalSeconds\":300,\"historyEnabled\":true,\"historyDefault\":true,\"viewerIds\":[],\"phoneIds\":[\"demo\"],\"displayIds\":[],\"viewers\":[],\"phones\":[{\"id\":\"demo\",\"name\":\"示例家人的手机\"}],\"displays\":[],\"history\":{\"pending\":0,\"archived\":2,\"deleting\":0}}"); throw new ApiError(403); diff --git a/android-display/tests/phone-preview/LocationQueue.java b/android-display/tests/phone-preview/LocationQueue.java index 6b3f0ad..aa7bcdd 100644 --- a/android-display/tests/phone-preview/LocationQueue.java +++ b/android-display/tests/phone-preview/LocationQueue.java @@ -1,3 +1,13 @@ package cn.ucvl.zhaodisplay; -/** Test-only empty queue; never touches production storage. */ -final class LocationQueue {LocationQueue(android.content.Context c){}static String digest(String s){return "fixture";}long[] stats(String owner){return new long[]{0,0,0,0};}long total(){return 0;}void discard(String owner){}} +import org.json.*; +/** In-memory synthetic queue only. Production encryption and batch checks have separate tests. */ +final class LocationQueue { + static final int MAX_INFLIGHT=4;JSONObject remembered;int appended=0; + LocationQueue(android.content.Context c){}static String digest(String s){return "fixture";}static String id(){return java.util.UUID.randomUUID().toString();} + long[] stats(String owner){return new long[]{0,0,0,0};}long total(){return 0;}void discard(String owner){} + void latest(String owner,JSONObject f){remembered=f;}JSONObject latest(String owner){return remembered;}void clearLatest(String owner){remembered=null;} + boolean append(String owner,String session,JSONObject point){appended++;return true;} + boolean hasBatches(String owner){return false;}boolean ready(String owner,long cutoff){return false;} + static class Batch {JSONObject request(){return new JSONObject();}}Batch next(String owner,long cutoff,long now){return null;} + boolean acknowledge(String owner,Batch batch,JSONObject receipt){return false;} +} diff --git a/android-display/tests/phone-preview/LocationSchedule.java b/android-display/tests/phone-preview/LocationSchedule.java new file mode 100644 index 0000000..367d5e7 --- /dev/null +++ b/android-display/tests/phone-preview/LocationSchedule.java @@ -0,0 +1,7 @@ +package cn.ucvl.zhaodisplay; +final class LocationSchedule { + static final int SAMPLE=4501,REPORT=4502; + static boolean enabled(android.content.SharedPreferences p){return p.getBoolean("active",false)&&"scheduled".equals(p.getString("sharingMode","scheduled"))&&p.getString("token","").equals(p.getString("sessionToken",""))&&p.getLong("expires",0)>System.currentTimeMillis();} + static void cancel(android.content.Context c){}static void cancelSampling(android.content.Context c){} + static void resume(android.content.Context c){}static void arm(android.content.Context c,int id,long at){}static void retry(android.content.Context c,long delay){} +} diff --git a/android-display/tests/phone-preview/LocationService.java b/android-display/tests/phone-preview/LocationService.java index 0ec12af..f3ff384 100644 --- a/android-display/tests/phone-preview/LocationService.java +++ b/android-display/tests/phone-preview/LocationService.java @@ -1,3 +1,60 @@ package cn.ucvl.zhaodisplay; -/** Test-only noncollecting service. There are no location or foreground-service permissions. */ -public class LocationService extends android.app.Service {static boolean busy=false;static boolean locationEnabled(android.location.LocationManager m){return false;}public android.os.IBinder onBind(android.content.Intent i){return null;}} +import android.content.*; +import android.location.Location; +import android.os.*; +/** Runs production service control flow, with synthetic fixes and no network/GPS permission. */ +final class LocationCycleChecks { + static class Probe extends LocationService { + int listens=0,finishes=0;boolean online=true; + Probe(Context c){attachBaseContext(c);onCreate();} + void notification(String s){} + void bounded(){deadline=SystemClock.elapsedRealtime()+90000;} + void listen(){listens++;capturing=true;captureStarted=System.currentTimeMillis();} + boolean connected(){return online;} + void finishWork(){finishes++;detach();} + void dispose(){destroyed=true;detach();ui.removeCallbacksAndMessages(null);worker.shutdownNow();busy=false;} + } + static void check(boolean value,String message){if(!value)throw new AssertionError(message);} + static void run(Context c,Runnable done){ + SharedPreferences p=c.getSharedPreferences("location",0);long now=System.currentTimeMillis(); + p.edit().putBoolean("active",true).putString("sharingMode","scheduled").putString("sessionToken","synthetic-token").putString("sessionNonce","test") + .putLong("collectionStarted",now-10000).putLong("expires",now+86400000).putInt("intervalSeconds",7200).putInt("sampleIntervalSeconds",300) + .putLong("nextReportAt",now+7200000).putBoolean("collectHistory",true).putString("collectionId","fake-session").apply(); + Probe failure=new Probe(c);failure.restore();failure.deadline=SystemClock.elapsedRealtime()+90000; + p.edit().putLong("nextReportAt",0).putLong("lastLiveAt",0).apply();DisplayApi.offline=true;failure.cycle(); + check(p.getBoolean("reportPending",false),"HTTP failure preserves overdue report for retry");DisplayApi.offline=false;failure.dispose(); + p.edit().putBoolean("reportPending",false).putLong("nextReportAt",now+7200000).apply(); + Probe receipt=new Probe(c);receipt.restore();receipt.deadline=SystemClock.elapsedRealtime()+90000;receipt.cycle(); + check(p.getLong("nextReportAt",0)==now+7200000,"receipt retry never advances configured upload cadence");receipt.dispose(); + Probe service=new Probe(c);service.onStartCommand(new Intent("SAMPLE").putExtra("session","test"),0,1); + check(service.listens==1&&service.capturing,"scheduled wake starts one sample"); + Location fix=new Location("fixture");fix.setLatitude(0);fix.setLongitude(0);fix.setAccuracy(12);fix.setTime(System.currentTimeMillis());fix.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos()); + service.onLocationChanged(fix);check(!service.capturing,"first fix releases listener immediately"); + new Handler().postDelayed(()->{ + check(service.finishes>0,"scheduled cycle completes");check(p.getBoolean("active",false),"logical sharing survives sample completion"); + check(p.getLong("nextSampleAt",0)>System.currentTimeMillis(),"next sample scheduled"); + check(p.getLong("nextReportAt",0)==now+7200000,"sampling does not advance upload cadence"); + check(service.queue.remembered!=null&&service.queue.appended==1,"fix and history persisted once"); + service.dispose(); + Probe sync=new Probe(c);sync.onStartCommand(new Intent("SYNC"),0,2); + new Handler().postDelayed(()->{ + check(sync.listens==0,"manual sync never starts GPS");check(sync.finishes>0,"sync cycle completes"); + sync.dispose(); + Probe offline=new Probe(c);offline.online=false;offline.onStartCommand(new Intent("SYNC"),0,3); + new Handler().postDelayed(()->{ + check(offline.finishes>0&&!offline.capturing,"offline sync sleeps instead of permanent service");check(p.getBoolean("reportPending",false),"offline work is retained");offline.dispose(); + Probe stop=new Probe(c);stop.online=false;stop.onStartCommand(new Intent("STOP"),0,4); + new Handler().postDelayed(()->{ + check(!p.getBoolean("active",true)&&p.getBoolean("stopPending",false),"offline stop prevents new sampling immediately"); + check(stop.finishes>0&&!stop.capturing,"offline stop service terminates");stop.dispose(); + p.edit().putBoolean("active",true).putBoolean("stopPending",false).putString("sessionNonce","new").apply(); + Probe realtime=new Probe(c);realtime.active=true;realtime.realtime=true;realtime.capturing=true;realtime.captureStarted=System.currentTimeMillis();realtime.collectionStarted=now-10000; + fix.setTime(System.currentTimeMillis());fix.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());realtime.onLocationChanged(fix); + check(realtime.capturing,"explicit realtime retains listener"); + new Handler().postDelayed(()->{realtime.dispose();p.edit().putBoolean("active",false).putBoolean("reportPending",false).apply();done.run();},150); + },200); + },200); + },200); + },250); + } +} diff --git a/android-display/tests/phone-preview/PhonePreviewActivity.java b/android-display/tests/phone-preview/PhonePreviewActivity.java index d7eb453..55e4d6a 100644 --- a/android-display/tests/phone-preview/PhonePreviewActivity.java +++ b/android-display/tests/phone-preview/PhonePreviewActivity.java @@ -18,7 +18,7 @@ public class PhonePreviewActivity extends LocationActivity { // 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)?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 save();}catch(Exception e){throw new RuntimeException(e);}},1800); + 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); } void check(boolean condition,String message){if(!condition)throw new AssertionError(message);} void exercise()throws Exception{ @@ -34,6 +34,11 @@ public class PhonePreviewActivity extends LocationActivity { phone.nav.getChildAt(0).performClick();check(phone.tab==0,"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"); + 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); else if(mode.equals("voice")||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("界面验收 · 不录音、不发送语音"); diff --git a/android-display/tests/phone-preview/QueueStorageChecks.java b/android-display/tests/phone-preview/QueueStorageChecks.java new file mode 100644 index 0000000..213edc3 --- /dev/null +++ b/android-display/tests/phone-preview/QueueStorageChecks.java @@ -0,0 +1,28 @@ +package cn.ucvl.zhaodisplay; +import android.content.*;import android.database.sqlite.*;import org.json.*; +/** Production SQLite/Keystore logic runs under the fixture's separate UID and database. */ +final class QueueStorageChecks { + static void check(boolean v,String msg){if(!v)throw new AssertionError(msg);} + static void run(Context c)throws Exception{ + c.deleteDatabase("storage-check.db");SQLiteDatabase old=c.openOrCreateDatabase("storage-check.db",0,null); + old.execSQL("CREATE TABLE points(id TEXT PRIMARY KEY,owner TEXT NOT NULL,session TEXT NOT NULL,at INTEGER,payload BLOB NOT NULL,batch TEXT)"); + old.execSQL("CREATE TABLE batches(id TEXT PRIMARY KEY,owner TEXT,session TEXT,payload BLOB,digest TEXT,count INTEGER,next_try INTEGER)"); + old.execSQL("CREATE TABLE totals(owner TEXT PRIMARY KEY,uploaded INTEGER NOT NULL,freed INTEGER NOT NULL)"); + old.execSQL("INSERT INTO points VALUES ('old','legacy','old-session',1,X'01',NULL)");old.setVersion(1);old.close(); + StoredLocationQueue q=new StoredLocationQueue(c); + check(q.stats("legacy")[0]==1,"v1 pending rows survive migration"); + check(q.getReadableDatabase().getVersion()==2,"database migrated to v2"); + q.discard("legacy");String owner=StoredLocationQueue.digest("synthetic"),session="test-session"; + JSONObject point=new JSONObject().put("latitude",0).put("longitude",0).put("accuracy",5).put("at",System.currentTimeMillis()/1000d); + q.latest(owner,point);check(q.latest(owner).getDouble("latitude")==0,"encrypted latest round trip"); + check(q.append(owner,session,point),"encrypted sample persisted"); + StoredLocationQueue.Batch batch=q.next(owner,System.currentTimeMillis()+1000,System.currentTimeMillis()); + check(batch!=null,"batch created");JSONObject accepted=new JSONObject().put("batchId",batch.id).put("sha256",batch.digest).put("count",batch.count).put("state","accepted"); + check(!q.acknowledge(owner,batch,accepted)&&q.stats(owner)[0]==1,"accepted receipt keeps local data"); + try{q.acknowledge(owner,batch,new JSONObject(accepted.toString()).put("sha256","wrong").put("state","verified"));throw new AssertionError("mismatched receipt accepted");}catch(SecurityException expected){} + check(q.stats(owner)[0]==1,"invalid receipt keeps pending row"); + check(q.acknowledge(owner,batch,accepted.put("state","verified")),"verified receipt clears batch"); + check(q.stats(owner)[0]==0&&q.stats(owner)[2]==1,"only verified point removed"); + q.clearLatest(owner);check(q.latest(owner)==null,"latest removed on stop");q.close();c.deleteDatabase("storage-check.db"); + } +} diff --git a/family_voice.py b/family_voice.py index 7244866..079dec0 100644 --- a/family_voice.py +++ b/family_voice.py @@ -76,6 +76,9 @@ class Voice: self.messages.pop(key,None) if key in self.receipts:self.receipts[key]['status']='expired' self.history.delivery(key,'expired') + for key,receipt in self.receipts.items(): + if receipt['expires']<=now and receipt['status'] in ('queued','transferring','received'): + self.history.delivery(key,'expired') self.receipts={k:v for k,v in self.receipts.items() if v['expires']>now} self.online={k:v for k,v in self.online.items() if now-v<60} self.rates={k:v for k,v in self.rates.items() if now-v[0]<60} @@ -172,11 +175,11 @@ class Voice: if action=='take': m=self.messages.get(key) if not m or m['target']!=me or not self.permitted(self.endpoint(m['sender']),actor):raise a.Problem('语音已过期或没有接收权限',404) - del self.messages[key];receipt['status']='received' - self.history.delivery(key,'received') + del self.messages[key];receipt['status']='transferring' + self.history.delivery(key,'transferring') return dict(id=key,senderName=m['senderName'],seconds=m['seconds'],audio=base64.b64encode(m['audio']).decode()) if action=='ack': - if not receipt or receipt['target']!=me or receipt['status']!='received':raise a.Problem('喊话回执不存在',404) - if body.get('status') not in ('played','rejected'):raise a.Problem('回执不正确') + if not receipt or receipt['target']!=me or receipt['status'] not in ('transferring','received'):raise a.Problem('喊话回执不存在',404) + if body.get('status') not in ('received','played','rejected'):raise a.Problem('回执不正确') receipt['status']=body['status'];self.history.delivery(key,body['status']);return dict(ok=True) raise a.Problem('喊话操作不正确') diff --git a/frontend/package.json b/frontend/package.json index 4ce7ff5..1688977 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "zhao-steward-ui", "private": true, - "version": "0.1.53", + "version": "0.1.54", "type": "module", "scripts": { "build": "vite build", diff --git a/member_locations.py b/member_locations.py index 1fc4fc5..c3766e6 100644 --- a/member_locations.py +++ b/member_locations.py @@ -158,7 +158,7 @@ class Locations: viewerIds=[v['id'] for v in grant['viewers']],displayIds=[v['id'] for v in grant['displays']], phoneIds=[v['id'] for v in grant.get('phones',[])],receipt=grant['receipt'], intervalSeconds=grant.get('intervalSeconds',300),viewOnly=grant.get('viewOnly',False), - sampleIntervalSeconds=grant.get('sampleIntervalSeconds',60), + sampleIntervalSeconds=grant.get('sampleIntervalSeconds',60),sharingMode=grant.get('sharingMode','scheduled'), historyEnabled=grant.get('historyEnabled',False),historyDefault=grant.get('historyDefault',False) and 'historyEnabled' not in grant, history=self.a.HISTORY.own_status(row['member_id'])) if action=='configure': @@ -168,22 +168,25 @@ class Locations: 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 not 10 <= sample <= 86400:raise a.Problem('采集间隔可自定义 10 秒至 1 天,不支持一周等更长间隔') + mode=body.get('sharingMode','scheduled') + if mode not in ('scheduled','realtime'):raise a.Problem('请选择定时采集或实时共享') + if mode=='realtime':interval=sample=10 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) self.sync.close(sid) - grant.update(chosen,viewOnly=False,intervalSeconds=interval,sampleIntervalSeconds=sample,consentProtocol=3,historyEnabled=history) + grant.update(chosen,viewOnly=False,intervalSeconds=interval,sampleIntervalSeconds=sample,sharingMode=mode,consentProtocol=3,historyEnabled=history) self.refresh_receipt(grant) a.DB.execute('UPDATE member_location_shares SET enabled=0,grant_json=? WHERE id=?',(json.dumps(grant),sid)) self.latest.pop(sid,None) - return dict(ok=True,receipt=grant['receipt'],intervalSeconds=interval,sampleIntervalSeconds=sample,historyEnabled=history,**chosen) + return dict(ok=True,receipt=grant['receipt'],intervalSeconds=interval,sampleIntervalSeconds=sample,sharingMode=mode,historyEnabled=history,**chosen) if action=='start': if grant.get('viewOnly'):raise a.Problem('此手机仅用于查看家人,请先由本人设置共享对象',403) if body.get('consent') is not True or body.get('receipt')!=grant['receipt']:raise a.Problem('请本人核对姓名及查看人,并同意开启共享',403) a.DB.execute('UPDATE member_location_shares SET enabled=1 WHERE id=?',(sid,)) self.latest[sid]=dict(seen=0,started=now,fix=None,signal='waiting') collection=self.sync.start(row,grant) if body.get('bufferedHistory') is True else {} - return dict(ok=True,expires=row['expires'],intervalSeconds=grant.get('intervalSeconds',300),sampleIntervalSeconds=grant.get('sampleIntervalSeconds',60),**collection) + return dict(ok=True,expires=row['expires'],intervalSeconds=grant.get('intervalSeconds',300),sampleIntervalSeconds=grant.get('sampleIntervalSeconds',60),sharingMode=grant.get('sharingMode','scheduled'),**collection) if action!='update' or not row['enabled']:raise a.Problem('位置共享尚未开启',403) old=self.latest.get(sid,dict(started=now,fix=None)) if now-old.get('seen',0)<10:raise a.Problem('位置更新过于频繁',429) @@ -235,7 +238,7 @@ class Locations: 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=upload,sampleIntervalSeconds=sample,scheduleReason='sampling' if sampling and sample>upload else 'upload', + intervalSeconds=upload,sampleIntervalSeconds=sample,sharingMode=grant.get('sharingMode','scheduled'),scheduleReason='sampling' if sampling and sample>upload else 'upload', nextSampleAt=next_sample,nextUploadAt=next_upload)) return items diff --git a/test_family_voice.py b/test_family_voice.py index c9e7615..889d06c 100644 --- a/test_family_voice.py +++ b/test_family_voice.py @@ -46,6 +46,18 @@ class VoiceTests(unittest.TestCase): result=self.send(a,b);self.assertEqual(self.send(a,b)['id'],result['id']);self.assertEqual(len(app.VOICE.messages),1) self.call(b,'take',id=result['id']);self.send(a,b);self.assertEqual(len(app.VOICE.messages),0) + def test_delivery_requires_device_confirmation_and_is_separate_from_cloud(self): + a,b=self.phone('甲'),self.phone('乙');self.receive(b,a) + key=self.send(a,b)['id'];self.call(b,'take',id=key) + row=app.VOICE.history.existing(key);self.assertEqual(row['delivery'],'transferring');self.assertEqual(row['state'],'pending') + self.call(b,'ack',id=key,status='received') + self.assertEqual(app.VOICE.history.existing(key)['delivery'],'received') + self.assertEqual(app.VOICE.history.existing(key)['state'],'pending') + with self.assertRaises(app.Problem):self.call(a,'ack',id=key,status='received') + self.call(b,'ack',id=key,status='played') + self.assertEqual(app.VOICE.history.existing(key)['delivery'],'played') + with self.assertRaises(app.Problem):self.call(b,'ack',id=key,status='received') + def test_cross_family_and_foreign_inbox_rejected(self): a,b,c=self.phone('甲'),self.phone('乙'),self.phone('其他',self.other) with self.assertRaises(app.Problem):self.receive(b,c) diff --git a/test_phone_locations.py b/test_phone_locations.py index 13c208a..1d75e2b 100644 --- a/test_phone_locations.py +++ b/test_phone_locations.py @@ -95,6 +95,21 @@ class PhoneLocationTests(unittest.TestCase): self.assertEqual(self.listing(viewer), []) self.assertEqual(len(app.LOCATIONS.listing(self.aid, user=self.members[self.aid])), 1) + def test_two_explicit_modes_and_changed_consent(self): + source,viewer=self.phone('本人'),self.phone('查看人') + result=self.configure(source,phoneIds=[viewer['sid']],sharingMode='scheduled',sampleIntervalSeconds=3600,intervalSeconds=86400) + self.assertEqual((result['sharingMode'],result['sampleIntervalSeconds'],result['intervalSeconds']),('scheduled',3600,86400)) + self.start(source);self.point(source) + self.assertEqual(self.listing(viewer)[0]['sharingMode'],'scheduled') + old=source['receipt'] + result=self.configure(source,phoneIds=[viewer['sid']],sharingMode='realtime',sampleIntervalSeconds=3600,intervalSeconds=86400) + self.assertNotEqual(old,result['receipt']);self.assertEqual(self.listing(viewer),[]) + self.assertEqual((result['sampleIntervalSeconds'],result['intervalSeconds']),(10,10)) + started=self.start(source);self.assertEqual(started['sharingMode'],'realtime') + self.assertEqual(app.LOCATIONS.native(source['token'],dict(action='settings'))['sharingMode'],'realtime') + for bad in ('continuous','',None,True,{},[]): + with self.subTest(mode=bad),self.assertRaises(app.Problem):self.configure(source,phoneIds=[viewer['sid']],sharingMode=bad) + def test_other_family_self_and_invalid_recipients_rejected(self): source, foreign = self.phone('本人'), self.phone('乙家庭', self.other) for options in (dict(phoneIds=[foreign['sid']]), dict(phoneIds=[source['sid']]), diff --git a/test_voice_history.py b/test_voice_history.py index 334e1dd..9f4855a 100644 --- a/test_voice_history.py +++ b/test_voice_history.py @@ -44,7 +44,9 @@ class VoiceHistoryTests(unittest.TestCase): a,b=self.pair_of_phones();key=self.send(a,b)['id'];archive=app.VOICE.history local=archive.folder/archive.filename(key);cipher=local.read_bytes() self.assertNotEqual(cipher,base64.b64decode(audio())) - upload=lambda *args:dict(fs_id=17) + def upload(*args): + self.assertEqual(archive.existing(key)['state'],'uploading') + return dict(fs_id=17) with patch.object(app.BAIDU,'upload',side_effect=upload),patch.object(app.BAIDU,'verify_file',side_effect=ValueError('bad checksum')): archive.tick() self.assertTrue(local.exists());self.assertEqual(archive.existing(key)['state'],'retry') @@ -88,9 +90,13 @@ class VoiceHistoryTests(unittest.TestCase): for n in range(121): with app.LOCK,app.DB:app.VOICE.history.accept(actor['archiveKey']+':'+f'{n:032x}',actor,target,base64.b64decode(audio()),.64) before=0;seen=[] + initial=self.call(a,'history',peer=self.peer(b)) + self.assertEqual(len(initial['items']),10) + maximum=app.DB.execute('SELECT max(seq) FROM voice_history').fetchone()[0] + self.assertEqual([r['seq'] for r in initial['items']],list(range(maximum-9,maximum+1))) while True: page=self.call(a,'history',peer=self.peer(b),before=before);ids=[r['seq'] for r in page['items']] - self.assertEqual(ids,sorted(ids));self.assertLessEqual(len(ids),50);seen+=ids + self.assertEqual(ids,sorted(ids));self.assertLessEqual(len(ids),10);seen+=ids before=page['before'] if not before:break self.assertEqual(len(seen),121);self.assertEqual(len(set(seen)),121) diff --git a/voice_history.py b/voice_history.py index 05f05fa..0f3f52e 100644 --- a/voice_history.py +++ b/voice_history.py @@ -42,11 +42,13 @@ class VoiceHistory: attempts INTEGER DEFAULT 0, next_try REAL DEFAULT 0)''') a.DB.execute('CREATE INDEX IF NOT EXISTS voice_history_sender ON voice_history(family,sender,seq)') a.DB.execute('CREATE INDEX IF NOT EXISTS voice_history_target ON voice_history(family,target,seq)') + a.DB.execute('CREATE INDEX IF NOT EXISTS voice_history_pair ON voice_history(family,sender,target,seq)') a.DB.execute('CREATE INDEX IF NOT EXISTS voice_history_pending ON voice_history(state,next_try,seq)') if not a.setting('voice_history_key'): a.set_setting('voice_history_key', base64.b64encode(secrets.token_bytes(32)).decode()) # A restart ends live playback, but never removes the conversation. - a.DB.execute("UPDATE voice_history SET delivery='expired' WHERE delivery IN ('queued','received')") + a.DB.execute("UPDATE voice_history SET delivery='expired' WHERE delivery IN ('queued','transferring','received')") + a.DB.execute("UPDATE voice_history SET state='retry' WHERE state='uploading'") self.folder.mkdir(parents=True, exist_ok=True) os.chmod(self.folder, 0o700) with a.LOCK: @@ -123,12 +125,16 @@ class VoiceHistory: if not isinstance(peer, str) or not re.fullmatch(r'[a-f0-9]{64}', peer) or type(before) is not int or before < 0 or before > 2**63-1: raise self.a.Problem('请选择有效的沟通对象和记录页') me = actor['archiveKey'] - rows = self.a.DB.execute('''SELECT * FROM voice_history WHERE family=? - AND ((sender=? AND target=?) OR (target=? AND sender=?)) - AND (?=0 OR seq 50 - rows = rows[:50] + # Two bounded index scans; do not sort a lifetime of messages to fetch ten rows. + cutoff=before or 2**63-1 + rows = self.a.DB.execute('''SELECT * FROM (SELECT * FROM voice_history + WHERE family=? AND sender=? AND target=? AND seq 10 + rows = rows[:10] return dict(items=[dict(id=r['id'], seq=r['seq'], mine=r['sender']==me, senderName=r['sender_name'], targetName=r['target_name'], at=r['at'], seconds=r['seconds'], delivery=r['delivery'], archive=r['state']) for r in reversed(rows)], @@ -172,6 +178,7 @@ class VoiceHistory: row=a.DB.execute("SELECT * FROM voice_history WHERE state!='cloud' AND next_try<=? ORDER BY seq LIMIT 1", (time.time(),)).fetchone() if not row:return row=dict(row) + with a.DB:a.DB.execute("UPDATE voice_history SET state='uploading' WHERE id=?",(row['id'],)) local=self.folder/self.filename(row['id']) try: with local.open('rb') as stream: cipher=stream.read(MAX_FILE+1)