Release 0.1.49: self-hosted maps and consented cloud location history
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
# V0.1.49 — 内置地图与家庭轨迹
|
||||
|
||||
## 使用
|
||||
|
||||
- 家庭总览和显示终端使用 MapLibre 道路地图;手机 App 内嵌同一个地图页面。JS、CSS、Worker、字体、图标与底图都从本系统加载。
|
||||
- 全国概览常驻;本人主动共享的位置进入省份后自动准备该省详细地图,完成后前端自动发现。粗略省界用于选择下载范围,不用于界址或导航。
|
||||
- 地图包归档到百度应用目录的 `地图/底图/20261017`。本机上限 3 GiB,保留至少 10 GiB 磁盘空闲,单任务最大 2 GiB、一个下载任务、两个连接。世界与全国概览固定保留。超过容量或源不可用时保留概览并显示任务状态,不会无限增长。
|
||||
- 本机回收仅针对已完成云端 SHA-256 回读校验、近期未用的省份副本。网盘文件不随本机缓存清理而删除。文件索引也写入数据库,随现有数据库备份保存。
|
||||
- “平台存储与审计”增加地图归档、恢复、失败重试、缓存占用状态。
|
||||
- 新手机配对预选保存历史,但首次开启必须由手机使用者确认长期保存;已有授权保持原设置。实时共享关闭后停止采集并清除实时位置,他人历史查询也停止;已存历史由本人手动删除。
|
||||
- 历史按天、周(周一开始)、月、年、一生及网页自定义时段查看。一生仅含实际保存的记录,不推断未采集的位置。长时段分批读取并抽样绘制,明确显示完成进度;原始点保留,30 分钟以上间断不连线。查看画面一分钟后清除。
|
||||
- 网盘目录 `家庭轨迹/家庭编号/成员编号/年/月/日`。AES-256-GCM 加密、gzip 压缩;每小时批次归档,校验后清理本机密文点。新查看人不自动取得过去记录;超级管理员没有读取别人轨迹的旁路。本人删除先立即隐藏,再异步删除云文件,失败重试。
|
||||
- 待上传轨迹本机有 32 MiB 密文点上限,打包临时副本另占少量空间;空间不足暂停新增历史,不影响实时共享,手机设置显示异常。历史索引随记录数量缓慢增长。
|
||||
- 手机增加后台定位权限入口。Android 11 及以上在系统设置中选择“始终允许”;授权不会自动开启共享。普通 APK,不改固件、桌面、HOME 或开机行为。
|
||||
|
||||
## 部署与恢复
|
||||
|
||||
1. 安装 `python3 -m pip install -r requirements.txt`。Python 需要 `cryptography`(本次部署环境 46.0.5,本机测试 50.0.1;AESGCM 接口)。其他 Web 后端仍使用标准库。
|
||||
2. 首次 Linux 部署运行 `python3 deploy/prepare-maps.py`,安装 `deploy/zhaovision-maps.service` 并启用。它只监听 `127.0.0.1:8841`,内存上限 256 MiB;主应用 `/maps/*` 提供同源入口。
|
||||
3. 地图归档和历史上传是主应用内部任务,随主服务启动,无需单独设置计划任务。
|
||||
4. **恢复历史必须恢复原数据库**:数据库包含云文件索引和随机加密密钥。不可只保留网盘 `.track` 文件后丢弃数据库备份。地图索引可由数据库设置 `map_archive` 恢复。
|
||||
5. 省份下载使用固定的 2026-10-17 Protomaps 数据版本。已归档地图可持续恢复;如果上游停止提供该版本,新增省份会提示失败,应在核验样式兼容后更新数据版本。未默认下载全球详细地图。
|
||||
|
||||
## 数据与许可
|
||||
|
||||
- [MapLibre GL JS](https://github.com/maplibre/maplibre-gl-js),6.15.0,BSD-3-Clause。
|
||||
- 本地许可全文随版本包含在 `web/vendor/maps-LICENSES.txt`,可从 `/vendor/maps-LICENSES.txt` 查看。
|
||||
- [Protomaps basemaps](https://github.com/protomaps/basemaps),5.7.2,BSD-3-Clause;[go-pmtiles](https://github.com/protomaps/go-pmtiles),1.31.2,BSD-3-Clause。
|
||||
- [OpenStreetMap](https://www.openstreetmap.org/copyright) 底图数据,ODbL;页面保留来源署名。
|
||||
- [Protomaps 本地字体及图标](https://github.com/protomaps/basemaps-assets),字体 OFL 文件与下载资源一起保存。
|
||||
- [Natural Earth 5.1.2](https://github.com/nvkelso/natural-earth-vector/tree/v5.1.2),public domain。`map-provinces.json` 为省份粗略多边形摘取,源 SHA-256 随文件记录;港澳台按省级范围聚合。此表只负责本地判断下载区域,不把家人精确坐标发送给地图提供方。
|
||||
|
||||
## 验收边界
|
||||
|
||||
Python 全套 309 项、地图与轨迹等专项 33 项、JS 全套 191 项通过。Edge 桌面、手机宽度、日夜主题、定位清除与轨迹绘制检查通过,无页面错误、失败请求或外部地图请求。Vue 与两款 APK 构建通过。
|
||||
|
||||
安卓设备当前离线,不能把构建通过等同于真机后台 GPS 或厂商省电测试通过。网盘已归档并回读验证世界概览、全国概览及山东详细地图。未替任何家人开启共享或历史保存。
|
||||
@@ -1,4 +1,4 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="4" android:versionName="0.1.48">
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="5" android:versionName="0.1.49">
|
||||
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="4" android:versionName="0.1.48">
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="5" android:versionName="0.1.49">
|
||||
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30"/>
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
|
||||
@@ -8,6 +8,7 @@
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
|
||||
<application android:label="赵府智家" android:allowBackup="false" android:usesCleartextTraffic="true" android:theme="@android:style/Theme.Material.Light.NoActionBar">
|
||||
<activity android:name=".MainActivity" android:label="赵府家庭显示终端" android:exported="true" android:configChanges="orientation|screenSize|keyboardHidden" android:launchMode="singleTask">
|
||||
<intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LEANBACK_LAUNCHER"/></intent-filter>
|
||||
|
||||
@@ -14,8 +14,9 @@ import java.util.*;
|
||||
/** Paired member identity, family viewing and voluntary sharing; no account or display UI. */
|
||||
public class LocationActivity extends Activity {
|
||||
static volatile boolean pairing=false;
|
||||
TextView identity,status,viewStatus;EditText code;Button pair,reload;
|
||||
CheckBox consent;Switch sharing;Spinner cadence;LinearLayout settings,recipients,familyList,homeContent,shareControls;
|
||||
TextView identity,status,viewStatus,permissionStatus;EditText code;Button pair,reload;
|
||||
CheckBox consent,historyConsent;Switch sharing;Spinner cadence;LinearLayout settings,recipients,familyList,homeContent,shareControls;
|
||||
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;
|
||||
int generation=0,settingsRequest=0;long lastList=0;String settingsReceipt="",settingsError="";
|
||||
@@ -50,21 +51,29 @@ public class LocationActivity extends Activity {
|
||||
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);
|
||||
consent=new CheckBox(this);consent.setText("我已核对本人身份、有效期和所选查看人,同意按上述频率共享位置。关闭后停止采集并清除位置。");shareControls.addView(consent);
|
||||
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);
|
||||
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);
|
||||
Button backgroundButton=button("后台定位权限 · 始终允许",shareControls);backgroundButton.setOnClickListener(v->backgroundPermission());
|
||||
try{if(!java.util.Arrays.asList(getPackageManager().getPackageInfo(getPackageName(),PackageManager.GET_PERMISSIONS).requestedPermissions).contains(Manifest.permission.ACCESS_BACKGROUND_LOCATION))backgroundButton.setVisibility(View.GONE);}catch(Exception ignored){}
|
||||
button("打开手机系统定位设置",shareControls).setOnClickListener(v->startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)));
|
||||
settings.setVisibility(prefs.getString("token","").isEmpty()?View.VISIBLE:View.GONE);
|
||||
homeContent=new LinearLayout(this);homeContent.setOrientation(1);layout.addView(homeContent);
|
||||
text("家人现在的位置",22,homeContent);viewStatus=text("",16,homeContent);
|
||||
map=new LocationMapView(this);homeContent.addView(map,new LinearLayout.LayoutParams(-1,(int)(260*getResources().getDisplayMetrics().density)));
|
||||
text("世界位置概览 · 可拖动、双指缩放;点家人卡片定位。底图为本地陆地轮廓,不含道路。",13,homeContent);
|
||||
map=new LocationMapView(this);homeContent.addView(map,new LinearLayout.LayoutParams(-1,(int)(360*getResources().getDisplayMetrics().density)));
|
||||
text("智家内置地图 · 可拖动、双指缩放;点家人卡片查看道路位置。圆圈表示定位精度范围。",13,homeContent);
|
||||
button("查看全部位置",homeContent).setOnClickListener(v->map.reset());
|
||||
reload=button("刷新家人位置",homeContent);reload.setOnClickListener(v->loadFamily());
|
||||
familyList=new LinearLayout(this);familyList.setOrientation(1);homeContent.addView(familyList);
|
||||
voice=new VoicePanel(this,"phone",()->prefs.getString("token",""));root.addView(voice,new LinearLayout.LayoutParams(-1,-2));render();
|
||||
}
|
||||
void render(){
|
||||
permissionStatus.setText(locationPermissionText());
|
||||
boolean paired=!prefs.getString("token","").isEmpty(),active=prefs.getBoolean("active",false),busy=pairing||LocationService.busy;
|
||||
homeContent.setVisibility(paired?View.VISIBLE:View.GONE);shareControls.setVisibility(paired?View.VISIBLE:View.GONE);settingsButton.setVisibility(paired?View.VISIBLE:View.GONE);voice.setVisibility(paired?View.VISIBLE:View.GONE);
|
||||
if(!paired)settings.setVisibility(View.VISIBLE);
|
||||
@@ -73,7 +82,7 @@ public class LocationActivity extends Activity {
|
||||
status.setText(settingsError.isEmpty()?"我的位置:"+prefs.getString("status","共享关闭,不采集定位"):settingsError);
|
||||
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);
|
||||
pair.setEnabled(!active&&!busy);cadence.setEnabled(!active&&!busy);consent.setEnabled(!active&&!busy);historyConsent.setEnabled(!active&&!busy&&settingsReady);
|
||||
for(List<CheckBox> list:choices.values())for(CheckBox c:list)c.setEnabled(!active&&!busy);
|
||||
reload.setEnabled(paired&&!loading&&!pairing);
|
||||
}
|
||||
@@ -97,7 +106,7 @@ public class LocationActivity extends Activity {
|
||||
new Thread(()->{try{
|
||||
JSONObject response=DisplayApi.call("/api/location/update",token,new JSONObject().put("action","list"));
|
||||
runOnUiThread(()->{if(!visible||g!=generation)return;JSONArray list=response.optJSONArray("items");map.setItems(list);familyList.removeAllViews();viewStatus.setText(list==null||list.length()==0?"尚无家人授权给这台手机的位置。请对方在自己的位置设置里勾选你的手机,并开启共享。":"只显示仍在授权有效期内的最新位置。");
|
||||
if(list!=null)for(int i=0;i<list.length();i++){JSONObject row=list.optJSONObject(i);if(row==null)continue;JSONObject pos=row.optJSONObject("position");String detail=pos==null?("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);});}
|
||||
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")));}
|
||||
});
|
||||
}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();
|
||||
}
|
||||
@@ -107,22 +116,67 @@ 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);settingsReady=true;render();});
|
||||
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();});
|
||||
}catch(Exception e){runOnUiThread(()->{if(visible&&g==generation&&request==settingsRequest){settingsReady=false;settingsError="无法读取我的位置设置,请检查网络或配对有效期,重新打开设置重试。";render();}});}},"location-settings").start();
|
||||
}
|
||||
void start(){
|
||||
if(pairing||LocationService.busy||prefs.getBoolean("active",false)||!settingsReady)return;
|
||||
if(!consent.isChecked()){Toast.makeText(this,"请本人核对并勾选共享说明",1).show();return;}
|
||||
if(historyConsent.isChecked()&&!historyAcknowledged){new AlertDialog.Builder(this).setTitle("同意长期保存我的轨迹").setMessage("定位点将加密上传家庭百度网盘,按天、周、月、年或全部历史查看,长期保留直到你手动删除。共享时所选查看人能读取其获授权期间的历史。关闭实时共享不会删除历史。是否同意?").setNegativeButton("暂不启用",null).setPositiveButton("本人同意并开启",(d,w)->{historyAcknowledged=true;start();}).show();return;}
|
||||
if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED&&checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},45);return;}
|
||||
if(!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()]);}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;}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 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();
|
||||
}
|
||||
public void onRequestPermissionsResult(int request,String[] permissions,int[] results){super.onRequestPermissionsResult(request,permissions,results);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;voice.active(true);lastList=0;if(!settingsReady)loadSettings();ui.post(refresh);if(pendingStart){pendingStart=false;start();}}
|
||||
public void onPause(){visible=false;voice.active(false);generation++;loading=false;ui.removeCallbacksAndMessages(null);if(map!=null)map.setItems(new JSONArray());if(familyList!=null)familyList.removeAllViews();super.onPause();}
|
||||
public void onDestroy(){if(voice!=null)voice.close();ui.removeCallbacksAndMessages(null);super.onDestroy();}
|
||||
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();
|
||||
if(choice==4){historyLoad(member,String.format(Locale.US,"%04d-%02d-%02d",c.get(Calendar.YEAR),c.get(Calendar.MONTH)+1,c.get(Calendar.DAY_OF_MONTH)),period,0,true);return;}
|
||||
new DatePickerDialog(this,(view,y,m,d)->historyLoad(member,String.format(Locale.US,"%04d-%02d-%02d",y,m+1,d),period,0,true),c.get(Calendar.YEAR),c.get(Calendar.MONTH),c.get(Calendar.DAY_OF_MONTH)).show();
|
||||
}).show();
|
||||
}
|
||||
void historyLoad(String member,String date,String period,int cursor,boolean reset){
|
||||
int g=generation,request=++historyRequest;String token=prefs.getString("token","");
|
||||
if(historyMore!=null)historyMore.setEnabled(false);Toast.makeText(this,"正在从网盘读取历史…",0).show();
|
||||
new Thread(()->{try{JSONObject result=DisplayApi.call("/api/location/update",token,new JSONObject().put("action","history-list").put("memberId",member).put("date",date).put("period",period).put("cursor",cursor));runOnUiThread(()->{
|
||||
if(!visible||g!=generation||request!=historyRequest)return;
|
||||
if(reset){
|
||||
if(historyDialog!=null)historyDialog.dismiss();historyPoints=new JSONArray();LinearLayout box=new LinearLayout(this);box.setOrientation(1);historyNotice=text("",16,box);
|
||||
historyMap=new LocationMapView(this);box.addView(historyMap,new LinearLayout.LayoutParams(-1,0,1));historyMore=button("继续加载",box);historyDialog=new Dialog(this);historyDialog.setContentView(box);
|
||||
button("关闭",box).setOnClickListener(v->historyDialog.dismiss());historyDialog.setOnDismissListener(v->{historyRequest++;if(historyMap!=null){historyMap.close();historyMap=null;}historyPoints=new JSONArray();});
|
||||
historyDialog.show();historyDialog.getWindow().setLayout(-1,-1);
|
||||
}
|
||||
if(historyMap==null)return;JSONArray added=result.optJSONArray("points");if(added!=null)for(int i=0;i<added.length();i++)historyPoints.put(added.optJSONObject(i));
|
||||
if(historyPoints.length()>10000){JSONArray sampled=new JSONArray();for(int i=0;i<10000;i++)sampled.put(historyPoints.optJSONObject((int)Math.round(i*(historyPoints.length()-1)/9999.0)));historyPoints=sampled;}
|
||||
historyMap.setTrack(historyPoints);historyNotice.setText(date+" · "+period+"\n已读取 "+result.optInt("loadedFiles")+" / "+result.optInt("totalFiles")+" 段 · "+historyPoints.length()+" 个采样点\n概览连线不代表道路路线。1 分钟后清除画面。");
|
||||
int next=result.isNull("nextCursor")?-1:result.optInt("nextCursor",-1);historyMore.setVisibility(next<0?View.GONE:View.VISIBLE);historyMore.setEnabled(true);historyMore.setOnClickListener(v->historyLoad(member,date,period,next,false));
|
||||
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();}
|
||||
String locationPermissionText(){
|
||||
boolean foreground=checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)==0||checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)==0;
|
||||
if(!foreground)return "定位权限:未允许。查看家人不需要开启自己的定位。";
|
||||
if(Build.VERSION.SDK_INT<29||checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)==0)return "定位权限:已允许后台定位。只有本人开启共享后才采集;可随时关闭。";
|
||||
return "定位权限:仅使用期间允许。可选择始终允许;后台共享仍受系统省电设置影响。";
|
||||
}
|
||||
void backgroundPermission(){
|
||||
if(Build.VERSION.SDK_INT<29){Toast.makeText(this,"当前系统无需单独申请后台定位权限",1).show();return;}
|
||||
if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)!=0&&checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)!=0){
|
||||
new AlertDialog.Builder(this).setTitle("先允许定位").setMessage("请先允许使用期间定位,然后再设置始终允许。授权不会自动开启位置共享。").setNegativeButton("暂不设置",null).setPositiveButton("允许定位",(d,w)->requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},47)).show();return;
|
||||
}
|
||||
if(checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)==0){Toast.makeText(this,"已允许后台定位",0).show();return;}
|
||||
String label=Build.VERSION.SDK_INT>=30?getPackageManager().getBackgroundPermissionOptionLabel().toString():"始终允许";
|
||||
new AlertDialog.Builder(this).setTitle("后台位置共享").setMessage("本人开启共享后,允许在锁屏或切换应用时继续更新位置。请在位置权限中选择「"+label+"」。关闭共享立即停止采集;查看名单仍由你决定。你可以暂不设置,继续查看获授权家人。").setNegativeButton("暂不设置",null).setPositiveButton("去设置",(d,w)->{
|
||||
if(Build.VERSION.SDK_INT==29)requestPermissions(new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION},48);
|
||||
else startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,android.net.Uri.parse("package:"+getPackageName())));
|
||||
}).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 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();}
|
||||
}
|
||||
|
||||
@@ -1,31 +1,42 @@
|
||||
package cn.ucvl.zhaodisplay;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.*;
|
||||
import android.view.*;
|
||||
import android.webkit.*;
|
||||
import android.net.Uri;
|
||||
import android.view.MotionEvent;
|
||||
import org.json.*;
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
import java.io.ByteArrayInputStream;
|
||||
|
||||
/** Bundled Natural Earth outline; no coordinates sent to third-party map providers. */
|
||||
final class LocationMapView extends View {
|
||||
final Paint paint=new Paint(3);final List<JSONArray> rings=new ArrayList<>();
|
||||
JSONArray items=new JSONArray();float zoom=1,lastX,lastY;double lon=0,lat=10;
|
||||
final ScaleGestureDetector scale;
|
||||
LocationMapView(Context context){super(context);setContentDescription("家人位置地图,可拖动和双指缩放");
|
||||
try(InputStream input=context.getAssets().open("world-land.json")){ByteArrayOutputStream out=new ByteArrayOutputStream();byte[] buffer=new byte[4096];int n;while((n=input.read(buffer))>0)out.write(buffer,0,n);JSONArray polygons=new JSONObject(out.toString("UTF-8")).getJSONArray("features").getJSONObject(0).getJSONObject("geometry").getJSONArray("coordinates");for(int i=0;i<polygons.length();i++)rings.add(polygons.getJSONArray(i).getJSONArray(0));}catch(Exception ignored){}
|
||||
scale=new ScaleGestureDetector(context,new ScaleGestureDetector.SimpleOnScaleGestureListener(){public boolean onScale(ScaleGestureDetector detector){zoom=Math.max(1,Math.min(64,zoom*detector.getScaleFactor()));invalidate();return true;}});
|
||||
/** First-party map only. No pairing token or native bridge is exposed to JavaScript. */
|
||||
final class LocationMapView extends WebView {
|
||||
JSONArray items=new JSONArray(),track=new JSONArray();boolean ready=false,closed=false;
|
||||
LocationMapView(Context context){
|
||||
super(context);setContentDescription("家人位置地图,可拖动和双指缩放");
|
||||
WebSettings s=getSettings();s.setJavaScriptEnabled(true);s.setDomStorageEnabled(false);
|
||||
s.setAllowFileAccess(false);s.setAllowContentAccess(false);s.setGeolocationEnabled(false);
|
||||
s.setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);s.setMediaPlaybackRequiresUserGesture(true);
|
||||
CookieManager.getInstance().setAcceptThirdPartyCookies(this,false);
|
||||
setWebViewClient(new WebViewClient(){
|
||||
public boolean shouldOverrideUrlLoading(WebView view,WebResourceRequest request){return true;}
|
||||
public WebResourceResponse shouldInterceptRequest(WebView view,WebResourceRequest request){
|
||||
Uri uri=request.getUrl();String path=uri.getPath();
|
||||
if(!"https".equals(uri.getScheme())||!"zhao.ucvl.cn".equals(uri.getHost())||(uri.getPort()!=-1&&uri.getPort()!=443)||path==null||!(path.startsWith("/maps/")||path.startsWith("/ui/assets/")))return new WebResourceResponse("text/plain","UTF-8",new ByteArrayInputStream(new byte[0]));
|
||||
return null;
|
||||
}
|
||||
public void onPageFinished(WebView view,String url){if(!closed&&url.startsWith("https://zhao.ucvl.cn/maps/phone")){ready=true;push();}}
|
||||
public void onReceivedError(WebView view,WebResourceRequest request,WebResourceError error){if(request.isForMainFrame())ready=false;}
|
||||
});
|
||||
loadUrl("https://zhao.ucvl.cn/maps/phone");
|
||||
}
|
||||
void setItems(JSONArray value){items=value==null?new JSONArray():value;invalidate();}
|
||||
void reset(){zoom=1;lon=0;lat=10;invalidate();}
|
||||
void focus(JSONObject point){lon=point.optDouble("longitude");lat=point.optDouble("latitude");zoom=16;invalidate();}
|
||||
float x(double value){return getWidth()/2f+(float)(value-lon)*getWidth()/360f*zoom;}
|
||||
float y(double value){return getHeight()/2f-(float)(value-lat)*getWidth()/360f*zoom;}
|
||||
protected void onDraw(Canvas canvas){super.onDraw(canvas);canvas.drawColor(0xffe6eeea);paint.setColor(0xffceddd4);paint.setStyle(Paint.Style.FILL);
|
||||
for(JSONArray ring:rings){Path path=new Path();for(int i=0;i<ring.length();i++){JSONArray p=ring.optJSONArray(i);float px=x(p.optDouble(0)),py=y(p.optDouble(1));if(i==0)path.moveTo(px,py);else path.lineTo(px,py);}path.close();canvas.drawPath(path,paint);}
|
||||
float density=getResources().getDisplayMetrics().density;paint.setTextSize(14*density);
|
||||
for(int i=0;i<items.length();i++){JSONObject person=items.optJSONObject(i),point=person.optJSONObject("position");if(point==null)continue;float px=x(point.optDouble("longitude")),py=y(point.optDouble("latitude"));paint.setColor(0xff287764);canvas.drawCircle(px,py,5*density,paint);paint.setColor(0xff183e31);canvas.drawText(person.optString("name"),px+8*density,py-8*density,paint);}
|
||||
}
|
||||
public boolean onTouchEvent(MotionEvent event){scale.onTouchEvent(event);if(event.getActionMasked()==MotionEvent.ACTION_DOWN){lastX=event.getX();lastY=event.getY();getParent().requestDisallowInterceptTouchEvent(true);return true;}if(event.getActionMasked()==MotionEvent.ACTION_MOVE){if(!scale.isInProgress()){float unit=getWidth()/360f*zoom;lon=Math.max(-180,Math.min(180,lon-(event.getX()-lastX)/unit));lat=Math.max(-90,Math.min(90,lat+(event.getY()-lastY)/unit));invalidate();}lastX=event.getX();lastY=event.getY();return true;}if(event.getActionMasked()==MotionEvent.ACTION_UP||event.getActionMasked()==MotionEvent.ACTION_CANCEL){getParent().requestDisallowInterceptTouchEvent(false);performClick();}return true;}
|
||||
void run(String expression){if(ready&&!closed)evaluateJavascript("if(window.ZhaoMap){"+expression+"}",null);}
|
||||
void push(){run("window.ZhaoMap.setItems(JSON.parse("+JSONObject.quote(items.toString())+"));window.ZhaoMap.setTrack(JSON.parse("+JSONObject.quote(track.toString())+"));");}
|
||||
void setTrack(JSONArray value){track=value==null?new JSONArray():value;push();}
|
||||
void setItems(JSONArray value){items=value==null?new JSONArray():value;push();}
|
||||
void reset(){run("window.ZhaoMap.fit();");}
|
||||
void focus(JSONObject point){for(int i=0;i<items.length();i++){JSONObject row=items.optJSONObject(i);if(row!=null&&row.optJSONObject("position")==point){run("window.ZhaoMap.focus("+JSONObject.quote(row.optString("id"))+");");return;}}}
|
||||
void resumeMap(){onResume();if(!ready&&!closed)reload();}
|
||||
void pauseMap(){track=new JSONArray();setItems(new JSONArray());onPause();}
|
||||
void close(){items=new JSONArray();closed=true;ready=false;stopLoading();destroy();}
|
||||
public boolean onTouchEvent(MotionEvent event){if(event.getActionMasked()==MotionEvent.ACTION_DOWN)getParent().requestDisallowInterceptTouchEvent(true);if(event.getActionMasked()==MotionEvent.ACTION_UP||event.getActionMasked()==MotionEvent.ACTION_CANCEL)getParent().requestDisallowInterceptTouchEvent(false);return super.onTouchEvent(event);}
|
||||
public boolean performClick(){super.performClick();return true;}
|
||||
}
|
||||
|
||||
@@ -48,6 +48,8 @@ import family_voice
|
||||
import family_members
|
||||
import recording_archive
|
||||
import app_downloads
|
||||
import map_service
|
||||
import location_history
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
os.umask(0o077)
|
||||
@@ -101,6 +103,8 @@ JOURNAL = journal.Journal(sys.modules[__name__])
|
||||
CLOUD_IMAGES = cloud_images.CloudImages(sys.modules[__name__])
|
||||
DISPLAYS = displays.Displays(sys.modules[__name__])
|
||||
LOCATIONS = family_locations.Locations(sys.modules[__name__])
|
||||
MAPS = map_service.Maps(sys.modules[__name__])
|
||||
HISTORY = location_history.History(sys.modules[__name__])
|
||||
VOICE = family_voice.Voice(sys.modules[__name__])
|
||||
MEMBERS = family_members.Members(sys.modules[__name__])
|
||||
ARCHIVE = recording_archive.Archive(sys.modules[__name__])
|
||||
@@ -732,7 +736,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.login(data, path == '/api/setup')
|
||||
return
|
||||
self.require_auth()
|
||||
if path not in ('/api/locations', '/api/logout', '/api/account/password', '/api/preferences', '/api/households/layout', '/api/family/restore',
|
||||
if path not in ('/api/locations', '/api/location-history', '/api/logout', '/api/account/password', '/api/preferences', '/api/households/layout', '/api/family/restore',
|
||||
'/api/family/person', '/api/family/link', '/api/family/event', '/api/heritage', '/api/ptz', '/api/ptz/presets',
|
||||
'/api/journal', '/api/journal/action', '/api/journal/upload', '/api/journal/finish', '/api/journal/pause', '/api/journal/draft', '/api/journal/abandon-draft', '/api/journal/remove-upload', '/api/journal/restore-upload'):
|
||||
self.require_manager()
|
||||
@@ -743,6 +747,16 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.answer({'ok': True}, cookie='vision=; Path=/; Max-Age=0; HttpOnly; SameSite=Strict')
|
||||
elif path == '/api/locations':
|
||||
self.answer(LOCATIONS.manage(self.user,data))
|
||||
elif path == '/api/maps':
|
||||
self.require_admin()
|
||||
if data.get('action')!='retry':raise Problem('地图操作不正确')
|
||||
if data.get('id') not in MAPS.archive.specs():raise Problem('地图区域不存在',404)
|
||||
MAPS.archive.update(data['id'],nextTry=0,state='queued',attempts=0)
|
||||
MAPS.archive.wake.set()
|
||||
self.answer(MAPS.archive.status())
|
||||
elif path == '/api/location-history':
|
||||
if data.get('action')!='delete' or data.get('confirm') is not True:raise Problem('请确认删除历史轨迹')
|
||||
self.answer(HISTORY.delete(HOUSEHOLDS.scope(self.user),data.get('memberId'),user=self.user))
|
||||
elif path == '/api/display-voice':
|
||||
self.answer(VOICE.manage_display(self.user,data))
|
||||
elif path == '/api/members':
|
||||
@@ -1000,6 +1014,9 @@ class Handler(BaseHTTPRequestHandler):
|
||||
parsed = url.urlsplit(self.path)
|
||||
path = parsed.path
|
||||
query = {k: v[0] for k, v in url.parse_qs(parsed.query).items()}
|
||||
if path.startswith('/maps/') and path != '/maps/phone':
|
||||
MAPS.serve(self,path)
|
||||
return
|
||||
if path in ('/api/app-release','/downloads/ZhaoDisplay.apk','/downloads/ZhaoTerminal.apk'):
|
||||
self.require_auth()
|
||||
if path == '/api/app-release': self.answer(app_downloads.release(sys.modules[__name__],query.get('variant','phone'))[1])
|
||||
@@ -1048,6 +1065,10 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.answer(ACCOUNTS.state(self.user, status()))
|
||||
elif path == '/api/locations':
|
||||
self.answer(LOCATIONS.snapshot(self.user))
|
||||
elif path == '/api/maps':
|
||||
self.require_admin();self.answer(MAPS.archive.status())
|
||||
elif path == '/api/location-history':
|
||||
self.answer(HISTORY.query(HOUSEHOLDS.scope(self.user),query.get('memberId'),query.get('date'),user=self.user,period=query.get('period','day'),until=query.get('until'),cursor=query.get('cursor',0)))
|
||||
elif path == '/api/members':
|
||||
self.answer(MEMBERS.snapshot(self.user))
|
||||
elif path == '/api/family-directory':
|
||||
@@ -1245,9 +1266,11 @@ class Handler(BaseHTTPRequestHandler):
|
||||
files[path] = path[1:]
|
||||
if path in ('/tv', '/tv/'):
|
||||
files[path] = 'ui/tv.html'
|
||||
if path == '/maps/phone':
|
||||
files[path] = 'ui/map.html'
|
||||
if path in ('/downloads','/downloads/'):
|
||||
files[path] = 'downloads.html'
|
||||
for resource in ('downloads.js','downloads.css','vendor/bootstrap.min.css'):
|
||||
for resource in ('downloads.js','downloads.css','vendor/bootstrap.min.css','vendor/maps-LICENSES.txt'):
|
||||
files['/'+resource] = resource
|
||||
if path not in files or not (ROOT / 'web' / files[path]).is_file():
|
||||
raise Problem('页面不存在', 404)
|
||||
@@ -1281,6 +1304,7 @@ def initialize():
|
||||
MEMBERS.initialize()
|
||||
DISPLAYS.initialize()
|
||||
LOCATIONS.initialize()
|
||||
HISTORY.initialize()
|
||||
VOICE.initialize()
|
||||
ARCHIVE.initialize()
|
||||
HERITAGE.initialize()
|
||||
@@ -1307,6 +1331,8 @@ if __name__ == '__main__':
|
||||
threading.Thread(target=VOICE.watch, daemon=True).start()
|
||||
threading.Thread(target=ARCHIVE.watch, daemon=True).start()
|
||||
threading.Thread(target=JOURNAL.watch, daemon=True).start()
|
||||
threading.Thread(target=MAPS.archive.watch, daemon=True).start()
|
||||
threading.Thread(target=HISTORY.watch, daemon=True).start()
|
||||
bindings = [h.strip() for h in os.environ.get('VISION_BIND', '127.0.0.1').split(',') if h.strip()]
|
||||
port = int(os.environ.get('VISION_PORT', '8790'))
|
||||
servers = []
|
||||
|
||||
@@ -433,3 +433,18 @@ class Baidu:
|
||||
info = result.get('info')
|
||||
if result.get('taskid') or not isinstance(info,list) or len(info)!=1 or info[0].get('path')!=remote or info[0].get('errno')!=0:
|
||||
raise self.a.Problem('网盘未确认录像删除结果,将稍后重试',502)
|
||||
|
||||
def delete_history_file(self,remote):
|
||||
root='/apps/'+self.public_config()['appFolder']+'/家庭轨迹/'
|
||||
if not remote.startswith(root) or not re.fullmatch(r'[a-f0-9]{16,32}/[a-f0-9]{16,32}/\d{4}/\d{2}/\d{2}/[a-f0-9]{32}\.track',remote[len(root):]):
|
||||
raise self.a.Problem('轨迹删除路径不正确')
|
||||
parent=remote.rsplit('/',1)[0]
|
||||
try:items=self.list_directory(parent)
|
||||
except self.a.Problem as error:
|
||||
if getattr(error,'baidu_code','')=='-9':return
|
||||
raise
|
||||
if not any(v.get('path')==remote for v in items):return
|
||||
result=self.request('shared','file','filemanager',{'async':0,'filelist':json.dumps([remote])},opera='delete')
|
||||
info=result.get('info')
|
||||
if result.get('taskid') or not isinstance(info,list) or len(info)!=1 or info[0].get('path')!=remote or info[0].get('errno')!=0:
|
||||
raise self.a.Problem('网盘未确认轨迹删除,将继续重试',502)
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Provision the bundled map service on Linux; run before enabling its systemd unit.
|
||||
|
||||
Public downloads only. No location, family or credential data is sent upstream.
|
||||
Python 3.11+; install python3-cryptography for the app's encrypted track archive.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import hashlib,os,shutil,subprocess,tarfile,urllib.request,zipfile
|
||||
|
||||
root=Path('/var/lib/zhaovision/maps');root.mkdir(parents=True,exist_ok=True)
|
||||
tools=Path('/opt/zhaovision/tools');tools.mkdir(parents=True,exist_ok=True)
|
||||
if shutil.disk_usage(root).free<12*1024**3:raise SystemExit('At least 12 GiB free space is required')
|
||||
|
||||
def download(url,dest,sha=None,accept=None):
|
||||
if dest.exists() and (not sha or hashlib.file_digest(dest.open('rb'),'sha256').hexdigest()==sha):return
|
||||
temporary=dest.with_suffix(dest.suffix+'.part')
|
||||
headers={'User-Agent':'ZhaoVision-map-provisioner'}
|
||||
if accept:headers['Accept']=accept
|
||||
try:
|
||||
with urllib.request.urlopen(urllib.request.Request(url,headers=headers),timeout=90) as response,temporary.open('wb') as out:
|
||||
while chunk:=response.read(262144):
|
||||
if shutil.disk_usage(root).free<10*1024**3:raise RuntimeError('Disk reserve reached')
|
||||
out.write(chunk)
|
||||
if sha and hashlib.file_digest(temporary.open('rb'),'sha256').hexdigest()!=sha:raise RuntimeError('Checksum mismatch')
|
||||
os.replace(temporary,dest)
|
||||
finally:temporary.unlink(missing_ok=True)
|
||||
|
||||
archive=root/'pmtiles-tool.tar.gz'
|
||||
download('https://api.github.com/repos/protomaps/go-pmtiles/releases/assets/486313332',archive,
|
||||
'3ed7dbf4ec2e6dfe5e25b6f70d1ffc932729f93c86db353bf514dd71010a312f','application/octet-stream')
|
||||
with tarfile.open(archive) as tar:(tools/'pmtiles').write_bytes(tar.extractfile('pmtiles').read())
|
||||
(tools/'pmtiles').chmod(0o755);archive.unlink()
|
||||
for name,opts in [('world',['--maxzoom=6']),('china',['--maxzoom=9','--bbox=73,3,135.2,53.7'])]:
|
||||
dest=root/(name+'.pmtiles');partial=root/(name+'.pmtiles.part')
|
||||
if not dest.exists():
|
||||
partial.unlink(missing_ok=True)
|
||||
subprocess.run([str(tools/'pmtiles'),'extract','https://build.protomaps.com/20261017.pmtiles',str(partial),'--download-threads=2',*opts],check=True,timeout=5400,env=dict(os.environ,GOMEMLIMIT='192MiB',GOMAXPROCS='1'))
|
||||
subprocess.run([str(tools/'pmtiles'),'verify',str(partial)],check=True,timeout=180);os.replace(partial,dest)
|
||||
subprocess.run([str(tools/'pmtiles'),'verify',str(dest)],check=True,timeout=180)
|
||||
assets=root/'assets.zip'
|
||||
download('https://codeload.github.com/protomaps/basemaps-assets/zip/refs/heads/main',assets)
|
||||
with zipfile.ZipFile(assets) as bundle:
|
||||
for member in bundle.infolist():
|
||||
parts=Path(member.filename).parts[1:]
|
||||
if not parts or member.is_dir() or parts[0] not in ('fonts','sprites') or '..' in parts:continue
|
||||
dest=root/'assets'/Path(*parts);dest.parent.mkdir(parents=True,exist_ok=True);dest.write_bytes(bundle.read(member))
|
||||
assets.unlink()
|
||||
import pwd
|
||||
identity=pwd.getpwnam('zhaovision')
|
||||
for file in [root,*root.rglob('*')]:os.chown(file,identity.pw_uid,identity.pw_gid)
|
||||
print('Prepared world + China overview. Provinces download on authorized arrival.')
|
||||
@@ -0,0 +1,24 @@
|
||||
[Unit]
|
||||
Description=ZhaoVision built-in vector basemap
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=zhaovision
|
||||
Group=zhaovision
|
||||
ExecStart=/opt/zhaovision/tools/pmtiles serve /var/lib/zhaovision/maps --interface=127.0.0.1 --port=8841 --cache-size=32
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
Environment=GOMEMLIMIT=160MiB
|
||||
MemoryMax=256M
|
||||
CPUQuota=50%
|
||||
TasksMax=32
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectHome=true
|
||||
ProtectSystem=strict
|
||||
ReadOnlyPaths=/var/lib/zhaovision/maps
|
||||
UMask=0077
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="data:,"><title>家人位置地图</title></head><body><div id="map" class="family-map-canvas"></div><div id="status" role="status">正在加载内置地图…</div><script type="module" src="/src/maps/phone.js"></script></body></html>
|
||||
@@ -1,19 +1,21 @@
|
||||
{
|
||||
"name": "zhao-steward-ui",
|
||||
"private": true,
|
||||
"version": "0.1.48",
|
||||
"version": "0.1.49",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "vite build",
|
||||
"dev": "vite --host 127.0.0.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@protomaps/basemaps": "5.7.2",
|
||||
"@tiptap/core": "3.32.0",
|
||||
"@tiptap/pm": "3.32.0",
|
||||
"@tiptap/starter-kit": "3.32.0",
|
||||
"@tiptap/vue-3": "3.32.0",
|
||||
"bootstrap": "5.3.8",
|
||||
"echarts": "6.1.0",
|
||||
"maplibre-gl": "6.15.0",
|
||||
"vue": "^3.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
Generated
+186
@@ -8,6 +8,9 @@ importers:
|
||||
|
||||
.:
|
||||
dependencies:
|
||||
'@protomaps/basemaps':
|
||||
specifier: 5.7.2
|
||||
version: 5.7.2
|
||||
'@tiptap/core':
|
||||
specifier: 3.32.0
|
||||
version: 3.32.0(@tiptap/pm@3.32.0)
|
||||
@@ -26,6 +29,9 @@ importers:
|
||||
echarts:
|
||||
specifier: 6.1.0
|
||||
version: 6.1.0
|
||||
maplibre-gl:
|
||||
specifier: 6.15.0
|
||||
version: 6.15.0
|
||||
vue:
|
||||
specifier: ^3.5.0
|
||||
version: 3.5.43
|
||||
@@ -224,6 +230,35 @@ packages:
|
||||
'@jridgewell/sourcemap-codec@1.6.0':
|
||||
resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==}
|
||||
|
||||
'@mapbox/jsonlint-lines-primitives@2.0.3':
|
||||
resolution: {integrity: sha512-0SElaV0uMxEnxzBhhX9WTuPyUeMsAN/SS0i16tjuba4/mio63MG9khjC1a0JAiPGXAwvwm4UfHJURCN7nyudQg==}
|
||||
engines: {node: '>= 22'}
|
||||
|
||||
'@mapbox/point-geometry@1.1.0':
|
||||
resolution: {integrity: sha512-YGcBz1cg4ATXDCM/71L9xveh4dynfGmcLDqufR+nQQy3fKwsAZsWd/x4621/6uJaeB9mwOHE6hPeDgXz9uViUQ==}
|
||||
|
||||
'@mapbox/tiny-sdf@2.3.0':
|
||||
resolution: {integrity: sha512-gBvcNDBBB66bgQYvnaJ6Jk+VCaMmVq5+IZR2kWPisT88Z8s0kBQt6hfVi8QgRW8Vpg0UWZzBA4ZSyzHHC+VeRA==}
|
||||
|
||||
'@mapbox/unitbezier@1.0.0':
|
||||
resolution: {integrity: sha512-fqd515fjBmANKGGsQ286E2Wvj/XvDFpGzwJxq4CI6jMQue6Oy04uCKp+JWKF00xRTmk6cEu1jPJ9p3xqH8YWqQ==}
|
||||
|
||||
'@mapbox/vector-tile@3.0.0':
|
||||
resolution: {integrity: sha512-Qf10S1uIHMk20ri/IVBnpS+esUEkVaR5Hftmz88jTInrpmWgPGJfPe3LVjjlE77trLx8tH6qjTG7uWH9hIq/0Q==}
|
||||
|
||||
'@maplibre/geojson-vt@6.3.0':
|
||||
resolution: {integrity: sha512-3Zw2jsU9pIJG3G2CQFbLjWj2MlAHodhD7cSY+15iywUuLmmkgzcKRnueVRZ4AcC/5wOtfhidcJAAzBpoBNs3Xg==}
|
||||
|
||||
'@maplibre/maplibre-gl-style-spec@26.4.4':
|
||||
resolution: {integrity: sha512-hG4RZR4PBd/+6A3ODdZ3AnQRF106ZQk1y3bhwDg8bH/A4Oz2tnRUJVVWs9BZa6gXZ1d3UKe89C+Mm+olGBELvA==}
|
||||
hasBin: true
|
||||
|
||||
'@maplibre/mlt@1.3.0':
|
||||
resolution: {integrity: sha512-7M2O7ABM80Oi8XPkfkrjKB8mOBIxGoVgkA52Mu4RMWoBvvMdagQ522+WxVYujZsMpqIr3BpzrTbXrm4k8lCzCQ==}
|
||||
|
||||
'@maplibre/vt-pbf@4.3.2':
|
||||
resolution: {integrity: sha512-j6p0AdjvAR19Z3XaCysle7A4ZSo08tYOzxD0Y9NQylwPAkwJJeYub5b2eVucdeDh7erhv69DahoLOevDRERRUw==}
|
||||
|
||||
'@napi-rs/lzma-linux-x64-gnu@1.5.1':
|
||||
resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==}
|
||||
engines: {node: ^22.20 || ^24.12 || >=25}
|
||||
@@ -234,6 +269,10 @@ packages:
|
||||
'@popperjs/core@2.11.8':
|
||||
resolution: {integrity: sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==}
|
||||
|
||||
'@protomaps/basemaps@5.7.2':
|
||||
resolution: {integrity: sha512-K1Yk6bWdULulYg+R2QRVXx4NzJZan5YQhpejEG0c1/sXruJrfPIPZuakpf3jwAgVmjIRVQwAv+yRafDeN0aaUQ==}
|
||||
hasBin: true
|
||||
|
||||
'@rolldown/pluginutils@1.0.1':
|
||||
resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==}
|
||||
|
||||
@@ -526,6 +565,9 @@ packages:
|
||||
'@types/estree@1.0.9':
|
||||
resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==}
|
||||
|
||||
'@types/geojson@7946.0.16':
|
||||
resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==}
|
||||
|
||||
'@vitejs/plugin-vue@6.0.9':
|
||||
resolution: {integrity: sha512-rD/MORlhaZMlXWW0rEn4FB4wMinWC0z/D7Ye160S5+Rs1mC8ZDAdcDp4SjKfUhG5t8q1ktcPVw4xuTkPRlzrSA==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
@@ -560,6 +602,9 @@ packages:
|
||||
'@vue/shared@3.5.43':
|
||||
resolution: {integrity: sha512-uksS7YGMR5NZyr4JNq0Rp+QyLns0ueaz20KwzIPW9R0LH1Vnt4E+XUM29PNseEbf1www2gOuhuDi5AKOIXag9Q==}
|
||||
|
||||
bidi-js@1.1.0:
|
||||
resolution: {integrity: sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==}
|
||||
|
||||
bootstrap@5.3.8:
|
||||
resolution: {integrity: sha512-HP1SZDqaLDPwsNiqRqi5NcP0SSXciX2s9E+RyqJIIqGo+vJeN5AJVM98CXmW/Wux0nQ5L7jeWUdplCEf0Ee+tg==}
|
||||
peerDependencies:
|
||||
@@ -568,6 +613,9 @@ packages:
|
||||
csstype@3.2.3:
|
||||
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
|
||||
|
||||
earcut@3.2.4:
|
||||
resolution: {integrity: sha512-FHc6yNpnTORB0tM5kmZ03iD2mDuNakDE2lvf4Hw1XkfxtEHIGVi01B/GqUSwx+NcC1WGjidAfpTXzeALtPtfpg==}
|
||||
|
||||
echarts@6.1.0:
|
||||
resolution: {integrity: sha512-q0yaFPggC9FUdsWH4blavRWFmxdrIodbkoKNAjJudAI6CA9gNPxHtV2RcZNEepZVlk4yvBYkOkbk6HIVpIyHZA==}
|
||||
|
||||
@@ -597,12 +645,31 @@ packages:
|
||||
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
|
||||
os: [darwin]
|
||||
|
||||
gl-matrix@3.4.4:
|
||||
resolution: {integrity: sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ==}
|
||||
|
||||
json-stringify-pretty-compact@4.0.0:
|
||||
resolution: {integrity: sha512-3CNZ2DnrpByG9Nqj6Xo8vqbjT4F6N+tb4Gb28ESAZjYZ5yqvmc56J+/kuIwkaAMOyblTQhUW7PxMkUb8Q36N3Q==}
|
||||
|
||||
kdbush@4.1.0:
|
||||
resolution: {integrity: sha512-e9vurzrXJQrFX6ckpHP3bvj5l+9CnYzkxDNnNQ1h2QTqdWsUAJgXiKdGNcOa1EY85dU8KbQ+z/FdQdB7P+9yfQ==}
|
||||
|
||||
linkifyjs@4.3.3:
|
||||
resolution: {integrity: sha512-P8aEP5U/D1/IlTY2OeYsErdwh9bGuLE30NcXtKEjgdHcahveQoQwM2yZNsioQHsWFz0P7KKudisbrzCgR0sDHg==}
|
||||
|
||||
magic-string@0.30.21:
|
||||
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
|
||||
|
||||
maplibre-gl@6.15.0:
|
||||
resolution: {integrity: sha512-kxFetbvUHDOVaAP1CYb226Mdk2QhzIPddqM0xJTFD35wu78Mpd6NM7+H68ALjc6Oa0kAOX5EAdMKyvD2u3qfcg==}
|
||||
engines: {node: '>=16.14.0', npm: '>=8.1.0'}
|
||||
|
||||
minimist@1.2.8:
|
||||
resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==}
|
||||
|
||||
murmurhash-js@1.0.0:
|
||||
resolution: {integrity: sha512-TvmkNhkv8yct0SVBSy+o8wYzXjE4Zz3PCesbfs8HiCXXdcTuocApFv11UWlNFWKYsP2okqrhb7JNlSm9InBhIw==}
|
||||
|
||||
nanoid@3.3.19:
|
||||
resolution: {integrity: sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==}
|
||||
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
|
||||
@@ -611,6 +678,10 @@ packages:
|
||||
orderedmap@2.1.1:
|
||||
resolution: {integrity: sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==}
|
||||
|
||||
pbf@5.1.2:
|
||||
resolution: {integrity: sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==}
|
||||
hasBin: true
|
||||
|
||||
picocolors@1.1.1:
|
||||
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
|
||||
|
||||
@@ -622,6 +693,9 @@ packages:
|
||||
resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==}
|
||||
engines: {node: ^10 || ^12 || >=14}
|
||||
|
||||
potpack@2.1.0:
|
||||
resolution: {integrity: sha512-pcaShQc1Shq0y+E7GqJqvZj8DTthWV1KeHGdi0Z6IAin2Oi3JnLCOfwnCo84qc+HAp52wT9nK9H7FAJp5a44GQ==}
|
||||
|
||||
prosemirror-changeset@2.4.4:
|
||||
resolution: {integrity: sha512-Gyuz9jYdrAeA9I7AholyOes9KUmv/lEwsC5O9s5xF5VB3EgTPsXMGUxz4+H1B+wKVPdZbvRcg1Cp3x8qX+8ofA==}
|
||||
|
||||
@@ -661,6 +735,19 @@ packages:
|
||||
prosemirror-view@1.42.6:
|
||||
resolution: {integrity: sha512-3g25f6hKV2bBxo3puH3EcYWmmVNSH0iWmNsMVT7sugDSpA025jgpOLarcDWr39SdzPjYMaiYtRdNtXialPSjEQ==}
|
||||
|
||||
protocol-buffers-schema@3.6.1:
|
||||
resolution: {integrity: sha512-VG2K63Igkiv9p76tk1lilczEK1cT+kCjKtkdhw1dQZV3k3IXJbd3o6Ho8b9zJZaHSnT2hKe4I+ObmX9w6m5SmQ==}
|
||||
|
||||
quickselect@3.0.0:
|
||||
resolution: {integrity: sha512-XdjUArbK4Bm5fLLvlm5KpTFOiOThgfWWI4axAZDWg4E/0mKdZyI9tNEfds27qCi1ze/vwTR16kvmmGhRra3c2g==}
|
||||
|
||||
require-from-string@2.0.2:
|
||||
resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
resolve-protobuf-schema@2.1.0:
|
||||
resolution: {integrity: sha512-kI5ffTiZWmJaS/huM8wZfEMer1eRd7oJQhDuxeCLe3t7N7mX3z94CN0xPxBQxFYQTSNz9T0i+v6inKqSdK8xrQ==}
|
||||
|
||||
rollup@4.64.0:
|
||||
resolution: {integrity: sha512-gjA/kFeDfffII8COoPsvLPvE16hWDTEc1+0QKQNKUkuV8iJjqsC4xXs8/FzuL0v9EV39kuxTbAgcFoTRyy2TGQ==}
|
||||
engines: {node: '>=18.0.0', npm: '>=8.0.0'}
|
||||
@@ -677,6 +764,9 @@ packages:
|
||||
resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
|
||||
engines: {node: '>=12.0.0'}
|
||||
|
||||
tinyqueue@3.0.0:
|
||||
resolution: {integrity: sha512-gRa9gwYU3ECmQYv3lslts5hxuIa90veaEcxDYuu3QGOIAEM2mOZkVHp48ANJuu1CURtRdHKUBY5Lm1tHV+sD4g==}
|
||||
|
||||
tslib@2.3.0:
|
||||
resolution: {integrity: sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==}
|
||||
|
||||
@@ -840,11 +930,50 @@ snapshots:
|
||||
|
||||
'@jridgewell/sourcemap-codec@1.6.0': {}
|
||||
|
||||
'@mapbox/jsonlint-lines-primitives@2.0.3': {}
|
||||
|
||||
'@mapbox/point-geometry@1.1.0': {}
|
||||
|
||||
'@mapbox/tiny-sdf@2.3.0': {}
|
||||
|
||||
'@mapbox/unitbezier@1.0.0': {}
|
||||
|
||||
'@mapbox/vector-tile@3.0.0':
|
||||
dependencies:
|
||||
'@mapbox/point-geometry': 1.1.0
|
||||
'@types/geojson': 7946.0.16
|
||||
pbf: 5.1.2
|
||||
|
||||
'@maplibre/geojson-vt@6.3.0':
|
||||
dependencies:
|
||||
kdbush: 4.1.0
|
||||
|
||||
'@maplibre/maplibre-gl-style-spec@26.4.4':
|
||||
dependencies:
|
||||
'@mapbox/jsonlint-lines-primitives': 2.0.3
|
||||
'@mapbox/unitbezier': 1.0.0
|
||||
json-stringify-pretty-compact: 4.0.0
|
||||
minimist: 1.2.8
|
||||
quickselect: 3.0.0
|
||||
tinyqueue: 3.0.0
|
||||
|
||||
'@maplibre/mlt@1.3.0':
|
||||
dependencies:
|
||||
'@mapbox/point-geometry': 1.1.0
|
||||
|
||||
'@maplibre/vt-pbf@4.3.2':
|
||||
dependencies:
|
||||
'@mapbox/point-geometry': 1.1.0
|
||||
'@types/geojson': 7946.0.16
|
||||
pbf: 5.1.2
|
||||
|
||||
'@napi-rs/lzma-linux-x64-gnu@1.5.1':
|
||||
optional: true
|
||||
|
||||
'@popperjs/core@2.11.8': {}
|
||||
|
||||
'@protomaps/basemaps@5.7.2': {}
|
||||
|
||||
'@rolldown/pluginutils@1.0.1': {}
|
||||
|
||||
'@rollup/rollup-android-arm-eabi@4.64.0':
|
||||
@@ -1090,6 +1219,8 @@ snapshots:
|
||||
|
||||
'@types/estree@1.0.9': {}
|
||||
|
||||
'@types/geojson@7946.0.16': {}
|
||||
|
||||
'@vitejs/plugin-vue@6.0.9(vite@7.3.6)(vue@3.5.43)':
|
||||
dependencies:
|
||||
'@rolldown/pluginutils': 1.0.1
|
||||
@@ -1150,12 +1281,18 @@ snapshots:
|
||||
|
||||
'@vue/shared@3.5.43': {}
|
||||
|
||||
bidi-js@1.1.0:
|
||||
dependencies:
|
||||
require-from-string: 2.0.2
|
||||
|
||||
bootstrap@5.3.8(@popperjs/core@2.11.8):
|
||||
dependencies:
|
||||
'@popperjs/core': 2.11.8
|
||||
|
||||
csstype@3.2.3: {}
|
||||
|
||||
earcut@3.2.4: {}
|
||||
|
||||
echarts@6.1.0:
|
||||
dependencies:
|
||||
tslib: 2.3.0
|
||||
@@ -1201,16 +1338,51 @@ snapshots:
|
||||
fsevents@2.3.3:
|
||||
optional: true
|
||||
|
||||
gl-matrix@3.4.4: {}
|
||||
|
||||
json-stringify-pretty-compact@4.0.0: {}
|
||||
|
||||
kdbush@4.1.0: {}
|
||||
|
||||
linkifyjs@4.3.3: {}
|
||||
|
||||
magic-string@0.30.21:
|
||||
dependencies:
|
||||
'@jridgewell/sourcemap-codec': 1.6.0
|
||||
|
||||
maplibre-gl@6.15.0:
|
||||
dependencies:
|
||||
'@mapbox/point-geometry': 1.1.0
|
||||
'@mapbox/tiny-sdf': 2.3.0
|
||||
'@mapbox/unitbezier': 1.0.0
|
||||
'@mapbox/vector-tile': 3.0.0
|
||||
'@maplibre/geojson-vt': 6.3.0
|
||||
'@maplibre/maplibre-gl-style-spec': 26.4.4
|
||||
'@maplibre/mlt': 1.3.0
|
||||
'@maplibre/vt-pbf': 4.3.2
|
||||
'@types/geojson': 7946.0.16
|
||||
bidi-js: 1.1.0
|
||||
earcut: 3.2.4
|
||||
gl-matrix: 3.4.4
|
||||
kdbush: 4.1.0
|
||||
murmurhash-js: 1.0.0
|
||||
pbf: 5.1.2
|
||||
potpack: 2.1.0
|
||||
quickselect: 3.0.0
|
||||
tinyqueue: 3.0.0
|
||||
|
||||
minimist@1.2.8: {}
|
||||
|
||||
murmurhash-js@1.0.0: {}
|
||||
|
||||
nanoid@3.3.19: {}
|
||||
|
||||
orderedmap@2.1.1: {}
|
||||
|
||||
pbf@5.1.2:
|
||||
dependencies:
|
||||
resolve-protobuf-schema: 2.1.0
|
||||
|
||||
picocolors@1.1.1: {}
|
||||
|
||||
picomatch@4.0.7: {}
|
||||
@@ -1221,6 +1393,8 @@ snapshots:
|
||||
picocolors: 1.1.1
|
||||
source-map-js: 1.2.2
|
||||
|
||||
potpack@2.1.0: {}
|
||||
|
||||
prosemirror-changeset@2.4.4:
|
||||
dependencies:
|
||||
prosemirror-transform: 1.12.2
|
||||
@@ -1295,6 +1469,16 @@ snapshots:
|
||||
prosemirror-state: 1.4.4
|
||||
prosemirror-transform: 1.12.2
|
||||
|
||||
protocol-buffers-schema@3.6.1: {}
|
||||
|
||||
quickselect@3.0.0: {}
|
||||
|
||||
require-from-string@2.0.2: {}
|
||||
|
||||
resolve-protobuf-schema@2.1.0:
|
||||
dependencies:
|
||||
protocol-buffers-schema: 3.6.1
|
||||
|
||||
rollup@4.64.0:
|
||||
dependencies:
|
||||
'@types/estree': 1.0.9
|
||||
@@ -1336,6 +1520,8 @@ snapshots:
|
||||
fdir: 6.5.0(picomatch@4.0.7)
|
||||
picomatch: 4.0.7
|
||||
|
||||
tinyqueue@3.0.0: {}
|
||||
|
||||
tslib@2.3.0: {}
|
||||
|
||||
vite@7.3.6:
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
allowBuilds:
|
||||
esbuild: true
|
||||
minimumReleaseAgeExclude:
|
||||
- maplibre-gl@6.15.0
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
<script setup>
|
||||
import {ref,computed,watch,onBeforeUnmount} from 'vue'
|
||||
import {snapshot,bridge} from '../composables/bridge.js'
|
||||
import LocalChart from './LocalChart.vue'
|
||||
import FamilyMap from './FamilyMap.vue'
|
||||
import LocationHistory from './LocationHistory.vue'
|
||||
const result=ref(null),error=ref(''),consent=ref(false),days=ref(7),code=ref(''),expires=ref(0),busy=ref(false),selected=ref('')
|
||||
const memberId=ref(''),viewerIds=ref([]),displayIds=ref([]),phoneIds=ref([]),viewOnly=ref(true)
|
||||
const binding=computed(()=>result.value?.bindings?.find(x=>x.memberId===memberId.value))
|
||||
@@ -12,10 +13,6 @@ 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 location=d=>d.position?`${d.position.latitude.toFixed(4)}°, ${d.position.longitude.toFixed(4)}° · 精度约 ${Math.round(d.position.accuracy)} 米`:'尚无有效位置'
|
||||
const option=computed(()=>{
|
||||
const focus=items.value.find(x=>x.id===selected.value)?.position
|
||||
return {geo:{map:'world-land',roam:true,center:focus?[focus.longitude,focus.latitude]:[0,10],zoom:focus?5:1,boundingCoords:[[-180,90],[180,-90]],itemStyle:{areaColor:'#d9e4df',borderColor:'#94b2a6'},emphasis:{disabled:true},silent:false},tooltip:{show:false},series:[{type:'scatter',coordinateSystem:'geo',symbolSize:14,label:{show:true,position:'top',formatter:'{b}'},data:items.value.filter(d=>d.position).map(d=>({name:d.name,targetId:d.id,value:[d.position.longitude,d.position.latitude],itemStyle:{color:d.status==='stale'?'#c18d3e':'#257a68'}}))}]}
|
||||
})
|
||||
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=''}}
|
||||
catch(err){if(e===epoch&&r===requestId){result.value=null;error.value=err.message}}
|
||||
@@ -30,10 +27,11 @@ watch([memberId,viewerIds,displayIds,phoneIds,viewOnly,days],()=>{code.value=''}
|
||||
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 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 class="row g-3"><div class="col-12 col-lg-8"><LocalChart :option="option" :height="360" label="家庭位置世界平面图,详细位置见右侧列表" @select="selected=$event"/><p class="small text-secondary mb-0">可拖动缩放,点击家人定位。底图:Natural Earth 陆地轮廓(本地资源);定位采用 WGS84 经纬度。</p></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>
|
||||
<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>
|
||||
<p v-if="!result?.members?.length" class="alert alert-info">请先在“家庭成员”登记本人或家人;普通账号需关联本人档案。</p>
|
||||
@@ -43,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">手机可在“我的位置设置”选择实时(约 10 秒)、1 分钟或 5 分钟上传,默认 5 分钟。实时位置仅在内存中保存,关闭共享后清除;本人可另行开启历史保存,长期归档到百度网盘并手动删除。定位或网络中断超过 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>
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<script setup>
|
||||
import {ref,watch,onMounted,onBeforeUnmount} from 'vue'
|
||||
const props=defineProps({items:{type:Array,default:()=>[]},track:{type:Array,default:()=>[]},selected:{type:String,default:''},height:{type:Number,default:380},night:Boolean})
|
||||
const emit=defineEmits(['select']);const canvas=ref(),status=ref('正在加载内置地图…');let controller,themeObserver,sequence=0
|
||||
async function start(){const s=++sequence;controller?.destroy();status.value='正在加载内置地图…';try{const {createFamilyMap}=await import('../maps/controller.js');if(s!==sequence)return;controller=createFamilyMap(canvas.value,{night:props.night||['night','dark'].includes(document.documentElement.dataset.theme),onStatus:value=>status.value=value,onSelect:id=>emit('select',id)});controller.setItems(props.items);controller.setTrack(props.track)}catch{if(s===sequence)status.value='地图组件未能加载,请重试'}}
|
||||
onMounted(()=>{start();themeObserver=new MutationObserver(()=>controller?.setNight(props.night||['night','dark'].includes(document.documentElement.dataset.theme)));themeObserver.observe(document.documentElement,{attributes:true,attributeFilter:['data-theme']})})
|
||||
watch(()=>props.items,value=>controller?.setItems(value),{deep:true})
|
||||
watch(()=>props.track,value=>controller?.setTrack(value),{deep:true})
|
||||
watch(()=>props.selected,value=>value?controller?.focus(value):controller?.fit())
|
||||
watch(()=>props.night,value=>controller?.setNight(value))
|
||||
onBeforeUnmount(()=>{sequence++;themeObserver?.disconnect();controller?.destroy()})
|
||||
</script>
|
||||
<template><div><div ref="canvas" class="family-map-canvas" :style="{height:height+'px'}" aria-label="家人位置地图,可拖动缩放"/><p class="family-map-status" role="status">{{status}} <button v-if="/未能|无法|未就绪/.test(status)" class="btn btn-sm btn-outline-secondary" @click="start">重试地图</button></p></div></template>
|
||||
@@ -0,0 +1,12 @@
|
||||
<script setup>
|
||||
import {ref,watch,onBeforeUnmount} from 'vue'
|
||||
import {bridge,snapshot} from '../composables/bridge.js'
|
||||
import FamilyMap from './FamilyMap.vue'
|
||||
const props=defineProps({members:{type:Array,default:()=>[]}}),selected=ref(''),date=ref(new Intl.DateTimeFormat('sv-SE',{timeZone:'Asia/Shanghai'}).format(new Date())),until=ref(date.value),period=ref('day'),points=ref([]),status=ref(''),busy=ref(false),next=ref(null)
|
||||
let epoch=0,expiry
|
||||
function clear(){epoch++;points.value=[];status.value='';busy.value=false;next.value=null;clearTimeout(expiry)}
|
||||
watch([selected,date,until,period,()=>snapshot.value.state.familyId,()=>snapshot.value.page,()=>snapshot.value.session],clear)
|
||||
async function load(more=false){const cursor=more?next.value:0;if(!more)clear();const e=epoch;busy.value=true;status.value='正在从网盘读取…';try{const r=await bridge().api('/api/location-history?'+new URLSearchParams({memberId:selected.value,date:date.value,until:until.value,period:period.value,cursor}));if(e===epoch){const joined=[...points.value,...r.points],byTime=new Map(joined.map(p=>[p.at,p]));let values=[...byTime.values()].sort((a,b)=>a.at-b.at);if(values.length>10000)values=Array.from({length:10000},(_,i)=>values[Math.round(i*(values.length-1)/9999)]);points.value=values;next.value=r.nextCursor;status.value=`已读取 ${r.loadedFiles} / ${r.totalFiles} 段归档 · 显示 ${values.length} 个采样点${r.nextCursor!==null?',点击继续加载读取其余记录':',本时段已读取完毕'}`;clearTimeout(expiry);expiry=setTimeout(clear,60000)}}catch(err){if(e===epoch){points.value=[];next.value=null;status.value=err.message}}finally{if(e===epoch)busy.value=false}}
|
||||
function hidden(){if(document.hidden)clear()}document.addEventListener('visibilitychange',hidden);onBeforeUnmount(()=>{clear();document.removeEventListener('visibilitychange',hidden)})
|
||||
</script>
|
||||
<template><details class="border-top mt-3 pt-3"><summary>历史轨迹 · 每天到一生</summary><p class="small text-secondary mt-2">仅记录本人同意保存的轨迹,长期保留至本人删除。关闭共享后他人不能读取;新查看人不自动获得过去记录。长时段分批从网盘读取,概览抽样展示,原始定位点仍保留。连线不是实际道路路线。画面 1 分钟后清除,需要时重新读取。</p><form class="row g-2 my-2" @submit.prevent="load(false)"><label class="col-sm-3">家人<select v-model="selected" required class="form-select"><option value="">请选择</option><option v-for="m in members" :key="m.id" :value="m.id">{{m.name}}</option></select></label><label class="col-sm-2">时段<select v-model="period" class="form-select"><option value="day">每天</option><option value="week">每周</option><option value="month">每月</option><option value="year">每年</option><option value="life">一生 · 全部已存记录</option><option value="custom">自定义</option></select></label><label v-if="period!=='life'" class="col-sm-3">{{period==='custom'?'开始日期':'选择该时段内的日期'}}<input type="date" v-model="date" required class="form-control"></label><label v-if="period==='custom'" class="col-sm-3">结束日期<input type="date" v-model="until" required class="form-control"></label><div class="col-sm-3 align-self-end"><button class="btn btn-primary" :disabled="busy">{{busy?'读取中':'查看轨迹'}}</button></div></form><FamilyMap v-if="points.length" :track="points" :height="420"/><p role="status">{{status}}</p><button v-if="next!==null" class="btn btn-outline-primary" :disabled="busy" @click="load(true)">继续加载</button></details></template>
|
||||
@@ -0,0 +1,12 @@
|
||||
<script setup>
|
||||
import {ref,computed,watch,onBeforeUnmount} from 'vue'
|
||||
import {snapshot,bridge} from '../composables/bridge.js'
|
||||
const data=ref(null),error=ref(''),active=computed(()=>snapshot.value.loggedIn&&snapshot.value.page==='storage'&&snapshot.value.platformAdmin)
|
||||
let timer,epoch=0
|
||||
const size=n=>((n||0)/1024/1024).toFixed(1)+' MB'
|
||||
const names={queued:'等待下载',downloading:'下载底图',restoring:'从网盘恢复',uploading:'上传网盘',verifying:'核对云端文件',ready:'可使用',cloud:'已归档 · 本地已释放',retry:'等待重试'}
|
||||
async function load(){const e=epoch;try{const v=await bridge().api('/api/maps');if(e===epoch){data.value=v;error.value=''}}catch(err){if(e===epoch)error.value=err.message}finally{if(e===epoch&&active.value)timer=setTimeout(load,15000)}}
|
||||
async function retry(id){try{await bridge().api('/api/maps',{action:'retry',id});clearTimeout(timer);load()}catch(err){error.value=err.message}}
|
||||
watch(active,v=>{epoch++;clearTimeout(timer);if(v)load()},{immediate:true});onBeforeUnmount(()=>{epoch++;clearTimeout(timer)})
|
||||
</script>
|
||||
<template><section v-if="active" class="panel mb-4"><div class="d-flex justify-content-between"><h2 class="fs-5">内置地图 · 网盘归档与本机缓存</h2><span class="badge text-bg-light">全国概览常驻</span></div><p class="text-secondary small">家人开启位置共享、进入某个省份后,自动准备该省详细地图。同一省份共用一份。上传并核对成功的省份缓存可回收,需要时从百度网盘取回。</p><p v-if="data">本机 {{size(data.usedBytes)}} / {{size(data.cacheLimitBytes)}} · 为其他服务至少预留 {{size(data.reserveBytes)}}</p><div class="table-responsive"><table class="table align-middle"><thead><tr><th>地图</th><th>状态</th><th>本机</th><th>百度网盘</th><th></th></tr></thead><tbody><tr v-for="item in data?.items" :key="item.id"><td>{{item.name}}</td><td>{{names[item.state]||item.state}}<small v-if="item.error" class="d-block text-danger">{{item.error}}</small></td><td>{{size(item.localBytes)}}</td><td>{{item.cloud?'已校验归档':item.progress?item.progress+'%':'待归档'}}</td><td><button v-if="item.state==='retry'" class="btn btn-sm btn-outline-primary" @click="retry(item.id)">重试</button></td></tr></tbody></table></div><p v-if="error||data?.error" class="text-danger">{{error||data.error}}</p></section></template>
|
||||
@@ -9,8 +9,10 @@ import UploadTasks from './UploadTasks.vue'
|
||||
import RichJournalEditor from './RichJournalEditor.vue'
|
||||
import FamilyMembers from './FamilyMembers.vue'
|
||||
import AccountAccess from './AccountAccess.vue'
|
||||
import MapStorage from './MapStorage.vue'
|
||||
</script>
|
||||
<template>
|
||||
<MapStorage />
|
||||
<section id="page-members" class="page" hidden><FamilyMembers /></section>
|
||||
<section id="page-accounts" class="page" hidden><AccountAccess /></section>
|
||||
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import {Map as LibreMap,Marker,NavigationControl,ScaleControl,AttributionControl,setWorkerUrl,setWorkerCount} from 'maplibre-gl'
|
||||
import workerUrl from 'maplibre-gl/dist/maplibre-gl-worker.mjs?worker&url'
|
||||
import 'maplibre-gl/dist/maplibre-gl.css'
|
||||
import {layers,namedFlavor} from '@protomaps/basemaps'
|
||||
import {visiblePeople,accuracyCircle,regionAt,trackCollection} from './model.mjs'
|
||||
import './map.css'
|
||||
setWorkerUrl(workerUrl)
|
||||
setWorkerCount(2)
|
||||
|
||||
export function createFamilyMap(container,{onSelect=()=>{},onStatus=()=>{},night=false}={}){
|
||||
let map,disposed=false,people=[],track=[],selected='',markers=new globalThis.Map(),initialFit=false,available=false,theme=night,catalog={regions:[]},expiry,poll,resize,styleKey='',loadingCatalog=false
|
||||
const abort=new AbortController()
|
||||
const origin=location.origin
|
||||
const chosen=(lon,lat)=>regionAt(catalog.regions||[],lon,lat)
|
||||
const style=()=>{
|
||||
const flavor={...namedFlavor(theme?'dark':'light'),...(theme?{earth:'#192725',background:'#15211f',water:'#173747',minor_a:'#33483e',minor_b:'#33483e',major:'#496354',highway:'#6f7160',roads_label_minor:'#b1c3b9',roads_label_major:'#c8d8ce',subplace_label:'#adbbb3',city_label:'#d0ddcf',state_label:'#d0ddcf',country_label:'#d0ddcf',roads_label_minor_halo:'#192725',roads_label_major_halo:'#192725',subplace_label_halo:'#192725',city_label_halo:'#192725'}:{earth:'#f3f0e7',water:'#bad8e6',park_a:'#d7e4cf'})}
|
||||
const center=map?.getCenter()||{lng:117.8,lat:36.6},zoom=map?.getZoom()||6
|
||||
let region=chosen(center.lng,center.lat)
|
||||
if(zoom<=6)region=catalog.regions.find(r=>r.id==='world')||region
|
||||
else if(zoom<9&®ion?.id.startsWith('cn-'))region=catalog.regions.find(r=>r.id==='china')||region
|
||||
region=region||catalog.regions[0];styleKey=region.id+theme+region.revision
|
||||
return {version:8,glyphs:`${origin}/maps/assets/fonts/{fontstack}/{range}.pbf`,sprite:`${origin}/maps/assets/sprites/v4/${theme?'dark':'light'}`,
|
||||
sources:{base:{type:'vector',tiles:[`${origin}/maps/tiles/${region.id}/{z}/{x}/{y}.mvt`],minzoom:0,maxzoom:region.maxZoom,bounds:region.bounds}},layers:layers('base',flavor,{lang:'zh'})}
|
||||
}
|
||||
const maximum=r=>r?.id.startsWith('cn-')?18:r?.id==='china'?11:6
|
||||
function report(){if(!map||!available)return;const c=map.getCenter(),r=chosen(c.lng,c.lat);onStatus(r?.id.startsWith('cn-')?`${r.name}详细地图 · 道路与建筑`:`${r?.name||'概览'} · 进入省份后后台准备详细地图,完成后自动可用`)}
|
||||
function refreshStyle(){if(!map||!available||disposed)return;const old=styleKey,next=style();if(old!==styleKey){map.setStyle(next);map.once('style.load',paint)}const c=map.getCenter(),max=maximum(chosen(c.lng,c.lat));if(map.getMaxZoom()!==max)map.setMaxZoom(max);report()}
|
||||
function clearMarkers(){for(const m of markers.values())m.remove();markers.clear()}
|
||||
function paint(){
|
||||
if(!map||disposed)return
|
||||
const valid=visiblePeople(people),ids=new Set(valid.map(p=>p.id))
|
||||
for(const [id,marker] of markers)if(!ids.has(id)){marker.remove();markers.delete(id)}
|
||||
for(const p of valid){
|
||||
if(markers.has(p.id)){const marker=markers.get(p.id),el=marker.getElement();marker.setLngLat([p.position.longitude,p.position.latitude]);el.classList.toggle('selected',p.id===selected);el.firstChild.textContent=String(p.name||'家人').slice(0,1);el.lastChild.textContent=String(p.name||'家人');el.setAttribute('aria-label',`查看${p.name||'家人'}的位置`);continue}
|
||||
const el=document.createElement('button');el.type='button';el.className='family-map-pin'+(p.id===selected?' selected':'')
|
||||
el.setAttribute('aria-label',`查看${p.name||'家人'}的位置`)
|
||||
const avatar=document.createElement('span');avatar.textContent=String(p.name||'家人').slice(0,1)
|
||||
const label=document.createElement('b');label.textContent=String(p.name||'家人');el.append(avatar,label)
|
||||
el.onclick=()=>{selected=p.id;onSelect(p.id);focus(p.id)}
|
||||
markers.set(p.id,new Marker({element:el,anchor:'bottom'}).setLngLat([p.position.longitude,p.position.latitude]).addTo(map))
|
||||
}
|
||||
if(map.isStyleLoaded()){
|
||||
const data={type:'FeatureCollection',features:valid.filter(p=>!selected||p.id===selected).map(accuracyCircle)}
|
||||
if(map.getSource('family-accuracy'))map.getSource('family-accuracy').setData(data)
|
||||
else {map.addSource('family-accuracy',{type:'geojson',data});map.addLayer({id:'family-accuracy-fill',type:'fill',source:'family-accuracy',paint:{'fill-color':'#238e79','fill-opacity':.12}});map.addLayer({id:'family-accuracy-line',type:'line',source:'family-accuracy',paint:{'line-color':'#238e79','line-width':1,'line-opacity':.6}})}
|
||||
const history=trackCollection(track)
|
||||
if(map.getSource('family-track'))map.getSource('family-track').setData(history)
|
||||
else{map.addSource('family-track',{type:'geojson',data:history});map.addLayer({id:'family-track-line',type:'line',source:'family-track',filter:['==',['geometry-type'],'LineString'],paint:{'line-color':'#e49a26','line-width':4,'line-opacity':.85}});map.addLayer({id:'family-track-points',type:'circle',source:'family-track',filter:['==',['geometry-type'],'Point'],paint:{'circle-radius':['case',['get','edge'],6,3],'circle-color':'#217d6b','circle-stroke-color':'#fff','circle-stroke-width':1}})}
|
||||
}
|
||||
if(!initialFit&&valid.length){initialFit=true;fit()}
|
||||
}
|
||||
function fit(){if(!map)return;if(track.length){const pts=trackCollection(track).features.filter(f=>f.geometry.type==='Point').map(f=>f.geometry.coordinates);if(pts.length){map.setMaxZoom(18);map.fitBounds([[Math.min(...pts.map(p=>p[0])),Math.min(...pts.map(p=>p[1]))],[Math.max(...pts.map(p=>p[0])),Math.max(...pts.map(p=>p[1]))]],{padding:55,maxZoom:14,duration:400});return}}const valid=visiblePeople(people);if(valid.length===1){focus(valid[0].id);return}if(!valid.length){map.easeTo({center:[105,35],zoom:4,duration:400});return}
|
||||
const xs=valid.map(p=>p.position.longitude),ys=valid.map(p=>p.position.latitude)
|
||||
map.setMaxZoom(18)
|
||||
map.fitBounds([[Math.min(...xs),Math.min(...ys)],[Math.max(...xs),Math.max(...ys)]],{padding:65,maxZoom:13,duration:500})
|
||||
}
|
||||
function focus(id){const p=visiblePeople(people).find(p=>p.id===id);if(!map||!p)return;selected=id;const pos=p.position,max=maximum(chosen(pos.longitude,pos.latitude));map.setMaxZoom(max);map.easeTo({center:[pos.longitude,pos.latitude],zoom:Math.min(14,max),duration:450});paint()}
|
||||
const controller={setItems(items){people=Array.isArray(items)?items:[];if(!people.length){initialFit=false;selected=''}paint()},setTrack(points){track=Array.isArray(points)?points:[];paint();if(track.length)fit()},focus,fit,setNight(value){if(theme===value)return;theme=value;refreshStyle()},resize(){map?.resize()},destroy(){disposed=true;abort.abort();clearInterval(expiry);clearInterval(poll);resize?.disconnect();clearMarkers();map?.remove();map=null;people=[];track=[]},ready:Promise.resolve()}
|
||||
controller.ready=(async()=>{try{
|
||||
const timeout=setTimeout(()=>abort.abort(),10000);let response;try{response=await fetch('/maps/catalog.json',{signal:abort.signal})}finally{clearTimeout(timeout)}if(!response.ok)throw Error();catalog=await response.json();if(disposed)return;if(!catalog.regions?.length){onStatus('地图数据尚未就绪,家人位置可查看列表');return}
|
||||
map=new LibreMap({container,style:style(),center:[117.8,36.6],zoom:6,maxZoom:18,minZoom:1,attributionControl:false,renderWorldCopies:false,dragRotate:false,touchPitch:false,localIdeographFontFamily:'sans-serif'})
|
||||
map.addControl(new NavigationControl({showCompass:false}),'top-right');map.addControl(new ScaleControl({unit:'metric'}),'bottom-left')
|
||||
map.addControl(new AttributionControl({compact:true,customAttribution:'<a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noreferrer">© OpenStreetMap</a> · <a href="https://protomaps.com" target="_blank" rel="noreferrer">Protomaps</a>'}),'bottom-right')
|
||||
map.on('load',()=>{available=true;paint();if(track.length)fit();report()})
|
||||
map.on('error',()=>onStatus('部分地图未能加载,可重试;家人信息仍可查看列表'))
|
||||
map.on('moveend',refreshStyle)
|
||||
resize=new ResizeObserver(()=>map?.resize());resize.observe(container);expiry=setInterval(paint,15000)
|
||||
poll=setInterval(async()=>{if(disposed||loadingCatalog)return;loadingCatalog=true;try{const r=await fetch('/maps/catalog.json',{signal:abort.signal,cache:'no-store'});if(r.ok){const next=await r.json();if(next.regions?.length&&next.revision!==catalog.revision){catalog=next;refreshStyle()}}}catch{}finally{loadingCatalog=false}},20000)
|
||||
}catch{if(!disposed)onStatus('此设备暂时无法绘制地图,请查看家人列表或更新系统 WebView')}})()
|
||||
return controller
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
.family-map-canvas{height:100%;width:100%;min-height:240px;background:#e5efea;border-radius:16px;overflow:hidden;position:relative}.family-map-pin{display:flex;align-items:center;gap:6px;border:0;background:transparent;color:#193d34;cursor:pointer;padding:4px;font-family:inherit}.family-map-pin>span{display:grid;place-items:center;width:40px;height:40px;background:#207e6e;border:3px solid white;border-radius:50%;color:white;font-size:17px;box-shadow:0 3px 14px #12392e40}.family-map-pin>b{background:#fffffff2;border-radius:8px;padding:5px 9px;box-shadow:0 2px 8px #12392e20;max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:14px}.family-map-pin.selected>span{background:#d37f3a;outline:3px solid #e8bc72}.maplibregl-ctrl button{min-width:36px;min-height:36px}.maplibregl-ctrl-attrib a{color:#375e51}.maplibregl-canvas:focus-visible{outline:3px solid #207e6e;outline-offset:-3px}[data-theme=night] .family-map-canvas{background:#1d2d27}[data-theme=night] .family-map-pin>b{background:#243c34;color:#cad9d2}.family-map-status{font-size:.8rem;color:#627c70;margin:.4rem 0}.maplibregl-control-container{font:12px sans-serif}
|
||||
@@ -0,0 +1,17 @@
|
||||
export const inBounds=(b,lon,lat)=>Array.isArray(b)&&lon>=b[0]&&lon<=b[2]&&lat>=b[1]&&lat<=b[3]
|
||||
export const regionAt=(regions,lon,lat)=>regions.find(r=>r.id.startsWith('cn-')&&inBounds(r.bounds,lon,lat))||regions.find(r=>r.id==='china'&&inBounds(r.bounds,lon,lat))||regions.find(r=>r.id==='world')
|
||||
export function trackCollection(points){
|
||||
const valid=(points||[]).filter(v=>Number.isFinite(v.longitude)&&Number.isFinite(v.latitude)&&Number.isFinite(v.at)&&Math.abs(v.longitude)<=180&&Math.abs(v.latitude)<85).slice(0,10000).sort((a,b)=>a.at-b.at)
|
||||
const lines=[];let line=[]
|
||||
for(let i=0;i<valid.length;i++){const v=valid[i];if(i&&v.at-valid[i-1].at>1800){if(line.length>1)lines.push(line);line=[]}line.push([v.longitude,v.latitude])}if(line.length>1)lines.push(line)
|
||||
return {type:'FeatureCollection',features:[{type:'Feature',properties:{},geometry:{type:'MultiLineString',coordinates:lines}},...valid.map((v,i)=>({type:'Feature',properties:{at:v.at,edge:i===0||i===valid.length-1},geometry:{type:'Point',coordinates:[v.longitude,v.latitude]}}))]}
|
||||
}
|
||||
export function visiblePeople(items,now=Date.now()){
|
||||
return (Array.isArray(items)?items:[]).filter(p=>{const v=p?.position;return p.status!=='stale'&&v&&Number.isFinite(v.longitude)&&Number.isFinite(v.latitude)&&Math.abs(v.longitude)<=180&&Math.abs(v.latitude)<=85.051129&&Number.isFinite(v.at)&&now/1000-v.at<900&&v.at<=now/1000+60}).slice(0,200)
|
||||
}
|
||||
export function accuracyCircle(p){
|
||||
const {longitude:lon,latitude:lat,accuracy}=p.position,r=Math.min(50000,Math.max(0,Number(accuracy)||0)),coords=[]
|
||||
for(let i=0;i<=64;i++){const t=i*Math.PI/32;coords.push([lon+r*Math.cos(t)/(111320*Math.cos(lat*Math.PI/180)),lat+r*Math.sin(t)/111320])}
|
||||
return {type:'Feature',properties:{id:p.id},geometry:{type:'Polygon',coordinates:[coords]}}
|
||||
}
|
||||
export const emptyCollection=()=>({type:'FeatureCollection',features:[]})
|
||||
@@ -0,0 +1 @@
|
||||
html,body{margin:0;width:100%;height:100%;background:#e5efea;font-family:system-ui,sans-serif}#map{height:calc(100% - 28px);border-radius:0;min-height:0}#status{height:28px;box-sizing:border-box;padding:5px 9px;font-size:12px;color:#456354;background:#f3f7f4;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}[data-theme=night] body,[data-theme=night] #status{background:#1d2d27;color:#a8bfb3}
|
||||
@@ -0,0 +1,9 @@
|
||||
import {createFamilyMap} from './controller.js'
|
||||
import './phone.css'
|
||||
const map=createFamilyMap(document.getElementById('map'),{onStatus:text=>document.getElementById('status').textContent=text})
|
||||
// Native layer supplies already-authorized points; no token crosses the WebView boundary.
|
||||
window.ZhaoMap={setItems:items=>map.setItems(items),setTrack:points=>map.setTrack(points),focus:id=>map.focus(id),fit:()=>map.fit(),setNight:value=>{document.documentElement.dataset.theme=value?'night':'day';map.setNight(value)}}
|
||||
document.addEventListener('visibilitychange',()=>{if(document.hidden){map.setItems([]);map.setTrack([])}})
|
||||
window.addEventListener('pagehide',()=>map.setItems([]))
|
||||
const theme=()=>window.ZhaoMap.setNight(new Date().getHours()>=20||new Date().getHours()<7)
|
||||
theme();setInterval(theme,60000)
|
||||
@@ -2,6 +2,7 @@
|
||||
import {ref,computed,watch,onMounted,onBeforeUnmount} from 'vue'
|
||||
import {chinaParts,weatherLabel} from './time.mjs'
|
||||
import {createDisplayConnection} from './connection.mjs'
|
||||
import FamilyMap from '../components/FamilyMap.vue'
|
||||
const data=ref(null),clock=ref(Date.now()),error=ref(''),lastSync=ref(0),paging=ref(0),offset=ref(0),fullscreen=ref(false)
|
||||
const authRequired=ref(false),loading=ref(false)
|
||||
let tick,cycle,wake
|
||||
@@ -18,6 +19,7 @@ const greeting=computed(()=>+time.value.hour<6?'夜深了,愿你好梦':+time.
|
||||
const angles=computed(()=>({hour:(+time.value.hour%12)*30+(+time.value.minute)/2,minute:(+time.value.minute)*6,second:(+time.value.second)*6}))
|
||||
const devices=computed(()=>{const all=data.value?.devices||[],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 weather=computed(()=>data.value?.weather)
|
||||
@@ -53,7 +55,7 @@ onBeforeUnmount(()=>{connection.stop();clearInterval(tick);clearInterval(cycle);
|
||||
</section>
|
||||
<div class="tv-bottom">
|
||||
<section class="tv-card tv-devices"><div class="tv-section-heading"><h2>家中设备</h2><span>{{data?.home.deviceCount??'—'}} 台 · {{data?.home.spaces??'—'}} 处区域</span></div><div class="tv-device-grid"><article v-for="d in devices" :key="d.id" class="tv-device"><div class="device-emblem">{{/电视|显示/.test(d.type)?'▣':/摄像/.test(d.type)?'◉':/路由|网关/.test(d.type)?'⌁':'◇'}}</div><div><h3>{{d.name}}</h3><p>{{d.location}}</p><span :class="['tv-status',d.status]"><i></i>{{d.statusLabel}}</span></div></article><div class="tv-empty" v-if="!devices.length">设备接入后,会在这里与你见面。</div></div><div class="tv-page-count" v-if="(data?.devices.length||0)>3">设备分组自动轮换 · 每 15 秒</div></section>
|
||||
<section class="tv-family-presence tv-card"><div><h2>家人位置</h2><p v-if="!positions.length">等待家人主动开启位置共享</p><div v-else class="tv-positions"><div v-for="p in positions" :key="p.id"><b>{{p.name}}</b><span :class="{warning:p.status==='stale'}">{{locationText(p)}}</span><small v-if="p.position">{{new Date(p.position.at*1000).toLocaleTimeString('zh-CN',{hour:'2-digit',minute:'2-digit'})}} 更新</small></div></div></div><span v-if="!positions.length">暂无共享位置</span></section>
|
||||
<section class="tv-family-presence tv-card"><div><h2>家人位置</h2><p v-if="!positions.length">等待家人主动开启位置共享</p><FamilyMap v-if="mapPositions.some(p=>p.position)" :items="mapPositions" :night="night" :height="220"/><div v-if="positions.length" class="tv-positions"><div v-for="p in positions" :key="p.id"><b>{{p.name}}</b><span :class="{warning:p.status==='stale'}">{{locationText(p)}}</span><small v-if="p.position">{{new Date(p.position.at*1000).toLocaleTimeString('zh-CN',{hour:'2-digit',minute:'2-digit'})}} 更新</small></div></div></div><span v-if="!positions.length">暂无共享位置</span></section>
|
||||
</div>
|
||||
<footer class="tv-footer"><span :class="{warning:!!error}"><i></i>{{syncLabel}}</span><span v-if="error" class="sync-error">{{error}}</span><span>愿每个平常日,都有家的温度</span><a href="https://open-meteo.com/" target="_blank" rel="noreferrer">天气 Open-Meteo</a></footer>
|
||||
</div>
|
||||
|
||||
@@ -11,3 +11,4 @@
|
||||
[data-theme=day] .clock-hour{stroke:#167f98}[data-theme=day] .clock-minute{stroke:#169881}[data-theme=day] .clock-second{stroke:#e05260}
|
||||
.tv-family-presence{order:-1;min-height:5vh}.tv-family-presence>div{flex:1}.tv-positions{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:1vw}.tv-positions>div{display:flex;flex-direction:column;gap:.2vh}.tv-positions b{font-size:1.1vh;font-weight:500}.tv-positions span,.tv-positions small{font-size:.85vh;color:#818b76}.tv-positions .warning{color:#bd8b5d}
|
||||
.tv-reconnect{padding:1.5vh 2vw;border:1px solid #a7774f;border-radius:1vh;background:#f3e7d7;color:#65462e;font-size:1.4vh}.tv-reconnect strong{font-size:1.8vh}.tv-reconnect p{margin:.6vh 0}.tv-reconnect button{padding:.7vh 1.5vw;border:1px solid currentColor;border-radius:.5vh;background:transparent;color:inherit;font-size:inherit}[data-theme=night] .tv-reconnect{background:#30271f;color:#c5ad8a}
|
||||
.tv-family-presence .family-map-canvas{height:clamp(130px,13vh,260px)!important;min-height:130px;margin:.5vh 0}.tv-family-presence .family-map-status{font-size:max(10px,.75vh);margin:.2vh 0}.tv-family-presence .maplibregl-ctrl-attrib{font-size:10px}
|
||||
|
||||
@@ -4,4 +4,4 @@ import {readdirSync,readFileSync} from 'node:fs'
|
||||
import {createHash} from 'node:crypto'
|
||||
const hash=createHash('sha256')
|
||||
for(const name of readdirSync('../web').filter(n=>n.endsWith('.js')).sort())hash.update(name).update(readFileSync('../web/'+name))
|
||||
export default defineConfig({define:{__LEGACY_REVISION__:JSON.stringify(hash.digest('hex').slice(0,16))},plugins:[vue({template:{transformAssetUrls:false}})],base:'/ui/',build:{target:'es2018',outDir:'../web/ui',emptyOutDir:true,assetsDir:'assets',rollupOptions:{input:{index:'index.html',tv:'tv.html'}}}})
|
||||
export default defineConfig({define:{__LEGACY_REVISION__:JSON.stringify(hash.digest('hex').slice(0,16))},plugins:[vue({template:{transformAssetUrls:false}})],base:'/ui/',build:{target:'es2018',outDir:'../web/ui',emptyOutDir:true,assetsDir:'assets',rollupOptions:{input:{index:'index.html',tv:'tv.html',map:'map.html'}}}})
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
"""Explicit opt-in, encrypted cloud history. Real-time sharing stays RAM-only.
|
||||
|
||||
SQLite holds bounded encrypted pending points and a small cloud index. The random
|
||||
encryption key is a DB setting, so the existing database backup recovers the key
|
||||
and index together. Cloud files are never public or exposed as direct links.
|
||||
"""
|
||||
import base64,datetime as dt,gzip,hashlib,json,os,secrets,shutil,threading,time
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||
|
||||
LIMIT=32*1024*1024
|
||||
MAX_READ=2*1024*1024
|
||||
READ_SLOTS=threading.BoundedSemaphore(2)
|
||||
|
||||
class History:
|
||||
def __init__(self,app):self.a=app;self.worker=threading.Lock();self.last_error=''
|
||||
|
||||
def initialize(self):
|
||||
a=self.a
|
||||
with a.LOCK,a.DB:
|
||||
a.DB.execute('CREATE TABLE IF NOT EXISTS location_history_points (id TEXT PRIMARY KEY, family TEXT, member TEXT, at REAL, payload BLOB, batch TEXT)')
|
||||
a.DB.execute('CREATE INDEX IF NOT EXISTS history_points_member ON location_history_points(member,at)')
|
||||
a.DB.execute('CREATE TABLE IF NOT EXISTS location_history_files (id TEXT PRIMARY KEY,family TEXT,member TEXT,start REAL,end REAL,body TEXT)')
|
||||
a.DB.execute('CREATE INDEX IF NOT EXISTS history_files_member ON location_history_files(member,start)')
|
||||
if not a.setting('location_history_key'):a.set_setting('location_history_key',base64.b64encode(secrets.token_bytes(32)).decode())
|
||||
|
||||
def seal(self,value,aad):
|
||||
nonce=secrets.token_bytes(12);key=base64.b64decode(self.a.setting('location_history_key'))
|
||||
return nonce+AESGCM(key).encrypt(nonce,gzip.compress(json.dumps(value,separators=(',',':')).encode()),aad.encode())
|
||||
|
||||
def unseal(self,value,aad):
|
||||
key=base64.b64decode(self.a.setting('location_history_key'))
|
||||
return json.loads(gzip.decompress(AESGCM(key).decrypt(value[:12],value[12:],aad.encode())))
|
||||
|
||||
def record(self,row,grant,fix):
|
||||
if grant.get('historyEnabled') is not True:return
|
||||
a=self.a
|
||||
with a.LOCK,a.DB:
|
||||
used=a.DB.execute('SELECT coalesce(sum(length(payload)),0) FROM location_history_points').fetchone()[0]
|
||||
if used>=LIMIT or shutil.disk_usage(a.DATA).free<1024**3:
|
||||
self.last_error='轨迹待上传空间已满,新增历史暂停;实时共享继续';return
|
||||
if a.DB.execute('SELECT 1 FROM location_history_points WHERE member=? AND at=?',(row['member_id'],fix['at'])).fetchone():return
|
||||
key=secrets.token_hex(16)
|
||||
payload=self.seal(dict(position=fix,viewers=[v['id'] for v in grant['viewers']],phones=[v['id'] for v in grant.get('phones',[])]),key)
|
||||
a.DB.execute('INSERT INTO location_history_points VALUES (?,?,?,?,?,NULL)',(key,row['family_id'],row['member_id'],fix['at'],payload))
|
||||
self.last_error=''
|
||||
|
||||
def own_status(self,member):
|
||||
a=self.a
|
||||
with a.LOCK:
|
||||
pending=a.DB.execute('SELECT count(*) FROM location_history_points WHERE member=?',(member,)).fetchone()[0]
|
||||
rows=a.DB.execute('SELECT body FROM location_history_files WHERE member=?',(member,)).fetchall()
|
||||
files=[json.loads(r[0]) for r in rows]
|
||||
return dict(pending=pending,archived=sum(f.get('state')=='cloud' for f in files),deleting=sum(f.get('state')=='deleting' for f in files),
|
||||
error=next((f.get('error') for f in files if f.get('error')),self.last_error),retention='forever')
|
||||
|
||||
def access(self,family,member,*,user=None,phone=None,delete=False):
|
||||
a=self.a
|
||||
with a.LOCK:
|
||||
if phone:
|
||||
current=a.DB.execute('SELECT * FROM member_location_shares WHERE id=? AND expires>?',(phone['id'],time.time())).fetchone()
|
||||
if not current or current['family_id']!=family or not a.LOCATIONS.eligible(family,current['member_id']):raise a.Problem('手机授权已失效',401)
|
||||
valid=a.LOCATIONS.eligible(family,member)
|
||||
if not valid:raise a.Problem('家庭成员不存在',404)
|
||||
own=bool(phone and phone['member_id']==member or user and user.get('personId')==valid[1]['id'])
|
||||
if user and (user.get('disabled') or not a.HOUSEHOLDS.grant(a.get_object('users',user['id']),family)):raise a.Problem('家庭授权已失效',403)
|
||||
if own:return ('owner',None)
|
||||
if delete:raise a.Problem('只有本人可以删除自己的历史轨迹',403)
|
||||
row=a.DB.execute('SELECT * FROM member_location_shares WHERE member_id=? AND family_id=? AND enabled=1 AND expires>?',(member,family,time.time())).fetchone()
|
||||
grant=json.loads(row['grant_json']) if row else {}
|
||||
kind='viewers' if user else 'phones';actor=user['id'] if user else phone['id'] if phone else ''
|
||||
if not grant.get('historyEnabled') or actor not in {v['id'] for v in grant.get(kind,[])}:raise a.Problem('本人未授权查看历史轨迹,或共享已关闭',403)
|
||||
return kind,actor
|
||||
|
||||
@staticmethod
|
||||
def day_range(date,period='day',until=None):
|
||||
try:
|
||||
day=dt.datetime.strptime(date,'%Y-%m-%d').replace(tzinfo=dt.timezone(dt.timedelta(hours=8)))
|
||||
if period=='life':return 0,time.time()+86400
|
||||
if period=='week':day-=dt.timedelta(days=day.weekday());end=day+dt.timedelta(days=7)
|
||||
elif period=='month':day=day.replace(day=1);end=(day.replace(day=28)+dt.timedelta(days=4)).replace(day=1)
|
||||
elif period=='year':day=day.replace(month=1,day=1);end=day.replace(year=day.year+1)
|
||||
elif period=='custom':
|
||||
end=dt.datetime.strptime(until,'%Y-%m-%d').replace(tzinfo=day.tzinfo)+dt.timedelta(days=1)
|
||||
if end<=day:raise ValueError()
|
||||
elif period=='day':end=day+dt.timedelta(days=1)
|
||||
else:raise ValueError()
|
||||
return day.timestamp(),end.timestamp()
|
||||
except (ValueError,TypeError):raise ValueError('请选择有效日期') from None
|
||||
|
||||
def query(self,*args,**kwargs):
|
||||
if not READ_SLOTS.acquire(False):raise self.a.Problem('历史读取任务较多,请稍后重试',429)
|
||||
try:return self._query(*args,**kwargs)
|
||||
finally:READ_SLOTS.release()
|
||||
|
||||
def _query(self,family,member,date,*,user=None,phone=None,period='day',until=None,cursor=0):
|
||||
a=self.a;kind,actor=self.access(family,member,user=user,phone=phone)
|
||||
try:
|
||||
start,end=self.day_range(date,period,until);cursor=int(cursor)
|
||||
if not 0<=cursor<=1000000:raise ValueError()
|
||||
except ValueError:raise a.Problem('请选择有效日期') from None
|
||||
with a.LOCK:
|
||||
generation=a.setting('history_deleted:'+member,0)
|
||||
# Pending ciphertext is globally capped at 32 MiB. Sample after access
|
||||
# filtering, across the whole interval, rather than dropping its tail.
|
||||
pending=a.DB.execute('SELECT id,payload FROM location_history_points WHERE family=? AND member=? AND at>=? AND at<? ORDER BY at',(family,member,start,end)).fetchall() if cursor==0 else []
|
||||
files=a.DB.execute('SELECT * FROM location_history_files WHERE family=? AND member=? AND end>=? AND start<? ORDER BY start,id LIMIT 9 OFFSET ?',(family,member,start,end,cursor)).fetchall()
|
||||
total=a.DB.execute('SELECT count(*) FROM location_history_files WHERE family=? AND member=? AND end>=? AND start<?',(family,member,start,end)).fetchone()[0]
|
||||
more=len(files)>8;files=files[:8]
|
||||
values=[self.unseal(r['payload'],r['id']) for r in pending]
|
||||
for row in files:
|
||||
meta=json.loads(row['body'])
|
||||
if meta.get('state')!='cloud':continue
|
||||
with a.BAIDU.open_file('shared',dict(remotePath=meta['remote'],fsId=meta['fsId'])) as response:raw=response.read(MAX_READ+1)
|
||||
if len(raw)>MAX_READ or hashlib.sha256(raw).hexdigest()!=meta['sha256']:raise a.Problem('历史轨迹校验失败,未显示数据',502)
|
||||
values.extend(self.unseal(raw,row['id']))
|
||||
# Recheck after slow cloud reads: revocation or deletion takes effect immediately.
|
||||
kind,actor=self.access(family,member,user=user,phone=phone)
|
||||
with a.LOCK:
|
||||
if generation!=a.setting('history_deleted:'+member,0):raise a.Problem('历史已删除,请重新读取',409)
|
||||
current={r[0] for r in a.DB.execute('SELECT id FROM location_history_files WHERE family=? AND member=?',(family,member))}
|
||||
if any(r['id'] not in current for r in files):raise a.Problem('轨迹已变更,请重新读取',409)
|
||||
if any(json.loads(r[0]).get('state')=='deleting' for r in a.DB.execute('SELECT body FROM location_history_files WHERE family=? AND member=?',(family,member))):raise a.Problem('轨迹正在删除',409)
|
||||
points={v['position']['at']:v['position'] for v in values if start<=v['position']['at']<end and (kind=='owner' or actor in v.get(kind,[]))}
|
||||
values=[points[k] for k in sorted(points)]
|
||||
if values:
|
||||
for point in (values[0],values[-1]):
|
||||
try:a.MAPS.archive.for_point(point)
|
||||
except Exception:pass
|
||||
if len(values)>4000:values=[values[round(i*(len(values)-1)/3999)] for i in range(4000)]
|
||||
return dict(points=values,date=date,period=period,retention='forever',totalFiles=total,loadedFiles=cursor+len(files),nextCursor=cursor+8 if more else None,sampled=len(points)>4000)
|
||||
|
||||
def delete(self,family,member,*,user=None,phone=None):
|
||||
self.access(family,member,user=user,phone=phone,delete=True);a=self.a
|
||||
with a.LOCK,a.DB:
|
||||
a.set_setting('history_deleted:'+member,time.time())
|
||||
a.DB.execute('DELETE FROM location_history_points WHERE family=? AND member=?',(family,member))
|
||||
for row in a.DB.execute('SELECT id,body FROM location_history_files WHERE family=? AND member=?',(family,member)).fetchall():
|
||||
meta=json.loads(row['body']);meta.update(state='deleting',nextTry=0,error='')
|
||||
a.DB.execute('UPDATE location_history_files SET body=? WHERE id=?',(json.dumps(meta),row['id']))
|
||||
return dict(ok=True,message='历史已隐藏,云端删除任务会继续重试直至完成')
|
||||
|
||||
def native(self,token,body):
|
||||
a=self.a
|
||||
with a.LOCK:
|
||||
row=a.DB.execute('SELECT * FROM member_location_shares WHERE token_hash=? AND expires>?',(hashlib.sha256(token.encode()).hexdigest(),time.time())).fetchone()
|
||||
if not row or not a.LOCATIONS.eligible(row['family_id'],row['member_id']):raise a.Problem('手机配对已失效',401)
|
||||
row=dict(row)
|
||||
member=body.get('memberId') or row['member_id']
|
||||
if body['action']=='history-delete':
|
||||
if body.get('confirm') is not True:raise a.Problem('请确认删除历史轨迹')
|
||||
return self.delete(row['family_id'],member,phone=row)
|
||||
return self.query(row['family_id'],member,body.get('date'),phone=row,period=body.get('period','day'),until=body.get('until'),cursor=body.get('cursor',0))
|
||||
|
||||
def package(self):
|
||||
a=self.a
|
||||
with a.LOCK,a.DB:
|
||||
seed=a.DB.execute('SELECT * FROM location_history_points WHERE batch IS NULL AND at<? ORDER BY at LIMIT 1',(time.time()-3600,)).fetchone()
|
||||
if not seed:return
|
||||
rows=a.DB.execute('SELECT * FROM location_history_points WHERE batch IS NULL AND family=? AND member=? AND at<? ORDER BY at LIMIT 1000',(seed['family'],seed['member'],seed['at']+3600)).fetchall()
|
||||
key=secrets.token_hex(16);date=dt.datetime.fromtimestamp(seed['at'],dt.timezone(dt.timedelta(hours=8)))
|
||||
remote='/apps/'+a.BAIDU.public_config()['appFolder']+'/家庭轨迹/'+seed['family']+'/'+seed['member']+'/'+date.strftime('%Y/%m/%d/')+key+'.track'
|
||||
meta=dict(state='pending',remote=remote,attempts=0,nextTry=0)
|
||||
a.DB.execute('INSERT INTO location_history_files VALUES (?,?,?,?,?,?)',(key,seed['family'],seed['member'],rows[0]['at'],rows[-1]['at'],json.dumps(meta)))
|
||||
a.DB.executemany('UPDATE location_history_points SET batch=? WHERE id=?',[(key,r['id']) for r in rows])
|
||||
|
||||
def process(self,row):
|
||||
a=self.a;meta=json.loads(row['body']);file=a.DATA/('history-'+row['id']+'.partial')
|
||||
try:
|
||||
if meta['state']=='deleting':
|
||||
# Even an interrupted upload has a deterministic path to clean up.
|
||||
a.BAIDU.delete_history_file(meta['remote'])
|
||||
with a.LOCK,a.DB:a.DB.execute('DELETE FROM location_history_files WHERE id=?',(row['id'],))
|
||||
return
|
||||
with a.LOCK:points=a.DB.execute('SELECT id,payload FROM location_history_points WHERE batch=? ORDER BY at',(row['id'],)).fetchall()
|
||||
if not points:return
|
||||
raw=self.seal([self.unseal(p['payload'],p['id']) for p in points],row['id'])
|
||||
# Persist stable ciphertext before upload: retries must use exactly the same bytes.
|
||||
with a.LOCK,a.DB:
|
||||
current=json.loads(a.DB.execute('SELECT body FROM location_history_files WHERE id=?',(row['id'],)).fetchone()[0])
|
||||
if current['state']=='deleting':return
|
||||
if current.get('payload'):raw=base64.b64decode(current['payload'])
|
||||
else:current['payload']=base64.b64encode(raw).decode();a.DB.execute('UPDATE location_history_files SET body=? WHERE id=?',(json.dumps(current),row['id']))
|
||||
file.write_bytes(raw)
|
||||
result=a.BAIDU.upload('shared',file,meta['remote']);digest=hashlib.sha256(raw).hexdigest()
|
||||
a.BAIDU.verify_file(meta['remote'],str(result['fs_id']),len(raw),digest)
|
||||
with a.LOCK,a.DB:
|
||||
current=json.loads(a.DB.execute('SELECT body FROM location_history_files WHERE id=?',(row['id'],)).fetchone()[0])
|
||||
if current['state']!='deleting':current.update(state='cloud',fsId=str(result['fs_id']),sha256=digest,bytes=len(raw),error='')
|
||||
current.pop('payload',None)
|
||||
a.DB.execute('UPDATE location_history_files SET body=? WHERE id=?',(json.dumps(current),row['id']))
|
||||
a.DB.execute('DELETE FROM location_history_points WHERE batch=?',(row['id'],))
|
||||
except Exception:
|
||||
with a.LOCK,a.DB:
|
||||
current=a.DB.execute('SELECT body FROM location_history_files WHERE id=?',(row['id'],)).fetchone()
|
||||
if current:
|
||||
current=json.loads(current[0]);attempt=current.get('attempts',0)+1
|
||||
current.update(attempts=attempt,nextTry=time.time()+min(21600,60*2**min(attempt,8)),error='网盘任务未完成,将自动重试;本地待上传资料保留')
|
||||
a.DB.execute('UPDATE location_history_files SET body=? WHERE id=?',(json.dumps(current),row['id']))
|
||||
finally:file.unlink(missing_ok=True)
|
||||
|
||||
def tick(self):
|
||||
if not self.worker.acquire(False):return
|
||||
try:
|
||||
self.package()
|
||||
with self.a.LOCK:rows=self.a.DB.execute('SELECT * FROM location_history_files ORDER BY start').fetchall()
|
||||
for row in rows:
|
||||
meta=json.loads(row['body'])
|
||||
if meta['state']!='cloud' and meta.get('nextTry',0)<=time.time():self.process(dict(row));break
|
||||
finally:self.worker.release()
|
||||
|
||||
def watch(self):
|
||||
while True:
|
||||
try:self.tick()
|
||||
except Exception:self.last_error='历史归档暂未完成,将自动重试'
|
||||
time.sleep(30)
|
||||
File diff suppressed because one or more lines are too long
+163
@@ -0,0 +1,163 @@
|
||||
"""One bounded map download/archive worker. Public geography only, no family data."""
|
||||
from pathlib import Path
|
||||
import hashlib,json,os,shutil,subprocess,threading,time
|
||||
import map_regions
|
||||
|
||||
GB=1024**3
|
||||
SOURCE='20261017'
|
||||
LIMIT=3*GB
|
||||
RESERVE=10*GB
|
||||
JOB_LIMIT=2*GB
|
||||
|
||||
class Archive:
|
||||
def __init__(self,maps):
|
||||
self.maps=maps;self.a=maps.app;self.guard=threading.RLock();self.wake=threading.Event()
|
||||
self.running=threading.Lock();self.last_seen={};self.last_error=''
|
||||
|
||||
def read(self):
|
||||
try:return json.loads((self.maps.root/'archive.json').read_text(encoding='utf8'))
|
||||
except (OSError,ValueError):
|
||||
return self.a.setting('map_archive',{'entries':{}}) if hasattr(self.a,'setting') else {'entries':{}}
|
||||
|
||||
def write(self,data):
|
||||
self.maps.root.mkdir(parents=True,exist_ok=True)
|
||||
tmp=self.maps.root/'archive.partial';tmp.write_text(json.dumps(data,ensure_ascii=False),encoding='utf8');os.replace(tmp,self.maps.root/'archive.json')
|
||||
# The ordinary database backup also carries the cloud file index.
|
||||
if hasattr(self.a,'set_setting'):self.a.set_setting('map_archive',data)
|
||||
|
||||
def specs(self):
|
||||
return {'world':dict(id='world',name='世界概览',bounds=[-180,-85,180,85],maxZoom=6),
|
||||
'china':dict(id='china',name='全国概览',bounds=map_regions.CHINA,maxZoom=9),**map_regions.definitions()}
|
||||
|
||||
def observe(self,fix):
|
||||
if not fix or time.time()-fix['at']>900 or fix.get('accuracy',0)>10000:return
|
||||
self.for_point(fix)
|
||||
|
||||
def for_point(self,fix):
|
||||
p=map_regions.locate(fix['longitude'],fix['latitude'])
|
||||
if p:self.request(p['id'])
|
||||
|
||||
def request(self,key):
|
||||
if key not in self.specs():raise self.a.Problem('地图区域不存在',404)
|
||||
now=time.time()
|
||||
with self.guard:
|
||||
self.last_seen[key]=now
|
||||
data=self.read();entry=data['entries'].setdefault(key,dict(state='queued',attempts=0,nextTry=0))
|
||||
if entry.get('state')=='cloud':entry.update(state='queued',nextTry=0,attempts=0)
|
||||
if now-entry.get('used',0)>3600 or entry['state']=='queued':
|
||||
entry['used']=now;self.write(data)
|
||||
self.wake.set()
|
||||
|
||||
def status(self):
|
||||
with self.guard:data=self.read()
|
||||
specs=self.specs();items=[]
|
||||
for key,e in data['entries'].items():
|
||||
if key not in specs:continue
|
||||
file=self.maps.root/(key+'.pmtiles')
|
||||
items.append(dict(id=key,name=specs[key]['name'],state=e.get('state','queued'),bytes=e.get('bytes',0),
|
||||
localBytes=file.stat().st_size if file.exists() else 0,cloud=bool(e.get('remote')),error=e.get('error',''),progress=e.get('progress',0)))
|
||||
return dict(items=items,cacheLimitBytes=LIMIT,usedBytes=self.used(),reserveBytes=RESERVE,error=self.last_error)
|
||||
|
||||
def used(self):
|
||||
return sum(p.stat().st_size for p in self.maps.root.glob('*.pmtiles*') if p.is_file())
|
||||
|
||||
def update(self,key,**fields):
|
||||
with self.guard:
|
||||
data=self.read();data['entries'].setdefault(key,{}).update(fields);self.write(data)
|
||||
|
||||
def room(self,need=0,exclude=''):
|
||||
"""Only verified cloud copies can be evicted; national overviews stay pinned."""
|
||||
with self.guard:
|
||||
data=self.read()
|
||||
for key,e in sorted(data['entries'].items(),key=lambda kv:kv[1].get('used',0)):
|
||||
if self.used()+need<=LIMIT and shutil.disk_usage(self.maps.root).free-need>=RESERVE:return
|
||||
if key in ('world','china',exclude) or not e.get('remote') or time.time()-self.last_seen.get(key,0)<3600:continue
|
||||
file=self.maps.root/(key+'.pmtiles')
|
||||
if file.exists():file.unlink();e['state']='cloud';self.write(data)
|
||||
if self.used()+need>LIMIT or shutil.disk_usage(self.maps.root).free-need<RESERVE:
|
||||
raise self.a.Problem('地图缓存空间不足,已暂停下载;可用全国概览',507)
|
||||
|
||||
def binary(self):return os.environ.get('VISION_PMTILES','/opt/zhaovision/tools/pmtiles')
|
||||
|
||||
def extract(self,key,spec,temp):
|
||||
args=[self.binary(),'extract','https://build.protomaps.com/'+SOURCE+'.pmtiles',str(temp),
|
||||
'--maxzoom='+str(spec['maxZoom']),'--download-threads=2','-q']
|
||||
if key!='world':args+=['--bbox='+','.join(map(str,spec['bounds']))]
|
||||
# No shell or client-controlled URL. Only known public province bounds leave server.
|
||||
env=dict(os.environ,GOMEMLIMIT='192MiB',GOMAXPROCS='1')
|
||||
child=subprocess.Popen(args,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,env=env,
|
||||
creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))
|
||||
deadline=time.monotonic()+5400
|
||||
try:
|
||||
while child.poll() is None:
|
||||
time.sleep(2);size=temp.stat().st_size if temp.exists() else 0
|
||||
if size>JOB_LIMIT or time.monotonic()>deadline:raise self.a.Problem('地图包超过单任务容量或时间限制,已暂停',507)
|
||||
self.room(exclude=key);self.update(key,bytes=size)
|
||||
if child.returncode:raise self.a.Problem('地图源下载未完成,稍后自动重试',502)
|
||||
finally:
|
||||
if child.poll() is None:child.kill();child.wait(timeout=10)
|
||||
if not temp.exists() or not 0<temp.stat().st_size<=JOB_LIMIT:raise self.a.Problem('地图包大小不正确',502)
|
||||
subprocess.run([self.binary(),'verify',str(temp)],check=True,timeout=180,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,
|
||||
creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))
|
||||
|
||||
def restore(self,entry,temp,key):
|
||||
self.room(entry['bytes'],exclude=key)
|
||||
sha=hashlib.sha256();size=0
|
||||
with self.a.BAIDU.open_file('shared',dict(remotePath=entry['remote'],fsId=entry['fsId'])) as r,temp.open('wb') as out:
|
||||
while chunk:=r.read(256*1024):
|
||||
size+=len(chunk)
|
||||
if size>entry['bytes'] or size>JOB_LIMIT:raise self.a.Problem('云端地图大小不正确',502)
|
||||
if shutil.disk_usage(self.maps.root).free<RESERVE:raise self.a.Problem('磁盘预留空间不足,已暂停',507)
|
||||
out.write(chunk);sha.update(chunk)
|
||||
if size!=entry['bytes'] or sha.hexdigest()!=entry['sha256']:raise self.a.Problem('云端地图校验失败,未使用文件',502)
|
||||
|
||||
def process(self,key,entry):
|
||||
file=self.maps.root/(key+'.pmtiles');temp=self.maps.root/(key+'.pmtiles.part');spec=self.specs()[key]
|
||||
try:
|
||||
if not file.exists():
|
||||
temp.unlink(missing_ok=True);self.room(64*1024*1024,exclude=key)
|
||||
self.update(key,state='restoring' if entry.get('remote') else 'downloading',error='',progress=0)
|
||||
if entry.get('remote'):self.restore(entry,temp,key)
|
||||
else:self.extract(key,spec,temp)
|
||||
self.room(exclude=key);os.replace(temp,file)
|
||||
size=file.stat().st_size;self.update(key,bytes=size,state='ready' if entry.get('remote') else 'uploading')
|
||||
if not entry.get('remote'):
|
||||
with file.open('rb') as r:digest=hashlib.file_digest(r,'sha256').hexdigest()
|
||||
root='/apps/'+self.a.BAIDU.public_config()['appFolder']+'/地图/底图/'+SOURCE
|
||||
remote=root+'/'+key+'-'+digest[:16]+'.pmtiles'
|
||||
result=self.a.BAIDU.upload('shared',file,remote,lambda n,total:self.update(key,progress=round(n*100/max(1,total))))
|
||||
self.update(key,state='verifying')
|
||||
self.a.BAIDU.verify_file(remote,str(result['fs_id']),size,digest)
|
||||
self.update(key,remote=remote,fsId=str(result['fs_id']),sha256=digest,bytes=size)
|
||||
self.update(key,state='ready',attempts=0,nextTry=0,error='',progress=100)
|
||||
except Exception as error:
|
||||
attempts=entry.get('attempts',0)+1
|
||||
message=str(error) if isinstance(error,self.a.Problem) else '地图任务未完成,稍后自动重试'
|
||||
self.update(key,state='retry',error=message,attempts=attempts,nextTry=time.time()+min(21600,60*2**min(attempts,8)))
|
||||
finally:temp.unlink(missing_ok=True)
|
||||
|
||||
def tick(self):
|
||||
if not self.running.acquire(False):return
|
||||
try:
|
||||
with self.guard:
|
||||
data=self.read()
|
||||
for key,e in data['entries'].items():
|
||||
if key in self.specs() and e.get('state')=='ready' and not (self.maps.root/(key+'.pmtiles')).exists():e['state']='cloud' if e.get('remote') else 'queued'
|
||||
for key in ('world','china'):
|
||||
entry=data['entries'].setdefault(key,dict(state='queued',attempts=0,used=time.time()))
|
||||
if entry.get('state')=='cloud':entry.update(state='queued',nextTry=0)
|
||||
# Import only known files placed by the deployment, not arbitrary paths.
|
||||
for key in self.specs():
|
||||
if (self.maps.root/(key+'.pmtiles')).is_file():data['entries'].setdefault(key,dict(state='queued',attempts=0,used=time.time()))
|
||||
self.write(data)
|
||||
for key,e in data['entries'].items():
|
||||
if key in self.specs() and e.get('state') not in ('ready','cloud') and e.get('nextTry',0)<=time.time():
|
||||
self.process(key,e);break
|
||||
self.room()
|
||||
finally:self.running.release()
|
||||
|
||||
def watch(self):
|
||||
while True:
|
||||
try:self.tick();self.last_error=''
|
||||
except Exception:self.last_error='地图缓存检查未完成,将自动重试'
|
||||
self.wake.wait(20);self.wake.clear()
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Local WGS84 province lookup; coordinates never leave the application."""
|
||||
import json
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
CHINA = [73, 3, 135.2, 53.7]
|
||||
@lru_cache(maxsize=1)
|
||||
def provinces():
|
||||
return json.loads((Path(__file__).parent/'map-provinces.json').read_text(encoding='utf8'))['features']
|
||||
|
||||
def contains(bounds, lon, lat):
|
||||
return bounds[0] <= lon <= bounds[2] and bounds[1] <= lat <= bounds[3]
|
||||
|
||||
def ring_inside(ring, x, y):
|
||||
inside=False
|
||||
for i,(ax,ay) in enumerate(ring):
|
||||
bx,by=ring[i-1]
|
||||
if (ay>y)!=(by>y) and x < (bx-ax)*(y-ay)/(by-ay)+ax: inside=not inside
|
||||
return inside
|
||||
|
||||
def locate(lon,lat):
|
||||
for f in provinces():
|
||||
if not contains(f['properties']['bounds'],lon,lat): continue
|
||||
geom=f['geometry'];polygons=geom['coordinates'] if geom['type']=='MultiPolygon' else [geom['coordinates']]
|
||||
if any(ring_inside(p[0],lon,lat) and not any(ring_inside(h,lon,lat) for h in p[1:]) for p in polygons):
|
||||
return f['properties']
|
||||
return None
|
||||
|
||||
def definitions():
|
||||
return {p['properties']['id']:p['properties'] for p in provinces()}
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Same-origin public basemap gateway. Never receives member tokens or coordinates.
|
||||
|
||||
Only immutable geography is cached; family locations stay on the existing auth APIs.
|
||||
The bundled PMTiles daemon listens on loopback and reads prebuilt archives.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
import urllib.parse
|
||||
import map_archive
|
||||
|
||||
SLOTS = threading.BoundedSemaphore(6)
|
||||
MAX_TILE = 2 * 1024 * 1024
|
||||
|
||||
|
||||
class Maps:
|
||||
def __init__(self, app):
|
||||
self.app = app
|
||||
self.root = Path(os.environ.get('VISION_MAP_DATA', app.DATA / 'maps')).resolve()
|
||||
self.port = int(os.environ.get('VISION_MAP_PORT', '8841'))
|
||||
self.archive = map_archive.Archive(self)
|
||||
|
||||
def catalog(self):
|
||||
# Readiness comes from atomic, verified archive installation, never a partial.
|
||||
regions=[]
|
||||
for key,spec in self.archive.specs().items():
|
||||
file=self.root/(key+'.pmtiles')
|
||||
if file.is_file():regions.append(dict(spec,revision=str(file.stat().st_mtime_ns)))
|
||||
return dict(revision='|'.join(r['id']+r['revision'] for r in regions),regions=regions,
|
||||
attribution='© OpenStreetMap contributors · Protomaps')
|
||||
|
||||
def respond(self, handler, raw, mime, *, status=200, encoding=None, cache=True):
|
||||
handler.send_response(status)
|
||||
handler.send_header('Content-Type', mime)
|
||||
handler.send_header('Content-Length', str(len(raw)))
|
||||
handler.send_header('X-Content-Type-Options', 'nosniff')
|
||||
handler.send_header('Cache-Control', 'public, max-age=3600' if status==200 and cache else 'no-store')
|
||||
if encoding: handler.send_header('Content-Encoding', encoding)
|
||||
handler.end_headers()
|
||||
if handler.command != 'HEAD': handler.wfile.write(raw)
|
||||
|
||||
def serve(self, handler, path):
|
||||
if path == '/maps/catalog.json':
|
||||
self.respond(handler, json.dumps(self.catalog(), ensure_ascii=False).encode(), 'application/json; charset=utf-8',cache=False)
|
||||
return
|
||||
match = re.fullmatch(r'/maps/tiles/(world|china|cn-\d{2})/(\d{1,2})/(\d{1,5})/(\d{1,5})\.mvt', path)
|
||||
if match:
|
||||
name,z,x,y=match.groups(); z,x,y=map(int,(z,x,y))
|
||||
spec=self.archive.specs().get(name)
|
||||
if not spec or z > spec['maxZoom'] or not 0<=x<2**z or not 0<=y<2**z:
|
||||
raise self.app.Problem('地图层级不存在', 404)
|
||||
if not (self.root/(name+'.pmtiles')).is_file():
|
||||
self.respond(handler,b'','application/vnd.mapbox-vector-tile',status=204);return
|
||||
if not SLOTS.acquire(blocking=False): raise self.app.Problem('地图正在加载,请稍后重试', 503)
|
||||
connection = http.client.HTTPConnection('127.0.0.1', self.port, timeout=4)
|
||||
try:
|
||||
# No browser headers, cookies, bearer tokens, queries or user URLs forwarded.
|
||||
connection.request('GET', f'/{name}/{z}/{x}/{y}.mvt', headers={'Accept-Encoding':'gzip'})
|
||||
response=connection.getresponse()
|
||||
if response.status in (204,404):
|
||||
self.respond(handler,b'', 'application/vnd.mapbox-vector-tile',status=204);return
|
||||
if response.status!=200: raise self.app.Problem('内置地图暂时不可用',503)
|
||||
raw=response.read(MAX_TILE+1)
|
||||
if len(raw)>MAX_TILE: raise self.app.Problem('地图数据超出限制',502)
|
||||
encoding=response.getheader('Content-Encoding')
|
||||
if encoding not in (None,'gzip'): raise self.app.Problem('地图编码不支持',502)
|
||||
self.respond(handler,raw,'application/vnd.mapbox-vector-tile',encoding=encoding)
|
||||
except (OSError,http.client.HTTPException):
|
||||
raise self.app.Problem('内置地图暂时不可用',503)
|
||||
finally:
|
||||
connection.close();SLOTS.release()
|
||||
return
|
||||
asset=urllib.parse.unquote(path.removeprefix('/maps/assets/'))
|
||||
if path.startswith('/maps/assets/') and (re.fullmatch(r'fonts/(?:Noto Sans (?:Regular|Medium|Italic)|Noto Sans Devanagari Regular)/(?:\d{1,5}-\d{1,5}\.pbf)',asset) or re.fullmatch(r'sprites/v4/(?:light|dark)(?:@2x)?\.(?:json|png)',asset)):
|
||||
file=(self.root/'assets'/asset).resolve()
|
||||
if not file.is_relative_to(self.root/'assets') or not file.is_file(): raise self.app.Problem('地图资源不存在',404)
|
||||
if file.stat().st_size>MAX_TILE: raise self.app.Problem('地图资源超出限制',502)
|
||||
mime='image/png' if file.suffix=='.png' else 'application/json' if file.suffix=='.json' else 'application/x-protobuf'
|
||||
self.respond(handler,file.read_bytes(),mime);return
|
||||
raise self.app.Problem('地图资源不存在',404)
|
||||
+26
-4
@@ -1,4 +1,4 @@
|
||||
"""Member-bound location sharing. Pairing is not consent; coordinates are RAM-only."""
|
||||
"""Member-bound sharing. Live fixes stay in RAM; history needs separate consent."""
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
@@ -86,7 +86,7 @@ class Locations:
|
||||
grant=dict(memberId=member['id'],personId=person['id'],memberName=person['name'],familyId=family,
|
||||
home=a.get_object('households',family)['name'],until=now+600,expires=now+days*86400,
|
||||
**chosen,viewOnly=view_only,intervalSeconds=300,createdBy=user['id'],
|
||||
consentProtocol=3 if view_only or chosen['phones'] else 2)
|
||||
historyDefault=True,consentProtocol=3 if view_only or chosen['phones'] else 2)
|
||||
self.refresh_receipt(grant)
|
||||
self.codes[digest]=grant
|
||||
return dict(code=code,validSeconds=600,expires=grant['expires'])
|
||||
@@ -116,6 +116,24 @@ 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') in ('history-list','history-delete'):
|
||||
return self.a.HISTORY.native(token,body)
|
||||
result=self._native(token,body)
|
||||
if body.get('action')=='update' and body.get('position') and body.get('signal')=='available':
|
||||
with self.a.LOCK:
|
||||
row=self.a.DB.execute('SELECT * FROM member_location_shares WHERE token_hash=? AND enabled=1 AND expires>?',(hashlib.sha256(token.encode()).hexdigest(),time.time())).fetchone()
|
||||
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)
|
||||
else:fix=None
|
||||
else:fix=None
|
||||
if fix:
|
||||
try:self.a.MAPS.archive.observe(fix)
|
||||
except Exception:pass # A public map outage cannot break real-time sharing.
|
||||
return result
|
||||
|
||||
def _native(self, token, body):
|
||||
a=self.a;now=time.time()
|
||||
if not isinstance(token,str) or len(token)!=43:raise a.Problem('需要手机配对授权',401)
|
||||
with a.LOCK,a.DB:
|
||||
@@ -135,14 +153,18 @@ class Locations:
|
||||
return dict(viewers=users,displays=displays,phones=[p for p in self.phones(row['family_id']) if p['id']!=sid],
|
||||
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))
|
||||
intervalSeconds=grant.get('intervalSeconds',300),viewOnly=grant.get('viewOnly',False),
|
||||
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 any(chosen.values()):raise a.Problem('至少选择一位查看人;只查看家人无需开启自己的共享')
|
||||
grant.update(chosen,viewOnly=False,intervalSeconds=interval,consentProtocol=3)
|
||||
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.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)
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
cryptography>=46.0.5,<51
|
||||
@@ -38,7 +38,7 @@ class AndroidLocationContractTests(unittest.TestCase):
|
||||
self.assertEqual(launchers, ['.LocationActivity'])
|
||||
self.assertEqual(television, ['.MainActivity'])
|
||||
self.assertEqual(manifest.get(NS+'versionName'), (ROOT/'VERSION').read_text().strip())
|
||||
self.assertEqual(manifest.get(NS+'versionCode'), '4')
|
||||
self.assertGreaterEqual(int(manifest.get(NS+'versionCode')), 5)
|
||||
|
||||
def test_collection_is_visible_foreground_and_never_boot_started(self):
|
||||
manifest = ET.parse(ANDROID/'AndroidManifest.xml').getroot()
|
||||
@@ -54,14 +54,21 @@ class AndroidLocationContractTests(unittest.TestCase):
|
||||
self.assertIn('new int[]{10,60,300}', ui)
|
||||
self.assertIn('consent.isChecked()', ui)
|
||||
|
||||
def test_map_has_local_assets_no_external_coordinate_requests(self):
|
||||
def test_map_uses_first_party_tiles_and_never_exposes_pairing_token(self):
|
||||
source = (ANDROID/'src/cn/ucvl/zhaodisplay/LocationMapView.java').read_text(encoding='utf-8')
|
||||
self.assertIn('getAssets().open("world-land.json")', source)
|
||||
self.assertNotIn('http', source)
|
||||
build = (ANDROID/'build.ps1').read_text(encoding='utf-8')
|
||||
for name in ('world-land.json', 'WORLD-LAND-LICENSE.txt'):
|
||||
self.assertIn(name, build)
|
||||
self.assertTrue((ROOT/'frontend/src/data'/name).exists())
|
||||
for text in ('https://zhao.ucvl.cn/maps/phone','shouldInterceptRequest','setGeolocationEnabled(false)','setAllowFileAccess(false)','JSONObject.quote','setItems(new JSONArray())'):
|
||||
self.assertIn(text,source)
|
||||
self.assertNotIn('addJavascriptInterface',source)
|
||||
self.assertNotIn('getSharedPreferences',source)
|
||||
def test_background_permission_only_in_phone_and_separately_requested(self):
|
||||
for name,expected in [('AndroidManifest.xml',True),('AndroidManifest-terminal.xml',False)]:
|
||||
manifest=ET.parse(ANDROID/name).getroot()
|
||||
permissions=[x.get(NS+'name') for x in manifest.findall('uses-permission')]
|
||||
self.assertEqual('android.permission.ACCESS_BACKGROUND_LOCATION' in permissions,expected)
|
||||
source=(ANDROID/'src/cn/ucvl/zhaodisplay/LocationActivity.java').read_text(encoding='utf-8')
|
||||
self.assertIn('ACTION_APPLICATION_DETAILS_SETTINGS',source)
|
||||
self.assertIn('new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION},48',source)
|
||||
self.assertIn('if(request==47||request==48){render();return;}',source)
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import io,json,time,unittest
|
||||
from unittest.mock import patch
|
||||
import test_phone_locations as fixtures
|
||||
app=fixtures.app
|
||||
|
||||
class HistoryTests(unittest.TestCase):
|
||||
setUp=fixtures.PhoneLocationTests.setUp
|
||||
stop_server=fixtures.PhoneLocationTests.stop_server
|
||||
phone=fixtures.PhoneLocationTests.phone
|
||||
configure=fixtures.PhoneLocationTests.configure
|
||||
start=fixtures.PhoneLocationTests.start
|
||||
point=fixtures.PhoneLocationTests.point
|
||||
def date(self):return time.strftime('%Y-%m-%d',time.gmtime(time.time()+8*3600))
|
||||
def history(self,phone,source=None):
|
||||
return app.LOCATIONS.native(phone['token'],dict(action='history-list',date=self.date(),memberId=(source or phone)['member']['id']))
|
||||
def enabled(self):
|
||||
source,viewer=self.phone('本人'),self.phone('查看人')
|
||||
self.configure(source,phoneIds=[viewer['sid']],historyEnabled=True,historyConsent=True)
|
||||
self.start(source);self.point(source)
|
||||
return source,viewer
|
||||
def package(self):
|
||||
with patch('location_history.time.time',return_value=time.time()+3601):app.HISTORY.package()
|
||||
return dict(app.DB.execute('SELECT * FROM location_history_files').fetchone())
|
||||
def cloud(self,row):
|
||||
files={}
|
||||
def upload(key,file,remote):files[remote]=file.read_bytes();return dict(fs_id=5)
|
||||
with patch.object(app.BAIDU,'upload',side_effect=upload),patch.object(app.BAIDU,'verify_file'):
|
||||
app.HISTORY.process(row)
|
||||
return files
|
||||
def test_history_requires_separate_opt_in(self):
|
||||
p=self.phone('本人');self.configure(p,viewerIds=[self.owner['id']]);self.start(p);self.point(p)
|
||||
self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_points').fetchone()[0],0)
|
||||
with self.assertRaises(app.Problem):self.configure(p,viewerIds=[self.owner['id']],historyEnabled=True)
|
||||
def test_default_is_a_proposal_not_silent_collection(self):
|
||||
p=self.phone('新成员');settings=app.LOCATIONS.native(p['token'],dict(action='settings'))
|
||||
self.assertTrue(settings['historyDefault']);self.assertFalse(settings['historyEnabled'])
|
||||
self.assertEqual(app.HISTORY.own_status(p['member']['id'])['pending'],0)
|
||||
def test_day_week_month_year_life_and_custom_ranges(self):
|
||||
from location_history import History
|
||||
day=History.day_range('2026-10-18');week=History.day_range('2026-10-18','week');month=History.day_range('2026-10-18','month');year=History.day_range('2026-10-18','year')
|
||||
self.assertEqual(day[1]-day[0],86400);self.assertEqual(week[1]-week[0],7*86400);self.assertEqual(month[1]-month[0],31*86400);self.assertEqual(year[1]-year[0],365*86400)
|
||||
self.assertEqual(History.day_range('2026-10-18','life')[0],0)
|
||||
self.assertEqual(History.day_range('2026-10-01','custom','2026-10-18')[1]-History.day_range('2026-10-01','custom','2026-10-18')[0],18*86400)
|
||||
for period in ['bogus','custom']:
|
||||
with self.assertRaises(ValueError):History.day_range('2026-10-18',period,'2026-10-01')
|
||||
def test_ciphertext_and_explicit_recipient(self):
|
||||
p,v=self.enabled();row=app.DB.execute('SELECT payload FROM location_history_points').fetchone()
|
||||
self.assertNotIn(b'longitude',row[0]);self.assertEqual(len(self.history(v,p)['points']),1)
|
||||
with self.assertRaises(app.Problem):app.HISTORY.query(self.aid,p['member']['id'],self.date(),user=self.root)
|
||||
stranger=self.phone('无权查看人')
|
||||
with self.assertRaises(app.Problem):self.history(stranger,p)
|
||||
def test_new_viewer_does_not_get_old_points(self):
|
||||
p,v=self.enabled();n=self.phone('新查看人')
|
||||
self.configure(p,phoneIds=[v['sid'],n['sid']],historyEnabled=True,historyConsent=True);self.start(p)
|
||||
self.assertEqual(self.history(n,p)['points'],[]);self.assertEqual(len(self.history(v,p)['points']),1)
|
||||
def test_stop_revokes_read_but_owner_can_read(self):
|
||||
p,v=self.enabled();app.LOCATIONS.native(p['token'],dict(action='stop'))
|
||||
with self.assertRaises(app.Problem):self.history(v,p)
|
||||
self.assertEqual(len(self.history(p)['points']),1)
|
||||
def test_cloud_verify_before_local_release_and_restore(self):
|
||||
p,v=self.enabled();row=self.package();files=self.cloud(row)
|
||||
self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_points').fetchone()[0],0)
|
||||
self.assertEqual(json.loads(app.DB.execute('SELECT body FROM location_history_files').fetchone()[0])['state'],'cloud')
|
||||
with patch.object(app.BAIDU,'open_file',side_effect=lambda key,item:io.BytesIO(files[item['remotePath']])):
|
||||
self.assertEqual(len(self.history(v,p)['points']),1)
|
||||
def test_failed_upload_preserves_stable_ciphertext_for_retry(self):
|
||||
p,v=self.enabled();row=self.package()
|
||||
with patch.object(app.BAIDU,'upload',side_effect=OSError('failure')):app.HISTORY.process(row)
|
||||
saved=json.loads(app.DB.execute('SELECT body FROM location_history_files').fetchone()[0]);self.assertIn('payload',saved)
|
||||
self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_points').fetchone()[0],1)
|
||||
row=dict(app.DB.execute('SELECT * FROM location_history_files').fetchone());files=self.cloud(row)
|
||||
import base64
|
||||
self.assertEqual(next(iter(files.values())),base64.b64decode(saved['payload']))
|
||||
def test_failed_verification_does_not_delete_pending(self):
|
||||
p,v=self.enabled();row=self.package()
|
||||
with patch.object(app.BAIDU,'upload',return_value={'fs_id':5}),patch.object(app.BAIDU,'verify_file',side_effect=OSError()):app.HISTORY.process(row)
|
||||
self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_points').fetchone()[0],1)
|
||||
def test_only_self_can_delete_and_cloud_removal_is_queued(self):
|
||||
p,v=self.enabled();row=self.package();self.cloud(row)
|
||||
with self.assertRaises(app.Problem):app.LOCATIONS.native(v['token'],dict(action='history-delete',memberId=p['member']['id'],confirm=True))
|
||||
app.LOCATIONS.native(p['token'],dict(action='history-delete',confirm=True))
|
||||
with self.assertRaises(app.Problem):self.history(v,p)
|
||||
row=dict(app.DB.execute('SELECT * FROM location_history_files').fetchone())
|
||||
with patch.object(app.BAIDU,'delete_history_file') as remove:app.HISTORY.process(row);remove.assert_called_once()
|
||||
self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_files').fetchone()[0],0)
|
||||
def test_deleted_during_cloud_read_is_not_returned(self):
|
||||
p,v=self.enabled();row=self.package();files=self.cloud(row)
|
||||
def read(key,item):
|
||||
app.LOCATIONS.native(p['token'],dict(action='history-delete',confirm=True));return io.BytesIO(files[item['remotePath']])
|
||||
with patch.object(app.BAIDU,'open_file',side_effect=read),self.assertRaises(app.Problem):self.history(v,p)
|
||||
def test_bounds_pause_new_history_without_stopping_live(self):
|
||||
p,v=self.phone('本人'),self.phone('家人');self.configure(p,phoneIds=[v['sid']],historyEnabled=True,historyConsent=True);self.start(p)
|
||||
with patch('location_history.LIMIT',0):self.point(p)
|
||||
self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_points').fetchone()[0],0)
|
||||
self.assertTrue(app.LOCATIONS.latest[p['sid']]['fix'])
|
||||
def test_revoked_during_cloud_read_is_not_returned(self):
|
||||
p,v=self.enabled();row=self.package();files=self.cloud(row)
|
||||
def read(key,item):
|
||||
app.LOCATIONS.native(p['token'],dict(action='stop'));return io.BytesIO(files[item['remotePath']])
|
||||
with patch.object(app.BAIDU,'open_file',side_effect=read),self.assertRaises(app.Problem):self.history(v,p)
|
||||
def test_cloud_delete_failure_stays_queued_and_hidden(self):
|
||||
p,v=self.enabled();self.cloud(self.package())
|
||||
app.LOCATIONS.native(p['token'],dict(action='history-delete',confirm=True))
|
||||
row=dict(app.DB.execute('SELECT * FROM location_history_files').fetchone())
|
||||
with patch.object(app.BAIDU,'delete_history_file',side_effect=OSError('offline')):app.HISTORY.process(row)
|
||||
meta=json.loads(app.DB.execute('SELECT body FROM location_history_files').fetchone()[0])
|
||||
self.assertEqual(meta['state'],'deleting');self.assertGreater(meta['nextTry'],time.time())
|
||||
with self.assertRaises(app.Problem):self.history(p)
|
||||
def test_pending_over_ten_thousand_samples_whole_interval(self):
|
||||
p,v=self.enabled();member=p['member']['id'];base=time.time()-11000
|
||||
with app.LOCK,app.DB:
|
||||
app.DB.execute('DELETE FROM location_history_points')
|
||||
app.DB.executemany('INSERT INTO location_history_points VALUES (?,?,?,?,?,NULL)',[(str(i),self.aid,member,base+i,str(i).encode()) for i in range(10005)])
|
||||
def unseal(raw,key):return dict(position=dict(longitude=117,latitude=36,at=base+int(raw)))
|
||||
with patch.object(app.HISTORY,'unseal',side_effect=unseal):
|
||||
result=app.LOCATIONS.native(p['token'],dict(action='history-list',period='life',date=self.date()))
|
||||
self.assertEqual(len(result['points']),4000);self.assertTrue(result['sampled'])
|
||||
self.assertEqual(result['points'][0]['at'],base);self.assertEqual(result['points'][-1]['at'],base+10004)
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,26 @@
|
||||
import {test} from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {visiblePeople,accuracyCircle,regionAt,trackCollection} from './frontend/src/maps/model.mjs'
|
||||
const now=1792310000000
|
||||
const person=(id,overrides={})=>({id,name:'测试成员',status:'live',position:{longitude:117,latitude:36,accuracy:30,at:now/1000,...overrides}})
|
||||
test('only fresh valid points are visible',()=>{
|
||||
const items=[person('ok'),person('old',{at:now/1000-901}),person('bad',{longitude:Infinity}),person('future',{at:now/1000+1000}),{...person('stale'),status:'stale'},{id:'empty'}]
|
||||
assert.deepEqual(visiblePeople(items,now).map(p=>p.id),['ok']);assert.deepEqual(visiblePeople(null,now),[])
|
||||
})
|
||||
test('no future labels or invalid latitudes sneak into map',()=>{assert.equal(visiblePeople([person('bad',{latitude:90}),person('bad',{longitude:'117'})],now).length,0)})
|
||||
test('accuracy is a bounded closed polygon',()=>{const circle=accuracyCircle(person('a'));assert.equal(circle.geometry.coordinates[0].length,65);assert.ok(Math.abs(circle.geometry.coordinates[0][0][0]-117)<.001);assert.deepEqual(circle.geometry.coordinates[0][0],circle.geometry.coordinates[0][64])})
|
||||
test('coverage chooses downloaded province then overview',()=>{
|
||||
const world={id:'world',bounds:[-180,-85,180,85]},china={id:'china',bounds:[73,3,135,54]},province={id:'cn-37',bounds:[114.7,34.3,122.8,38.6]}
|
||||
assert.equal(regionAt([world,china,province],117,36),province)
|
||||
assert.equal(regionAt([world,china],117,36),china)
|
||||
assert.equal(regionAt([world,china],-.1,51),world)
|
||||
assert.equal(regionAt([],117,36),undefined)
|
||||
})
|
||||
test('tracks sort valid points and never bridge a long gap',()=>{
|
||||
const p=(at,longitude=117)=>({at,longitude,latitude:36})
|
||||
const result=trackCollection([p(4000),p(300),p(200),p(5000,Infinity),p(4100)])
|
||||
assert.equal(result.features[0].geometry.coordinates.length,2)
|
||||
assert.deepEqual(result.features.slice(1).map(f=>f.properties.at),[200,300,4000,4100])
|
||||
assert.equal(result.features[1].properties.edge,true)
|
||||
assert.equal(result.features.at(-1).properties.edge,true)
|
||||
})
|
||||
@@ -0,0 +1,46 @@
|
||||
import json,tempfile,time,unittest
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch,Mock
|
||||
import map_regions,map_service,map_archive
|
||||
from test_map_service import Problem
|
||||
|
||||
class ArchiveTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
|
||||
self.a=SimpleNamespace(DATA=Path(self.tmp.name),Problem=Problem,BAIDU=Mock())
|
||||
self.maps=map_service.Maps(self.a);self.maps.root.mkdir();self.archive=self.maps.archive
|
||||
def test_local_regions_cover_all_provinces_and_recognize_coordinates(self):
|
||||
self.assertEqual(len(map_regions.definitions()),34)
|
||||
for lon,lat,key in [(117.03,36.67,'cn-37'),(116.4,39.9,'cn-11'),(121.47,31.23,'cn-31'),(113.26,23.13,'cn-44'),(114.17,22.3,'cn-81'),(121.56,25.03,'cn-71')]:
|
||||
self.assertEqual(map_regions.locate(lon,lat)['id'],key)
|
||||
self.assertIsNone(map_regions.locate(-.1,51))
|
||||
def test_arrival_deduplicates_and_never_stores_coordinates(self):
|
||||
for _ in range(3):self.archive.observe(dict(longitude=117.03,latitude=36.67,accuracy=10,at=time.time()))
|
||||
data=self.archive.read();self.assertEqual(list(data['entries']),['cn-37'])
|
||||
self.assertNotIn('longitude',json.dumps(data));self.assertNotIn('117.03',json.dumps(data))
|
||||
def test_eviction_only_after_verified_cloud_copy(self):
|
||||
for key in ['world','cn-37','cn-11']:(self.maps.root/(key+'.pmtiles')).write_bytes(b'1'*10)
|
||||
self.archive.write(dict(entries={'world':dict(remote='cloud'),'cn-37':dict(remote='verified'),'cn-11':dict(state='retry')}))
|
||||
with patch('map_archive.LIMIT',20),patch('map_archive.RESERVE',0):self.archive.room()
|
||||
self.assertTrue((self.maps.root/'world.pmtiles').exists());self.assertFalse((self.maps.root/'cn-37.pmtiles').exists());self.assertTrue((self.maps.root/'cn-11.pmtiles').exists())
|
||||
def test_active_cache_not_evicted_under_pressure(self):
|
||||
(self.maps.root/'cn-37.pmtiles').write_bytes(b'123')
|
||||
self.archive.write(dict(entries={'cn-37':dict(remote='verified')}));self.archive.last_seen['cn-37']=time.time()
|
||||
with patch('map_archive.LIMIT',1),patch('map_archive.RESERVE',0),self.assertRaises(Problem):self.archive.room()
|
||||
def test_no_cloud_mark_until_verify_success(self):
|
||||
file=self.maps.root/'cn-37.pmtiles';file.write_bytes(b'123')
|
||||
self.a.BAIDU.public_config.return_value={'appFolder':'fixture'};self.a.BAIDU.upload.return_value={'fs_id':4};self.a.BAIDU.verify_file.side_effect=OSError()
|
||||
self.archive.process('cn-37',{})
|
||||
e=self.archive.read()['entries']['cn-37'];self.assertFalse(e.get('remote'));self.assertEqual(e['state'],'retry');self.assertTrue(file.exists())
|
||||
def test_unlisted_or_untrusted_job_rejected(self):
|
||||
for key in ['../../vision.db','http://bad','cn-99']:
|
||||
with self.assertRaises(Problem):self.archive.request(key)
|
||||
def test_pinned_overview_restores_after_local_loss(self):
|
||||
self.archive.write(dict(entries={'world':dict(state='ready',remote='verified',bytes=10)}))
|
||||
with patch.object(self.archive,'process') as process,patch.object(self.archive,'room'):
|
||||
self.archive.tick()
|
||||
self.assertEqual(process.call_args.args[0],'world')
|
||||
self.assertEqual(self.archive.read()['entries']['world']['state'],'queued')
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,59 @@
|
||||
import io,json,tempfile,threading,unittest
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer
|
||||
from unittest.mock import patch
|
||||
import map_service
|
||||
|
||||
class Problem(Exception):
|
||||
def __init__(self,message,status=400):super().__init__(message);self.status=status
|
||||
|
||||
class Output:
|
||||
command='GET'
|
||||
def __init__(self):self.headers={};self.wfile=io.BytesIO()
|
||||
def send_response(self,status):self.status=status
|
||||
def send_header(self,key,value):self.headers[key]=value
|
||||
def end_headers(self):pass
|
||||
|
||||
class MapServiceTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
|
||||
self.maps=map_service.Maps(SimpleNamespace(DATA=Path(self.tmp.name),Problem=Problem));self.maps.root.mkdir()
|
||||
def test_catalog_reports_missing_not_fake_coverage(self):
|
||||
self.assertEqual(self.maps.catalog()['regions'],[])
|
||||
(self.maps.root/'world.pmtiles').write_bytes(b'fixture')
|
||||
(self.maps.root/'china.pmtiles.part').write_bytes(b'partial')
|
||||
out=Output();self.maps.serve(out,'/maps/catalog.json')
|
||||
self.assertNotIn('secret',json.loads(out.wfile.getvalue()));self.assertEqual(out.status,200)
|
||||
self.assertEqual([r['id'] for r in self.maps.catalog()['regions']],['world'])
|
||||
def test_paths_and_tile_coordinates_are_bounded(self):
|
||||
for path in ['/maps/assets/../../vision.db','/maps/assets/fonts/%2e%2e/vision.db','/maps/tiles/world/7/0/0.mvt','/maps/tiles/world/3/8/0.mvt','/maps/tiles/shandong/16/0/0.mvt','/maps/tiles/http://evil/x','/maps/tiles/world/1/-1/0.mvt']:
|
||||
with self.subTest(path=path),self.assertRaises(Problem):self.maps.serve(Output(),path)
|
||||
def test_font_and_binary_headers(self):
|
||||
file=self.maps.root/'assets/fonts/Noto Sans Regular/0-255.pbf';file.parent.mkdir(parents=True);file.write_bytes(b'font')
|
||||
out=Output();self.maps.serve(out,'/maps/assets/fonts/Noto%20Sans%20Regular/0-255.pbf')
|
||||
self.assertEqual(out.wfile.getvalue(),b'font');self.assertEqual(out.headers['Content-Type'],'application/x-protobuf')
|
||||
def test_loopback_proxy_never_forwards_identity(self):
|
||||
captured=[]
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self,*a):pass
|
||||
def do_GET(self):
|
||||
captured.append((self.path,dict(self.headers)));self.send_response(200);self.send_header('Content-Encoding','gzip');self.end_headers();self.wfile.write(b'bytes')
|
||||
server=ThreadingHTTPServer(('127.0.0.1',0),Handler);thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start()
|
||||
try:
|
||||
(self.maps.root/'world.pmtiles').write_bytes(b'fixture')
|
||||
self.maps.port=server.server_port;out=Output();out.headers_in={'Cookie':'secret','Authorization':'Bearer secret'}
|
||||
self.maps.serve(out,'/maps/tiles/world/2/1/2.mvt');self.assertEqual(out.wfile.getvalue(),b'bytes');self.assertEqual(out.headers['Content-Encoding'],'gzip')
|
||||
self.assertEqual(captured[0][0],'/world/2/1/2.mvt');self.assertNotIn('Cookie',captured[0][1]);self.assertNotIn('Authorization',captured[0][1])
|
||||
finally:server.shutdown();server.server_close();thread.join()
|
||||
def test_outage_returns_error_and_releases_slot(self):
|
||||
(self.maps.root/'world.pmtiles').write_bytes(b'fixture')
|
||||
with patch('map_service.http.client.HTTPConnection') as connection:
|
||||
connection.return_value.request.side_effect=OSError()
|
||||
with self.assertRaises(Problem) as e:self.maps.serve(Output(),'/maps/tiles/world/0/0/0.mvt')
|
||||
self.assertEqual(e.exception.status,503)
|
||||
slots=[map_service.SLOTS.acquire(False) for _ in range(6)]
|
||||
self.assertTrue(all(slots))
|
||||
for _ in slots:map_service.SLOTS.release()
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
File diff suppressed because one or more lines are too long
-2
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
import"./modulepreload-polyfill-B5Qt9EMX.js";import{createFamilyMap as n}from"./controller-Je5cOZA3.js";const e=n(document.getElementById("map"),{onStatus:t=>document.getElementById("status").textContent=t});window.ZhaoMap={setItems:t=>e.setItems(t),setTrack:t=>e.setTrack(t),focus:t=>e.focus(t),fit:()=>e.fit(),setNight:t=>{document.documentElement.dataset.theme=t?"night":"day",e.setNight(t)}};document.addEventListener("visibilitychange",()=>{document.hidden&&(e.setItems([]),e.setTrack([]))});window.addEventListener("pagehide",()=>e.setItems([]));const s=()=>window.ZhaoMap.setNight(new Date().getHours()>=20||new Date().getHours()<7);s();setInterval(s,6e4);
|
||||
@@ -0,0 +1 @@
|
||||
html,body{margin:0;width:100%;height:100%;background:#e5efea;font-family:system-ui,sans-serif}#map{height:calc(100% - 28px);border-radius:0;min-height:0}#status{height:28px;box-sizing:border-box;padding:5px 9px;font-size:12px;color:#456354;background:#f3f7f4;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}[data-theme=night] body,[data-theme=night] #status{background:#1d2d27;color:#a8bfb3}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))i(e);new MutationObserver(e=>{for(const r of e)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function s(e){const r={};return e.integrity&&(r.integrity=e.integrity),e.referrerPolicy&&(r.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?r.credentials="include":e.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(e){if(e.ep)return;e.ep=!0;const r=s(e);fetch(e.href,r)}})();
|
||||
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
+5
-4
@@ -1,5 +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-0U8VZKRt.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/bootstrap.min-CBPvWlfP.js">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/bootstrap-DBkz-poX.css">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/index-22eWvMYM.css">
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#244d43"><link rel="icon" href="/zhao-icon.png"><link rel="apple-touch-icon" href="/zhao-icon.png"><title>赵府 · 智能数字管家</title> <script type="module" crossorigin src="/ui/assets/index-Ctw7iCDS.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/modulepreload-polyfill-B5Qt9EMX.js">
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/FamilyMap-CoPJzTbz.js">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/FamilyMap-DBkz-poX.css">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/index-C1TAw2ld.css">
|
||||
</head><body><div id="app"></div></body></html>
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="data:,"><title>家人位置地图</title> <script type="module" crossorigin src="/ui/assets/map-CT6w3aO1.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/modulepreload-polyfill-B5Qt9EMX.js">
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/controller-Je5cOZA3.js">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/controller-CWvM1oPI.css">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/map-iMS-WZxJ.css">
|
||||
</head><body><div id="map" class="family-map-canvas"></div><div id="status" role="status">正在加载内置地图…</div></body></html>
|
||||
+5
-4
@@ -1,5 +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="#f3eee4"><meta name="referrer" content="no-referrer"><link rel="icon" href="/zhao-icon.png"><title>赵府 · 家庭时光</title> <script type="module" crossorigin src="/ui/assets/tv-CGtsIoJR.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/bootstrap.min-CBPvWlfP.js">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/bootstrap-DBkz-poX.css">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/tv-C-Rk3l6q.css">
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f3eee4"><meta name="referrer" content="no-referrer"><link rel="icon" href="/zhao-icon.png"><title>赵府 · 家庭时光</title> <script type="module" crossorigin src="/ui/assets/tv-BLhSIH0H.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/modulepreload-polyfill-B5Qt9EMX.js">
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/FamilyMap-CoPJzTbz.js">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/FamilyMap-DBkz-poX.css">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/tv-CPkSOema.css">
|
||||
</head><body><div id="app"></div></body></html>
|
||||
|
||||
Vendored
+196
@@ -0,0 +1,196 @@
|
||||
Local map components and data notices
|
||||
|
||||
MapLibre GL JS 6.15.0
|
||||
Copyright (c) 2023, MapLibre contributors
|
||||
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
* Neither the name of MapLibre GL JS nor the names of its contributors
|
||||
may be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
-------------------------------------------------------------------------------
|
||||
|
||||
Contains code from mapbox-gl-js v1.13 and earlier
|
||||
|
||||
Version v1.13 of mapbox-gl-js and earlier are licensed under a BSD-3-Clause license
|
||||
|
||||
Copyright (c) 2020, Mapbox
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
* Neither the name of Mapbox GL JS nor the names of its contributors
|
||||
may be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
|
||||
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
-------------------------------------------------------------------------------
|
||||
|
||||
Contains code from glfx.js
|
||||
|
||||
Copyright (C) 2011 by Evan Wallace
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Contains a portion of d3-color https://github.com/d3/d3-color
|
||||
|
||||
Copyright 2010-2016 Mike Bostock
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name of the author nor the names of contributors may be used to
|
||||
endorse or promote products derived from this software without specific prior
|
||||
written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
Protomaps basemaps 5.7.2
|
||||
Source: https://api.github.com/repos/protomaps/basemaps/contents/LICENSE.md?ref=main
|
||||
# Code Licenses and Attribution
|
||||
|
||||
# The BSD 3-Clause License (BSD-3-Clause)
|
||||
|
||||
Copyright 2019-2023 Protomaps LLC, Kelso Cartography
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
# Visual Design
|
||||
|
||||
The visual design of the Protomaps basemap styles was created by Geraldine Sarmiento for Protomaps LLC and released under a Creative Commons 0 (CC0) license.
|
||||
|
||||
https://creativecommons.org/publicdomain/zero/1.0/
|
||||
|
||||
Certain map styles may also include derivatives of icons designed for Mapzen and released under an MIT license.
|
||||
|
||||
https://github.com/tangrams/icons/blob/master/LICENSE.md
|
||||
|
||||
# Tile Schema
|
||||
|
||||
The organization of layers and tags is adapted from the Tilezen project.
|
||||
|
||||
https://github.com/tilezen/vector-datasource
|
||||
https://github.com/tilezen/vector-datasource/blob/master/docs/LICENSE-SCHEMA.md
|
||||
|
||||
# The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015-2018 Mapzen
|
||||
Copyright (c) 2019 Linux Foundation
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
|
||||
go-pmtiles 1.31.2
|
||||
Source: https://api.github.com/repos/protomaps/go-pmtiles/contents/LICENSE?ref=v1.31.2
|
||||
Copyright 2021 Protomaps LLC
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
Map data: Copyright OpenStreetMap contributors, ODbL. https://www.openstreetmap.org/copyright
|
||||
Natural Earth 5.1.2 coarse administrative boundaries: public domain. https://www.naturalearthdata.com/about/terms-of-use/
|
||||
Font OFL notices are preserved in the separately installed basemaps-assets directory.
|
||||
Reference in New Issue
Block a user