feat: V0.1.53 location timeline and durable device conversations
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
# 赵府智家 · 视觉系统
|
||||
|
||||
## v0.1.52 · 家人位置手机端三页改版
|
||||
## v0.1.53 · 位置、沟通与长期语音记录
|
||||
|
||||
按三屏参考图组织「家人 / 喊话 / 我的」:地图与最近位置、大号圆形喊话按钮、分组的共享与轨迹设置。采用暖白和青绿色,明细设置全屏打开;保留本人授权、离线加密暂存、补传校验和清理。手机端请从配套 App 下载页覆盖安装。[本版说明](RELEASE-v0.1.52.md)。
|
||||
底部统一为「位置 / 沟通 / 我的」。位置按采集时间排序,点击在地图上脉冲定位;沟通页固定接收对象和说话按钮,中间查看和回听长期聊天记录。语音加密归档百度网盘,回读校验后清理服务器暂存,记录按家庭内的成员手机或显示终端档案归属。接收和共享设置统一到「我的」。[本版说明](RELEASE-v0.1.53.md)。
|
||||
|
||||
## v0.1.48 · 显示终端与家人喊话
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# V0.1.53 — 位置 / 沟通 / 我的
|
||||
|
||||
## 操作与界面
|
||||
|
||||
- 位置页只保留状态检查、地图、位置列表。当前获授权的位置按实际采集时间从新到旧排列,尚无定位的成员在后;显示完整采集日期时间。点列表会滚回地图并以三次柔和脉冲突出对应标记,系统减少动态效果时改为边框强调。
|
||||
- 移除位置页底部喊话区。沟通页上方选择接收对象,中间聊天记录独立滚动,下方固定大号按住说话按钮;随屏幕高度调整按钮区,保留小屏聊天可见空间。松开发送,上滑取消,单条最长 30 秒。
|
||||
- 聊天按时间显示发送设备、时间、时长、送达/播放状态、网盘归档状态,可点语音回听。“更早”逐页查询长期记录,“最近”返回最新一页;不会一次加载全部历史。
|
||||
- 「我的」按位置共享、允许谁查看、定位与轨迹、沟通与声音、设备与系统分组。接收开关、允许喊话名单及麦克风权限入口归入这里。
|
||||
|
||||
## 历史记录与权限
|
||||
|
||||
- 手机会话绑定“家庭+成员手机”,目前每名成员支持一台配对手机;显示终端会话绑定“家庭+设备档案”。同一档案重新配对可继续查看已有记录,旧令牌失效。换成员、换家庭不能继承原会话权限。
|
||||
- 数据库保存文字索引、发送/接收对象、时间、时长、状态、网盘文件路径和摘要。语音使用 AES-GCM 加密,存入应用目录下的 `家庭沟通/家庭编号/会话编号/年/月/日`;通过平台授权解密回听,不暴露公共语音链接。
|
||||
- 归档不设置时间过期。关闭接收仅停止新喊话,已有会话双方仍能查看历史。只有当前有效配对且属于会话双方的设备可读取;同家庭第三人、其他家庭、失效设备无法读取。下载期间会再次检查配对,避免撤权竞态。
|
||||
- 新发送先可靠写入有界加密暂存,再确认接受;后台上传后完整回读校验,成功才删除对应服务器临时文件。暂存上限 16 MiB,保留 256 MiB 磁盘余量;满时明确拒绝新消息,不覆盖已有未归档消息。网盘故障自动退避重试,页面显示“归档重试中”。
|
||||
- 实时自动播放仍要求接收方明确允许发送者、打开 App 且在线;过期或暂停自动播放的消息保留在会话中,供主动回听。回听不要求重新开启接收,不会把回听误报为新的送达回执。
|
||||
- 升级前已过期的临时喊话没有存档,无法补回;长期存档从本版本开始。
|
||||
|
||||
## 验证与安装
|
||||
|
||||
- 覆盖历史长期保留、幂等发送、错误编号、分页、配对轮换、家庭隔离、迁移设备、网盘校验失败保留暂存、成功清理、下载途中撤权等自动化回归。
|
||||
- 使用 Android 11 隔离包运行正式页面控制器,验证手机导航、时间排序、列表定位、设置归属、聊天加载、小屏及大字体。测试包没有网络、定位或麦克风权限,使用合成记录;结束后卸载并恢复原前台应用。
|
||||
- 后端回归 343 项、前端回归 192 项通过;11 种 Android 页面/操作检查包含聊天历史翻页和返回最新记录。320×640 dp 页面额外检查聊天窗口仍有可见高度和话筒保持大触控面积。
|
||||
- 百度网盘已使用合成会话做真实加密上传、回读校验、临时副本清理及重启回听测试,测试文件和专用空目录已清理。
|
||||
- 从配套 App 下载页获取 **家人位置手机版** 覆盖安装,保留配对和待上传轨迹。显示终端安装包单独提供。服务器发布不会自动安装到尚未连接的用户手机,实际双端扬声器和麦克风仍需手机联测。
|
||||
@@ -1,4 +1,4 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="8" android:versionName="0.1.52">
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="9" android:versionName="0.1.53">
|
||||
<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="8" android:versionName="0.1.52">
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="9" android:versionName="0.1.53">
|
||||
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30"/>
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
|
||||
|
||||
@@ -77,9 +77,11 @@ public class LocationActivity extends Activity {
|
||||
button("打开手机系统定位设置",permissionSection).setOnClickListener(v->startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)));
|
||||
sharing.setOnCheckedChangeListener((v,checked)->{if(rendering)return;if(checked)confirmSharing();else{startService(new Intent(this,LocationService.class).setAction("STOP"));consent.setChecked(false);}render();});
|
||||
map=new LocationMapView(this);phone.mapSlot.addView(map,0,new FrameLayout.LayoutParams(-1,-1));phone.fit.setOnClickListener(v->map.reset());reload.setOnClickListener(v->loadFamily());
|
||||
voice=new VoicePanel(this,"phone",()->prefs.getString("token",""));voice.dock.compactHome();phone.dockSlot.addView(voice,new LinearLayout.LayoutParams(-1,-2));phone.pages[1].addView(voice.page());
|
||||
voice.dock.expand.setText("喊话");voice.dock.expand.setOnClickListener(v->selectTab(1));voice.dock.recipient.setOnClickListener(v->selectTab(1));
|
||||
phone.onTab=i->{voice.finish(false);if(i==2&&!settingsReady)loadSettings();};
|
||||
voice=new VoicePanel(this,"phone",()->prefs.getString("token",""));phone.pages[1].addView(voice.page(),new LinearLayout.LayoutParams(-1,0,1));phone.voiceSettings.addView(voice.dock.receiverCard);
|
||||
phone.voiceSettings.addView(style.label("仅接收你允许的家人或设备。聊天记录长期保存在家庭网盘,关闭接收不会删除历史。",12,PhoneStyle.MUTED));
|
||||
Button soundSettings=style.button("麦克风与声音权限",false);phone.voiceSettings.addView(soundSettings);soundSettings.setOnClickListener(v->startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,android.net.Uri.parse("package:"+getPackageName()))));
|
||||
try{phone.pages[2].addView(style.label("赵府智家 · "+getPackageManager().getPackageInfo(getPackageName(),0).versionName,12,PhoneStyle.MUTED));}catch(Exception ignored){}
|
||||
phone.onTab=i->{voice.finish(false);voice.communication(i==1);if(i==2&&!settingsReady)loadSettings();};
|
||||
settingsButton.setOnClickListener(v->selectTab(2));phone.check.setOnClickListener(v->{selectTab(2);if(pairingRequired())showDetail("配对我的手机",pairSection);else showDetail("定位权限",permissionSection);});
|
||||
phone.pairNow.setOnClickListener(v->{selectTab(2);showDetail("配对我的手机",pairSection);});
|
||||
phone.profile.setOnClickListener(v->showDetail("配对与设备",pairSection));phone.pairing.setOnClickListener(v->showDetail("配对与设备",pairSection));
|
||||
@@ -92,7 +94,7 @@ public class LocationActivity extends Activity {
|
||||
boolean paired(){return !prefs.getString("token","").isEmpty();}
|
||||
boolean pairingRequired(){long expires=prefs.getLong("expires",0);return !paired()||bindingRejected||expires>0&&expires<=System.currentTimeMillis();}
|
||||
LinearLayout section(){LinearLayout v=style.column();settings.addView(v);return v;}
|
||||
void selectTab(int tab){voice.finish(false);phone.select(tab);if(tab==2&&!settingsReady)loadSettings();}
|
||||
void selectTab(int tab){voice.finish(false);phone.select(tab);voice.communication(tab==1);if(tab==2&&!settingsReady)loadSettings();}
|
||||
void showDetail(String title,LinearLayout content){
|
||||
if(detailDialog!=null)detailDialog.dismiss();voice.finish(false);if(content.getParent()!=null)((android.view.ViewGroup)content.getParent()).removeView(content);
|
||||
LinearLayout frame=style.column();frame.setPadding(style.dp(20),style.dp(16),style.dp(20),style.dp(16));frame.setBackgroundColor(PhoneStyle.PAPER);
|
||||
@@ -115,7 +117,7 @@ public class LocationActivity extends Activity {
|
||||
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);voice.setVisibility(paired?View.VISIBLE:View.GONE);phone.pairIntro.setVisibility(paired?View.GONE:View.VISIBLE);phone.dockSlot.setVisibility(paired&&phone.tab==0?View.VISIBLE:View.GONE);
|
||||
homeContent.setVisibility(paired?View.VISIBLE:View.GONE);shareControls.setVisibility(paired?View.VISIBLE:View.GONE);voice.setVisibility(paired?View.VISIBLE:View.GONE);phone.pairIntro.setVisibility(paired?View.GONE:View.VISIBLE);
|
||||
long expires=prefs.getLong("expires",0);
|
||||
VoiceSurface.text(identity,prefs.getString("memberName","尚未配对本人"));VoiceSurface.text(phone.pairSummary,prefs.getString("home","无需注册 · 使用手机配对码"));VoiceSurface.text(phone.homeName,prefs.getString("home","配对后查看已授权的家人"));
|
||||
String member=prefs.getString("memberName","我");VoiceSurface.text(phone.avatar,member.isEmpty()?"我":member.substring(0,member.offsetByCodePoints(0,1)));
|
||||
@@ -156,12 +158,18 @@ public class LocationActivity extends Activity {
|
||||
int g=generation;loading=true;lastList=SystemClock.elapsedRealtime();render();
|
||||
new Thread(()->{try{
|
||||
JSONObject response=DisplayApi.call("/api/location/update",token,new JSONObject().put("action","list"));
|
||||
runOnUiThread(()->{if(!visible||g!=generation)return;JSONArray list=response.optJSONArray("items");map.setItems(list);familyList.removeAllViews();viewStatus.setText(list==null||list.length()==0?"尚无家人授权给这台手机的位置。请对方在自己的位置设置里勾选你的手机,并开启共享。":"点击家人查看位置,点「轨迹」回看已授权历史。");
|
||||
if(list!=null)for(int i=0;i<list.length();i++){JSONObject row=list.optJSONObject(i);if(row==null)continue;JSONObject pos=row.optJSONObject("position");String detail=pos==null?("scheduled".equals(row.optString("status"))?("sampling".equals(row.optString("scheduleReason"))?"等待下次采集":"等待下次上传"):("stale".equals(row.optString("status"))?"更新中断 · 已隐藏旧位置":"等待定位")):java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(new Date((long)(pos.optDouble("at")*1000)))+" 更新 · 约 "+Math.round(pos.optDouble("accuracy"))+" 米";phone.family(row.optString("name"),detail,pos!=null,()->{if(pos!=null)map.focus(pos);else Toast.makeText(this,"当前没有可显示的位置",0).show();},()->history(row.optString("id")));}
|
||||
runOnUiThread(()->{if(!visible||g!=generation)return;JSONArray list=sortPositions(response.optJSONArray("items"));map.setItems(list);familyList.removeAllViews();viewStatus.setText(list.length()==0?"尚无家人授权给这台手机的位置。请对方在自己的位置设置里勾选你的手机,并开启共享。":"按采集时间从新到旧 · 点击在地图上闪烁定位");
|
||||
for(int i=0;i<list.length();i++){JSONObject row=list.optJSONObject(i);if(row==null)continue;JSONObject pos=row.optJSONObject("position");String detail=pos==null?("scheduled".equals(row.optString("status"))?("sampling".equals(row.optString("scheduleReason"))?"等待下次采集":"等待下次上传"):("stale".equals(row.optString("status"))?"更新中断 · 已隐藏旧位置":"等待定位")):new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA).format(new Date((long)(pos.optDouble("at")*1000)))+" 采集 · 约 "+Math.round(pos.optDouble("accuracy"))+" 米";phone.family(row.optString("name"),detail,pos!=null,()->{if(pos!=null){phone.scrolls[0].smoothScrollTo(0,0);map.focus(pos);}else Toast.makeText(this,"当前没有可显示的位置",0).show();},()->history(row.optString("id")));}
|
||||
|
||||
});
|
||||
}catch(Exception e){runOnUiThread(()->{if(!visible||g!=generation)return;familyList.removeAllViews();map.setItems(new JSONArray());if(e instanceof DisplayApi.ApiError&&(((DisplayApi.ApiError)e).status==401||((DisplayApi.ApiError)e).status==403)){bindingRejected=true;boolean wasSharing=prefs.getBoolean("active",false);prefs.edit().putBoolean("active",false).apply();if(wasSharing||LocationService.busy)startService(new Intent(this,LocationService.class).setAction("STOP"));voice.rebound();settingsReady=false;settingsError="手机配对已失效,请在「我的」重新配对";}viewStatus.setText(e instanceof DisplayApi.ApiError&&((DisplayApi.ApiError)e).status==401?"手机配对已过期或解除,请重新配对。":"位置未能刷新,已隐藏旧画面,请检查网络。");});}finally{runOnUiThread(()->{if(g==generation){loading=false;render();}});}},"family-positions").start();
|
||||
}
|
||||
static JSONArray sortPositions(JSONArray source){
|
||||
ArrayList<JSONObject> rows=new ArrayList<>();if(source!=null)for(int i=0;i<source.length();i++){JSONObject row=source.optJSONObject(i);if(row!=null)rows.add(row);}
|
||||
rows.sort((a,b)->{int time=Double.compare(positionTime(b),positionTime(a));return time!=0?time:a.optString("id").compareTo(b.optString("id"));});
|
||||
JSONArray sorted=new JSONArray();for(JSONObject row:rows)sorted.put(row);return sorted;
|
||||
}
|
||||
static double positionTime(JSONObject row){JSONObject p=row.optJSONObject("position");double at=p==null?0:p.optDouble("at",0);return Double.isFinite(at)&&at>0?at:0;}
|
||||
void loadSettings(){
|
||||
String token=prefs.getString("token","");if(token.isEmpty()||pairing)return;int g=generation,request=++settingsRequest;settingsReady=false;settingsError="";render();
|
||||
new Thread(()->{try{
|
||||
|
||||
@@ -9,7 +9,7 @@ import java.util.function.IntConsumer;
|
||||
/** Three persistent phone pages. All members, permissions and statuses are supplied by the controller. */
|
||||
final class PhoneLayout extends LinearLayout {
|
||||
final PhoneStyle s;final ScrollView[] scrolls=new ScrollView[3];final LinearLayout[] pages=new LinearLayout[3];
|
||||
final LinearLayout nav,homeContent,familyList,dockSlot,mineContent,pairIntro,shareCard,profile;
|
||||
final LinearLayout nav,homeContent,familyList,mineContent,pairIntro,shareCard,profile,voiceSettings;
|
||||
final FrameLayout mapSlot;final TextView homeName,identity,avatar,homeStatus,myStatus,viewStatus,pairSummary;
|
||||
final Button settingsButton,check,refresh,fit,pairNow,myCheck;final Switch sharing;
|
||||
final PhoneStyle.Row viewers,expiry,sampling,upload,history,pairing,permissions;
|
||||
@@ -18,7 +18,9 @@ final class PhoneLayout extends LinearLayout {
|
||||
super(app);s=new PhoneStyle(app);setOrientation(VERTICAL);setBackgroundColor(PhoneStyle.PAPER);
|
||||
FrameLayout content=new FrameLayout(app);addView(content,new LayoutParams(-1,0,1));
|
||||
for(int i=0;i<3;i++){scrolls[i]=new ScrollView(app);scrolls[i].setFillViewport(true);scrolls[i].setClipToPadding(false);pages[i]=s.column();pages[i].setPadding(s.dp(18),s.dp(18),s.dp(18),s.dp(16));scrolls[i].addView(pages[i]);content.addView(scrolls[i],new FrameLayout.LayoutParams(-1,-1));}
|
||||
LinearLayout heading=s.line();TextView title=s.bold("家人位置",28);heading.addView(title,new LayoutParams(0,-2,1));settingsButton=s.iconButton("settings","打开我的位置共享设置");heading.addView(settingsButton,new LayoutParams(s.dp(48),s.dp(48)));pages[0].addView(heading);
|
||||
// Keep recipient and microphone visible while only the conversation scrolls.
|
||||
scrolls[1].removeView(pages[1]);content.removeView(scrolls[1]);content.addView(pages[1],new FrameLayout.LayoutParams(-1,-1));
|
||||
LinearLayout heading=s.line();TextView title=s.bold("位置",28);heading.addView(title,new LayoutParams(0,-2,1));settingsButton=s.iconButton("settings","打开我的设置");heading.addView(settingsButton,new LayoutParams(s.dp(48),s.dp(48)));pages[0].addView(heading);
|
||||
homeName=s.label("配对后查看家人",16,PhoneStyle.MUTED);pages[0].addView(homeName);s.gap(pages[0],16);
|
||||
LinearLayout banner=s.line();banner.setPadding(s.dp(14),s.dp(8),s.dp(8),s.dp(8));banner.setBackground(s.shape(0xfffff1d6,16));
|
||||
homeStatus=s.label("尚未配对本人",14,0xff805c23);banner.addView(homeStatus,new LayoutParams(0,-2,1));check=s.button("检查",false);banner.addView(check);pages[0].addView(banner);s.gap(pages[0],12);
|
||||
@@ -26,26 +28,26 @@ final class PhoneLayout extends LinearLayout {
|
||||
mapSlot=new FrameLayout(app);mapSlot.setBackground(s.shape(0xffe5ede5,22));mapSlot.setClipToOutline(true);homeContent.addView(mapSlot,new LayoutParams(-1,s.dp(330)));
|
||||
fit=s.iconButton("location","在地图上查看全部家人");FrameLayout.LayoutParams fitParams=new FrameLayout.LayoutParams(s.dp(48),s.dp(48),Gravity.RIGHT|Gravity.CENTER_VERTICAL);fitParams.setMargins(0,0,s.dp(12),0);mapSlot.addView(fit,fitParams);
|
||||
TextView privacy=s.label("仅显示已授权的位置",11,PhoneStyle.GREEN);privacy.setPadding(s.dp(10),s.dp(7),s.dp(10),s.dp(7));privacy.setBackground(s.shape(PhoneStyle.CARD,20));FrameLayout.LayoutParams pp=new FrameLayout.LayoutParams(-2,-2,Gravity.LEFT|Gravity.TOP);pp.setMargins(s.dp(10),s.dp(12),s.dp(64),0);mapSlot.addView(privacy,pp);
|
||||
s.gap(homeContent,14);LinearLayout recent=s.column();s.card(recent);homeContent.addView(recent);LinearLayout recentHead=s.line();recentHead.addView(s.bold("最近位置",17),new LayoutParams(0,-2,1));refresh=s.iconButton("refresh","刷新家人位置");recentHead.addView(refresh,new LayoutParams(s.dp(48),s.dp(48)));recent.addView(recentHead);
|
||||
s.gap(homeContent,14);LinearLayout recent=s.column();s.card(recent);homeContent.addView(recent);LinearLayout recentHead=s.line();recentHead.addView(s.bold("位置列表",17),new LayoutParams(0,-2,1));refresh=s.iconButton("refresh","刷新家人位置");recentHead.addView(refresh,new LayoutParams(s.dp(48),s.dp(48)));recent.addView(recentHead);
|
||||
viewStatus=s.label("正在读取家人授权…",13,PhoneStyle.MUTED);viewStatus.setPadding(0,0,0,s.dp(8));recent.addView(viewStatus);familyList=s.column();recent.addView(familyList);s.gap(homeContent,10);
|
||||
dockSlot=s.column();dockSlot.setPadding(s.dp(12),s.dp(6),s.dp(12),s.dp(6));addView(dockSlot,new LayoutParams(-1,-2));
|
||||
pairIntro=s.column();s.card(pairIntro);pages[0].addView(pairIntro);pairIntro.addView(s.bold("与家人连接",23));s.gap(pairIntro,12);pairIntro.addView(s.label("使用手机配对码关联自己的成员档案,无需注册。配对后就能查看已授权给你的家人。",16,PhoneStyle.MUTED));s.gap(pairIntro,20);pairNow=s.button("去配对我的手机",true);pairIntro.addView(pairNow);
|
||||
// The voice page is populated with the same production VoiceSurface used by the controller.
|
||||
pages[1].setPadding(0,0,0,s.dp(8));
|
||||
pages[2].addView(s.bold("我的位置共享",27));s.gap(pages[2],20);
|
||||
pages[2].addView(s.bold("我的",27));s.gap(pages[2],20);
|
||||
profile=s.line();avatar=s.avatar("我",54);profile.addView(avatar);LinearLayout words=s.column();words.setPadding(s.dp(14),0,0,0);identity=s.bold("尚未配对本人",19);pairSummary=s.label("无需注册 · 使用手机配对码",13,PhoneStyle.MUTED);words.addView(identity);s.gap(words,5);words.addView(pairSummary);profile.addView(words,new LayoutParams(0,-2,1));TextView chevron=s.label("›",28,PhoneStyle.MUTED);profile.addView(chevron);profile.setMinimumHeight(s.dp(64));profile.setFocusable(true);profile.setClickable(true);pages[2].addView(profile);s.gap(pages[2],18);
|
||||
mineContent=s.column();pages[2].addView(mineContent);
|
||||
shareCard=s.column();s.card(shareCard);mineContent.addView(shareCard);sharing=new Switch(app);sharing.setText("共享我的位置");sharing.setTextSize(19);sharing.setTypeface(null,Typeface.BOLD);sharing.setTextColor(PhoneStyle.INK);sharing.setMinHeight(s.dp(50));sharing.setThumbTintList(new android.content.res.ColorStateList(new int[][]{new int[]{android.R.attr.state_checked},new int[]{}},new int[]{PhoneStyle.GREEN,0xffb5bcb6}));shareCard.addView(sharing);
|
||||
LinearLayout state=s.line();state.setPadding(s.dp(10),s.dp(6),s.dp(4),s.dp(6));state.setBackground(s.shape(0xfffff4de,12));myStatus=s.label("共享关闭",13,0xff805c23);state.addView(myStatus,new LayoutParams(0,-2,1));myCheck=s.button("检查权限",false);state.addView(myCheck);shareCard.addView(state);s.gap(shareCard,10);shareCard.addView(s.label("查看家人位置,无需开启自己的共享。",12,PhoneStyle.MUTED));
|
||||
section(mineContent,"允许谁查看");LinearLayout access=s.column();s.card(access);mineContent.addView(access);viewers=s.row("family","查看人名单","读取中");access.addView(viewers);expiry=s.row("clock","共享有效期","跟随本机配对有效期");access.addView(expiry);
|
||||
section(mineContent,"定位与轨迹");LinearLayout location=s.column();s.card(location);mineContent.addView(location);sampling=s.row("location","定位采集频率","每 1 分钟");upload=s.row("cloud","集中上传周期","每 5 分钟");history=s.row("track","我的历史轨迹","每天、每周、每月、每年、一生");permissions=s.row("shield","定位权限与系统设置","本人开启共享后才采集");for(View row:new View[]{sampling,upload,history,permissions})location.addView(row);
|
||||
s.gap(pages[2],12);LinearLayout device=s.column();s.card(device);pages[2].addView(device);pairing=s.row("phone","配对与设备","查看或更换手机配对");device.addView(pairing);
|
||||
nav=s.line();nav.setBackgroundColor(PhoneStyle.CARD);nav.setPadding(s.dp(8),s.dp(4),s.dp(8),s.dp(6));addView(nav,new LayoutParams(-1,-2));String[] names={"家人","喊话","我的"},icons={"family","mic","person"};
|
||||
section(mineContent,"沟通与声音");voiceSettings=s.column();s.card(voiceSettings);mineContent.addView(voiceSettings);
|
||||
section(pages[2],"设备与系统");LinearLayout device=s.column();s.card(device);pages[2].addView(device);pairing=s.row("phone","配对与设备","查看或更换手机配对");device.addView(pairing);
|
||||
nav=s.line();nav.setBackgroundColor(PhoneStyle.CARD);nav.setPadding(s.dp(8),s.dp(4),s.dp(8),s.dp(6));addView(nav,new LayoutParams(-1,-2));String[] names={"位置","沟通","我的"},icons={"location","mic","person"};
|
||||
for(int i=0;i<3;i++){final int index=i;LinearLayout item=s.column();item.setGravity(Gravity.CENTER);item.setMinimumHeight(s.dp(64));item.setPadding(0,s.dp(6),0,s.dp(6));navIcons[i]=new ImageView(app);item.addView(navIcons[i],new LayoutParams(s.dp(25),s.dp(25)));s.gap(item,5);navLabels[i]=s.label(names[i],12,PhoneStyle.MUTED);navLabels[i].setGravity(Gravity.CENTER);item.addView(navLabels[i]);item.setContentDescription(names[i]);item.setFocusable(true);item.setClickable(true);item.setOnClickListener(v->{select(index);if(onTab!=null)onTab.accept(index);});nav.addView(item,new LayoutParams(0,-2,1));}
|
||||
select(0);
|
||||
}
|
||||
void section(LinearLayout parent,String title){s.gap(parent,22);parent.addView(s.bold(title,17));s.gap(parent,10);}
|
||||
void select(int next){tab=next;dockSlot.setVisibility(next==0&&homeContent.getVisibility()==VISIBLE?VISIBLE:GONE);for(int i=0;i<3;i++){scrolls[i].setVisibility(i==next?VISIBLE:GONE);nav.getChildAt(i).setSelected(i==next);navLabels[i].setTextColor(i==next?PhoneStyle.GREEN:PhoneStyle.MUTED);navLabels[i].setTypeface(null,i==next?Typeface.BOLD:Typeface.NORMAL);navIcons[i].setImageDrawable(new PhoneStyle.Icon(new String[]{"family","mic","person"}[i],i==next?PhoneStyle.GREEN:PhoneStyle.MUTED,s.dp(25)));}}
|
||||
void select(int next){tab=next;pages[1].setVisibility(next==1?VISIBLE:GONE);for(int i=0;i<3;i++){scrolls[i].setVisibility(i==next?VISIBLE:GONE);nav.getChildAt(i).setSelected(i==next);navLabels[i].setTextColor(i==next?PhoneStyle.GREEN:PhoneStyle.MUTED);navLabels[i].setTypeface(null,i==next?Typeface.BOLD:Typeface.NORMAL);navIcons[i].setImageDrawable(new PhoneStyle.Icon(new String[]{"location","mic","person"}[i],i==next?PhoneStyle.GREEN:PhoneStyle.MUTED,s.dp(25)));}}
|
||||
void family(String name,String detail,boolean position,Runnable focus,Runnable history){
|
||||
LinearLayout row=s.line();row.setPadding(0,s.dp(10),0,s.dp(10));TextView avatar=s.avatar(name,42);row.addView(avatar);LinearLayout words=s.column();words.setPadding(s.dp(12),0,s.dp(6),0);TextView title=s.bold(name,17);words.addView(title);s.gap(words,5);words.addView(s.label(detail,12,PhoneStyle.MUTED));words.setMinimumHeight(s.dp(48));words.setFocusable(true);words.setClickable(true);words.setOnClickListener(v->focus.run());words.setContentDescription(name+","+detail+(position?",在地图上查看":""));row.addView(words,new LayoutParams(0,-2,1));Button more=s.button("轨迹",false);more.setContentDescription("查看 "+name+" 的已授权历史轨迹");more.setOnClickListener(v->history.run());row.addView(more);familyList.addView(row);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package cn.ucvl.zhaodisplay;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.view.*;
|
||||
import android.widget.*;
|
||||
import org.json.*;
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** A bounded page of a permanent conversation; older pages are fetched on demand. */
|
||||
final class VoiceChat extends LinearLayout {
|
||||
final PhoneStyle s;final LinearLayout messages;final TextView notice,heading;final Button older,latest;final ScrollView scroll;
|
||||
boolean night=false,savedMore=false,savedPast=false;JSONArray saved=new JSONArray();
|
||||
String signature="";Consumer<String> replay=id->{};
|
||||
VoiceChat(Activity app){
|
||||
super(app);s=new PhoneStyle(app);setOrientation(VERTICAL);s.card(this);
|
||||
LinearLayout head=s.line();heading=s.bold("聊天记录",18);head.addView(heading,new LayoutParams(0,-2,1));older=s.button("更早",false);latest=s.button("最近",false);head.addView(older);head.addView(latest);addView(head);
|
||||
notice=s.label("选择沟通对象后查看记录",12,PhoneStyle.MUTED);addView(notice);
|
||||
scroll=new ScrollView(app);scroll.setFillViewport(true);messages=s.column();scroll.addView(messages);addView(scroll,new LayoutParams(-1,s.dp(218)));
|
||||
scroll.setOnTouchListener((v,e)->{if(e.getActionMasked()==MotionEvent.ACTION_DOWN)v.getParent().requestDisallowInterceptTouchEvent(true);if(e.getActionMasked()==MotionEvent.ACTION_UP||e.getActionMasked()==MotionEvent.ACTION_CANCEL)v.getParent().requestDisallowInterceptTouchEvent(false);return false;});
|
||||
older.setEnabled(false);
|
||||
}
|
||||
void clear(String text){signature="";saved=new JSONArray();messages.removeAllViews();notice.setText(text);older.setEnabled(false);}
|
||||
void theme(boolean value){if(night==value)return;night=value;setBackground(s.shape(night?0xff21372d:PhoneStyle.CARD,20));heading.setTextColor(night?0xffc8d5cd:PhoneStyle.INK);notice.setTextColor(night?0xff96aaa0:PhoneStyle.MUTED);for(Button b:new Button[]{older,latest}){b.setTextColor(night?0xffc8d5cd:PhoneStyle.GREEN);b.setBackground(s.shape(night?0xff2d4439:PhoneStyle.PALE,14));}if(saved.length()>0){signature="";show(saved,savedMore,savedPast,replay);}}
|
||||
void show(JSONArray items,boolean hasMore,boolean past,Consumer<String> play){
|
||||
replay=play;saved=items;savedMore=hasMore;savedPast=past;older.setEnabled(hasMore);notice.setText(past?"较早的记录 · 可继续向前翻阅":"长期保留 · 点击语音回听");
|
||||
String next=items.toString();if(next.equals(signature))return;boolean follow=signature.isEmpty()||scroll.getScrollY()+scroll.getHeight()>=messages.getHeight()-s.dp(32);int oldScroll=scroll.getScrollY();signature=next;messages.removeAllViews();
|
||||
if(items.length()==0){TextView empty=s.label("还没有聊天记录\n按住下方按钮,给家人说句话吧",15,PhoneStyle.MUTED);empty.setGravity(Gravity.CENTER);empty.setPadding(0,s.dp(42),0,s.dp(30));messages.addView(empty);return;}
|
||||
for(int i=0;i<items.length();i++){
|
||||
JSONObject item=items.optJSONObject(i);if(item==null)continue;boolean mine=item.optBoolean("mine");
|
||||
int ink=night?0xffc8d5cd:PhoneStyle.INK,muted=night?0xff96aaa0:PhoneStyle.MUTED;
|
||||
LinearLayout row=s.column();row.setPadding(s.dp(12),s.dp(10),s.dp(12),s.dp(10));row.setBackground(s.shape(night?(mine?0xff2e4d40:0xff2a3d33):mine?PhoneStyle.PALE:0xfff1f0e9,14));LayoutParams lp=new LayoutParams(-1,-2);lp.topMargin=s.dp(9);lp.leftMargin=s.dp(mine?22:0);lp.rightMargin=s.dp(mine?0:22);messages.addView(row,lp);
|
||||
String name=(mine?"我 · ":"")+item.optString("senderName","设备");TextView author=s.bold(name,14);author.setTextColor(ink);row.addView(author);
|
||||
row.addView(s.label(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA).format(new Date((long)(item.optDouble("at")*1000))),11,muted));
|
||||
Button voice=s.button("▶ 语音 · "+String.format(Locale.CHINA,"%.1f",item.optDouble("seconds"))+" 秒",mine);if(night){voice.setTextColor(ink);voice.setBackground(s.shape(0xff355549,14));}voice.setContentDescription("播放 "+name+" 的语音");voice.setOnClickListener(v->replay.accept(item.optString("id")));row.addView(voice,new LayoutParams(-1,-2));
|
||||
String delivery=item.optString("delivery"),archive=item.optString("archive");
|
||||
String state=delivery.equals("played")?"已播放":delivery.equals("received")?"已送达":delivery.equals("queued")?"等待播放":"未自动播放 · 可以回听";
|
||||
row.addView(s.label(state+" · "+(archive.equals("cloud")?"已存网盘":archive.equals("retry")?"网盘归档重试中":"网盘归档中"),11,muted));
|
||||
}
|
||||
if(!past&&follow)scroll.post(()->scroll.fullScroll(FOCUS_DOWN));else scroll.post(()->scroll.scrollTo(0,past?0:oldScroll));
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ final class VoicePanel extends LinearLayout {
|
||||
final Handler ui=new Handler();final ExecutorService worker=Executors.newSingleThreadExecutor();
|
||||
final TextView status;final Button speak,settings,stop;final VoiceSurface dock;VoiceSurface expanded,page;Dialog sheet;
|
||||
String selectedId="";boolean networkReady=false;long feedbackAt=0;
|
||||
boolean communicationVisible=false,historyLoading=false,historyPlayback=false;long historyBefore=0,nextBefore=0;int historyEpoch=0,playbackRequest=0;String historyPeer="";
|
||||
final AudioManager audio;final AudioAttributes attributes=new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build();
|
||||
AudioFocusRequest focus;MediaRecorder recorder;MediaPlayer player;File recording,playing;
|
||||
JSONArray choices=new JSONArray(),allowed=new JSONArray(),destinations=new JSONArray();
|
||||
@@ -36,9 +37,12 @@ final class VoicePanel extends LinearLayout {
|
||||
for(File file:Optional.ofNullable(app.getCacheDir().listFiles()).orElse(new File[0]))if(file.getName().startsWith("voice-"))file.delete();
|
||||
}
|
||||
void showStatus(String text){VoiceSurface.text(status,text);feedbackAt=SystemClock.elapsedRealtime();if(expanded!=null)VoiceSurface.text(expanded.status,text);if(page!=null)VoiceSurface.text(page.status,text);}
|
||||
VoiceSurface page(){if(page==null){page=new VoiceSurface(app,true);wire(page);page.expand.setVisibility(GONE);page.applyTheme(night);}renderSurfaces();return page;}
|
||||
VoiceSurface page(){if(page==null){page=new VoiceSurface(app,true);page.communicationPage();wire(page);page.expand.setVisibility(GONE);page.applyTheme(night);}renderSurfaces();return page;}
|
||||
void communication(boolean value){communicationVisible=value;if(value)loadConversation(false);}
|
||||
void chooseTarget(){if(recorder!=null||sending)return;if(destinations==null||destinations.length()==0){new AlertDialog.Builder(app).setTitle("暂无可接收的家人").setMessage("请对方打开 App,在接收设置中允许你向其喊话。显示终端也需要先授权。").setPositiveButton("知道了",null).show();return;}String[] names=new String[destinations.length()];int selected=-1;for(int i=0;i<names.length;i++){JSONObject d=destinations.optJSONObject(i);names[i]=d.optString("name")+" · "+(d.optBoolean("online")?"在线":"未打开 App");if(d.optString("id").equals(selectedId))selected=i;}final JSONArray snapshot=destinations;new AlertDialog.Builder(app).setTitle("发给谁").setSingleChoiceItems(names,selected,(d,i)->{choose(snapshot.optJSONObject(i).optString("id"));d.dismiss();}).setNegativeButton("取消",null).show();}
|
||||
void wire(VoiceSurface view){
|
||||
view.chat.older.setOnClickListener(v->{if(!historyLoading&&nextBefore>0){historyBefore=nextBefore;loadConversation(true);}});
|
||||
view.chat.latest.setOnClickListener(v->{if(!historyLoading){historyBefore=0;loadConversation(true);}});
|
||||
view.settings.setOnClickListener(v->configure());view.stop.setOnClickListener(v->stopPlayer("rejected"));
|
||||
view.destinationCard.setOnClickListener(v->chooseTarget());
|
||||
view.receiver.setOnClickListener(v->{view.receiver.setChecked(enabled);if(enabled)saveSettings(false,new JSONArray());else configure();});
|
||||
@@ -60,16 +64,16 @@ final class VoicePanel extends LinearLayout {
|
||||
expanded=new VoiceSurface(app,true);wire(expanded);expanded.applyTheme(night);
|
||||
ScrollView scroll=new ScrollView(app);scroll.setFillViewport(true);scroll.addView(expanded);
|
||||
sheet=new Dialog(app,android.R.style.Theme_Material_Light_NoActionBar);sheet.setContentView(scroll);
|
||||
sheet.setOnDismissListener(d->{finish(false);expanded=null;sheet=null;});sheet.show();
|
||||
sheet.setOnDismissListener(d->{finish(false);expanded=null;sheet=null;});sheet.show();loadConversation(false);
|
||||
sheet.getWindow().setLayout(-1,-1);sheet.getWindow().setStatusBarColor(night?0xff172820:0xfff8f5ed);sheet.getWindow().setNavigationBarColor(night?0xff172820:0xfff8f5ed);
|
||||
sheet.getWindow().getDecorView().setSystemUiVisibility(night?0:View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR|View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
|
||||
renderSurfaces();
|
||||
}
|
||||
JSONObject destination(){if(destinations!=null)for(int i=0;i<destinations.length();i++){JSONObject d=destinations.optJSONObject(i);if(d!=null&&d.optString("id").equals(selectedId))return d;}return null;}
|
||||
void choose(String id){if(recorder!=null||sending)return;selectedId=id;lastMessage="";JSONObject d=destination();showStatus(d!=null&&d.optBoolean("online")?"按住说话,松开发送给 "+d.optString("name"):"请先让对方打开 App,再向其喊话");renderSurfaces();}
|
||||
void choose(String id){if(recorder!=null||sending)return;stopPlayer("rejected");selectedId=id;lastMessage="";clearHistory("正在读取聊天记录…");JSONObject d=destination();showStatus(d!=null&&d.optBoolean("online")?"按住说话,松开发送给 "+d.optString("name"):"可以回听历史;发送需要对方授权并在线");renderSurfaces();loadConversation(true);}
|
||||
void renderSurfaces(){
|
||||
JSONObject selected=destination();String name=selected==null?"":selected.optString("name");boolean available=selected!=null&&selected.optBoolean("online");
|
||||
boolean can=networkReady&&available&&!sending&µphone();int amplitude=0;if(recorder!=null)try{amplitude=recorder.getMaxAmplitude();}catch(Exception ignored){}
|
||||
boolean can=networkReady&&available&&selected.optBoolean("canSend",true)&&!sending&µphone();int amplitude=0;if(recorder!=null)try{amplitude=recorder.getMaxAmplitude();}catch(Exception ignored){}
|
||||
for(VoiceSurface view:new VoiceSurface[]{dock,expanded,page}){if(view==null)continue;
|
||||
if(recorder==null||view.full)VoiceSurface.text(view.recipient,name.isEmpty()?"选择一位家人":view.full?name:name+" · "+(available?"已打开 App":"未打开 App")+" ›");view.destination(selected,networkReady);view.receiving(enabled,networkReady&&recorder==null&&!sending);
|
||||
VoiceSurface.text(view.receive,enabled?"● 接收已开启 · 仅限你允许的家人":"○ 接收已关闭 · 可在接收设置中开启");
|
||||
@@ -83,7 +87,7 @@ final class VoicePanel extends LinearLayout {
|
||||
boolean current(int e,String t){return visible&&!closed&&e==epoch&&t.equals(token.get());}
|
||||
void active(boolean value){
|
||||
if(closed)return;visible=value;epoch++;ui.removeCallbacks(refresh);ui.removeCallbacks(visual);
|
||||
if(value){ui.post(refresh);ui.post(visual);}else{if(sheet!=null)sheet.dismiss();finish(false);stopPlayer("rejected");String t=token.get();if(!t.isEmpty())worker.execute(()->{try{DisplayApi.call("/api/voice",t,body("offline"));}catch(Exception ignored){}});}
|
||||
if(value){ui.post(refresh);ui.post(visual);}else{clearHistory("打开沟通后读取记录");if(sheet!=null)sheet.dismiss();finish(false);stopPlayer("rejected");String t=token.get();if(!t.isEmpty())worker.execute(()->{try{DisplayApi.call("/api/voice",t,body("offline"));}catch(Exception ignored){}});}
|
||||
}
|
||||
void rebound(){active(false);choices=new JSONArray();allowed=new JSONArray();destinations=new JSONArray();enabled=false;networkReady=false;selectedId="";lastMessage="";active(true);}
|
||||
void close(){active(false);closed=true;ui.removeCallbacksAndMessages(null);worker.shutdown();}
|
||||
@@ -93,14 +97,41 @@ final class VoicePanel extends LinearLayout {
|
||||
worker.execute(()->{try{
|
||||
JSONObject value=DisplayApi.call("/api/voice",t,body("status"));
|
||||
ui.post(()->{if(!current(e,t))return;choices=value.optJSONArray("candidates");allowed=value.optJSONArray("allowed");enabled=value.optBoolean("enabled");networkReady=true;settings.setEnabled(true);
|
||||
if(!enabled&&player!=null)stopPlayer("rejected");
|
||||
if(recorder==null&&!sending){destinations=value.optJSONArray("targets");if(destination()==null){selectedId="";if(destinations!=null&&destinations.length()>0){selectedId=destinations.optJSONObject(0).optString("id");for(int i=0;i<destinations.length();i++){JSONObject d=destinations.optJSONObject(i);if(d.optBoolean("online")){selectedId=d.optString("id");break;}}}}}
|
||||
if(!enabled&&player!=null&&!historyPlayback)stopPlayer("rejected");
|
||||
if(recorder==null&&!sending){destinations=withConversations(value);if(destination()==null){selectedId="";if(destinations!=null&&destinations.length()>0){selectedId=destinations.optJSONObject(0).optString("id");for(int i=0;i<destinations.length();i++){JSONObject d=destinations.optJSONObject(i);if(d.optBoolean("online")){selectedId=d.optString("id");break;}}}}}
|
||||
JSONArray sent=value.optJSONArray("sent");if(sent!=null&&!lastMessage.isEmpty()&&recorder==null&&player==null&&!sending)for(int i=0;i<sent.length();i++){JSONObject r=sent.optJSONObject(i);if(lastMessage.equals(r.optString("id"))){String s=r.optString("status");showStatus(s.equals("played")?"对方已播放":s.equals("rejected")?"对方已停止或未播放":s.equals("expired")?"喊话已过期,未播放":s.equals("received")?"对方正在接收":"已发送,等待对方播放");}}
|
||||
if(lastMessage.isEmpty()&&player==null&&recorder==null&&!sending&&SystemClock.elapsedRealtime()-feedbackAt>12000)showStatus(destination()==null?"暂无允许接收的家人,请对方开启接收":!destination().optBoolean("online")?"请对方打开 App 后再说话":"按住说话,松开发送 · 上滑取消");
|
||||
renderSurfaces();
|
||||
loadConversation(false);
|
||||
JSONArray inbox=value.optJSONArray("inbox");if(enabled&&player==null&&recorder==null&&!sending&&inbox!=null&&inbox.length()>0)take(inbox.optJSONObject(0).optString("id"));
|
||||
});
|
||||
}catch(Exception error){ui.post(()->{if(current(e,t)){networkReady=false;speak.setEnabled(false);settings.setEnabled(false);if(error instanceof DisplayApi.ApiError&&(((DisplayApi.ApiError)error).status==401||((DisplayApi.ApiError)error).status==403)){finish(false);stopPlayer("rejected");enabled=false;destinations=new JSONArray();}showStatus("喊话连接暂不可用,请检查网络和配对");}});}finally{ui.post(()->polling=false);}});
|
||||
}catch(Exception error){ui.post(()->{if(current(e,t)){networkReady=false;speak.setEnabled(false);settings.setEnabled(false);if(error instanceof DisplayApi.ApiError&&(((DisplayApi.ApiError)error).status==401||((DisplayApi.ApiError)error).status==403)){finish(false);stopPlayer("rejected");enabled=false;destinations=new JSONArray();clearHistory("配对失效,请重新配对后查看");}showStatus("沟通连接暂不可用,请检查网络和配对");}});}finally{ui.post(()->polling=false);}});
|
||||
}
|
||||
JSONArray withConversations(JSONObject value){
|
||||
JSONArray result=new JSONArray(),targets=value.optJSONArray("targets"),saved=value.optJSONArray("conversations");HashSet<String> keys=new HashSet<>();
|
||||
if(targets!=null)for(int i=0;i<targets.length();i++){JSONObject item=targets.optJSONObject(i);if(item!=null){result.put(item);keys.add(item.optString("archiveKey"));}}
|
||||
if(saved!=null)for(int i=0;i<saved.length();i++){JSONObject item=saved.optJSONObject(i);if(item==null||keys.contains(item.optString("archiveKey")))continue;try{JSONObject copy=new JSONObject(item.toString());copy.put("id","archive:"+item.optString("archiveKey")).put("online",false).put("canSend",false);result.put(copy);}catch(Exception ignored){}}
|
||||
return result;
|
||||
}
|
||||
void clearHistory(String reason){historyEpoch++;historyLoading=false;historyPeer="";historyBefore=0;nextBefore=0;for(VoiceSurface v:new VoiceSurface[]{page,expanded})if(v!=null){v.chat.clear(reason);v.chat.latest.setEnabled(true);}}
|
||||
void loadConversation(boolean force){
|
||||
if(!visible||closed||!networkReady||(!communicationVisible&&expanded==null)||historyLoading)return;
|
||||
JSONObject d=destination();String peer=d==null?"":d.optString("archiveKey");
|
||||
if(peer.isEmpty()){clearHistory("选择允许沟通的家人或设备");return;}
|
||||
if(!peer.equals(historyPeer)){clearHistory("正在读取聊天记录…");historyPeer=peer;}
|
||||
if(!force&&historyBefore>0)return;
|
||||
final String t=token.get();final int e=epoch,request=++historyEpoch;final long before=historyBefore;historyLoading=true;
|
||||
for(VoiceSurface view:new VoiceSurface[]{page,expanded})if(view!=null){view.chat.older.setEnabled(false);view.chat.latest.setEnabled(false);}
|
||||
worker.execute(()->{try{
|
||||
JSONObject result=DisplayApi.call("/api/voice",t,body("history").put("peer",peer).put("before",before));
|
||||
ui.post(()->{if(!current(e,t)||request!=historyEpoch||!peer.equals(historyPeer))return;nextBefore=result.optLong("before");JSONArray items=result.optJSONArray("items");for(VoiceSurface view:new VoiceSurface[]{page,expanded})if(view!=null)view.chat.show(items==null?new JSONArray():items,nextBefore>0,before>0,this::replay);});
|
||||
}catch(Exception error){ui.post(()->{if(current(e,t)&&request==historyEpoch)for(VoiceSurface view:new VoiceSurface[]{page,expanded})if(view!=null)view.chat.notice.setText("聊天记录未能刷新,点“最近”重试");});}
|
||||
finally{ui.post(()->{if(request==historyEpoch){historyLoading=false;for(VoiceSurface view:new VoiceSurface[]{page,expanded})if(view!=null){view.chat.latest.setEnabled(true);view.chat.older.setEnabled(nextBefore>0);}}});}});
|
||||
}
|
||||
void replay(String id){
|
||||
if(!visible||!networkReady||recorder!=null||sending)return;stopPlayer("rejected");playingId=id;historyPlayback=true;String t=token.get();int e=epoch,request=++playbackRequest;showStatus("正在读取历史语音…");
|
||||
worker.execute(()->{try{JSONObject clip=DisplayApi.call("/api/voice",t,body("replay").put("id",id));byte[] bytes=Base64.decode(clip.getString("audio"),Base64.DEFAULT);ui.post(()->{if(current(e,t)&&request==playbackRequest&&historyPlayback&&playingId.equals(id)&&recorder==null)play(clip,t,bytes);});}
|
||||
catch(Exception error){ui.post(()->{if(current(e,t)&&request==playbackRequest&&playingId.equals(id)){stopPlayer("rejected");showStatus("未能回听,请检查网盘和网络后再点一次");}});}});
|
||||
}
|
||||
String selectedTarget(){return destination()==null?"":selectedId;}
|
||||
void night(boolean value){night=value;dock.applyTheme(value);if(expanded!=null)expanded.applyTheme(value);if(page!=null)page.applyTheme(value);renderSurfaces();}
|
||||
@@ -119,7 +150,7 @@ final class VoicePanel extends LinearLayout {
|
||||
}
|
||||
void begin(){
|
||||
if(!visible||!networkReady||recorder!=null||sending||selectedTarget().isEmpty())return;
|
||||
JSONObject target=destination();if(target==null||!target.optBoolean("online")){showStatus("请先让对方打开 App");return;}
|
||||
JSONObject target=destination();if(target==null||!target.optBoolean("online")||!target.optBoolean("canSend",true)){showStatus("请先让对方授权并打开 App");return;}
|
||||
if(!microphone()){showStatus("请先连接麦克风;仍可接收家人喊话");return;}
|
||||
if(app.checkSelfPermission(Manifest.permission.RECORD_AUDIO)!=0){app.requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO},46);showStatus("授权麦克风后,再次按住说话");return;}
|
||||
stopPlayer("rejected");cancelled=false;recordTarget=selectedTarget();recordToken=token.get();lastMessage="";
|
||||
@@ -144,27 +175,28 @@ final class VoicePanel extends LinearLayout {
|
||||
}
|
||||
void take(String id){
|
||||
// Reserve the playback slot while the download is in flight.
|
||||
if(!playingId.isEmpty())return;playingId=id;String t=token.get();int e=epoch;
|
||||
if(!playingId.isEmpty())return;playingId=id;historyPlayback=false;String t=token.get();int e=epoch,request=++playbackRequest;
|
||||
worker.execute(()->{try{
|
||||
JSONObject clip=DisplayApi.call("/api/voice",t,body("take").put("id",id));byte[] bytes=Base64.decode(clip.getString("audio"),Base64.DEFAULT);
|
||||
ui.post(()->{if(!current(e,t)||!enabled||recorder!=null||!playingId.equals(id)){ack(t,id,"rejected");return;}play(clip,t,bytes);});
|
||||
}catch(Exception error){ui.post(()->{if(current(e,t)&&playingId.equals(id))playingId="";});}});
|
||||
ui.post(()->{if(!current(e,t)||request!=playbackRequest||!enabled||recorder!=null||!playingId.equals(id)){ack(t,id,"rejected");return;}play(clip,t,bytes);});
|
||||
}catch(Exception error){ui.post(()->{if(current(e,t)&&request==playbackRequest&&playingId.equals(id))playingId="";});}});
|
||||
}
|
||||
void play(JSONObject clip,String t,byte[] bytes){
|
||||
try{
|
||||
playingToken=t;focus=new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT).setAudioAttributes(attributes).setOnAudioFocusChangeListener(change->{if(change<0)stopPlayer("rejected");}).build();
|
||||
if(audio.requestAudioFocus(focus)!=AudioManager.AUDIOFOCUS_REQUEST_GRANTED)throw new IOException("Audio busy");
|
||||
playing=File.createTempFile("voice-play-",".aac",app.getCacheDir());Files.write(playing.toPath(),bytes);player=new MediaPlayer();player.setAudioAttributes(attributes);player.setDataSource(playing.getAbsolutePath());
|
||||
player.setOnPreparedListener(p->{if(visible&&enabled&&p==player){p.start();stop.setEnabled(true);showStatus(clip.optString("senderName")+"正在喊话 · "+clip.optDouble("seconds")+" 秒");}else stopPlayer("rejected");});
|
||||
player.setOnPreparedListener(p->{if(visible&&(enabled||historyPlayback)&&p==player){p.start();stop.setEnabled(true);showStatus(clip.optString("senderName")+(historyPlayback?" · 历史语音 · ":"正在喊话 · ")+clip.optDouble("seconds")+" 秒");}else stopPlayer("rejected");});
|
||||
player.setOnCompletionListener(p->stopPlayer("played"));player.setOnErrorListener((p,what,extra)->{stopPlayer("rejected");return true;});player.prepareAsync();
|
||||
}catch(Exception error){stopPlayer("rejected");showStatus("语音未能播放,请检查扬声器");}
|
||||
}
|
||||
void stopPlayer(String outcome){
|
||||
playbackRequest++;
|
||||
if(player!=null){try{player.release();}catch(Exception ignored){}player=null;}
|
||||
if(focus!=null){audio.abandonAudioFocusRequest(focus);focus=null;}
|
||||
if(playing!=null){playing.delete();playing=null;}
|
||||
if(!playingId.isEmpty()&&!playingToken.isEmpty())ack(playingToken,playingId,outcome);
|
||||
playingId="";playingToken="";stop.setEnabled(false);renderSurfaces();
|
||||
if(!historyPlayback&&!playingId.isEmpty()&&!playingToken.isEmpty())ack(playingToken,playingId,outcome);
|
||||
playingId="";playingToken="";historyPlayback=false;stop.setEnabled(false);renderSurfaces();
|
||||
}
|
||||
void ack(String t,String id,String state){if(!worker.isShutdown())worker.execute(()->{try{DisplayApi.call("/api/voice",t,body("ack").put("id",id).put("status",state));}catch(Exception ignored){}});}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,8 @@ final class VoiceSurface extends LinearLayout {
|
||||
final boolean full;final TextView title,subtitle,recipient,status,hint,clock,receive;
|
||||
final Button speak,settings,stop,expand;final LinearLayout people,compose;final HorizontalScrollView strip;
|
||||
final VoiceArt art;final Switch receiver;final LinearLayout destinationCard,receiverCard,playbackCard;final TextView availability;final ImageView destinationIcon;
|
||||
boolean night=false;String targetSignature="",controlSignature="";
|
||||
final VoiceChat chat;
|
||||
boolean night=false,communicationPage=false,compact=false;String targetSignature="",controlSignature="";
|
||||
int ink(){return night?0xffc8d5cd:0xff29443c;}int muted(){return night?0xff96aaa0:0xff65766d;}
|
||||
int accent(){return night?0xff456b5e:0xff17695e;}int paper(){return night?0xff172820:0xfff8f5ed;}
|
||||
int card(){return night?0xff21372d:0xfffffefa;}
|
||||
@@ -22,7 +23,7 @@ final class VoiceSurface extends LinearLayout {
|
||||
VoiceSurface(Activity activity,boolean expanded){
|
||||
super(activity);full=expanded;setOrientation(VERTICAL);setPadding(dp(full?20:12),dp(full?20:8),dp(full?20:12),dp(full?22:8));
|
||||
LinearLayout header=new LinearLayout(activity);header.setGravity(Gravity.CENTER_VERTICAL);addView(header);
|
||||
title=label(full?"家人喊话":"家人喊话",full?30:19);title.setTypeface(null,Typeface.BOLD);header.addView(title,new LayoutParams(0,-2,1));
|
||||
title=label("沟通",full?28:19);title.setTypeface(null,Typeface.BOLD);header.addView(title,new LayoutParams(0,-2,1));
|
||||
settings=button("管理",14);expand=button(full?"收起":"展开",14);if(!full)header.addView(expand);
|
||||
subtitle=label("一句问候,家就在身边",15);if(full){addView(subtitle);space(20);}
|
||||
strip=new HorizontalScrollView(activity);strip.setHorizontalScrollBarEnabled(false);strip.setClipToPadding(false);
|
||||
@@ -33,6 +34,7 @@ final class VoiceSurface extends LinearLayout {
|
||||
TextView sendLabel=label("发送到",12);sendLabel.setTextColor(0xff718078);targetWords.addView(sendLabel);
|
||||
recipient=label("选择一位家人",full?21:15);recipient.setTypeface(null,Typeface.BOLD);recipient.setMaxLines(2);recipient.setEllipsize(android.text.TextUtils.TruncateAt.END);if(full)targetWords.addView(recipient);else addView(recipient);
|
||||
availability=label("切换接收对象 ›",13);targetWords.addView(availability);destinationCard.setFocusable(true);destinationCard.setClickable(true);
|
||||
chat=new VoiceChat(activity);if(full){space(12);addView(chat,new LayoutParams(-1,-2));}
|
||||
compose=new LinearLayout(activity);compose.setOrientation(VERTICAL);compose.setGravity(Gravity.CENTER_HORIZONTAL);compose.setPadding(dp(full?4:0),dp(full?20:0),dp(full?4:0),dp(full?12:0));addView(compose,new LayoutParams(-1,-2));
|
||||
art=new VoiceArt(activity);art.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
|
||||
clock=label("按住说话",22);clock.setGravity(Gravity.CENTER);
|
||||
@@ -48,6 +50,24 @@ final class VoiceSurface extends LinearLayout {
|
||||
applyTheme(false);
|
||||
}
|
||||
TextView label(String text,int size){TextView v=new TextView(getContext());v.setText(text);v.setTextSize(size);v.setPadding(0,dp(3),0,dp(3));return v;}
|
||||
void communicationPage(){
|
||||
communicationPage=true;
|
||||
removeView(receiverCard);removeView(playbackCard);chat.addView(playbackCard,new LayoutParams(-1,-2));
|
||||
subtitle.setVisibility(GONE);compose.setPadding(0,dp(8),0,0);speak.setLayoutParams(new LayoutParams(dp(150),dp(150)));clock.setLayoutParams(new LayoutParams(-1,dp(42)));art.setLayoutParams(new LayoutParams(-1,dp(18)));
|
||||
destinationCard.setPadding(dp(12),dp(10),dp(12),dp(10));setPadding(dp(16),dp(10),dp(16),dp(6));
|
||||
chat.setLayoutParams(new LayoutParams(-1,0,1));chat.scroll.setLayoutParams(new LayoutParams(-1,0,1));
|
||||
status.setTextSize(12);playbackCard.setPadding(0,dp(4),0,dp(4));
|
||||
}
|
||||
protected void onMeasure(int width,int height){
|
||||
int available=View.MeasureSpec.getSize(height);boolean small=available>0&&available<dp(680);
|
||||
if(communicationPage&&available>0&&small!=compact){compact=small;
|
||||
title.setTextSize(small?23:28);recipient.setTextSize(small?18:21);speak.setLayoutParams(new LayoutParams(dp(small?120:150),dp(small?120:150)));clock.setLayoutParams(new LayoutParams(-1,dp(small?32:42)));art.setLayoutParams(new LayoutParams(-1,dp(small?12:18)));
|
||||
for(int i=0;i<getChildCount();i++){View child=getChildAt(i);if(child.getClass()==View.class)child.setLayoutParams(new LayoutParams(1,dp(small?4:12)));}
|
||||
destinationIcon.setLayoutParams(new LayoutParams(dp(small?38:52),dp(small?38:52)));destinationCard.setPadding(dp(12),dp(small?5:10),dp(12),dp(small?5:10));
|
||||
chat.setPadding(dp(small?12:16),dp(small?10:16),dp(small?12:16),dp(small?10:16));
|
||||
}
|
||||
super.onMeasure(width,height);
|
||||
}
|
||||
void compactHome(){
|
||||
if(full)return;removeAllViews();for(View v:new View[]{recipient,speak,status,stop})if(v.getParent()!=null)((ViewGroup)v.getParent()).removeView(v);
|
||||
setPadding(dp(12),dp(10),dp(12),dp(8));setBackground(shape(card(),0,18));LinearLayout row=new LinearLayout(getContext());row.setGravity(Gravity.CENTER_VERTICAL);
|
||||
@@ -59,7 +79,7 @@ final class VoiceSurface extends LinearLayout {
|
||||
void space(int amount){spaceIn(this,amount);}void spaceIn(LinearLayout parent,int amount){parent.addView(new View(getContext()),new LayoutParams(1,dp(amount)));}
|
||||
GradientDrawable shape(int color,int border,int radius){GradientDrawable d=new GradientDrawable();d.setColor(color);d.setCornerRadius(dp(radius));if(border!=0)d.setStroke(dp(1),border);return d;}
|
||||
void applyTheme(boolean value){
|
||||
night=value;setBackgroundColor(paper());for(TextView t:new TextView[]{title,recipient,clock})t.setTextColor(ink());for(TextView t:new TextView[]{subtitle,status,hint,receive})t.setTextColor(muted());
|
||||
night=value;chat.theme(value);setBackgroundColor(paper());for(TextView t:new TextView[]{title,recipient,clock})t.setTextColor(ink());for(TextView t:new TextView[]{subtitle,status,hint,receive})t.setTextColor(muted());
|
||||
compose.setBackground(null);for(View v:new View[]{destinationCard,receiverCard,playbackCard})v.setBackground(full?shape(card(),0,20):null);receiver.setTextColor(ink());availability.setTextColor(muted());
|
||||
for(Button b:new Button[]{settings,stop,expand}){b.setTextColor(ink());b.setBackground(shape(night?0xff2d4439:0xffefeee6,0,18));}
|
||||
art.night=value;art.invalidate();targetSignature="";controlSignature="";
|
||||
@@ -67,7 +87,7 @@ final class VoiceSurface extends LinearLayout {
|
||||
void destination(JSONObject selected,boolean ready){
|
||||
String name=selected==null?"选择一位家人":selected.optString("name","家人");boolean online=selected!=null&&selected.optBoolean("online");
|
||||
destinationIcon.setImageDrawable(new PhoneStyle.Icon(selected!=null&&"display".equals(selected.optString("kind"))?"display":"person",accent(),dp(48)));
|
||||
text(availability,selected==null?"点击选择接收对象 ›":(!ready?"连接待恢复":online?"● 在线":"○ 未打开 App")+" · 切换 ›");destinationCard.setContentDescription("发送到 "+name+","+availability.getText());
|
||||
text(availability,selected==null?"点击选择接收对象 ›":(!ready?"连接待恢复":!selected.optBoolean("canSend",true)?"历史会话 · 发送需重新授权":online?"● 在线":"○ 未打开 App")+" · 切换 ›");destinationCard.setContentDescription("发送到 "+name+","+availability.getText());
|
||||
}
|
||||
void receiving(boolean enabled,boolean ready){receiver.setChecked(enabled);receiver.setEnabled(ready);}
|
||||
void targets(JSONArray values,String selected,Consumer<String> choose){
|
||||
@@ -90,7 +110,7 @@ final class VoiceSurface extends LinearLayout {
|
||||
android.text.SpannableString text=new android.text.SpannableString(" "+label);text.setSpan(new android.text.style.ImageSpan(inline,android.text.style.ImageSpan.ALIGN_BOTTOM),0,1,android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);if(!full&&(!android.text.TextUtils.equals(speak.getText(),text)||!controlSignature.equals(color+":"+night)))speak.setText(text);if(full){text(speak,"");speak.setContentDescription(label+",上滑取消,最长 30 秒");}speak.setTextColor(night?0xffd1dfd5:Color.WHITE);
|
||||
String signature=color+":"+night;if(!signature.equals(controlSignature)){controlSignature=signature;
|
||||
speak.setBackground(new RippleDrawable(ColorStateList.valueOf(0x337fffff),full?new VoiceCircle(color,night):shape(color,0,32),null));}
|
||||
clock.setTextSize(recording?32:23);clock.setTypeface(null,Typeface.BOLD);text(clock,recording?String.format(java.util.Locale.ROOT,"00:%02d",Math.min(30,duration/1000)):uploading?"正在发送…":"按住说话");clock.setTextColor(cancel?color:ink());
|
||||
clock.setTextSize(recording?(compact?24:32):compact?19:23);clock.setTypeface(null,Typeface.BOLD);text(clock,recording?String.format(java.util.Locale.ROOT,"00:%02d",Math.min(30,duration/1000)):uploading?"正在发送…":"按住说话");clock.setTextColor(cancel?color:ink());
|
||||
text(hint,recording?(cancel?"松开手指,取消这条语音":"上滑取消 · 松开发送 · 30 秒自动发送"):"上滑取消 · 最长 30 秒");hint.setTextColor(cancel?color:muted());
|
||||
art.setVisibility(recording?VISIBLE:INVISIBLE);art.level(recording,cancel,amplitude);if(!full&&recording)text(recipient,String.format(java.util.Locale.CHINA,"%s · %02d 秒",cancel?"松开即取消":"正在录音,上滑可取消",Math.min(30,duration/1000)));
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ $env:Path="$jdk\bin;$env:Path"
|
||||
'@ | Set-Content -LiteralPath "$stage\AndroidManifest.xml" -Encoding utf8
|
||||
& "$bt\aapt2.exe" link -o "$stage\unsigned.apk" -I $android --manifest "$stage\AndroidManifest.xml"
|
||||
if($LASTEXITCODE){throw 'Test resource linking failed'}
|
||||
$sources=@("$source\src\cn\ucvl\zhaodisplay\LocationActivity.java","$source\src\cn\ucvl\zhaodisplay\PhoneLayout.java","$source\src\cn\ucvl\zhaodisplay\PhoneStyle.java","$source\src\cn\ucvl\zhaodisplay\VoicePanel.java","$source\src\cn\ucvl\zhaodisplay\VoiceSurface.java","$source\src\cn\ucvl\zhaodisplay\VoiceGesture.java","$source\src\cn\ucvl\zhaodisplay\LocationCadence.java") + @((Get-ChildItem "$tests\phone-preview" -Filter "*.java").FullName)
|
||||
$sources=@("$source\src\cn\ucvl\zhaodisplay\LocationActivity.java","$source\src\cn\ucvl\zhaodisplay\PhoneLayout.java","$source\src\cn\ucvl\zhaodisplay\PhoneStyle.java","$source\src\cn\ucvl\zhaodisplay\VoicePanel.java","$source\src\cn\ucvl\zhaodisplay\VoiceSurface.java","$source\src\cn\ucvl\zhaodisplay\VoiceChat.java","$source\src\cn\ucvl\zhaodisplay\VoiceGesture.java","$source\src\cn\ucvl\zhaodisplay\LocationCadence.java") + @((Get-ChildItem "$tests\phone-preview" -Filter "*.java").FullName)
|
||||
& "$jdk\bin\javac.exe" -encoding UTF-8 -source 8 -target 8 -cp $android -d "$stage\classes" @sources
|
||||
if($LASTEXITCODE){throw 'Test Java compile failed'}
|
||||
& "$jdk\bin\jar.exe" cf "$stage\classes.jar" -C "$stage\classes" .
|
||||
|
||||
@@ -6,8 +6,11 @@ final class DisplayApi {
|
||||
static class ApiError extends Exception {final int status;ApiError(int status){this.status=status;}}
|
||||
static JSONObject call(String path,String token,JSONObject body)throws Exception{
|
||||
if(expired)throw new ApiError(401);if(offline)throw new ApiError(503);String action=body.optString("action");
|
||||
if(path.equals("/api/voice"))return new JSONObject("{\"enabled\":false,\"allowed\":[],\"candidates\":[{\"id\":\"phone:demo\",\"name\":\"示例家人的手机\"}],\"targets\":[{\"id\":\"display:demo\",\"name\":\"家庭显示终端\",\"kind\":\"display\",\"online\":true}],\"sent\":[],\"inbox\":[]}");
|
||||
if(action.equals("list")){JSONObject a=new JSONObject("{\"id\":\"a\",\"name\":\"家人甲(示例)\",\"status\":\"live\"}");a.put("position",new JSONObject().put("latitude",0).put("longitude",0).put("accuracy",25).put("at",System.currentTimeMillis()/1000));JSONObject b=new JSONObject("{\"id\":\"b\",\"name\":\"家人乙(示例)\",\"status\":\"scheduled\",\"scheduleReason\":\"sampling\"}");return new JSONObject().put("items",new JSONArray().put(a).put(b));}
|
||||
if(path.equals("/api/voice")){
|
||||
if(action.equals("history")){boolean old=body.optLong("before")>0;JSONArray items=new JSONArray();for(int i=0;i<3;i++)items.put(new JSONObject().put("id","chat-"+i).put("seq",i+1).put("mine",i%2==0).put("senderName",i%2==0?"示例成员的手机":"家庭显示终端").put("at",1792387200+i*60-(old?86400:0)).put("seconds",i+3.6).put("delivery",i==2?"queued":"played").put("archive",i==2?"pending":"cloud"));return new JSONObject().put("items",items).put("before",old?0:12);}
|
||||
return new JSONObject("{\"enabled\":false,\"allowed\":[],\"candidates\":[{\"id\":\"phone:demo\",\"name\":\"示例家人的手机\"}],\"targets\":[{\"id\":\"display:demo\",\"archiveKey\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"name\":\"家庭显示终端\",\"kind\":\"display\",\"online\":true}],\"conversations\":[],\"sent\":[],\"inbox\":[]}");
|
||||
}
|
||||
if(action.equals("list")){JSONObject a=new JSONObject("{\"id\":\"a\",\"name\":\"家人甲(示例)\",\"status\":\"live\"}");a.put("position",new JSONObject().put("latitude",0).put("longitude",0).put("accuracy",25).put("at",System.currentTimeMillis()/1000-120));JSONObject b=new JSONObject("{\"id\":\"b\",\"name\":\"家人乙(示例)\",\"status\":\"scheduled\",\"scheduleReason\":\"sampling\"}");JSONObject c=new JSONObject().put("id","c").put("name","家人丙(示例)").put("position",new JSONObject().put("latitude",0).put("longitude",0).put("accuracy",10).put("at",System.currentTimeMillis()/1000));return new JSONObject().put("items",new JSONArray().put(b).put(a).put(c));}
|
||||
if(action.equals("settings"))return new JSONObject("{\"receipt\":\"fixture\",\"intervalSeconds\":7200,\"sampleIntervalSeconds\":300,\"historyEnabled\":true,\"historyDefault\":true,\"viewerIds\":[],\"phoneIds\":[\"demo\"],\"displayIds\":[],\"viewers\":[],\"phones\":[{\"id\":\"demo\",\"name\":\"示例家人的手机\"}],\"displays\":[],\"history\":{\"pending\":0,\"archived\":2,\"deleting\":0}}");
|
||||
throw new ApiError(403);
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@ import android.graphics.*;
|
||||
import org.json.*;
|
||||
/** Clearly labelled placeholder: no map tiles or real coordinates in this offline fixture. */
|
||||
final class LocationMapView extends android.view.View {
|
||||
JSONArray items;Paint p=new Paint(3);
|
||||
JSONArray items;JSONObject focused;Paint p=new Paint(3);
|
||||
LocationMapView(android.content.Context c){super(c);setContentDescription("地图占位,隔离验收不加载真实位置");}
|
||||
void setItems(JSONArray a){items=a;invalidate();}void setTrack(JSONArray a){}void reset(){}void focus(JSONObject p){}void resumeMap(){}void pauseMap(){setItems(new JSONArray());}void close(){}
|
||||
void setItems(JSONArray a){items=a;invalidate();}void setTrack(JSONArray a){}void reset(){}void focus(JSONObject p){focused=p;}void resumeMap(){}void pauseMap(){setItems(new JSONArray());}void close(){}
|
||||
protected void onDraw(Canvas c){c.drawColor(0xffe7eee5);float d=getResources().getDisplayMetrics().density;p.setColor(0xffc9d9ce);p.setStrokeWidth(2*d);for(int x=0;x<getWidth();x+=60*d)c.drawLine(x,0,x,getHeight(),p);for(int y=0;y<getHeight();y+=60*d)c.drawLine(0,y,getWidth(),y,p);p.setColor(PhoneStyle.MUTED);p.setTextSize(15*d);p.setTextAlign(Paint.Align.CENTER);c.drawText("智家地图 · 隔离验收占位",getWidth()/2f,getHeight()/2f,p);p.setTextSize(12*d);c.drawText("正式版加载已授权家人位置",getWidth()/2f,getHeight()/2f+25*d,p);}
|
||||
}
|
||||
|
||||
@@ -18,13 +18,16 @@ public class PhonePreviewActivity extends LocationActivity {
|
||||
// Limit the actual Activity layout to a phone viewport without changing display configuration.
|
||||
((android.view.ViewGroup)phone.getParent()).removeView(phone);FrameLayout outer=new FrameLayout(this);outer.setBackgroundColor(PhoneStyle.PAPER);
|
||||
int width="narrow".equals(mode)||"large".equals(mode)?320:390;outer.addView(phone,new FrameLayout.LayoutParams(style.dp(width),style.dp("narrow".equals(mode)?640:844),Gravity.TOP|Gravity.CENTER_HORIZONTAL));previewRoot=phone;setContentView(outer);
|
||||
new Handler().postDelayed(()->{try{exercise();save();}catch(Exception e){throw new RuntimeException(e);}},1800);
|
||||
new Handler().postDelayed(()->{try{exercise();if(mode.equals("history"))exerciseHistory();else save();}catch(Exception e){throw new RuntimeException(e);}},1800);
|
||||
}
|
||||
void check(boolean condition,String message){if(!condition)throw new AssertionError(message);}
|
||||
void exercise()throws Exception{
|
||||
check(!prefs.getBoolean("active",false),"opening app must not share");
|
||||
if(!mode.equals("offline")&&!mode.equals("unpaired")&&!mode.equals("expired")){
|
||||
check(settingsReady,"settings loaded");check(samplePeriodSeconds()==300&&uploadPeriod()==7200,"independent cadence loaded");check(familyList.getChildCount()==2,"authorized family cards rendered");
|
||||
check(settingsReady,"settings loaded");check(samplePeriodSeconds()==300&&uploadPeriod()==7200,"independent cadence loaded");check(familyList.getChildCount()==3,"authorized family cards rendered");
|
||||
check(map.items.optJSONObject(0).optString("id").equals("c")&&map.items.optJSONObject(2).optString("id").equals("b"),"collection time descending, missing fixes last");
|
||||
((android.view.ViewGroup)familyList.getChildAt(0)).getChildAt(1).performClick();check(map.focused==map.items.optJSONObject(0).optJSONObject("position"),"row focuses the matching point");
|
||||
check(voice.getParent()==null,"no voice dock on the position page");check(voice.dock.receiverCard.getParent()==phone.voiceSettings,"receiver controls belong to my settings");
|
||||
phone.nav.getChildAt(2).performClick();check(phone.tab==2,"mine tab click");phone.sampling.performClick();check(detailDialog!=null&&detailDialog.isShowing(),"sampling opens full screen");detailDialog.dismiss();
|
||||
check(sampleCadence.getParent()==sampleSection,"sample controls retain their owner");
|
||||
phone.upload.performClick();check(detailDialog!=null,"upload detail");detailDialog.dismiss();
|
||||
@@ -32,7 +35,7 @@ public class PhonePreviewActivity extends LocationActivity {
|
||||
check(!prefs.getBoolean("active",false),"navigation never enables sharing");
|
||||
}
|
||||
if(mode.equals("mine")||mode.equals("large"))selectTab(2);
|
||||
else if(mode.equals("voice")||mode.equals("recording")||mode.equals("cancel")||mode.equals("narrow")){
|
||||
else if(mode.equals("voice")||mode.equals("recording")||mode.equals("cancel")||mode.equals("narrow")||mode.equals("history")){
|
||||
selectTab(1);voice.ui.removeCallbacks(voice.visual);VoiceSurface v=voice.page();v.expand.setVisibility(View.GONE);v.destination(new JSONObject("{\"name\":\"家庭显示终端\",\"kind\":\"display\",\"online\":true}"),true);v.recipient.setText("家庭显示终端");v.status.setText("界面验收 · 不录音、不发送语音");
|
||||
boolean recording=mode.equals("recording")||mode.equals("cancel");for(int i=0;i<31;i++)v.recording(recording,mode.equals("cancel"),8000,(int)(9000*Math.abs(Math.sin(i))),false,true);
|
||||
}
|
||||
@@ -40,8 +43,11 @@ public class PhonePreviewActivity extends LocationActivity {
|
||||
else selectTab(0);
|
||||
if(mode.equals("expired")){check(pairingRequired(),"expired requires re-pairing");check(!sharing.isEnabled(),"expired cannot start sharing");phone.check.performClick();check(detailDialog!=null&&pairSection.getParent()!=settings,"status routes to pairing instead of OS permission settings");detailDialog.dismiss();}
|
||||
if(mode.equals("offline")){check(familyList.getChildCount()==0,"offline stale positions removed");check(!sharing.isEnabled(),"offline cannot start sharing");}
|
||||
check(phone.nav.getChildCount()==3,"exactly three tabs");
|
||||
try(java.io.FileWriter f=new java.io.FileWriter(new java.io.File(getExternalFilesDir(null),"checks.txt"))){f.write("PASS "+mode+" production UI navigation, permission boundary and form ownership");}
|
||||
check(phone.nav.getChildCount()==3,"exactly three tabs");check(phone.navLabels[0].getText().toString().equals("位置")&&phone.navLabels[1].getText().toString().equals("沟通"),"requested navigation names");
|
||||
check(voice.page().receiverCard.getParent()==null,"communication page does not duplicate settings");
|
||||
}
|
||||
void save(){previewRoot.postDelayed(()->{try{check(sampleSection.getParent()==settings&&uploadSection.getParent()==settings,"dismissed forms safely returned after queued dialog callbacks");android.graphics.Bitmap b=android.graphics.Bitmap.createBitmap(previewRoot.getWidth(),previewRoot.getHeight(),android.graphics.Bitmap.Config.ARGB_8888);previewRoot.draw(new android.graphics.Canvas(b));try(java.io.FileOutputStream f=new java.io.FileOutputStream(new java.io.File(getExternalFilesDir(null),"preview.png"))){b.compress(android.graphics.Bitmap.CompressFormat.PNG,100,f);}b.recycle();}catch(Exception e){throw new RuntimeException(e);}},300);}
|
||||
void exerciseHistory(){
|
||||
new Handler().postDelayed(()->{check(voice.nextBefore==12,"history initial page");voice.page().chat.older.performClick();new Handler().postDelayed(()->{check(voice.historyBefore==12&&voice.nextBefore==0,"older page loaded");check(!voice.page().chat.older.isEnabled(),"end of history disables older");voice.page().chat.latest.performClick();new Handler().postDelayed(()->{check(voice.historyBefore==0&&voice.nextBefore==12,"return to latest page");check(!voice.enabled,"reading history does not enable reception");save();},250);},250);},250);
|
||||
}
|
||||
void save(){previewRoot.postDelayed(()->{try{check(sampleSection.getParent()==settings&&uploadSection.getParent()==settings,"dismissed forms safely returned after queued dialog callbacks");if(phone.tab==1){check(voice.page().chat.messages.getChildCount()==3,"real controller loads chat history");check(voice.nextBefore==12,"older history cursor available");check(voice.page().chat.scroll.getHeight()>=style.dp(90),"chat viewport="+voice.page().chat.scroll.getHeight()+", root="+voice.page().getHeight()+", chat="+voice.page().chat.getHeight()+", compose="+voice.page().compose.getHeight()+", compact="+voice.page().compact);check(voice.page().speak.getHeight()>=style.dp(110),"microphone remains a large target");}android.graphics.Bitmap b=android.graphics.Bitmap.createBitmap(previewRoot.getWidth(),previewRoot.getHeight(),android.graphics.Bitmap.Config.ARGB_8888);previewRoot.draw(new android.graphics.Canvas(b));try(java.io.FileOutputStream f=new java.io.FileOutputStream(new java.io.File(getExternalFilesDir(null),"preview.png"))){b.compress(android.graphics.Bitmap.CompressFormat.PNG,100,f);}b.recycle();try(java.io.FileWriter f=new java.io.FileWriter(new java.io.File(getExternalFilesDir(null),"checks.txt"))){f.write("PASS "+mode+" production navigation, chronological list, focus, chat visibility and settings ownership");}}catch(Exception e){throw new RuntimeException(e);}},600);}
|
||||
}
|
||||
|
||||
+29
-15
@@ -1,25 +1,30 @@
|
||||
"""Explicitly permitted, short household announcements. Audio is RAM-only with a TTL."""
|
||||
"""Explicitly permitted announcements plus durable, device-bound conversations."""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
from voice_history import VoiceHistory
|
||||
|
||||
|
||||
class Voice:
|
||||
def __init__(self, app):
|
||||
self.a=app; self.online={}; self.messages={}; self.receipts={}; self.rates={}
|
||||
self.a=app; self.online={}; self.messages={}; self.receipts={}; self.rates={}; self.history=VoiceHistory(app)
|
||||
|
||||
def initialize(self):
|
||||
with self.a.LOCK,self.a.DB:
|
||||
self.a.DB.execute('CREATE TABLE IF NOT EXISTS voice_receivers '
|
||||
'(endpoint TEXT PRIMARY KEY, family_id TEXT, enabled INTEGER, allowed TEXT)')
|
||||
self.online.clear(); self.messages.clear(); self.receipts.clear(); self.rates.clear()
|
||||
self.history.initialize()
|
||||
|
||||
def watch(self):
|
||||
while True:
|
||||
time.sleep(10)
|
||||
with self.a.LOCK:self.sweep()
|
||||
try:
|
||||
with self.a.LOCK,self.a.DB:self.sweep()
|
||||
self.history.tick()
|
||||
except Exception:pass # Pending cloud work stays durable for a later retry.
|
||||
|
||||
def endpoint(self, key):
|
||||
a=self.a;now=time.time()
|
||||
@@ -28,12 +33,12 @@ class Voice:
|
||||
if kind=='phone':
|
||||
row=a.DB.execute('SELECT * FROM member_location_shares WHERE id=? AND expires>?',(sid,now)).fetchone()
|
||||
valid=a.LOCATIONS.eligible(row['family_id'],row['member_id']) if row else None
|
||||
if valid:return dict(id=key,kind=kind,familyId=row['family_id'],name=valid[1]['name']+'的手机')
|
||||
if valid:return dict(id=key,kind=kind,familyId=row['family_id'],name=valid[1]['name']+'的手机',archiveKey=self.history.identity(row['family_id'],kind,row['member_id']))
|
||||
elif kind=='display':
|
||||
row=a.DB.execute('SELECT * FROM household_displays WHERE id=? AND revoked=0 AND expires_at>?',(sid,now)).fetchone()
|
||||
device=a.get_object('devices',row['device_id']) if row else None
|
||||
if device and a.HOUSEHOLDS.family_of(device)==row['family_id']:
|
||||
return dict(id=key,kind=kind,familyId=row['family_id'],name=device['name'])
|
||||
return dict(id=key,kind=kind,familyId=row['family_id'],name=device['name'],archiveKey=self.history.identity(row['family_id'],kind,row['device_id']))
|
||||
return None
|
||||
|
||||
def authorize(self, token, kind):
|
||||
@@ -70,6 +75,7 @@ class Voice:
|
||||
if message['expires']<=now or not self.permitted(self.endpoint(message['sender']),self.endpoint(message['target'])):
|
||||
self.messages.pop(key,None)
|
||||
if key in self.receipts:self.receipts[key]['status']='expired'
|
||||
self.history.delivery(key,'expired')
|
||||
self.receipts={k:v for k,v in self.receipts.items() if v['expires']>now}
|
||||
self.online={k:v for k,v in self.online.items() if now-v<60}
|
||||
self.rates={k:v for k,v in self.rates.items() if now-v[0]<60}
|
||||
@@ -115,14 +121,17 @@ class Voice:
|
||||
|
||||
def native(self, token, body):
|
||||
a=self.a;now=time.time()
|
||||
if body.get('action')=='replay':return self.history.replay(token,body,self.authorize)
|
||||
with a.LOCK,a.DB:
|
||||
actor=self.authorize(token,body.get('kind'));self.sweep()
|
||||
action=body.get('action');me=actor['id']
|
||||
if action=='configure':return self.configure(actor,body)
|
||||
if action=='history':return self.history.listing(actor,body)
|
||||
if action=='offline':
|
||||
self.online.pop(me,None)
|
||||
for key,m in list(self.messages.items()):
|
||||
if m['target']==me:self.messages.pop(key);self.receipts[key]['status']='rejected'
|
||||
if m['target']==me:
|
||||
self.messages.pop(key);self.receipts[key]['status']='rejected';self.history.delivery(key,'rejected')
|
||||
return dict(ok=True)
|
||||
if action=='status':
|
||||
self.online[me]=now
|
||||
@@ -130,17 +139,13 @@ class Voice:
|
||||
targets=[dict(ep,online=now-self.online.get(ep['id'],0)<20) for ep in candidates if self.permitted(actor,ep)]
|
||||
inbox=[dict(id=k,senderName=m['senderName'],seconds=m['seconds']) for k,m in self.messages.items() if m['target']==me]
|
||||
sent=[dict(id=k,status=r['status']) for k,r in self.receipts.items() if r['sender']==me]
|
||||
return dict(me=actor,**self.settings(actor),candidates=candidates,targets=targets,inbox=inbox,sent=sent)
|
||||
return dict(me=actor,**self.settings(actor),candidates=candidates,targets=targets,inbox=inbox,sent=sent,conversations=self.history.conversations(actor))
|
||||
if action=='send':
|
||||
target=self.endpoint(body.get('target'))
|
||||
if not self.permitted(actor,target):raise a.Problem('对方尚未允许你喊话,或已关闭接收',403)
|
||||
if now-self.online.get(target['id'],0)>=20:raise a.Problem('对方不在线,请等对方打开 App',409)
|
||||
if not target:raise a.Problem('接收设备配对已失效',403)
|
||||
message_id=body.get('id','')
|
||||
if not isinstance(message_id,str) or not re.fullmatch(r'[a-f0-9]{32}',message_id):raise a.Problem('喊话编号不正确')
|
||||
key=me+':'+message_id
|
||||
if key in self.receipts:return dict(ok=True,id=key,status=self.receipts[key]['status'])
|
||||
at,count=self.rates.get(me,(now,0))
|
||||
if count>=10:raise a.Problem('喊话过于频繁,请稍后再试',429)
|
||||
key=actor['archiveKey']+':'+message_id
|
||||
encoded=body.get('audio','')
|
||||
if not isinstance(encoded,str) or not 0<len(encoded)<=200000:raise a.Problem('语音大小超出限制')
|
||||
try:
|
||||
@@ -148,11 +153,19 @@ class Voice:
|
||||
if len(raw)>150000:raise ValueError()
|
||||
seconds=self.duration(raw)
|
||||
except (ValueError,TypeError):raise a.Problem('请上传 0.3 至 30 秒的 AAC 语音')
|
||||
if self.history.existing(key):
|
||||
previous=self.history.accept(key,actor,target,raw,seconds)
|
||||
return dict(ok=True,id=key,status=previous['delivery'],archive=previous['state'])
|
||||
if not self.permitted(actor,target):raise a.Problem('对方尚未允许你喊话,或已关闭接收',403)
|
||||
if now-self.online.get(target['id'],0)>=20:raise a.Problem('对方不在线,请等对方打开 App',409)
|
||||
at,count=self.rates.get(me,(now,0))
|
||||
if count>=10:raise a.Problem('喊话过于频繁,请稍后再试',429)
|
||||
if len(self.messages)>=48 or len(self.receipts)>=2048 or sum(m['target']==target['id'] for m in self.messages.values())>=3:raise a.Problem('对方还有待播放的喊话,请稍候',429)
|
||||
self.rates[me]=(at,count+1)
|
||||
self.history.accept(key,actor,target,raw,seconds)
|
||||
self.messages[key]=dict(sender=me,target=target['id'],senderName=actor['name'],audio=raw,seconds=seconds,expires=now+90)
|
||||
self.receipts[key]=dict(sender=me,target=target['id'],status='queued',expires=now+180)
|
||||
return dict(ok=True,id=key,status='queued')
|
||||
return dict(ok=True,id=key,status='queued',archive='pending')
|
||||
key=body.get('id','')
|
||||
if not isinstance(key,str):raise a.Problem('喊话编号不正确')
|
||||
receipt=self.receipts.get(key)
|
||||
@@ -160,9 +173,10 @@ class Voice:
|
||||
m=self.messages.get(key)
|
||||
if not m or m['target']!=me or not self.permitted(self.endpoint(m['sender']),actor):raise a.Problem('语音已过期或没有接收权限',404)
|
||||
del self.messages[key];receipt['status']='received'
|
||||
self.history.delivery(key,'received')
|
||||
return dict(id=key,senderName=m['senderName'],seconds=m['seconds'],audio=base64.b64encode(m['audio']).decode())
|
||||
if action=='ack':
|
||||
if not receipt or receipt['target']!=me or receipt['status']!='received':raise a.Problem('喊话回执不存在',404)
|
||||
if body.get('status') not in ('played','rejected'):raise a.Problem('回执不正确')
|
||||
receipt['status']=body['status'];return dict(ok=True)
|
||||
receipt['status']=body['status'];self.history.delivery(key,body['status']);return dict(ok=True)
|
||||
raise a.Problem('喊话操作不正确')
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "zhao-steward-ui",
|
||||
"private": true,
|
||||
"version": "0.1.52",
|
||||
"version": "0.1.53",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "vite build",
|
||||
|
||||
@@ -9,7 +9,7 @@ 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 abort=new AbortController();let pulseTimer
|
||||
const origin=location.origin
|
||||
const chosen=(lon,lat)=>regionAt(catalog.regions||[],lon,lat)
|
||||
const style=()=>{
|
||||
@@ -36,7 +36,7 @@ export function createFamilyMap(container,{onSelect=()=>{},onStatus=()=>{},night
|
||||
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)}
|
||||
el.onclick=()=>{selected=p.id;onSelect(p.id);focus(p.id,true)}
|
||||
markers.set(p.id,new Marker({element:el,anchor:'bottom'}).setLngLat([p.position.longitude,p.position.latitude]).addTo(map))
|
||||
}
|
||||
if(map.isStyleLoaded()){
|
||||
@@ -54,8 +54,8 @@ export function createFamilyMap(container,{onSelect=()=>{},onStatus=()=>{},night
|
||||
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()}
|
||||
function focus(id,pulse=false){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();if(pulse){clearTimeout(pulseTimer);for(const marker of markers.values())marker.getElement().classList.remove('pulsing');const el=markers.get(id)?.getElement();if(el){void el.offsetWidth;el.classList.add('pulsing');pulseTimer=setTimeout(()=>el.classList.remove('pulsing'),3300)}}}
|
||||
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();clearTimeout(pulseTimer);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'})
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
.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}
|
||||
.family-map-pin>b{color:#193d34}
|
||||
[data-theme=night] .family-map-pin>b{color:#cad9d2}
|
||||
.family-map-pin.pulsing>span{animation:family-position-pulse 1.1s ease-out 3}
|
||||
@keyframes family-position-pulse{0%,100%{box-shadow:0 0 0 0 #d37f3a70}65%{box-shadow:0 0 0 20px #d37f3a00}}
|
||||
@media(prefers-reduced-motion:reduce){.family-map-pin.pulsing>span{animation:none;outline:5px solid #d37f3a}}
|
||||
|
||||
@@ -2,7 +2,7 @@ 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)}}
|
||||
window.ZhaoMap={setItems:items=>map.setItems(items),setTrack:points=>map.setTrack(points),focus:id=>map.focus(id,true),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)
|
||||
|
||||
@@ -80,12 +80,16 @@ class AndroidLocationContractTests(unittest.TestCase):
|
||||
def test_phone_three_tabs_use_native_cards_and_keep_sharing_explicit(self):
|
||||
source=(ANDROID/'src/cn/ucvl/zhaodisplay/LocationActivity.java').read_text(encoding='utf-8')
|
||||
layout=(ANDROID/'src/cn/ucvl/zhaodisplay/PhoneLayout.java').read_text(encoding='utf-8')
|
||||
for value in ('"家人","喊话","我的"','scrolls[i].setVisibility(i==next?VISIBLE:GONE)','setContentDescription','共享我的位置'):
|
||||
for value in ('"位置","沟通","我的"','scrolls[i].setVisibility(i==next?VISIBLE:GONE)','setContentDescription','共享我的位置'):
|
||||
self.assertIn(value,layout)
|
||||
for value in ('voice.finish(false);phone.select(tab)','if(content.getParent()==scroll)','开启共享后生效','consent.setChecked(false)','showDetail("允许谁查看"','setLayout(-1,-1)'):
|
||||
self.assertIn(value,source)
|
||||
self.assertNotIn('startService',layout)
|
||||
self.assertNotIn('https://',layout)
|
||||
self.assertNotIn('dockSlot',layout)
|
||||
self.assertIn('sortPositions(response.optJSONArray',source)
|
||||
self.assertIn('voice.dock.receiverCard',source)
|
||||
self.assertIn('voice.communication(tab==1)',source)
|
||||
|
||||
def test_voice_page_uses_explicit_receiver_consent_and_cancels_on_navigation(self):
|
||||
source=(ANDROID/'src/cn/ucvl/zhaodisplay/VoicePanel.java').read_text(encoding='utf-8')
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import {test} from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import vm from 'node:vm'
|
||||
import {visiblePeople,accuracyCircle,regionAt,trackCollection} from './frontend/src/maps/model.mjs'
|
||||
|
||||
function fixture(){
|
||||
const timers=new Map(),elements=[],maps=[];let timer=0
|
||||
const el=()=>{const names=new Set();return {classList:{add:n=>names.add(n),remove:n=>names.delete(n),toggle:(n,v)=>v?names.add(n):names.delete(n),contains:n=>names.has(n)},offsetWidth:40,setAttribute(){},append(...children){this.firstChild=children[0];this.lastChild=children.at(-1)}}}
|
||||
class Marker{constructor({element}){this.element=element;elements.push(element)}setLngLat(pos){this.pos=pos;return this}addTo(){return this}remove(){}getElement(){return this.element}}
|
||||
class MapView{constructor(){this.events={};this.moves=[];maps.push(this)}getCenter(){return {lng:117,lat:36}}getZoom(){return 10}getMaxZoom(){return 18}setMaxZoom(){}addControl(){}on(name,fn){this.events[name]=fn}once(){}isStyleLoaded(){return false}easeTo(v){this.moves.push(v)}fitBounds(){}setStyle(){}resize(){}remove(){this.removed=true}}
|
||||
const source=fs.readFileSync('frontend/src/maps/controller.js','utf8').replace(/^import .*$/gm,'').replace('export function createFamilyMap','function createFamilyMap')+'\nthis.create=createFamilyMap'
|
||||
const context=vm.createContext({Map,Set,Math,Array,String,Date,AbortController,LibreMap:MapView,Marker,NavigationControl:class{},ScaleControl:class{},AttributionControl:class{},workerUrl:'local',setWorkerUrl(){},setWorkerCount(){},layers:()=>[],namedFlavor:()=>({}),visiblePeople,accuracyCircle,regionAt,trackCollection,location:{origin:'http://local'},document:{createElement:el},ResizeObserver:class{observe(){}disconnect(){}},setTimeout:fn=>{timers.set(++timer,fn);return timer},clearTimeout:id=>timers.delete(id),setInterval:()=>0,clearInterval(){},fetch:async()=>({ok:true,json:async()=>({regions:[{id:'cn-37',name:'山东',bounds:[114,34,123,39],maxZoom:18}]})})
|
||||
})
|
||||
vm.runInContext(source,context)
|
||||
return {controller:context.create({}),maps,elements,timers}
|
||||
}
|
||||
|
||||
test('click focus pulses only selected fresh point and preserves the map marker transform',async()=>{
|
||||
const f=fixture();await f.controller.ready
|
||||
f.controller.setItems([{id:'a',name:'甲',position:{longitude:117,latitude:36,accuracy:20,at:Date.now()/1000}},{id:'b',name:'乙',position:{longitude:117.1,latitude:36.1,accuracy:20,at:Date.now()/1000}}])
|
||||
assert.equal(f.elements.some(el=>el.classList.contains('pulsing')),false)
|
||||
f.controller.focus('b',true);assert.equal(f.elements[1].classList.contains('pulsing'),true);assert.equal(f.elements[0].classList.contains('pulsing'),false)
|
||||
assert.equal(f.maps[0].moves.at(-1).center[0],117.1)
|
||||
f.controller.focus('a',true);assert.equal(f.elements[1].classList.contains('pulsing'),false);assert.equal(f.elements[0].classList.contains('pulsing'),true)
|
||||
for(const fn of f.timers.values())fn();assert.equal(f.elements[0].classList.contains('pulsing'),false)
|
||||
const before=f.maps[0].moves.length;f.controller.focus('missing',true);assert.equal(f.maps[0].moves.length,before)
|
||||
f.controller.destroy();assert.equal(f.maps[0].removed,true)
|
||||
const css=fs.readFileSync('frontend/src/maps/map.css','utf8');assert.match(css,/\.family-map-pin\.pulsing>span/);assert.match(css,/prefers-reduced-motion:reduce/)
|
||||
})
|
||||
@@ -0,0 +1,141 @@
|
||||
"""Durable voice archive, consent boundary, paging, integrity and repair regressions."""
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import test_family_voice as fixtures
|
||||
app=fixtures.app
|
||||
audio=fixtures.audio
|
||||
|
||||
|
||||
class VoiceHistoryTests(unittest.TestCase):
|
||||
setUp=fixtures.VoiceTests.setUp
|
||||
stop_server=fixtures.VoiceTests.stop_server
|
||||
phone=fixtures.VoiceTests.phone
|
||||
call=fixtures.VoiceTests.call
|
||||
receive=fixtures.VoiceTests.receive
|
||||
send=fixtures.VoiceTests.send
|
||||
|
||||
def pair_of_phones(self):
|
||||
a,b=self.phone('甲'),self.phone('乙')
|
||||
self.receive(b,a)
|
||||
return a,b
|
||||
|
||||
def peer(self,phone):
|
||||
return self.call(phone,'status')['me']['archiveKey']
|
||||
|
||||
def test_long_term_history_survives_delivery_expiry_mute_and_restart(self):
|
||||
a,b=self.pair_of_phones();msg=self.send(a,b);key=msg['id']
|
||||
self.call(b,'configure',enabled=False,allowed=[])
|
||||
with patch('family_voice.time.time',return_value=time.time()+86400*400):app.VOICE.sweep()
|
||||
# Recipient switch controls new delivery, not their existing conversations.
|
||||
for p in (a,b):self.assertEqual(self.call(p,'replay',id=key)['audio'],audio())
|
||||
app.VOICE.initialize()
|
||||
self.assertEqual(self.call(b,'replay',id=key)['audio'],audio())
|
||||
history=self.call(a,'history',peer=self.peer(b))
|
||||
self.assertEqual(len(history['items']),1)
|
||||
self.assertEqual(history['items'][0]['senderName'],'甲的手机')
|
||||
self.assertTrue(history['items'][0]['mine'])
|
||||
self.assertEqual(self.call(a,'status')['conversations'][0]['archiveKey'],self.peer(b))
|
||||
|
||||
def test_cloud_verification_required_before_outbox_delete(self):
|
||||
a,b=self.pair_of_phones();key=self.send(a,b)['id'];archive=app.VOICE.history
|
||||
local=archive.folder/archive.filename(key);cipher=local.read_bytes()
|
||||
self.assertNotEqual(cipher,base64.b64decode(audio()))
|
||||
upload=lambda *args:dict(fs_id=17)
|
||||
with patch.object(app.BAIDU,'upload',side_effect=upload),patch.object(app.BAIDU,'verify_file',side_effect=ValueError('bad checksum')):
|
||||
archive.tick()
|
||||
self.assertTrue(local.exists());self.assertEqual(archive.existing(key)['state'],'retry')
|
||||
app.DB.execute('UPDATE voice_history SET next_try=0')
|
||||
with patch.object(app.BAIDU,'upload',side_effect=upload),patch.object(app.BAIDU,'verify_file') as verify:
|
||||
archive.tick()
|
||||
verify.assert_called_once()
|
||||
self.assertFalse(local.exists());row=archive.existing(key);self.assertEqual(row['state'],'cloud')
|
||||
self.assertIn('/家庭沟通/'+self.aid+'/',row['remote'])
|
||||
with patch.object(app.BAIDU,'open_file',return_value=io.BytesIO(cipher)):
|
||||
self.assertEqual(self.call(b,'replay',id=key)['audio'],audio())
|
||||
with patch.object(app.BAIDU,'open_file',return_value=io.BytesIO(cipher[:-1]+b'!')):
|
||||
with self.assertRaises(app.Problem):self.call(a,'replay',id=key)
|
||||
|
||||
def test_third_person_and_other_family_cannot_read_or_replay(self):
|
||||
a,b=self.pair_of_phones();c,d=self.phone('同家第三人'),self.phone('别家',self.other)
|
||||
key=self.send(a,b)['id']
|
||||
for stranger in (c,d):
|
||||
self.assertEqual(self.call(stranger,'history',peer=self.peer(a))['items'],[])
|
||||
self.assertEqual(self.call(stranger,'status')['conversations'],[])
|
||||
with self.assertRaises(app.Problem):self.call(stranger,'replay',id=key)
|
||||
for before in (-1,1.5,True,2**63,'0'):
|
||||
with self.assertRaises(app.Problem):self.call(a,'history',peer=self.peer(b),before=before)
|
||||
|
||||
def test_pair_token_rotation_recovers_same_member_but_invalidates_old_token(self):
|
||||
a,b=self.pair_of_phones();key=self.send(a,b)['id'];old=self.peer(a)
|
||||
# The real pairing path replaces the row with a new SID/token for the same member.
|
||||
row=dict(app.DB.execute('SELECT * FROM member_location_shares WHERE id=?',(a['sid'],)).fetchone())
|
||||
newtoken='x'*43;newsid='c'*32
|
||||
app.DB.execute('UPDATE member_location_shares SET id=?,token_hash=? WHERE id=?',(newsid,hashlib.sha256(newtoken.encode()).hexdigest(),a['sid']))
|
||||
repaired=dict(token=newtoken,sid=newsid)
|
||||
self.assertEqual(self.peer(repaired),old)
|
||||
self.assertEqual(self.call(repaired,'replay',id=key)['audio'],audio())
|
||||
with self.assertRaises(app.Problem):self.call(a,'replay',id=key)
|
||||
# A different member must never inherit the original member's history.
|
||||
stranger=self.phone('新成员')
|
||||
self.assertNotEqual(self.peer(stranger),old)
|
||||
|
||||
def test_conversation_pages_are_ordered_no_duplicate_or_time_limit(self):
|
||||
a,b=self.pair_of_phones();actor=app.VOICE.endpoint('phone:'+a['sid']);target=app.VOICE.endpoint('phone:'+b['sid'])
|
||||
for n in range(121):
|
||||
with app.LOCK,app.DB:app.VOICE.history.accept(actor['archiveKey']+':'+f'{n:032x}',actor,target,base64.b64decode(audio()),.64)
|
||||
before=0;seen=[]
|
||||
while True:
|
||||
page=self.call(a,'history',peer=self.peer(b),before=before);ids=[r['seq'] for r in page['items']]
|
||||
self.assertEqual(ids,sorted(ids));self.assertLessEqual(len(ids),50);seen+=ids
|
||||
before=page['before']
|
||||
if not before:break
|
||||
self.assertEqual(len(seen),121);self.assertEqual(len(set(seen)),121)
|
||||
|
||||
def test_duplicate_send_after_restart_and_id_collision(self):
|
||||
a,b=self.pair_of_phones();original=self.send(a,b);app.VOICE.initialize();self.receive(b,a)
|
||||
same=self.send(a,b);self.assertEqual(original['id'],same['id'])
|
||||
self.assertEqual(app.DB.execute('SELECT count(*) FROM voice_history').fetchone()[0],1)
|
||||
self.assertFalse(app.VOICE.messages)
|
||||
with self.assertRaises(app.Problem):self.send(a,b,audio=audio(11))
|
||||
self.call(b,'offline');self.call(b,'configure',enabled=False,allowed=[])
|
||||
self.assertEqual(self.send(a,b)['id'],original['id'])
|
||||
with self.assertRaises(app.Problem):self.send(a,b,id='e'*32)
|
||||
|
||||
def test_outbox_cap_rejects_without_claiming_delivery(self):
|
||||
a,b=self.pair_of_phones()
|
||||
with patch('voice_history.LIMIT',1):
|
||||
with self.assertRaises(app.Problem):self.send(a,b)
|
||||
self.assertFalse(app.VOICE.messages)
|
||||
self.assertEqual(app.DB.execute('SELECT count(*) FROM voice_history').fetchone()[0],0)
|
||||
|
||||
def test_replay_rechecks_binding_after_cloud_read(self):
|
||||
a,b=self.pair_of_phones();key=self.send(a,b)['id'];archive=app.VOICE.history;cipher=(archive.folder/archive.filename(key)).read_bytes()
|
||||
with patch.object(app.BAIDU,'upload',return_value=dict(fs_id=8)),patch.object(app.BAIDU,'verify_file'):archive.tick()
|
||||
class RevokingStream(io.BytesIO):
|
||||
def read(self,*args):
|
||||
app.DB.execute('DELETE FROM member_location_shares WHERE id=?',(b['sid'],))
|
||||
return super().read(*args)
|
||||
with patch.object(app.BAIDU,'open_file',return_value=RevokingStream(cipher)):
|
||||
with self.assertRaises(app.Problem):self.call(b,'replay',id=key)
|
||||
|
||||
def test_display_repair_retains_archive_but_family_move_does_not(self):
|
||||
a=self.phone('家人');device=app.INVENTORY.save(dict(name='显示终端',deviceType='显示终端'),self.owner)
|
||||
def pair():
|
||||
grant=app.DISPLAYS.manage(self.owner,dict(action='create',deviceId=device['id']))
|
||||
return app.DISPLAYS.pair(dict(code=grant['pairingCode']),'voice-history-test')['nativeToken']
|
||||
token=pair()
|
||||
def display(t,action,**kwargs):return app.VOICE.native(t,dict(kind='display',action=action,**kwargs))
|
||||
me=display(token,'status')['me'];display(token,'configure',enabled=True,allowed=['phone:'+a['sid']],consent=True)
|
||||
key=self.call(a,'send',target=me['id'],audio=audio(),id='d'*32)['id']
|
||||
repaired=pair();self.assertEqual(display(repaired,'status')['me']['archiveKey'],me['archiveKey'])
|
||||
self.assertEqual(display(repaired,'replay',id=key)['audio'],audio())
|
||||
with self.assertRaises(app.Problem):display(token,'replay',id=key)
|
||||
app.INVENTORY.transfer(dict(source='device',id=device['id'],targetFamilyId=self.bid),self.root)
|
||||
with self.assertRaises(app.Problem):display(repaired,'replay',id=key)
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,187 @@
|
||||
"""Participant-only voice conversations. SQLite indexes; bounded encrypted cloud outbox.
|
||||
|
||||
The logical phone is the household member's paired phone (currently one per member).
|
||||
Displays use the household + inventory device, never a temporary pairing token.
|
||||
Audio is retained indefinitely in Baidu after checksum verification, not in SQLite.
|
||||
"""
|
||||
import base64
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import threading
|
||||
import time
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||
|
||||
LIMIT = 16 * 1024 * 1024
|
||||
MAX_FILE = 150028
|
||||
READ_SLOTS = threading.BoundedSemaphore(2)
|
||||
|
||||
|
||||
class VoiceHistory:
|
||||
def __init__(self, app):
|
||||
self.a = app
|
||||
self.worker = threading.Lock()
|
||||
|
||||
@property
|
||||
def folder(self):
|
||||
return self.a.DATA / 'voice-outbox'
|
||||
|
||||
def initialize(self):
|
||||
a = self.a
|
||||
with a.LOCK, a.DB:
|
||||
a.DB.execute('''CREATE TABLE IF NOT EXISTS voice_history (
|
||||
seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT UNIQUE NOT NULL,
|
||||
family TEXT NOT NULL, sender TEXT NOT NULL, target TEXT NOT NULL,
|
||||
sender_name TEXT, target_name TEXT, sender_kind TEXT, target_kind TEXT,
|
||||
at REAL NOT NULL, seconds REAL NOT NULL, digest TEXT NOT NULL,
|
||||
delivery TEXT NOT NULL, remote TEXT NOT NULL, state TEXT NOT NULL,
|
||||
fs_id TEXT DEFAULT '', cipher_sha TEXT NOT NULL, size INTEGER NOT NULL,
|
||||
attempts INTEGER DEFAULT 0, next_try REAL DEFAULT 0)''')
|
||||
a.DB.execute('CREATE INDEX IF NOT EXISTS voice_history_sender ON voice_history(family,sender,seq)')
|
||||
a.DB.execute('CREATE INDEX IF NOT EXISTS voice_history_target ON voice_history(family,target,seq)')
|
||||
a.DB.execute('CREATE INDEX IF NOT EXISTS voice_history_pending ON voice_history(state,next_try,seq)')
|
||||
if not a.setting('voice_history_key'):
|
||||
a.set_setting('voice_history_key', base64.b64encode(secrets.token_bytes(32)).decode())
|
||||
# A restart ends live playback, but never removes the conversation.
|
||||
a.DB.execute("UPDATE voice_history SET delivery='expired' WHERE delivery IN ('queued','received')")
|
||||
self.folder.mkdir(parents=True, exist_ok=True)
|
||||
os.chmod(self.folder, 0o700)
|
||||
with a.LOCK:
|
||||
pending = {self.filename(r['id']) for r in a.DB.execute("SELECT id FROM voice_history WHERE state!='cloud'")}
|
||||
for file in self.folder.iterdir():
|
||||
if re.fullmatch(r'[a-f0-9]{64}\.(voice|partial)', file.name) and file.name not in pending:
|
||||
file.unlink(missing_ok=True)
|
||||
|
||||
@staticmethod
|
||||
def identity(family, kind, key):
|
||||
return hashlib.sha256((family + '|' + kind + '|' + key).encode()).hexdigest()
|
||||
|
||||
@staticmethod
|
||||
def filename(key):
|
||||
return hashlib.sha256(key.encode()).hexdigest() + '.voice'
|
||||
|
||||
def existing(self, key):
|
||||
return self.a.DB.execute('SELECT * FROM voice_history WHERE id=?', (key,)).fetchone()
|
||||
|
||||
def accept(self, key, actor, target, raw, seconds):
|
||||
"""Called under the app transaction, before acknowledging the accepted send."""
|
||||
a = self.a
|
||||
previous = self.existing(key)
|
||||
digest = hashlib.sha256(raw).hexdigest()
|
||||
if previous:
|
||||
if previous['sender'] != actor['archiveKey'] or previous['target'] != target['archiveKey'] or previous['digest'] != digest:
|
||||
raise a.Problem('语音编号已用于另一条内容,请重新录制', 409)
|
||||
return previous
|
||||
used = max(a.DB.execute("SELECT coalesce(sum(size),0) FROM voice_history WHERE state!='cloud'").fetchone()[0],
|
||||
sum(p.stat().st_size for p in self.folder.iterdir() if p.suffix in ('.voice','.partial')))
|
||||
if used + len(raw) + 28 > LIMIT or shutil.disk_usage(a.DATA).free < 256 * 1024 * 1024:
|
||||
raise a.Problem('语音归档等待空间不足,请稍后再发;已有记录保留', 507)
|
||||
now = time.time()
|
||||
nonce = secrets.token_bytes(12)
|
||||
cipher = nonce + AESGCM(base64.b64decode(a.setting('voice_history_key'))).encrypt(nonce, raw, key.encode())
|
||||
local = self.folder / self.filename(key)
|
||||
temporary = local.with_suffix('.partial')
|
||||
with temporary.open('wb') as stream:
|
||||
os.chmod(temporary, 0o600)
|
||||
stream.write(cipher)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, local)
|
||||
if os.name != 'nt':
|
||||
fd = os.open(self.folder, os.O_RDONLY)
|
||||
try: os.fsync(fd)
|
||||
finally: os.close(fd)
|
||||
date = dt.datetime.fromtimestamp(now, dt.timezone(dt.timedelta(hours=8)))
|
||||
conversation = hashlib.sha256('|'.join(sorted([actor['archiveKey'], target['archiveKey']])).encode()).hexdigest()
|
||||
remote = '/apps/' + a.BAIDU.public_config()['appFolder'] + '/家庭沟通/' + actor['familyId'] + '/' + conversation + '/' + date.strftime('%Y/%m/%d/') + local.name
|
||||
a.DB.execute('''INSERT INTO voice_history
|
||||
(id,family,sender,target,sender_name,target_name,sender_kind,target_kind,at,seconds,digest,delivery,remote,state,cipher_sha,size)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,'queued',?,'pending',?,?)''',
|
||||
(key, actor['familyId'], actor['archiveKey'], target['archiveKey'], actor['name'], target['name'], actor['kind'], target['kind'], now, seconds, digest, remote, hashlib.sha256(cipher).hexdigest(), len(cipher)))
|
||||
return None
|
||||
|
||||
def delivery(self, key, state):
|
||||
self.a.DB.execute('UPDATE voice_history SET delivery=? WHERE id=?', (state, key))
|
||||
|
||||
def conversations(self, actor):
|
||||
me = actor['archiveKey']
|
||||
rows = self.a.DB.execute('''SELECT * FROM voice_history WHERE seq IN (
|
||||
SELECT max(seq) FROM voice_history WHERE family=? AND (sender=? OR target=?)
|
||||
GROUP BY CASE WHEN sender=? THEN target ELSE sender END) ORDER BY seq DESC LIMIT 200''',
|
||||
(actor['familyId'], me, me, me)).fetchall()
|
||||
return [dict(archiveKey=r['target'] if r['sender']==me else r['sender'],
|
||||
name=r['target_name'] if r['sender']==me else r['sender_name'],
|
||||
kind=r['target_kind'] if r['sender']==me else r['sender_kind'],
|
||||
lastAt=r['at']) for r in rows]
|
||||
|
||||
def listing(self, actor, body):
|
||||
peer = body.get('peer', '')
|
||||
before = body.get('before', 0)
|
||||
if not isinstance(peer, str) or not re.fullmatch(r'[a-f0-9]{64}', peer) or type(before) is not int or before < 0 or before > 2**63-1:
|
||||
raise self.a.Problem('请选择有效的沟通对象和记录页')
|
||||
me = actor['archiveKey']
|
||||
rows = self.a.DB.execute('''SELECT * FROM voice_history WHERE family=?
|
||||
AND ((sender=? AND target=?) OR (target=? AND sender=?))
|
||||
AND (?=0 OR seq<?) ORDER BY seq DESC LIMIT 51''',
|
||||
(actor['familyId'], me, peer, me, peer, before, before)).fetchall()
|
||||
more = len(rows) > 50
|
||||
rows = rows[:50]
|
||||
return dict(items=[dict(id=r['id'], seq=r['seq'], mine=r['sender']==me,
|
||||
senderName=r['sender_name'], targetName=r['target_name'], at=r['at'],
|
||||
seconds=r['seconds'], delivery=r['delivery'], archive=r['state']) for r in reversed(rows)],
|
||||
before=rows[-1]['seq'] if more else 0)
|
||||
|
||||
def permitted_row(self, actor, key):
|
||||
row = self.existing(key) if isinstance(key,str) else None
|
||||
if not row or row['family'] != actor['familyId'] or actor['archiveKey'] not in (row['sender'], row['target']):
|
||||
raise self.a.Problem('聊天记录不存在或不属于此设备', 404)
|
||||
return dict(row)
|
||||
|
||||
def replay(self, token, body, authorize):
|
||||
if not READ_SLOTS.acquire(False): raise self.a.Problem('语音正在读取,请稍后再试', 429)
|
||||
try:
|
||||
with self.a.LOCK:
|
||||
actor = authorize(token, body.get('kind'))
|
||||
row = self.permitted_row(actor, body.get('id'))
|
||||
if row['state'] == 'cloud':
|
||||
with self.a.BAIDU.open_file('shared', dict(remotePath=row['remote'], fsId=row['fs_id'])) as stream:
|
||||
cipher = stream.read(MAX_FILE + 1)
|
||||
else:
|
||||
try:
|
||||
with (self.folder / self.filename(row['id'])).open('rb') as stream: cipher = stream.read(MAX_FILE + 1)
|
||||
except FileNotFoundError: raise self.a.Problem('语音归档状态刚更新,请重试', 409)
|
||||
if len(cipher)!=row['size'] or len(cipher)>MAX_FILE or hashlib.sha256(cipher).hexdigest()!=row['cipher_sha']:
|
||||
raise self.a.Problem('语音校验未通过,未播放', 502)
|
||||
with self.a.LOCK:
|
||||
# Authorization can change during the cloud request.
|
||||
self.permitted_row(authorize(token,body.get('kind')),row['id'])
|
||||
secret=base64.b64decode(self.a.setting('voice_history_key'))
|
||||
raw = AESGCM(secret).decrypt(cipher[:12], cipher[12:], row['id'].encode())
|
||||
if hashlib.sha256(raw).hexdigest()!=row['digest']: raise self.a.Problem('语音内容校验未通过',502)
|
||||
return dict(id=row['id'], senderName=row['sender_name'], seconds=row['seconds'], audio=base64.b64encode(raw).decode())
|
||||
finally: READ_SLOTS.release()
|
||||
|
||||
def tick(self):
|
||||
if not self.worker.acquire(False): return
|
||||
a=self.a
|
||||
try:
|
||||
with a.LOCK:
|
||||
row=a.DB.execute("SELECT * FROM voice_history WHERE state!='cloud' AND next_try<=? ORDER BY seq LIMIT 1", (time.time(),)).fetchone()
|
||||
if not row:return
|
||||
row=dict(row)
|
||||
local=self.folder/self.filename(row['id'])
|
||||
try:
|
||||
with local.open('rb') as stream: cipher=stream.read(MAX_FILE+1)
|
||||
if len(cipher)!=row['size'] or hashlib.sha256(cipher).hexdigest()!=row['cipher_sha']:raise ValueError('outbox integrity')
|
||||
result=a.BAIDU.upload('shared',local,row['remote'])
|
||||
a.BAIDU.verify_file(row['remote'],str(result['fs_id']),row['size'],row['cipher_sha'])
|
||||
with a.LOCK,a.DB:
|
||||
a.DB.execute("UPDATE voice_history SET state='cloud',fs_id=?,next_try=0 WHERE id=?",(str(result['fs_id']),row['id']))
|
||||
local.unlink(missing_ok=True)
|
||||
except Exception:
|
||||
with a.LOCK,a.DB:
|
||||
a.DB.execute("UPDATE voice_history SET state='retry',attempts=attempts+1,next_try=? WHERE id=? AND state!='cloud'",(time.time()+min(21600,30*2**min(row['attempts'],9)),row['id']))
|
||||
finally:self.worker.release()
|
||||
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-Ciz17yeg.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,!0),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);
|
||||
@@ -1 +0,0 @@
|
||||
import"./modulepreload-polyfill-B5Qt9EMX.js";import{createFamilyMap as n}from"./controller-NWgljfVQ.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);
|
||||
File diff suppressed because one or more lines are too long
+2
-2
@@ -1,6 +1,6 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#244d43"><link rel="icon" href="/zhao-icon.png"><link rel="apple-touch-icon" href="/zhao-icon.png"><title>赵府 · 智能数字管家</title> <script type="module" crossorigin src="/ui/assets/index-DDMaGFMK.js"></script>
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#244d43"><link rel="icon" href="/zhao-icon.png"><link rel="apple-touch-icon" href="/zhao-icon.png"><title>赵府 · 智能数字管家</title> <script type="module" crossorigin src="/ui/assets/index-MiXxMKt5.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/modulepreload-polyfill-B5Qt9EMX.js">
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/FamilyMap-CiWCoS6Z.js">
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/FamilyMap-DWpZ2672.js">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/FamilyMap-DBkz-poX.css">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/index-DLtOcw55.css">
|
||||
</head><body><div id="app"></div></body></html>
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="data:,"><title>家人位置地图</title> <script type="module" crossorigin src="/ui/assets/map-qt6gqu0E.js"></script>
|
||||
<!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-BZMeykFi.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/modulepreload-polyfill-B5Qt9EMX.js">
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/controller-NWgljfVQ.js">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/controller-B0JP7gQd.css">
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/controller-Ciz17yeg.js">
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/controller-B-jsg1m3.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>
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f3eee4"><meta name="referrer" content="no-referrer"><link rel="icon" href="/zhao-icon.png"><title>赵府 · 家庭时光</title> <script type="module" crossorigin src="/ui/assets/tv-CumBWqRi.js"></script>
|
||||
<!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-B8Fg_WRm.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/modulepreload-polyfill-B5Qt9EMX.js">
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/FamilyMap-CiWCoS6Z.js">
|
||||
<link rel="modulepreload" crossorigin href="/ui/assets/FamilyMap-DWpZ2672.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>
|
||||
|
||||
Reference in New Issue
Block a user