feat(location): durable offline GPS outbox and hourly daily uploads v0.1.50

This commit is contained in:
Codex
2026-10-19 00:57:33 +08:00
parent cd3ed420a2
commit e3afb2e07f
26 changed files with 697 additions and 135 deletions
+26
View File
@@ -0,0 +1,26 @@
# V0.1.50 — 手机离线轨迹与定时补传
## 手机使用
- “我的位置设置”分别设置定位采集频率(10 秒、1 分钟、5 分钟)和上传周期。上传保留实时、1/5 分钟,增加 1—5 小时、1—3 天,以及 1—720 小时 / 1—30 天的整数自定义周期。
- 开启本人位置共享和历史保存后,采集点先写入手机私有 SQLite 队列,使用 Android Keystore 的 AES-256-GCM 加密。采集写入与网络同步使用独立线程,关闭流量、断网或上传超时不会阻塞本地写入。
- 到达周期集中发送;断网恢复、解除网络限制、点击“立即同步”或重新打开有未完成队列的 App 时补传。只有采集授权窗口内的轨迹可以补传。授权到期停止新采集,但仍绑定的手机可以完成到期前记录的同步;解除手机绑定后不能上传。
- 手机对每批内容计算 SHA-256,服务端核对整批内容、点数、时间和采集授权。收到“已接收”仍保留手机副本;百度网盘完成上传并回读校验后,手机核对批次、SHA-256 和点数,再事务性清理这一批。网络重试、回执丢失、进程重启均复用同一批次,避免重复入库。
- 单批最多 128 点,最多 4 批等待校验。手机缓存以 50,000 点 / 12 MiB 密文先到为限,数据库最多 32 MiB,删除后的空页复用。达到上限暂停新增历史并提示,不能为了腾空间覆盖未确认记录。SQLite 事务日志可能临时增加少量占用。
- 设置显示待同步点数、占用、累计校验清理数量和释放的记录字节数。支持立即重试、明确确认后放弃本机副本,以及删除全部历史;最后一项暂停共享并清理本机未完成记录,服务器隐藏历史并持续重试网盘删除。
- 未完成队列存在时阻止直接更换配对,避免把同一个人的旧轨迹误归到另一个人。关闭共享立即停止新采集、清除实时位置;关闭前已经采集的授权轨迹继续完成同步。
## 平台与授权
- 网盘继续沿用 `家庭轨迹/家庭编号/成员编号/年/月/日`,只保存加密压缩文件。
- 每次采集会话保存当时的查看人范围。后来新增的查看人不能读取旧的离线轨迹;查看时仍需现行授权,超级管理员没有绕过权限的入口。
- 历史批次不覆盖“当前实时位置”。超过 15 分钟的坐标不作为实时点显示;长周期尚未到期显示“等待下次定时上传”,到期加宽限仍未收到才提示中断。排期时间持久化,服务端重启不应造成长周期误报。
- 旧版手机继续使用原位置接口。新的离线批次接口有独立大小上限和原子校验,容量不足返回失败并让手机保留数据。用户主动删除的旧历史不能被迟到重传重新创建。
## 验证与使用边界
- 后端专项覆盖整批校验、跨手机隔离、3 天补传、授权到期、关闭共享、删除防重放、云端失败、重复请求和长周期状态。
- 全量 Python 回归 326 项、JavaScript 回归 191 项通过。Edge 桌面与 390 像素手机宽度验证了排期提示、无错误中断警报和无横向溢出;Vue 生产构建与两个签名安装包构建通过。
- 独立 JVM 周期测试通过 92 条断言。Android 11 真机隔离测试通过 163 条断言:Keystore 加密、SQLite 持久化重开、错误 / 部分回执、确认后只删对应批次、容量上限、归属隔离及密文篡改。测试包不申请 GPS,不访问家庭数据,测试后已卸载。
- 真机存储测试不等于已在用户手机上验证移动 GPS、断流量和各厂商省电策略。需从下载页覆盖安装手机版本;测试不替任何家人开启定位或历史共享。
- 本地队列在 App 进程结束后保留。系统强制停止、卸载、清除应用数据或撤销定位权限时不能保证继续采集;重新打开 App 可补传已保存队列,新采集仍由本人开启。卸载 / 清数据会删除尚未上传的本机副本,请使用覆盖安装。
+1 -1
View File
@@ -1 +1 @@
0.1.49
0.1.50
+2 -2
View File
@@ -1,4 +1,4 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="5" android:versionName="0.1.49">
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="6" android:versionName="0.1.50">
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
@@ -17,6 +17,6 @@
</activity>
<service android:name=".MonitorService" android:exported="false" />
<activity android:name=".LocationActivity" android:label="赵府家人位置" android:exported="true" />
<service android:name=".LocationService" android:exported="false" android:foregroundServiceType="location" />
<service android:name=".LocationService" android:exported="false" android:foregroundServiceType="location|dataSync" />
</application>
</manifest>
+2 -2
View File
@@ -1,4 +1,4 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="5" android:versionName="0.1.49">
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="6" android:versionName="0.1.50">
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
@@ -15,7 +15,7 @@
</activity>
<service android:name=".MonitorService" android:exported="false"/>
<activity android:name=".LocationActivity" android:label="赵府家人位置" android:exported="true"><intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter></activity>
<service android:name=".LocationService" android:exported="false" android:foregroundServiceType="location"/>
<service android:name=".LocationService" android:exported="false" android:foregroundServiceType="location|dataSync"/>
<receiver android:name=".BootReceiver" android:exported="true"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED"/></intent-filter></receiver>
</application>
</manifest>
@@ -15,7 +15,9 @@ 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;LinearLayout settings,recipients,familyList,homeContent,shareControls;
CheckBox consent,historyConsent;Switch sharing;Spinner cadence,sampleCadence,customUnit;EditText customAmount;LinearLayout customPeriod,settings,recipients,familyList,homeContent,shareControls;
TextView queueStatus;LocationQueue outbox;String queueOwner="";
final int[] uploadIntervals={10,60,300,3600,7200,10800,14400,18000,86400,172800,259200,0};
TextView historyStatus,historyNotice;Dialog historyDialog;LocationMapView historyMap;Button historyMore;JSONArray historyPoints=new JSONArray();int historyRequest=0;boolean historyAcknowledged=false;
VoicePanel voice;Button settingsButton;
LocationMapView map;boolean rendering=false,visible=false,loading=false,settingsReady=false,pendingStart=false;
@@ -28,6 +30,7 @@ public class LocationActivity extends Activity {
Button button(String label,LinearLayout parent){Button b=new Button(this);b.setText(label);parent.addView(b);return b;}
public void onCreate(Bundle state){
super.onCreate(state);prefs=getSharedPreferences("location",0);
outbox=new LocationQueue(this);refreshQueueStats();
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.
@@ -49,13 +52,20 @@ public class LocationActivity extends Activity {
shareControls=new LinearLayout(this);shareControls.setOrientation(1);settings.addView(shareControls);
text("我的位置共享",22,shareControls);text("选择谁能看我的位置",16,shareControls);
recipients=new LinearLayout(this);recipients.setOrientation(1);shareControls.addView(recipients);
text("上传频率",16,shareControls);cadence=new Spinner(this);cadence.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"实时(约 10 秒)","每 1 分钟","每 5 分钟(默认)"}));cadence.setSelection(2);shareControls.addView(cadence);
text("实时档更耗电和流量;更新受信号、网络与系统省电影响。调整名单或频率前,先关闭共享。",14,shareControls);
text("定位采集频率",16,shareControls);sampleCadence=new Spinner(this);sampleCadence.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"每 10 秒(较耗电)","每 1 分钟(默认)","每 5 分钟(省电)"}));sampleCadence.setSelection(1);shareControls.addView(sampleCadence);
text("集中上传周期",16,shareControls);cadence=new Spinner(this);cadence.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"实时(约 10 秒)","每 1 分钟","每 5 分钟(默认)","每 1 小时","每 2 小时","每 3 小时","每 4 小时","每 5 小时","每 1 天","每 2 天","每 3 天","自定义小时 / 天"}));cadence.setSelection(2);shareControls.addView(cadence);
customPeriod=new LinearLayout(this);customPeriod.setOrientation(0);customAmount=new EditText(this);customAmount.setInputType(InputType.TYPE_CLASS_NUMBER);customAmount.setHint("正整数");customAmount.setText("6");customAmount.setFilters(new android.text.InputFilter[]{new android.text.InputFilter.LengthFilter(3)});customPeriod.addView(customAmount,new LinearLayout.LayoutParams(0,-2,1));customUnit=new Spinner(this);customUnit.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"小时","天"}));customPeriod.addView(customUnit);shareControls.addView(customPeriod);customPeriod.setVisibility(View.GONE);
cadence.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){public void onItemSelected(AdapterView<?> p,View v,int position,long id){customPeriod.setVisibility(position==uploadIntervals.length-1?View.VISIBLE:View.GONE);}public void onNothingSelected(AdapterView<?> p){}});
text("采集与上传分开:例如每分钟采集、每天集中上传。自定义 1—720 小时或 1—30 天。断网时本地暂存,恢复后自动补传;长周期期间家人无法看到实时移动。调整名单或频率前,先关闭共享。",14,shareControls);
historyConsent=new CheckBox(this);historyConsent.setText("另行同意保存我的历史轨迹到家庭网盘,长期保留至我手动删除;共享期间允许所选查看人读取其获授权期间的记录。");shareControls.addView(historyConsent);
historyStatus=text("未开启时不保存历史轨迹。关闭共享只清除当前位置,已保存历史可在下方删除。",14,shareControls);
button("查看我的历史轨迹",shareControls).setOnClickListener(v->history(""));
button("删除我的全部历史轨迹",shareControls).setOnClickListener(v->new AlertDialog.Builder(this).setTitle("删除自己的历史轨迹").setMessage("历史将立即隐藏,网盘文件随后删除;此操作不能撤销。若仍开启共享和历史保存,之后的新位置会继续记录。").setNegativeButton("取消",null).setPositiveButton("确认删除",(d,w)->deleteHistory()).show());
consent=new CheckBox(this);consent.setText("我已核对本人身份、有效期和所选查看人,同意按上述频率共享实时位置。关闭后停止采集并清除当前位置。");shareControls.addView(consent);
queueStatus=text("",15,shareControls);
button("立即同步待上传轨迹",shareControls).setOnClickListener(v->syncNow());
text("本机待同步上限:50,000 个点或 12 MiB 密文,先到为准。达到上限暂停新增历史,保留未上传记录。只有网盘完整回读校验通过才自动清理对应批次;手机数据库文件最多 32 MiB,空页循环复用。",13,shareControls);
button("放弃本机待同步记录",shareControls).setOnClickListener(v->new AlertDialog.Builder(this).setTitle("放弃尚未同步完的轨迹").setMessage("将停止本机共享并删除本机待同步副本,未上传内容无法恢复。已经被平台接收的记录不受此操作影响;如需彻底删除,请使用“删除我的全部历史轨迹”。").setNegativeButton("保留记录",null).setPositiveButton("确认放弃",(d,w)->discardLocal()).show());
button("删除我的全部历史轨迹",shareControls).setOnClickListener(v->new AlertDialog.Builder(this).setTitle("删除自己的历史轨迹").setMessage("将暂停共享、清空本机待同步轨迹并隐藏平台历史,网盘文件随后删除;此操作不能撤销。以后可重新开启共享和记录。").setNegativeButton("取消",null).setPositiveButton("确认删除",(d,w)->deleteHistory()).show());
consent=new CheckBox(this);consent.setText("我已核对本人身份、有效期和所选查看人,同意按上述周期采集和共享位置。启用历史保存后,断网会加密暂存并补传。关闭后停止新采集并清除当前位置,关闭前已采集轨迹仍会完成上传。");shareControls.addView(consent);
sharing=new Switch(this);sharing.setText("共享我的位置");sharing.setTextSize(20);sharing.setPadding(0,20,0,20);shareControls.addView(sharing);
sharing.setOnCheckedChangeListener((v,checked)->{if(rendering)return;if(checked)start();else{startService(new Intent(this,LocationService.class).setAction("STOP"));consent.setChecked(false);}render();});
permissionStatus=text("",14,shareControls);
@@ -80,23 +90,26 @@ public class LocationActivity extends Activity {
long expires=prefs.getLong("expires",0);
identity.setText(prefs.getString("memberName","尚未配对本人")+" · "+prefs.getString("home","请在我的位置设置中配对")+(expires>0?"\n配对有效至 "+java.text.DateFormat.getDateTimeInstance().format(new Date(expires)):""));
status.setText(settingsError.isEmpty()?"我的位置:"+prefs.getString("status","共享关闭,不采集定位"):settingsError);
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||!busy&&settingsReady));
pair.setEnabled(!active&&!busy);cadence.setEnabled(!active&&!busy);consent.setEnabled(!active&&!busy);historyConsent.setEnabled(!active&&!busy&&settingsReady);
sampleCadence.setEnabled(!active&&!busy);customAmount.setEnabled(!active&&!busy);customUnit.setEnabled(!active&&!busy);
for(List<CheckBox> 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;i<list.length();i++){if(names.length()>0)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)).apply();
prefs.edit().putString("receipt",response.getString("receipt")).putString("recipients",names.toString()).putInt("intervalSeconds",response.optInt("intervalSeconds",300)).putInt("sampleIntervalSeconds",response.optInt("sampleIntervalSeconds",60)).apply();
}
void pair(){
if(pairing||LocationService.busy||prefs.getBoolean("active",false))return;
if(outbox.total()>0){Toast.makeText(this,"还有本机待同步轨迹,请先完成同步,或明确放弃后再更换配对",1).show();return;}
String value=code.getText().toString().trim();if(!value.matches("[0-9]{8}")){Toast.makeText(this,"请输入八位手机配对码",1).show();return;}
pairing=true;render();
new Thread(()->{try{
JSONObject response=DisplayApi.call("/api/location/pair",null,new JSONObject().put("code",value).put("consentProtocol",3));remember(response);
prefs.edit().putString("memberName",response.getString("memberName")).putString("token",response.getString("token")).putString("home",response.getString("home")).putLong("expires",(long)(response.getDouble("expires")*1000)).putBoolean("active",false).putString("status","已配对;共享关闭,可查看获授权家人").apply();
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;generation++;loading=false;familyList.removeAllViews();map.setItems(new JSONArray());code.setText("");consent.setChecked(false);settingsReady=false;settings.setVisibility(View.GONE);voice.rebound();loadSettings();loadFamily();});
}catch(Exception e){runOnUiThread(()->{if(!isDestroyed())Toast.makeText(this,"配对未成功,请检查手机配对码或安装新版 App",1).show();});}finally{pairing=false;runOnUiThread(()->{if(!isDestroyed())render();});}},"location-pair").start();
}
@@ -106,9 +119,9 @@ public class LocationActivity extends Activity {
new Thread(()->{try{
JSONObject response=DisplayApi.call("/api/location/update",token,new JSONObject().put("action","list"));
runOnUiThread(()->{if(!visible||g!=generation)return;JSONArray list=response.optJSONArray("items");map.setItems(list);familyList.removeAllViews();viewStatus.setText(list==null||list.length()==0?"尚无家人授权给这台手机的位置。请对方在自己的位置设置里勾选你的手机,并开启共享。":"只显示仍在授权有效期内的最新位置。");
if(list!=null)for(int i=0;i<list.length();i++){JSONObject row=list.optJSONObject(i);if(row==null)continue;JSONObject pos=row.optJSONObject("position");String detail=pos==null?("stale".equals(row.optString("status"))?"更新中断,旧坐标已隐藏":"等待定位") : String.format(Locale.CHINA,"纬度 %.5f · 经度 %.5f\n精度约 %.0f 米 · %s",pos.optDouble("latitude"),pos.optDouble("longitude"),pos.optDouble("accuracy"),java.text.DateFormat.getTimeInstance().format(new Date((long)(pos.optDouble("at")*1000))));Button item=button(row.optString("name")+"\n"+detail,familyList);item.setAllCaps(false);item.setOnClickListener(v->{if(pos!=null)map.focus(pos);});button("查看 "+row.optString("name")+" 的已授权历史",familyList).setOnClickListener(v->history(row.optString("id")));}
if(list!=null)for(int i=0;i<list.length();i++){JSONObject row=list.optJSONObject(i);if(row==null)continue;JSONObject pos=row.optJSONObject("position");String detail=pos==null?("scheduled".equals(row.optString("status"))?"按设定周期上传中,当前没有实时坐标":("stale".equals(row.optString("status"))?"更新中断,旧坐标已隐藏":"等待定位")) : String.format(Locale.CHINA,"纬度 %.5f · 经度 %.5f\n精度约 %.0f 米 · %s",pos.optDouble("latitude"),pos.optDouble("longitude"),pos.optDouble("accuracy"),java.text.DateFormat.getTimeInstance().format(new Date((long)(pos.optDouble("at")*1000))));Button item=button(row.optString("name")+"\n"+detail,familyList);item.setAllCaps(false);item.setOnClickListener(v->{if(pos!=null)map.focus(pos);});button("查看 "+row.optString("name")+" 的已授权历史",familyList).setOnClickListener(v->history(row.optString("id")));}
});
}catch(Exception e){runOnUiThread(()->{if(!visible||g!=generation)return;familyList.removeAllViews();map.setItems(new JSONArray());if(e instanceof DisplayApi.ApiError&&(((DisplayApi.ApiError)e).status==401||((DisplayApi.ApiError)e).status==403)){prefs.edit().remove("token").putBoolean("active",false).apply();startService(new Intent(this,LocationService.class).setAction("STOP"));voice.rebound();settings.setVisibility(View.VISIBLE);}viewStatus.setText(e instanceof DisplayApi.ApiError&&((DisplayApi.ApiError)e).status==401?"手机配对已过期或解除,请重新配对。":"位置未能刷新,已隐藏旧画面,请检查网络。");});}finally{runOnUiThread(()->{if(g==generation){loading=false;render();}});}},"family-positions").start();
}catch(Exception e){runOnUiThread(()->{if(!visible||g!=generation)return;familyList.removeAllViews();map.setItems(new JSONArray());if(e instanceof DisplayApi.ApiError&&(((DisplayApi.ApiError)e).status==401||((DisplayApi.ApiError)e).status==403)){boolean wasSharing=prefs.getBoolean("active",false);prefs.edit().putBoolean("active",false).apply();if(wasSharing||LocationService.busy)startService(new Intent(this,LocationService.class).setAction("STOP"));voice.rebound();settings.setVisibility(View.VISIBLE);}viewStatus.setText(e instanceof DisplayApi.ApiError&&((DisplayApi.ApiError)e).status==401?"手机配对已过期或解除,请重新配对。":"位置未能刷新,已隐藏旧画面,请检查网络。");});}finally{runOnUiThread(()->{if(g==generation){loading=false;render();}});}},"family-positions").start();
}
void loadSettings(){
String token=prefs.getString("token","");if(token.isEmpty()||pairing)return;int g=generation,request=++settingsRequest;settingsReady=false;settingsError="";render();
@@ -116,7 +129,7 @@ public class LocationActivity extends Activity {
JSONObject result=DisplayApi.call("/api/location/update",token,new JSONObject().put("action","settings"));
runOnUiThread(()->{if(!visible||g!=generation||request!=settingsRequest)return;settingsReceipt=result.optString("receipt");recipients.removeAllViews();choices.clear();
for(String type:new String[]{"viewers","phones","displays"}){String key=type.equals("viewers")?"viewerIds":type.equals("phones")?"phoneIds":"displayIds";text(type.equals("viewers")?"平台查看账号":type.equals("phones")?"已配对的家人手机":"公共显示终端",16,recipients);JSONArray options=result.optJSONArray(type),selected=result.optJSONArray(key);Set<String> ids=new HashSet<>();if(selected!=null)for(int i=0;i<selected.length();i++)ids.add(selected.optString(i));List<CheckBox> list=new ArrayList<>();choices.put(key,list);if(options!=null)for(int i=0;i<options.length();i++){JSONObject item=options.optJSONObject(i);CheckBox c=new CheckBox(this);c.setText(item.optString("name"));c.setTag(item.optString("id"));c.setChecked(ids.contains(item.optString("id")));recipients.addView(c);list.add(c);}if(list.isEmpty())text("暂无可选对象",14,recipients);}
int seconds=result.optInt("intervalSeconds",300);cadence.setSelection(seconds==10?0:seconds==60?1:2);historyAcknowledged=result.optBoolean("historyEnabled",false);historyConsent.setChecked(historyAcknowledged||result.optBoolean("historyDefault",false));JSONObject h=result.optJSONObject("history");if(h!=null)historyStatus.setText("待归档 "+h.optInt("pending")+" 个定位点 · 已归档 "+h.optInt("archived")+" 段 · 待删除 "+h.optInt("deleting")+" 段\n"+h.optString("error")+"\n长期保留,由本人手动删除。修改设置前先关闭共享。");settingsReady=true;render();});
int seconds=result.optInt("intervalSeconds",300);setUploadPeriod(seconds);int sample=result.optInt("sampleIntervalSeconds",60);sampleCadence.setSelection(sample==10?0:sample==300?2:1);historyAcknowledged=result.optBoolean("historyEnabled",false);historyConsent.setChecked(historyAcknowledged||result.optBoolean("historyDefault",false));JSONObject h=result.optJSONObject("history");if(h!=null)historyStatus.setText("待归档 "+h.optInt("pending")+" 个定位点 · 已归档 "+h.optInt("archived")+" 段 · 待删除 "+h.optInt("deleting")+" 段\n"+h.optString("error")+"\n长期保留,由本人手动删除。修改设置前先关闭共享。");settingsReady=true;render();});
}catch(Exception e){runOnUiThread(()->{if(visible&&g==generation&&request==settingsRequest){settingsReady=false;settingsError="无法读取我的位置设置,请检查网络或配对有效期,重新打开设置重试。";render();}});}},"location-settings").start();
}
void start(){
@@ -125,12 +138,17 @@ public class LocationActivity extends Activity {
if(historyConsent.isChecked()&&!historyAcknowledged){new AlertDialog.Builder(this).setTitle("同意长期保存我的轨迹").setMessage("定位点将加密上传家庭百度网盘,按天、周、月、年或全部历史查看,长期保留直到你手动删除。共享时所选查看人能读取其获授权期间的历史。关闭实时共享不会删除历史。是否同意?").setNegativeButton("暂不启用",null).setPositiveButton("本人同意并开启",(d,w)->{historyAcknowledged=true;start();}).show();return;}
if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED&&checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},45);return;}
if(!LocationService.locationEnabled((android.location.LocationManager)getSystemService(LOCATION_SERVICE))){Toast.makeText(this,"请先打开手机系统定位开关",1).show();return;}
final JSONObject body=new JSONObject();try{int total=0;for(Map.Entry<String,List<CheckBox>> e:choices.entrySet()){JSONArray ids=new JSONArray();for(CheckBox c:e.getValue())if(c.isChecked()){ids.put((String)c.getTag());total++;}body.put(e.getKey(),ids);}if(total==0){Toast.makeText(this,"请选择至少一位查看人;只看家人无需开启此开关",1).show();return;}body.put("action","configure").put("consent",true).put("receipt",settingsReceipt).put("intervalSeconds",new int[]{10,60,300}[cadence.getSelectedItemPosition()]).put("historyEnabled",historyConsent.isChecked()).put("historyConsent",historyConsent.isChecked());}catch(Exception e){return;}
final JSONObject body=new JSONObject();try{int total=0;for(Map.Entry<String,List<CheckBox>> e:choices.entrySet()){JSONArray ids=new JSONArray();for(CheckBox c:e.getValue())if(c.isChecked()){ids.put((String)c.getTag());total++;}body.put(e.getKey(),ids);}if(total==0){Toast.makeText(this,"请选择至少一位查看人;只看家人无需开启此开关",1).show();return;}int upload=uploadPeriod();if(upload>=3600&&!historyConsent.isChecked()){Toast.makeText(this,"按小时或天集中上传需要本人启用历史保存,才能保留期间的轨迹",1).show();return;}body.put("action","configure").put("consent",true).put("receipt",settingsReceipt).put("intervalSeconds",upload).put("sampleIntervalSeconds",new int[]{10,60,300}[sampleCadence.getSelectedItemPosition()]).put("historyEnabled",historyConsent.isChecked()).put("historyConsent",historyConsent.isChecked());}catch(Exception e){Toast.makeText(this,"请填写 1—720 小时或 1—30 天的整数周期",1).show();return;}
final 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 uploadPeriod(){int index=cadence.getSelectedItemPosition();return uploadIntervals[index]>0?uploadIntervals[index]:LocationCadence.custom(Integer.parseInt(customAmount.getText().toString().trim()),customUnit.getSelectedItemPosition()==1);}
void setUploadPeriod(int seconds){for(int i=0;i<uploadIntervals.length-1;i++)if(uploadIntervals[i]==seconds){cadence.setSelection(i);return;}cadence.setSelection(uploadIntervals.length-1);boolean days=seconds%86400==0;customUnit.setSelection(days?1:0);customAmount.setText(Integer.toString(seconds/(days?86400:3600)));}
void refreshQueueStats(){try{queueOwner=LocationQueue.digest(prefs.getString("token",""));long[] values=outbox.stats(queueOwner);prefs.edit().putLong("pendingPoints",values[0]).putLong("pendingBytes",values[1]).putLong("uploadedPoints",values[2]).putLong("freedBytes",values[3]).apply();}catch(Exception e){prefs.edit().putString("syncStatus","本机轨迹暂不能读取,数据没有删除").apply();}}
void syncNow(){if(prefs.getString("token","").isEmpty())return;try{startForegroundService(new Intent(this,LocationService.class).setAction("SYNC"));Toast.makeText(this,"已开始同步;只有网盘完整校验后才清理本机记录",0).show();}catch(Exception e){Toast.makeText(this,"请保持页面打开再试一次",1).show();}}
void discardLocal(){prefs.edit().putLong("queueEpoch",System.currentTimeMillis()).commit();stopService(new Intent(this,LocationService.class));outbox.discard(queueOwner);prefs.edit().putBoolean("active",false).putBoolean("cacheFull",false).putString("syncStatus","已按本人要求放弃本机待同步副本").apply();refreshQueueStats();startService(new Intent(this,LocationService.class).setAction("STOP"));render();}
void history(String member){
new AlertDialog.Builder(this).setTitle("查看历史时段").setItems(new String[]{"每天","每周","每月","每年","一生 · 全部已存记录"},(dialog,choice)->{
String period=new String[]{"day","week","month","year","life"}[choice];Calendar c=Calendar.getInstance();
@@ -156,7 +174,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;new Thread(()->{try{DisplayApi.call("/api/location/update",prefs.getString("token",""),new JSONObject().put("action","history-delete").put("confirm",true));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();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 "定位权限:未允许。查看家人不需要开启自己的定位。";
@@ -176,7 +194,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;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.getLong("pendingPoints",0)>0)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(map!=null)map.close();if(voice!=null)voice.close();ui.removeCallbacksAndMessages(null);super.onDestroy();}
}
@@ -2,7 +2,11 @@ package cn.ucvl.zhaodisplay;
/** Shared scheduling rule, independent of Android for deterministic testing. */
final class LocationCadence {
static int seconds(int value){return value==10||value==60||value==300?value:300;}
static final int MAX_SECONDS=30*86400;
static boolean valid(int value){return value==10||value==60||value==300||value>=3600&&value<=MAX_SECONDS&&value%3600==0;}
static int seconds(int value){return valid(value)?value:300;}
static int sample(int value){return value==10||value==60||value==300?value:60;}
static int custom(int value,boolean days){long seconds=value*(days?86400L:3600L);if(value<1||seconds>MAX_SECONDS)throw new IllegalArgumentException("周期需在 1 小时至 30 天内");return (int)seconds;}
static boolean due(long now,long lastAttempt,int interval,boolean firstFix){
return lastAttempt==0||now-lastAttempt>=1000L*(firstFix?10:seconds(interval));
}
@@ -0,0 +1,95 @@
package cn.ucvl.zhaodisplay;
import android.content.*;
import android.database.Cursor;
import android.database.sqlite.*;
import android.security.keystore.*;
import org.json.*;
import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.*;
/** Private, encrypted outbox. Only a matching cloud-verification receipt releases rows. */
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);}
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)");
}
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){throw new IllegalStateException("Unsupported location outbox migration");}
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{
byte[] bytes=MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));StringBuilder result=new StringBuilder();for(byte b:bytes)result.append(String.format(Locale.US,"%02x",b&255));return result.toString();
}
private SecretKey key()throws Exception{
synchronized(LocationQueue.class){KeyStore store=KeyStore.getInstance("AndroidKeyStore");store.load(null);if(!store.containsAlias(KEY)){
KeyGenerator generator=KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,"AndroidKeyStore");
generator.init(new KeyGenParameterSpec.Builder(KEY,KeyProperties.PURPOSE_ENCRYPT|KeyProperties.PURPOSE_DECRYPT).setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).setKeySize(256).build());generator.generateKey();
}return (SecretKey)store.getKey(KEY,null);}
}
private byte[] encrypt(String value,String aad)throws Exception{
Cipher cipher=Cipher.getInstance("AES/GCM/NoPadding");cipher.init(Cipher.ENCRYPT_MODE,key());cipher.updateAAD(aad.getBytes(StandardCharsets.UTF_8));byte[] encrypted=cipher.doFinal(value.getBytes(StandardCharsets.UTF_8)),iv=cipher.getIV();byte[] out=new byte[iv.length+encrypted.length];System.arraycopy(iv,0,out,0,iv.length);System.arraycopy(encrypted,0,out,iv.length,encrypted.length);return out;
}
private String decrypt(byte[] value,String aad)throws Exception{
Cipher cipher=Cipher.getInstance("AES/GCM/NoPadding");cipher.init(Cipher.DECRYPT_MODE,key(),new GCMParameterSpec(128,Arrays.copyOfRange(value,0,12)));cipher.updateAAD(aad.getBytes(StandardCharsets.UTF_8));return new String(cipher.doFinal(value,12,value.length-12),StandardCharsets.UTF_8);
}
synchronized boolean append(String owner,String session,JSONObject position)throws Exception{
SQLiteDatabase db=getWritableDatabase();String id=id();byte[] encrypted=encrypt(new JSONObject().put("id",id).put("position",position).toString(),owner+id);
db.beginTransaction();try{
try(Cursor cursor=db.rawQuery("SELECT count(*),coalesce(sum(length(payload)),0) FROM points",null)){cursor.moveToFirst();if(cursor.getLong(0)>=MAX_POINTS||cursor.getLong(1)+encrypted.length>MAX_BYTES)return false;}
ContentValues row=new ContentValues();row.put("id",id);row.put("owner",owner);row.put("session",session);row.put("at",(long)(position.getDouble("at")*1000));row.put("payload",encrypted);db.insertOrThrow("points",null,row);db.setTransactionSuccessful();return true;
}catch(SQLiteFullException full){return false;}finally{db.endTransaction();}
}
static final class Batch {
final String id,payload,digest;final int count;
Batch(String id,String payload,String digest,int count){this.id=id;this.payload=payload;this.digest=digest;this.count=count;}
JSONObject request()throws Exception{return new JSONObject().put("action","history-batch").put("batchId",id).put("sha256",digest).put("payload",payload);}
}
synchronized Batch next(String owner,long cutoff,long now)throws Exception{
SQLiteDatabase db=getWritableDatabase();db.beginTransaction();try{
try(Cursor c=db.rawQuery("SELECT id,payload,digest,count FROM batches WHERE owner=? AND next_try<=? ORDER BY next_try,id LIMIT 1",new String[]{owner,Long.toString(now)})){
if(c.moveToFirst())return new Batch(c.getString(0),decrypt(c.getBlob(1),owner+c.getString(0)),c.getString(2),c.getInt(3));
}
if(cutoff<=0)return null;
try(Cursor c=db.rawQuery("SELECT count(*) FROM batches WHERE owner=?",new String[]{owner})){c.moveToFirst();if(c.getInt(0)>=MAX_INFLIGHT)return null;}
String session=null;
try(Cursor c=db.rawQuery("SELECT session FROM points WHERE owner=? AND batch IS NULL AND at<=? ORDER BY at,id LIMIT 1",new String[]{owner,Long.toString(cutoff)})){if(c.moveToFirst())session=c.getString(0);}
if(session==null)return null;
JSONArray points=new JSONArray();List<String> ids=new ArrayList<>();
try(Cursor c=db.rawQuery("SELECT id,payload FROM points WHERE owner=? AND session=? AND batch IS NULL AND at<=? ORDER BY at,id LIMIT "+BATCH_POINTS,new String[]{owner,session,Long.toString(cutoff)})){
while(c.moveToNext()){ids.add(c.getString(0));points.put(new JSONObject(decrypt(c.getBlob(1),owner+c.getString(0))));}
}
String id=id(),payload=new JSONObject().put("version",1).put("collectionId",session).put("points",points).toString(),sha=digest(payload);
ContentValues row=new ContentValues();row.put("id",id);row.put("owner",owner);row.put("session",session);row.put("payload",encrypt(payload,owner+id));row.put("digest",sha);row.put("count",points.length());row.put("next_try",0);db.insertOrThrow("batches",null,row);
for(String point:ids)db.execSQL("UPDATE points SET batch=? WHERE id=? AND owner=?",new Object[]{id,point,owner});
db.setTransactionSuccessful();return new Batch(id,payload,sha,points.length());
}finally{db.endTransaction();}
}
synchronized boolean acknowledge(String owner,Batch batch,JSONObject receipt)throws Exception{
if(!batch.id.equals(receipt.optString("batchId"))||!batch.digest.equals(receipt.optString("sha256"))||batch.count!=receipt.optInt("count",-1))throw new SecurityException("上传回执不匹配,本地记录已保留");
String state=receipt.optString("state");if(!"accepted".equals(state)&&!"verified".equals(state))throw new SecurityException("未收到完整校验回执,本地记录已保留");
SQLiteDatabase db=getWritableDatabase();db.beginTransaction();try{
if("accepted".equals(state)){db.execSQL("UPDATE batches SET next_try=? WHERE id=? AND owner=?",new Object[]{System.currentTimeMillis()+30000,batch.id,owner});db.setTransactionSuccessful();return false;}
long count,bytes;try(Cursor c=db.rawQuery("SELECT count(*),coalesce(sum(length(payload)),0) FROM points WHERE owner=? AND batch=?",new String[]{owner,batch.id})){c.moveToFirst();count=c.getLong(0);bytes=c.getLong(1);}
if(count!=batch.count)throw new SecurityException("本地批次条数不匹配,未清理");
db.delete("points","owner=? AND batch=?",new String[]{owner,batch.id});db.delete("batches","owner=? AND id=?",new String[]{owner,batch.id});
db.execSQL("INSERT OR IGNORE INTO totals VALUES (?,0,0)",new Object[]{owner});db.execSQL("UPDATE totals SET uploaded=uploaded+?,freed=freed+? WHERE owner=?",new Object[]{count,bytes,owner});db.setTransactionSuccessful();return true;
}finally{db.endTransaction();}
}
synchronized long[] stats(String owner){
SQLiteDatabase db=getReadableDatabase();long[] values=new long[4];
try(Cursor c=db.rawQuery("SELECT count(*),coalesce(sum(length(payload)),0) FROM points WHERE owner=?",new String[]{owner})){c.moveToFirst();values[0]=c.getLong(0);values[1]=c.getLong(1);}
try(Cursor c=db.rawQuery("SELECT uploaded,freed FROM totals WHERE owner=?",new String[]{owner})){if(c.moveToFirst()){values[2]=c.getLong(0);values[3]=c.getLong(1);}}
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();}}
}
@@ -4,97 +4,140 @@ import android.app.*;
import android.content.*;
import android.os.*;
import android.location.*;
import android.net.*;
import android.content.pm.PackageManager;
import android.Manifest;
import org.json.JSONObject;
import java.util.concurrent.*;
/** Visible, bounded sharing session. No boot receiver starts location collection. */
/** Visible sharing plus an encrypted outbox. No boot receiver starts GPS collection. */
public class LocationService extends Service implements LocationListener {
static volatile boolean busy=false;
String sessionToken="";
volatile boolean destroyed=false;
ScheduledExecutorService worker;LocationManager manager;android.content.SharedPreferences prefs;
volatile Location latest;volatile boolean active=false,stopping=false,starting=false;
long lastAttempt=0;boolean sentFix=false;int intervalSeconds=300;String lastSignal="";
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="";
final Handler ui=new Handler();
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 onCreate(){
super.onCreate();prefs=getSharedPreferences("location",0);manager=(LocationManager)getSystemService(LOCATION_SERVICE);
sessionToken=prefs.getString("token","");
NotificationManager nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nm.createNotificationChannel(new NotificationChannel("location","本人位置共享",NotificationManager.IMPORTANCE_LOW));
worker=Executors.newSingleThreadScheduledExecutor();
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;}
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();
try{connectivity.registerDefaultNetworkCallback(networkCallback);}catch(Exception ignored){}
}
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 notice=new Notification.Builder(this,"location").setContentTitle("赵府 · 位置共享").setContentText(text).setSmallIcon(android.R.drawable.ic_menu_mylocation).setContentIntent(open).setOngoing(true).addAction(new Notification.Action.Builder(null,"停止共享",stop).build()).build();
if(android.os.Build.VERSION.SDK_INT>=29)startForeground(45,notice,stopping?0:android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION);else startForeground(45,notice);
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());
}
public int onStartCommand(Intent intent,int flags,int id){
if(intent!=null&&"STOP".equals(intent.getAction())){stopSharing();return START_NOT_STICKY;}
if(intent==null){stopSelf();return START_NOT_STICKY;}
if(intent==null||sessionToken.isEmpty()){stopSelf();return START_NOT_STICKY;}
if(!ticking){ticking=true;worker.scheduleWithFixedDelay(this::tick,1,10,TimeUnit.SECONDS);}
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(active||stopping||starting)return START_NOT_STICKY;
starting=true;busy=true;
final String receipt=prefs.getString("receipt","");
notification("正在确认本人的共享授权");
starting=true;busy=true;notification("正在确认本人的共享授权");
worker.execute(()->{try{
JSONObject r=DisplayApi.call("/api/location/update",sessionToken,new JSONObject().put("action","start").put("consent",true).put("receipt",receipt));
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;
intervalSeconds=LocationCadence.seconds(r.optInt("intervalSeconds",300));
active=true;prefs.edit().putBoolean("active",true).putLong("expires",(long)(r.getDouble("expires")*1000)).putString("status","共享中,等待定位").apply();
ui.post(()->{if(!stopping){listen();notification("共享给 "+prefs.getString("recipients","")+" · 可随时停止");}});
worker.scheduleWithFixedDelay(this::upload,1,10,TimeUnit.SECONDS);
}catch(Exception e){if(!destroyed){prefs.edit().putBoolean("active",false).putString("status","未开启:请检查网络、配对有效期").apply();stopSelf();}}});
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();
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();}}});
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,intervalSeconds*1000L,0,this);}
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 upload(){
if(!active||stopping)return;
if(System.currentTimeMillis()>prefs.getLong("expires",0)){ui.post(this::stopSharing);return;}
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(){
if(destroyed||starting)return;
try{
String signal=checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED||checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)==PackageManager.PERMISSION_GRANTED?locationEnabled(manager)?"waiting":"location_disabled":"permission_denied";
// Permission/setting loss must clear the server fix without waiting five minutes.
boolean safetyChange=(!"waiting".equals(signal)&&!signal.equals(lastSignal));
if(!LocationCadence.due(SystemClock.elapsedRealtime(),lastAttempt,intervalSeconds,safetyChange||latest!=null&&!sentFix))return;
lastAttempt=SystemClock.elapsedRealtime();
JSONObject body=new JSONObject().put("action","update");Location fix=latest;
if(fix!=null&&"waiting".equals(signal)&&SystemClock.elapsedRealtimeNanos()-fix.getElapsedRealtimeNanos()<900000000000L){
body.put("position",new JSONObject().put("latitude",fix.getLatitude()).put("longitude",fix.getLongitude()).put("accuracy",fix.getAccuracy()).put("at",fix.getTime()/1000d));signal="available";
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()<nextAttempt)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;
}
body.put("signal",signal);DisplayApi.call("/api/location/update",sessionToken,body);
lastSignal=signal;
if("available".equals(signal))sentFix=true;
if(stopping||destroyed)return;
String message="available".equals(signal)?"共享中 · 最近更新 "+java.text.DateFormat.getTimeInstance().format(new java.util.Date()):"共享中 · 等待定位,请检查手机定位和权限";
prefs.edit().putString("status",message).apply();
}catch(DisplayApi.ApiError e){if(e.status==401||e.status==403)ui.post(this::stopSharing);else prefs.edit().putString("status","网络未同步,稍后自动重试").apply();}
catch(Exception e){prefs.edit().putString("status","网络未同步,稍后自动重试").apply();}
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;
}
for(int i=0;i<LocationQueue.MAX_INFLIGHT;i++){
LocationQueue.Batch batch=queue.next(owner,flushCutoff,now);if(batch==null)break;
JSONObject reply=DisplayApi.call("/api/location/update",sessionToken,batch.request());
if(destroyed)return;
boolean removed=queue.acknowledge(owner,batch,reply);
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("网络或同步暂未完成,手机轨迹已保留,恢复后自动补传");}
}
static boolean locationEnabled(LocationManager manager){
if(Build.VERSION.SDK_INT>=28)return manager.isLocationEnabled();
return manager.isProviderEnabled(LocationManager.GPS_PROVIDER)||manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
void retry(String message){failedNetwork=true;failures=Math.min(failures+1,5);nextAttempt=SystemClock.elapsedRealtime()+Math.min(300000,10000L*(1L<<failures));prefs.edit().putString("syncStatus",message).apply();}
void uploadLive()throws Exception{
String signal=checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED||checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)==PackageManager.PERMISSION_GRANTED?locationEnabled(manager)?"waiting":"location_disabled":"permission_denied";
boolean safetyChange=!"waiting".equals(signal)&&!signal.equals(lastSignal);
if(!LocationCadence.due(SystemClock.elapsedRealtime(),lastUpload,intervalSeconds,safetyChange||latest!=null&&!sentFix))return;
JSONObject body=new JSONObject().put("action","update").put("bufferedHistory",true);Location fix=latest;
if(fix!=null&&"waiting".equals(signal)&&SystemClock.elapsedRealtimeNanos()-fix.getElapsedRealtimeNanos()<900000000000L){body.put("position",position(fix));signal="available";}
body.put("signal",signal);DisplayApi.call("/api/location/update",sessionToken,body);lastUpload=SystemClock.elapsedRealtime();lastSignal=signal;if("available".equals(signal))sentFix=true;
if(!stopping&&!destroyed)prefs.edit().putString("status","available".equals(signal)?"共享中 · 最近上传 "+java.text.DateFormat.getTimeInstance().format(new java.util.Date()):"共享中 · 等待定位,请检查手机定位和权限").apply();
}
static JSONObject position(Location fix)throws Exception{return new JSONObject().put("latitude",fix.getLatitude()).put("longitude",fix.getLongitude()).put("accuracy",fix.getAccuracy()).put("at",fix.getTime()/1000d);}
void updateQueueStatus(){long[] stats=queue.stats(owner);prefs.edit().putLong("pendingPoints",stats[0]).putLong("pendingBytes",stats[1]).putLong("uploadedPoints",stats[2]).putLong("freedBytes",stats[3]).putBoolean("cacheFull",cacheFull).apply();}
static boolean locationEnabled(LocationManager manager){return Build.VERSION.SDK_INT>=28?manager.isLocationEnabled():manager.isProviderEnabled(LocationManager.GPS_PROVIDER)||manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}
void stopSharing(){
if(stopping)return;stopping=true;busy=true;active=false;latest=null;
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("本机已停止定位 · 正在通知平台清除");
worker.scheduleWithFixedDelay(()->{try{
String token=sessionToken;
if(!token.isEmpty())try{DisplayApi.call("/api/location/update",token,new JSONObject().put("action","stop"));}catch(DisplayApi.ApiError e){if(e.status!=401&&e.status!=403)throw e;}
if(destroyed)return;
prefs.edit().putBoolean("active",false).putString("status","共享关闭,平台已清除当前位置").apply();stopSelf();
}catch(Exception e){prefs.edit().putString("status","本机已停止,联网后清除平台位置,旧坐标最长 15 分钟后隐藏,也可在平台解除授权").apply();}},0,30,TimeUnit.SECONDS);
prefs.edit().putBoolean("active",false).putString("status","本机已停止采集,联网后通知平台清除当前位置;关闭前轨迹仍会补传").apply();notification("已停止定位 · 联网后完成同步");nextAttempt=0;
}
public void onLocationChanged(Location value){
if(!active||stopping)return;latest=new Location(value);if(!historyEnabled)return;
Location fix=new Location(value);String session=collection;long epoch=prefs.getLong("queueEpoch",0),started=collectionStarted;
recorder.execute(()->{try{
if(epoch!=prefs.getLong("queueEpoch",0))return;
long elapsed=fix.getElapsedRealtimeNanos()/1000000;
if(lastSample!=0&&elapsed-lastSample<sampleSeconds*1000L||fix.getTime()<started-5000||fix.getTime()>System.currentTimeMillis()+60000||System.currentTimeMillis()-fix.getTime()>900000)return;
if(queue.append(owner,session,position(fix))){lastSample=elapsed;cacheFull=false;}
else{cacheFull=true;prefs.edit().putString("syncStatus","本地缓存已达上限,暂停新增历史;未上传记录没有覆盖,请联网补传").apply();notification("轨迹缓存已满 · 请联网补传");}
updateQueueStatus();
}catch(Exception error){cacheFull=true;prefs.edit().putString("syncStatus","本地轨迹未能写入,请检查手机存储空间;已有记录保留").apply();}});
}
public void onLocationChanged(Location value){if(active&&!stopping)latest=new Location(value);}
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;}
public void onDestroy(){destroyed=true;active=false;latest=null;try{manager.removeUpdates(this);}catch(Exception ignored){}if(worker!=null)worker.shutdownNow();prefs.edit().putBoolean("active",false).apply();busy=false;super.onDestroy();}
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();
}
}
@@ -5,7 +5,7 @@ public class LocationCadenceTest {
static void require(boolean value){if(!value)throw new AssertionError();}
public static void main(String[] args){
int assertions=0;
for(int seconds:new int[]{10,60,300}){
for(int seconds:new int[]{10,60,300,3600,7200,10800,14400,18000,23*3600,86400,172800,259200,30*86400}){
require(LocationCadence.seconds(seconds)==seconds);assertions++;
require(LocationCadence.due(100000,0,seconds,false));assertions++;
require(!LocationCadence.due(1000+seconds*1000L-1,1000,seconds,false));assertions++;
@@ -13,7 +13,10 @@ public class LocationCadenceTest {
require(!LocationCadence.due(10999,1000,seconds,true));assertions++;
require(LocationCadence.due(11000,1000,seconds,true));assertions++;
}
for(int invalid:new int[]{-1,0,9,59,301}){require(LocationCadence.seconds(invalid)==300);assertions++;}
for(int invalid:new int[]{-1,0,9,59,301,3601,31*86400,Integer.MAX_VALUE}){require(LocationCadence.seconds(invalid)==300);assertions++;}
require(LocationCadence.custom(3,true)==259200);assertions++;
require(LocationCadence.custom(5,false)==18000);assertions++;
for(int invalid:new int[]{-1,0,721,Integer.MAX_VALUE}){try{LocationCadence.custom(invalid,false);throw new AssertionError();}catch(IllegalArgumentException expected){assertions++;}}
System.out.println("Location cadence: "+assertions+" assertions passed");
}
}
@@ -0,0 +1,43 @@
package cn.ucvl.zhaodisplay;
import android.app.*;
import android.os.Bundle;
import android.database.Cursor;
import org.json.*;
import java.nio.charset.StandardCharsets;
/** Isolated test package only. No GPS permission, family token or production data. */
public final class QueueInstrumentation extends Instrumentation {
int assertions=0;
void check(boolean condition){assertions++;if(!condition)throw new AssertionError("Assertion "+assertions);}
JSONObject position(double at)throws Exception{return new JSONObject().put("latitude",12.345678).put("longitude",45.678901).put("accuracy",7).put("at",at);}
JSONObject receipt(LocationQueue.Batch b,String state)throws Exception{return new JSONObject().put("batchId",b.id).put("sha256",b.digest).put("count",b.count).put("state",state);}
public void onCreate(Bundle args){super.onCreate(args);start();}
public void onStart(){Bundle result=new Bundle();LocationQueue queue=null;try{
getTargetContext().deleteDatabase("location-outbox.db");queue=new LocationQueue(getTargetContext());String owner=LocationQueue.digest("synthetic-owner"),other=LocationQueue.digest("synthetic-other"),session="a1111111111111111111111111111111";
for(int i=0;i<130;i++)check(queue.append(owner,session,position(1700000000+i)));
check(queue.append(other,session,position(1700000000)));
check(queue.stats(owner)[0]==130);check(queue.stats(other)[0]==1);
try(Cursor c=queue.getReadableDatabase().rawQuery("SELECT payload FROM points LIMIT 1",null)){c.moveToFirst();check(!new String(c.getBlob(0),StandardCharsets.UTF_8).contains("latitude"));}
LocationQueue.Batch batch=queue.next(owner,Long.MAX_VALUE,System.currentTimeMillis());check(batch.count==128);check(new JSONObject(batch.payload).getJSONArray("points").length()==128);
String digest=batch.digest,id=batch.id;queue.close();queue=new LocationQueue(getTargetContext());
batch=queue.next(owner,Long.MAX_VALUE,System.currentTimeMillis());check(batch.id.equals(id));check(batch.digest.equals(digest));check(queue.stats(owner)[0]==130);
try{queue.acknowledge(owner,batch,receipt(batch,"verified").put("sha256","f"));throw new AssertionError("Accepted corrupt receipt");}catch(SecurityException expected){assertions++;}
try{queue.acknowledge(owner,batch,receipt(batch,"verified").put("count",127));throw new AssertionError("Accepted partial receipt");}catch(SecurityException expected){assertions++;}
check(queue.stats(owner)[0]==130);check(!queue.acknowledge(owner,batch,receipt(batch,"accepted")));check(queue.stats(owner)[0]==130);
check(queue.append(owner,session,position(1700000500)));check(queue.acknowledge(owner,batch,receipt(batch,"verified")));check(queue.stats(owner)[0]==3);check(queue.stats(owner)[2]==128);check(queue.stats(other)[0]==1);
check(queue.next(owner,0,System.currentTimeMillis())==null);
batch=queue.next(owner,Long.MAX_VALUE,System.currentTimeMillis());check(batch.count==3);check(queue.acknowledge(owner,batch,receipt(batch,"verified")));check(queue.stats(owner)[0]==0);check(queue.stats(owner)[2]==131);check(queue.stats(owner)[3]>0);
queue.getWritableDatabase().beginTransaction();try{
for(int i=0;i<LocationQueue.MAX_POINTS-1;i++)queue.getWritableDatabase().execSQL("INSERT INTO points VALUES (?,?,?,0,?,NULL)",new Object[]{"cap-"+i,owner,session,new byte[16]});
queue.getWritableDatabase().setTransactionSuccessful();
}finally{queue.getWritableDatabase().endTransaction();}
check(queue.total()==LocationQueue.MAX_POINTS);check(!queue.append(owner,session,position(1700000600)));check(queue.total()==LocationQueue.MAX_POINTS);
queue.discard(owner);check(queue.stats(other)[0]==1);check(queue.stats(owner)[0]==0);
check(queue.append(owner,session,position(1700000700)));
queue.getWritableDatabase().execSQL("UPDATE points SET payload=zeroblob(40) WHERE owner=?",new Object[]{owner});
try{queue.next(owner,Long.MAX_VALUE,System.currentTimeMillis());throw new AssertionError("Decrypted corrupt payload");}catch(javax.crypto.AEADBadTagException expected){assertions++;}
check(queue.stats(owner)[0]==1);
result.putString("stream","PASS: "+assertions+" assertions; encrypted queue, restart, retry, receipts, owner isolation, capacity and tamper checks\n");finish(Activity.RESULT_OK,result);
}catch(Throwable error){result.putString("stream","FAIL: "+error.getClass().getSimpleName()+": "+error.getMessage()+"\n");finish(Activity.RESULT_CANCELED,result);}finally{if(queue!=null)queue.close();}}
}
@@ -0,0 +1,36 @@
param([string]$ToolRoot='C:\Users\Administrator\Documents\ChatGPT\优创未来\services\toplc-vpn-android\.tools')
$ErrorActionPreference='Stop'
$tests=Split-Path -Parent $MyInvocation.MyCommand.Path
$source=Split-Path -Parent $tests
$stage=Join-Path 'C:\CodexBuild' ('ZhaoQueueCheck-'+[guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $stage,"$stage\classes","$stage\dex" | Out-Null
$jdk=Join-Path $ToolRoot 'jdk-staging\jdk-21.0.12.1+1'
$sdk=Join-Path $ToolRoot 'android-sdk'
$bt=Join-Path $sdk 'build-tools\36.0.0'
$android=Join-Path $sdk 'platforms\android-37.0\android.jar'
$env:JAVA_HOME=$jdk
$env:Path="$jdk\bin;$env:Path"
@'
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay.queuecheck" android:versionCode="1" android:versionName="1">
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30"/>
<application android:label="轨迹队列隔离测试" android:allowBackup="false"/>
<instrumentation android:name="cn.ucvl.zhaodisplay.QueueInstrumentation" android:targetPackage="cn.ucvl.zhaodisplay.queuecheck"/>
</manifest>
'@ | Set-Content -LiteralPath "$stage\AndroidManifest.xml" -Encoding utf8
& "$bt\aapt2.exe" link -o "$stage\unsigned.apk" -I $android --manifest "$stage\AndroidManifest.xml"
if($LASTEXITCODE){throw 'Test resource linking failed'}
& "$jdk\bin\javac.exe" -encoding UTF-8 -source 8 -target 8 -cp $android -d "$stage\classes" "$source\src\cn\ucvl\zhaodisplay\LocationQueue.java" "$tests\QueueInstrumentation.java"
if($LASTEXITCODE){throw 'Test Java compile failed'}
& "$jdk\bin\jar.exe" cf "$stage\classes.jar" -C "$stage\classes" .
& "$bt\d8.bat" --lib $android --min-api 26 --output "$stage\dex" "$stage\classes.jar"
if($LASTEXITCODE){throw 'Test Dex compile failed'}
Add-Type -AssemblyName System.IO.Compression.FileSystem
$zip=[IO.Compression.ZipFile]::Open("$stage\unsigned.apk",[IO.Compression.ZipArchiveMode]::Update)
try{[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,"$stage\dex\classes.dex",'classes.dex',[IO.Compression.CompressionLevel]::Optimal) | Out-Null}finally{$zip.Dispose()}
& "$bt\zipalign.exe" -f 4 "$stage\unsigned.apk" "$stage\aligned.apk"
$keystore=Join-Path $env:LOCALAPPDATA 'ZhaoDisplay\display-signing.jks'
& "$bt\apksigner.bat" sign --ks $keystore --ks-pass pass:android --key-pass pass:android --ks-key-alias zhaodisplay --out "$source\build\QueueCheck.apk" "$stage\aligned.apk"
if($LASTEXITCODE){throw 'Test APK signing failed'}
& "$bt\apksigner.bat" verify "$source\build\QueueCheck.apk"
if($LASTEXITCODE){throw 'Test APK verification failed'}
Write-Output "$source\build\QueueCheck.apk"
+1 -1
View File
@@ -704,7 +704,7 @@ class Handler(BaseHTTPRequestHandler):
return
if path == '/api/location/update':
authorization=self.headers.get('Authorization','')
self.answer(LOCATIONS.native(authorization[7:] if authorization.startswith('Bearer ') else '',self.body(16384)))
self.answer(LOCATIONS.native(authorization[7:] if authorization.startswith('Bearer ') else '',self.body(131072)))
return
if path in ('/api/display/heartbeat','/api/display/preview'):
authorization = self.headers.get('Authorization','')
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "zhao-steward-ui",
"private": true,
"version": "0.1.49",
"version": "0.1.50",
"type": "module",
"scripts": {
"build": "vite build",
+4 -4
View File
@@ -11,7 +11,7 @@ const home=computed(()=>snapshot.value.state.households?.find(x=>x.id===snapshot
let timer,epoch=0,requestId=0
const items=computed(()=>result.value?.items||[])
const time=n=>n?new Date(n*1000).toLocaleString('zh-CN'):'尚未收到'
const status=d=>d.status==='stale'?'位置更新中断':d.status==='live'?'位置已更新':'等待手机定位'
const status=d=>d.status==='scheduled'?'等待下次定时上传':d.status==='stale'?'位置更新中断':d.status==='live'?'位置已更新':'等待手机定位'
const location=d=>d.position?`${d.position.latitude.toFixed(4)}°, ${d.position.longitude.toFixed(4)}° · 精度约 ${Math.round(d.position.accuracy)} 米`:'尚无有效位置'
async function load(){const e=epoch,r=++requestId;if(!active.value)return
try{const value=await bridge().api('/api/locations');if(e===epoch&&r===requestId){result.value=value;error.value=''}}
@@ -28,9 +28,9 @@ onBeforeUnmount(()=>{epoch++;clearTimeout(timer)})
</script>
<template><section v-if="active" class="panel family-locations mb-4" aria-label="家庭位置共享">
<div class="d-flex flex-wrap justify-content-between gap-2"><div><h2>家人位置</h2><p class="text-secondary small">{{home?.name}} · {{items.length}} 位家人正在共享 · 只显示本人同意分享的最新位置</p></div><button class="btn btn-sm btn-outline-secondary align-self-start" @click="selected=''">查看全部位置</button></div>
<div v-if="items.some(d=>d.status==='stale')" class="alert alert-warning" role="status">{{items.filter(d=>d.status==='stale').map(d=>d.name).join('、')}}的位置超过 15 分钟未更新。请检查手机网络、定位权限或省电设置;这不代表人员失联。</div>
<div v-if="items.some(d=>d.status==='stale')" class="alert alert-warning" role="status">{{items.filter(d=>d.status==='stale').map(d=>d.name).join('、')}}的位置超过约定上传周期仍未更新。请检查手机网络、定位权限或省电设置;这不代表人员失联。</div>
<div class="row g-3"><div class="col-12 col-lg-8"><FamilyMap :items="items" :selected="selected" :height="420" @select="selected=$event"/><p class="small text-secondary mb-0">点击家人卡片定位,圆圈表示定位精度范围。底图由智家提供,位置仅对获授权的人显示。</p></div>
<div class="col-12 col-lg-4"><div v-if="!items.length" class="location-empty"><span>⌖</span><h3 class="fs-5">等待家人主动分享</h3><p>家人无需注册账号。手机配对、本人同意并开启共享后,获准的查看人才能看到位置。</p></div><button v-for="d in items" :key="d.id" class="location-person w-100 text-start" :class="{'location-selected':selected===d.id}" @click="selected=d.id"><strong>{{d.name}}</strong><span :class="d.status==='stale'?'text-warning-emphasis':'text-success'">{{status(d)}}</span><small>{{location(d)}}</small><small>定位时间:{{time(d.position?.at)}}</small><small v-if="d.signal==='permission_denied'||d.signal==='location_disabled'">手机定位或权限未开启</small></button></div></div>
<div class="col-12 col-lg-4"><div v-if="!items.length" class="location-empty"><span>⌖</span><h3 class="fs-5">等待家人主动分享</h3><p>家人无需注册账号。手机配对、本人同意并开启共享后,获准的查看人才能看到位置。</p></div><button v-for="d in items" :key="d.id" class="location-person w-100 text-start" :class="{'location-selected':selected===d.id}" @click="selected=d.id"><strong>{{d.name}}</strong><span :class="d.status==='stale'?'text-warning-emphasis':'text-success'">{{status(d)}}</span><small>{{location(d)}}</small><small>定位时间:{{time(d.position?.at)}}</small><small v-if="d.status==='scheduled'">下次预计上传:{{time(d.nextUploadAt)}} · 期间轨迹保留在手机</small><small v-if="d.signal==='permission_denied'||d.signal==='location_disabled'">手机定位或权限未开启</small></button></div></div>
<LocationHistory :members="[...items,...(result?.members||[]).filter(m=>!items.some(i=>i.id===m.id))]"/>
<details class="mt-3 border-top pt-3"><summary>为家庭成员配对手机</summary>
<p class="small text-secondary mt-2">老人和孩子无需登录。先选择真实成员及具体查看人,再将配对码输入本人的手机。本人核对授权内容、允许定位并打开共享后才上传;管理员生成配对码不能代替本人同意。家庭屏需单独勾选。</p>
@@ -41,7 +41,7 @@ onBeforeUnmount(()=>{epoch++;clearTimeout(timer)})
<p v-if="binding">{{binding.enabled?'手机已开启共享':'手机已绑定,共享关闭'}} · {{time(binding.expires)}} 到期</p>
<div class="d-flex flex-wrap gap-2 mt-3"><button class="btn btn-primary" :disabled="busy||!memberId||(!viewOnly&&!viewerIds.length&&!displayIds.length&&!phoneIds.length)">生成配对码</button><button v-if="binding||code" type="button" class="btn btn-outline-danger" :disabled="busy" @click="action('stop')">解除该手机授权</button><a class="btn btn-outline-secondary" href="/downloads" target="_blank" rel="noreferrer">下载配套 App</a></div>
<div v-if="code" class="alert alert-success mt-3" role="status">配对码 <strong class="font-monospace fs-3">{{code}}</strong> · 10 分钟内使用一次<br>请在成员本人的手机核对姓名与查看名单,手机授权有效至 {{time(expires)}}。重新配对会替换旧手机授权。</div>
</form><p class="small text-secondary mt-3">手机可在“我的位置设置”选择实时(约 10 秒)、1 分钟或 5 分钟上传,默认 5 分钟。实时位置仅在内存中保存,关闭共享后清除;本人可另行开启历史保存,长期归档到百度网盘并手动删除。定位或网络中断超过 15 分钟隐藏旧坐标,提示更新中断,不表示人员失联。</p></details>
</form><p class="small text-secondary mt-3">手机可分别设置采集频率与上传周期:实时、1/5 分钟、1—5 小时、1—3 天,或自定义至 30 天。启用历史保存后,断网轨迹加密暂存在手机,联网后补传;百度网盘完整校验后清理对应本机记录。超过 15 分钟的旧坐标隐藏;长周期未到期显示等待上传,超过约定周期才提示更新中断,不表示人员失联。</p></details>
<p v-if="error" class="text-danger mt-2" role="alert">{{error}}</p>
</section></template>
<style scoped>.family-locations h2{font-size:1.3rem}.location-empty{display:grid;align-content:center;min-height:270px;text-align:center;color:var(--ui-muted,#64776f);padding:1rem}.location-empty>span{font-size:3rem;color:#6c9685}.location-person{display:flex;flex-direction:column;gap:.35rem;background:var(--panel,#fff);border:1px solid var(--ui-line,#d9e3dd);border-radius:12px;padding:14px;margin-bottom:10px;color:var(--ink,#243c32)}.location-person>span,.location-person small{font-size:.85rem}.location-selected{border-color:#257a68;box-shadow:inset 3px 0 #257a68}.family-locations summary{cursor:pointer}.family-locations input[type=checkbox]{min-width:18px;width:18px;min-height:18px}</style>
+1 -1
View File
@@ -20,7 +20,7 @@ const angles=computed(()=>({hour:(+time.value.hour%12)*30+(+time.value.minute)/2
const devices=computed(()=>{const all=data.value?.devices||[],start=(paging.value%Math.max(1,Math.ceil(all.length/3)))*3;return all.slice(start,start+3)})
const positions=computed(()=>{if(clock.value-lastSync.value>90000||error.value)return [];const all=data.value?.locations||[];return all.slice((paging.value%Math.max(1,Math.ceil(all.length/3)))*3,(paging.value%Math.max(1,Math.ceil(all.length/3)))*3+3)})
const mapPositions=computed(()=>clock.value-lastSync.value>90000||error.value?[]:data.value?.locations||[])
const locationText=d=>d.status==='stale'?'位置更新中断 · 请检查手机':d.position?`${d.position.latitude.toFixed(3)}°, ${d.position.longitude.toFixed(3)}°`:'等待手机定位'
const locationText=d=>d.status==='scheduled'?'按设定周期上传 · 等待下次更新':d.status==='stale'?'位置更新中断 · 请检查手机':d.position?`${d.position.latitude.toFixed(3)}°, ${d.position.longitude.toFixed(3)}°`:'等待手机定位'
const weather=computed(()=>data.value?.weather)
const syncLabel=computed(()=>authRequired.value?'等待重新连接':!lastSync.value?'正在连接家庭':error.value||clock.value-lastSync.value>90000?'网络暂时中断 · 显示上次资料':'家庭资料已同步')
+129
View File
@@ -0,0 +1,129 @@
"""Durable, consent-scoped upload batches; acknowledge only verified cloud files."""
import hashlib
import json
import math
import re
import secrets
import shutil
import time
import datetime as dt
MAX_INTERVAL = 30 * 86400
MAX_POINTS = 128
MAX_PAYLOAD = 64000
def interval_valid(value):
return type(value) is int and (value in (10, 60, 300) or 3600 <= value <= MAX_INTERVAL and value % 3600 == 0)
class Sync:
def __init__(self, app):
self.a = app
def initialize(self):
with self.a.LOCK, self.a.DB:
self.a.DB.execute('CREATE TABLE IF NOT EXISTS location_collection_sessions '
'(id TEXT PRIMARY KEY,share_id TEXT,family TEXT,member TEXT,started REAL,ended REAL,expires REAL,grant_json TEXT)')
self.a.DB.execute('CREATE INDEX IF NOT EXISTS collection_share ON location_collection_sessions(share_id)')
self.a.DB.execute('CREATE TABLE IF NOT EXISTS location_upload_timing (share_id TEXT PRIMARY KEY,started REAL,last_received REAL)')
def close(self, sid):
self.a.DB.execute('UPDATE location_collection_sessions SET ended=? WHERE share_id=? AND ended IS NULL', (time.time(), sid))
def start(self, row, grant):
self.close(row['id'])
self.a.DB.execute('INSERT OR REPLACE INTO location_upload_timing VALUES (?,?,0)', (row['id'], time.time()))
if not grant.get('historyEnabled'):
return dict(historyEnabled=False, collectionId='')
key = secrets.token_hex(16)
now = time.time()
self.a.DB.execute('INSERT INTO location_collection_sessions VALUES (?,?,?,?,?,NULL,?,?)',
(key, row['id'], row['family_id'], row['member_id'], now, row['expires'], json.dumps(grant)))
return dict(historyEnabled=True, collectionId=key, collectionStartedAt=now)
def seen(self, sid, started, now):
self.a.DB.execute('INSERT OR REPLACE INTO location_upload_timing VALUES (?,?,?)', (sid, started, now))
def timing(self, sid):
row=self.a.DB.execute('SELECT started,last_received FROM location_upload_timing WHERE share_id=?', (sid,)).fetchone()
return dict(started=row['started'],seen=row['last_received']) if row else {}
def batch(self, token, body):
a = self.a
if not isinstance(token, str) or len(token) != 43:
raise a.Problem('需要手机配对授权', 401)
batch_id, digest = body.get('batchId'), body.get('sha256')
if not isinstance(batch_id, str) or not re.fullmatch('[a-f0-9]{32}', batch_id) or not isinstance(digest, str) or not re.fullmatch('[a-f0-9]{64}', digest):
raise a.Problem('轨迹批次标识或校验值不正确')
with a.LOCK, a.DB:
row = a.DB.execute('SELECT * FROM member_location_shares WHERE token_hash=?', (hashlib.sha256(token.encode()).hexdigest(),)).fetchone()
if not row or not a.LOCATIONS.eligible(row['family_id'], row['member_id']):
raise a.Problem('手机绑定已解除,未接收本地轨迹', 401)
# Expiration stops new collection/viewing. A still-bound phone may finish
# uploading points collected inside its previously authorized window.
key = hashlib.sha256((row['id'] + ':' + batch_id).encode()).hexdigest()[:32]
existing = a.DB.execute('SELECT * FROM location_history_files WHERE id=?', (key,)).fetchone()
if existing:
meta = json.loads(existing['body'])
if meta.get('uploadDigest') != digest or meta.get('uploadShare') != row['id']:
raise a.Problem('批次内容与已接收记录不一致,未清除手机记录', 409)
if meta['state'] == 'deleting':
raise a.Problem('此历史已由本人删除,请在手机清理相应待上传记录', 409)
return self.receipt(batch_id, meta)
raw = body.get('payload')
if not isinstance(raw, str) or len(raw.encode('utf-8')) > MAX_PAYLOAD or hashlib.sha256(raw.encode('utf-8')).hexdigest() != digest:
raise a.Problem('轨迹内容校验失败,未接收记录')
try:
payload = json.loads(raw)
if not isinstance(payload, dict) or payload.get('version') != 1: raise ValueError()
session_id, points = payload['collectionId'], payload['points']
if not isinstance(session_id, str) or not isinstance(points, list) or not 1 <= len(points) <= MAX_POINTS: raise ValueError()
except (ValueError, KeyError, TypeError):
raise a.Problem('轨迹批次格式不正确') from None
session = a.DB.execute('SELECT * FROM location_collection_sessions WHERE id=? AND share_id=?', (session_id, row['id'])).fetchone()
if not session or session['member'] != row['member_id'] or session['family'] != row['family_id']:
raise a.Problem('找不到该批轨迹的本人采集授权', 403)
grant = json.loads(session['grant_json'])
now = time.time()
upper = min(session['expires'], session['ended'] if session['ended'] is not None else now + 60)
deleted = a.setting('history_deleted:' + row['member_id'], 0)
values, ids = [], set()
for item in points:
if not isinstance(item, dict): raise a.Problem('定位点格式不正确')
point_id, pos = item.get('id'), item.get('position')
if not isinstance(point_id, str) or not re.fullmatch('[a-f0-9]{32}', point_id) or point_id in ids or not isinstance(pos, dict):
raise a.Problem('定位点标识不正确或重复')
ids.add(point_id)
for name, low, high in [('latitude', -90, 90), ('longitude', -180, 180), ('accuracy', 0, 100000), ('at', session['started'] - 5, min(upper, now + 60))]:
value = pos.get(name)
if type(value) not in (int, float) or not math.isfinite(value) or not low <= value <= high:
raise a.Problem('定位点超出采集授权时间或范围:' + name)
if pos['at'] <= deleted:
raise a.Problem('此历史已由本人删除,不能重新上传', 409)
values.append(dict(position={k:pos[k] for k in ('latitude', 'longitude', 'accuracy', 'at')},
viewers=[v['id'] for v in grant['viewers']], phones=[v['id'] for v in grant.get('phones', [])]))
values.sort(key=lambda item:item['position']['at'])
encrypted = []
for index, value in enumerate(values):
point_key = key + ':' + str(index)
encrypted.append((point_key, row['family_id'], row['member_id'], value['position']['at'], a.HISTORY.seal(value, point_key), key))
import location_history
used = a.DB.execute('SELECT coalesce(sum(length(payload)),0) FROM location_history_points').fetchone()[0]
if used + sum(len(item[4]) for item in encrypted) > location_history.LIMIT or shutil.disk_usage(a.DATA).free < 1024**3:
raise a.Problem('服务器待上传空间不足,请保留手机记录,稍后重试', 507)
stamp = dt.datetime.fromtimestamp(values[0]['position']['at'], dt.timezone(dt.timedelta(hours=8)))
remote = '/apps/' + a.BAIDU.public_config()['appFolder'] + '/家庭轨迹/' + row['family_id'] + '/' + row['member_id'] + '/' + stamp.strftime('%Y/%m/%d/') + key + '.track'
meta = dict(state='pending', remote=remote, attempts=0, nextTry=0, uploadBatch=batch_id,
uploadShare=row['id'], uploadDigest=digest, uploadCount=len(values))
a.DB.execute('INSERT INTO location_history_files VALUES (?,?,?,?,?,?)',
(key, row['family_id'], row['member_id'], values[0]['position']['at'], values[-1]['position']['at'], json.dumps(meta)))
a.DB.executemany('INSERT INTO location_history_points VALUES (?,?,?,?,?,?)', encrypted)
# The surrounding SQLite transaction commits before an accepted response.
# Phone deletion requires a later cloud-verified response, not this one.
return self.receipt(batch_id, meta)
@staticmethod
def receipt(batch_id, meta):
return dict(ok=True, batchId=batch_id, sha256=meta['uploadDigest'], count=meta['uploadCount'],
state='verified' if meta['state'] == 'cloud' else 'accepted', retryAfterSeconds=30)
+22 -9
View File
@@ -4,11 +4,12 @@ import json
import math
import secrets
import time
from location_sync import Sync, interval_valid
class Locations:
def __init__(self, app):
self.a=app; self.codes={}; self.attempts={}; self.latest={}
self.a=app; self.codes={}; self.attempts={}; self.latest={}; self.sync=Sync(app)
def initialize(self):
with self.a.LOCK,self.a.DB:
@@ -19,6 +20,7 @@ class Locations:
if self.a.DB.execute("SELECT name FROM sqlite_master WHERE name='location_shares'").fetchone():
self.a.DB.execute('UPDATE location_shares SET enabled=0')
self.codes.clear(); self.latest.clear(); self.attempts.clear()
self.sync.initialize()
def eligible(self, family, key):
try: return self.a.MEMBERS.member(family,key,active=True)
@@ -116,6 +118,7 @@ class Locations:
return dict(token=token,**{k:grant[k] for k in ('home','memberName','viewers','displays','phones','viewOnly','intervalSeconds','expires','receipt','consentProtocol')})
def native(self, token, body):
if body.get('action')=='history-batch':return self.sync.batch(token,body)
if body.get('action') in ('history-list','history-delete'):
return self.a.HISTORY.native(token,body)
result=self._native(token,body)
@@ -125,7 +128,7 @@ class Locations:
if row:
fix=self.latest.get(row['id'],{}).get('fix');grant=json.loads(row['grant_json'])
if fix and fix['at']==body['position']['at']:
self.a.HISTORY.record(row,grant,fix)
if not body.get('bufferedHistory'):self.a.HISTORY.record(row,grant,fix)
else:fix=None
else:fix=None
if fix:
@@ -141,6 +144,7 @@ class Locations:
if not row:raise a.Problem('手机绑定已解除,请重新配对',401)
sid=row['id'];action=body.get('action');grant=json.loads(row['grant_json'])
if action in ('stop','revoke'):
self.sync.close(sid)
if action=='revoke':a.DB.execute('DELETE FROM member_location_shares WHERE id=?',(sid,))
else:a.DB.execute('UPDATE member_location_shares SET enabled=0 WHERE id=?',(sid,))
self.latest.pop(sid,None);return {'ok':True}
@@ -154,27 +158,32 @@ 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),
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':
if body.get('consent') is not True or body.get('receipt')!=grant['receipt']:raise a.Problem('请本人确认新的共享设置',403)
chosen=self.select_recipients(row['family_id'],body,own_id=sid)
interval=body.get('intervalSeconds',300)
if type(interval) is not int or interval not in (10,60,300):raise a.Problem('请选择实时、1 分钟或 5 分钟')
if not interval_valid(interval):raise a.Problem('上传周期可选 10 秒、1/5 分钟,或 1 至 720 小时(最多 30 天)')
sample=body.get('sampleIntervalSeconds',60)
if type(sample) is not int or sample not in (10,60,300):raise a.Problem('采集周期可选 10 秒、1 分钟或 5 分钟')
if 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)
grant.update(chosen,viewOnly=False,intervalSeconds=interval,consentProtocol=3,historyEnabled=history)
self.sync.close(sid)
grant.update(chosen,viewOnly=False,intervalSeconds=interval,sampleIntervalSeconds=sample,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,**chosen)
return dict(ok=True,receipt=grant['receipt'],intervalSeconds=interval,sampleIntervalSeconds=sample,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')
return dict(ok=True,expires=row['expires'],intervalSeconds=grant.get('intervalSeconds',300))
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)
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)
@@ -189,6 +198,7 @@ class Locations:
if not fix or pos['at']>fix['at']:fix={k:pos[k] for k in ('latitude','longitude','accuracy','at')}
if signal in ('permission_denied','location_disabled'):fix=None
self.latest[sid]=dict(started=old['started'],seen=now,fix=fix,signal=signal)
self.sync.seen(sid,old['started'],now)
return dict(ok=True,expires=row['expires'])
def listing(self, family, user=None, display_id=None, phone_id=None):
@@ -213,12 +223,15 @@ class Locations:
if user and user['id'] not in {v['id'] for v in grant['viewers']}:continue
if display_id and display_id not in {v['id'] for v in grant['displays']}:continue
if phone_id and phone_id!=row['id'] and phone_id not in {v['id'] for v in grant.get('phones',[])}:continue
recent=self.latest.get(row['id'],{});fix=recent.get('fix');seen=recent.get('seen',0)
recent=self.latest.get(row['id']) or self.sync.timing(row['id']);fix=recent.get('fix');seen=recent.get('seen',0)
age=now-(fix['at'] if fix else recent.get('started',row['created']))
state='stale' if age>900 or seen and now-seen>900 else 'live' if fix else 'waiting'
scheduled=grant.get('intervalSeconds',300)>900 and now-(seen or recent.get('started',row['created']))<=grant['intervalSeconds']+900
stale=age>900 or seen and now-seen>900
state='scheduled' if stale and scheduled else 'stale' if stale else 'live' if fix else 'waiting'
position=fix if fix and state=='live' else None
items.append(dict(id=row['member_id'],personId=valid[1]['id'],name=valid[1]['name'],status=state,
signal=recent.get('signal','waiting'),lastSeen=seen or None,position=position,expires=row['expires']))
signal=recent.get('signal','waiting'),lastSeen=seen or None,position=position,expires=row['expires'],
intervalSeconds=grant.get('intervalSeconds',300),nextUploadAt=(seen or recent.get('started',row['created']))+grant.get('intervalSeconds',300)))
return items
def snapshot(self,user):
+6 -1
View File
@@ -44,7 +44,7 @@ class AndroidLocationContractTests(unittest.TestCase):
manifest = ET.parse(ANDROID/'AndroidManifest.xml').getroot()
service = next(s for s in manifest.findall('application/service') if s.get(NS+'name') == '.LocationService')
self.assertEqual(service.get(NS+'exported'), 'false')
self.assertEqual(service.get(NS+'foregroundServiceType'), 'location')
self.assertEqual(set(service.get(NS+'foregroundServiceType').split('|')), {'location','dataSync'})
boot = (ANDROID/'src/cn/ucvl/zhaodisplay/BootReceiver.java').read_text()
self.assertNotIn('LocationService', boot)
self.assertIn('phoneMode', boot)
@@ -52,6 +52,11 @@ class AndroidLocationContractTests(unittest.TestCase):
self.assertNotIn('WebView', ui)
self.assertIn('共享我的位置', ui)
self.assertIn('new int[]{10,60,300}', ui)
self.assertIn('自定义小时 / 天',ui)
self.assertIn('LocationCadence.custom',ui)
queue=(ANDROID/'src/cn/ucvl/zhaodisplay/LocationQueue.java').read_text(encoding='utf-8')
for contract in ('AndroidKeyStore','AES/GCM/NoPadding','MAX_POINTS=50000','MAX_DATABASE_BYTES','batch.digest.equals','"verified".equals(state)','db.beginTransaction()'):
self.assertIn(contract,queue)
self.assertIn('consent.isChecked()', ui)
def test_map_uses_first_party_tiles_and_never_exposes_pairing_token(self):
+147
View File
@@ -0,0 +1,147 @@
"""Offline batches use synthetic coordinates and an isolated database/cloud stub."""
import hashlib
import json
import time
import unittest
from unittest.mock import patch
import test_phone_locations as fixtures
app=fixtures.app
class LocationSyncTests(unittest.TestCase):
setUp=fixtures.PhoneLocationTests.setUp
stop_server=fixtures.PhoneLocationTests.stop_server
phone=fixtures.PhoneLocationTests.phone
configure=fixtures.PhoneLocationTests.configure
def enabled(self, **options):
phone=self.phone('离线测试成员')
self.configure(phone,viewerIds=[self.owner['id']],historyEnabled=True,historyConsent=True,**options)
result=app.LOCATIONS.native(phone['token'],dict(action='start',consent=True,receipt=phone['receipt'],bufferedHistory=True))
phone.update(result)
return phone
def body(self,phone,count=2,at=None,batch='a'*32):
at=at or phone['collectionStartedAt']
points=[dict(id=f'{i:032x}',position=dict(latitude=36.61,longitude=117.1,accuracy=8,at=at+i)) for i in range(count)]
raw=json.dumps(dict(version=1,collectionId=phone['collectionId'],points=points),separators=(',',':'))
return dict(action='history-batch',batchId=batch,sha256=hashlib.sha256(raw.encode()).hexdigest(),payload=raw)
def send(self,phone,body=None):return app.LOCATIONS.native(phone['token'],body or self.body(phone))
def file(self):return dict(app.DB.execute('SELECT * FROM location_history_files').fetchone())
def verify_cloud(self):
with patch.object(app.BAIDU,'upload',return_value={'fs_id':123}),patch.object(app.BAIDU,'verify_file'):
app.HISTORY.process(self.file())
def test_acceptance_is_not_cloud_confirmation(self):
phone=self.enabled();body=self.body(phone);reply=self.send(phone,body)
self.assertEqual(reply['state'],'accepted');self.assertEqual(reply['count'],2);self.assertEqual(reply['sha256'],body['sha256'])
self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_points').fetchone()[0],2)
self.verify_cloud();reply=self.send(phone,body)
self.assertEqual(reply['state'],'verified');self.assertEqual(reply['batchId'],body['batchId'])
self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_points').fetchone()[0],0)
def test_repeated_batches_before_and_after_cloud_are_idempotent(self):
phone=self.enabled();body=self.body(phone)
for _ in range(3):self.send(phone,body)
self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_files').fetchone()[0],1)
self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_points').fetchone()[0],2)
self.verify_cloud()
for _ in range(3):self.assertEqual(self.send(phone,body)['state'],'verified')
self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_files').fetchone()[0],1)
def test_network_and_cloud_verification_failures_never_acknowledge(self):
phone=self.enabled();self.send(phone)
for operation in ('upload','verify_file'):
with patch.object(app.BAIDU,'upload',return_value={'fs_id':123}),patch.object(app.BAIDU,operation,side_effect=OSError('offline')):app.HISTORY.process(self.file())
self.assertEqual(self.send(phone)['state'],'accepted')
self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_points').fetchone()[0],2)
def test_old_points_accepted_after_three_days_without_becoming_live_position(self):
phone=self.enabled(intervalSeconds=3*86400);body=self.body(phone);later=time.time()+3*86400
with patch('location_sync.time.time',return_value=later):self.assertEqual(self.send(phone,body)['state'],'accepted')
self.assertIsNone(app.LOCATIONS.latest[phone['sid']]['fix'])
def test_expired_still_bound_phone_can_only_finish_prior_collection(self):
phone=self.enabled();body=self.body(phone)
with patch('location_sync.time.time',return_value=phone['expires']+86400):
self.assertEqual(self.send(phone,body)['state'],'accepted')
with self.assertRaises(app.Problem):app.LOCATIONS.native(phone['token'],dict(action='start',consent=True,receipt=phone['receipt']))
def test_wrong_digest_different_payload_and_duplicate_points_rejected(self):
phone=self.enabled();body=self.body(phone)
for changed in (dict(body,sha256='f'*64),dict(body,payload='{}')):
with self.assertRaises(app.Problem):self.send(phone,changed)
self.send(phone,body)
with self.assertRaises(app.Problem):self.send(phone,self.body(phone,count=1))
raw=json.loads(body['payload']);raw['points'][1]['id']=raw['points'][0]['id'];serialized=json.dumps(raw)
with self.assertRaises(app.Problem):self.send(phone,dict(body,batchId='b'*32,payload=serialized,sha256=hashlib.sha256(serialized.encode()).hexdigest()))
def test_batch_is_atomic_for_bad_coordinates_or_time(self):
phone=self.enabled()
for at in (phone['collectionStartedAt']-60,phone['expires']+100):
with self.assertRaises(app.Problem):self.send(phone,self.body(phone,at=at))
body=self.body(phone);raw=json.loads(body['payload']);raw['points'][1]['position']['latitude']=float('nan');serialized=json.dumps(raw)
with self.assertRaises(app.Problem):self.send(phone,dict(body,payload=serialized,sha256=hashlib.sha256(serialized.encode()).hexdigest()))
self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_files').fetchone()[0],0)
def test_other_phone_cannot_submit_or_confirm_ones_batch(self):
phone=self.enabled();other=self.phone('其他手机');body=self.body(phone);self.send(phone,body)
with self.assertRaises(app.Problem):self.send(other,body)
def test_stop_allows_previously_collected_but_not_later_points(self):
phone=self.enabled();body=self.body(phone,count=1)
app.LOCATIONS.native(phone['token'],dict(action='stop'))
self.assertEqual(self.send(phone,body)['state'],'accepted')
with self.assertRaises(app.Problem):self.send(phone,self.body(phone,count=1,at=time.time()+30,batch='b'*32))
def test_revocation_blocks_even_existing_receipts(self):
phone=self.enabled();body=self.body(phone);self.send(phone,body)
app.LOCATIONS.native(phone['token'],dict(action='revoke'))
with self.assertRaises(app.Problem):self.send(phone,body)
def test_new_viewer_does_not_get_old_offline_points(self):
phone=self.enabled();body=self.body(phone,count=1);viewer=self.phone('新增查看人')
self.configure(phone,phoneIds=[viewer['sid']],historyEnabled=True,historyConsent=True)
app.LOCATIONS.native(phone['token'],dict(action='start',consent=True,receipt=phone['receipt']))
self.send(phone,body)
result=app.HISTORY.native(viewer['token'],dict(action='history-list',memberId=phone['member']['id'],period='life',date='2026-10-19'))
self.assertEqual(result['points'],[])
def test_deleted_history_cannot_be_recreated_by_offline_retry(self):
phone=self.enabled();body=self.body(phone,count=1);self.send(phone,body)
app.HISTORY.native(phone['token'],dict(action='history-delete',confirm=True))
with self.assertRaises(app.Problem):self.send(phone,body)
with patch.object(app.BAIDU,'delete_history_file'):app.HISTORY.process(self.file())
with self.assertRaises(app.Problem):self.send(phone,body)
def test_capacity_rejects_without_accepting_or_losing_phone_receipt(self):
phone=self.enabled()
with patch('location_history.LIMIT',0),self.assertRaises(app.Problem):self.send(phone)
self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_files').fetchone()[0],0)
def test_payload_is_encrypted_at_rest(self):
phone=self.enabled();self.send(phone)
dump='\n'.join(app.DB.iterdump())
self.assertNotIn('latitude',dump);self.assertNotIn(phone['token'],dump)
def test_long_periods_and_independent_sampling(self):
phone=self.phone('周期测试')
for seconds in (3600,7200,10800,14400,18000,23*3600,86400,172800,259200,30*86400):
reply=self.configure(phone,viewerIds=[self.owner['id']],intervalSeconds=seconds,sampleIntervalSeconds=60)
self.assertEqual(reply['intervalSeconds'],seconds);self.assertEqual(reply['sampleIntervalSeconds'],60)
for invalid in (True,3601,31*86400,3600.0,'3600'):
with self.assertRaises(app.Problem):self.configure(phone,viewerIds=[self.owner['id']],intervalSeconds=invalid)
def test_long_period_wait_does_not_trigger_stale_alarm(self):
phone=self.enabled(intervalSeconds=86400);started=phone['collectionStartedAt']
with patch('member_locations.time.time',return_value=started+3600):
row=app.LOCATIONS.listing(self.aid,user=self.owner)[0];self.assertEqual(row['status'],'scheduled');self.assertIsNone(row['position'])
with patch('member_locations.time.time',return_value=started+86400+901):self.assertEqual(app.LOCATIONS.listing(self.aid,user=self.owner)[0]['status'],'stale')
def test_schedule_survives_server_memory_reset(self):
phone=self.enabled(intervalSeconds=3*86400);started=phone['collectionStartedAt'];app.LOCATIONS.latest.clear()
with patch('member_locations.time.time',return_value=started+86400):self.assertEqual(app.LOCATIONS.listing(self.aid,user=self.owner)[0]['status'],'scheduled')
if __name__=='__main__':unittest.main()
+1 -1
View File
@@ -1,6 +1,6 @@
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>配套 App · 赵府智家</title><link rel="icon" href="/brand-icon.png"><link rel="stylesheet" href="/vendor/bootstrap.min.css"><link rel="stylesheet" href="/downloads.css"><script src="/downloads.js" defer></script></head>
<body><main class="container py-4 py-md-5"><a href="/" class="back">← 返回赵府智家</a><section class="card border-0 shadow-sm p-4 p-md-5 mt-4"><div class="d-flex gap-3 align-items-center"><img src="/brand-icon.png" width="60" height="60" alt="赵府"><div><span class="text-secondary small">家庭成员均可下载</span><h1 class="h3 mb-0 mt-1">赵府智家 · 配套 App</h1></div></div><p class="mt-4 text-secondary">按设备选择手机或显示终端安装包。使用平台账号登录下载;安装后凭配对码使用,无需在 App 注册。两种版本使用同一个应用身份,请按实际用途选择。</p>
<div class="row g-3 my-2"><div class="col-md-6"><article class="p-3 rounded bg-light h-100"><h2 class="h5">家庭显示终端</h2><p class="mb-0">用于显示时间、天气、家人位置及家庭设备。安装后使用管理员提供的配对码,绑定指定家庭。</p></article></div><div class="col-md-6"><article class="p-3 rounded bg-light h-100"><h2 class="h5">手机家人位置</h2><p class="mb-0">手机打开“赵府家人位置”,输入绑定本人档案的手机配对码,无需注册或登录。可查看获授权的家人;“我的位置设置”可选择查看人、实时(约 10 秒)/ 1 分钟 / 5 分钟上传,再由本人打开共享开关。查看家人无需开启自己的定位。</p></article></div></div>
<div class="row g-3 my-2"><div class="col-md-6"><article class="p-3 rounded bg-light h-100"><h2 class="h5">家庭显示终端</h2><p class="mb-0">用于显示时间、天气、家人位置及家庭设备。安装后使用管理员提供的配对码,绑定指定家庭。</p></article></div><div class="col-md-6"><article class="p-3 rounded bg-light h-100"><h2 class="h5">手机家人位置</h2><p class="mb-0">手机打开“赵府家人位置”,输入绑定本人档案的手机配对码,无需注册或登录。可查看获授权的家人;“我的位置设置”可选择查看人,分别设置定位采集频率和上传周期:实时、分钟、小时或天(最多 30 天)。启用历史保存后,断网轨迹在手机加密暂存,恢复网络自动补传,网盘完整校验后清理本机副本。由本人打开共享开关。查看家人无需开启自己的定位。</p></article></div></div>
<form id="download-login" class="mt-4" hidden><h2 class="h5">登录后下载</h2><div class="row g-3"><label class="col-md-6">用户名<input class="form-control mt-1" name="username" autocomplete="username" required></label><label class="col-md-6">密码<input class="form-control mt-1" type="password" name="password" autocomplete="current-password" required></label></div><button class="btn btn-success mt-3" type="submit">登录并准备下载</button></form>
<div id="download-ready" class="mt-4" hidden><a id="apk-link" class="btn btn-success btn-lg" href="/downloads/ZhaoDisplay.apk">下载手机家人位置版</a><a id="terminal-link" class="btn btn-outline-success btn-lg ms-2" href="/downloads/ZhaoTerminal.apk" hidden>下载显示终端版</a><p id="terminal-info" class="small text-secondary mt-3"></p><details class="small"><summary>显示终端版校验</summary><code id="terminal-hash"></code></details><p id="release-info" class="small text-secondary mt-3"></p><details class="small"><summary>校验安装包</summary><p class="mt-2">SHA-256</p><code id="apk-hash"></code></details></div><p id="download-status" class="mt-3" role="status">正在检查登录状态…</p><button id="download-retry" class="btn btn-outline-secondary" hidden>重新检查</button>
<hr class="my-4"><p class="small text-secondary mb-0">支持 Android 8.0 及以上,ARM64 / ARMv7。下载后打开 APK,按系统提示完成安装。iPhone 可使用网页;此安装包不适用于 iOS。安装后仍按家庭授权访问资料。两端均提供“按住说话,松开发送”;接收方需先允许具体喊话人并打开 App。显示终端无需麦克风即可接收,接上话筒后可以发送。</p></section></main></body></html>
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -1,6 +1,6 @@
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#244d43"><link rel="icon" href="/zhao-icon.png"><link rel="apple-touch-icon" href="/zhao-icon.png"><title>赵府 · 智能数字管家</title> <script type="module" crossorigin src="/ui/assets/index-xETRcHmQ.js"></script>
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#244d43"><link rel="icon" href="/zhao-icon.png"><link rel="apple-touch-icon" href="/zhao-icon.png"><title>赵府 · 智能数字管家</title> <script type="module" crossorigin src="/ui/assets/index-w9su1uwq.js"></script>
<link rel="modulepreload" crossorigin href="/ui/assets/modulepreload-polyfill-B5Qt9EMX.js">
<link rel="modulepreload" crossorigin href="/ui/assets/FamilyMap-CiWCoS6Z.js">
<link rel="stylesheet" crossorigin href="/ui/assets/FamilyMap-DBkz-poX.css">
<link rel="stylesheet" crossorigin href="/ui/assets/index-CgbLhMOE.css">
<link rel="stylesheet" crossorigin href="/ui/assets/index-gJyED1pB.css">
</head><body><div id="app"></div></body></html>
+1 -1
View File
@@ -1,4 +1,4 @@
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f3eee4"><meta name="referrer" content="no-referrer"><link rel="icon" href="/zhao-icon.png"><title>赵府 · 家庭时光</title> <script type="module" crossorigin src="/ui/assets/tv-Dxkdq4LJ.js"></script>
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f3eee4"><meta name="referrer" content="no-referrer"><link rel="icon" href="/zhao-icon.png"><title>赵府 · 家庭时光</title> <script type="module" crossorigin src="/ui/assets/tv-8KQFA1ao.js"></script>
<link rel="modulepreload" crossorigin href="/ui/assets/modulepreload-polyfill-B5Qt9EMX.js">
<link rel="modulepreload" crossorigin href="/ui/assets/FamilyMap-CiWCoS6Z.js">
<link rel="stylesheet" crossorigin href="/ui/assets/FamilyMap-DBkz-poX.css">