Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fb87ae4de9 | |||
| d8826152c6 | |||
| f7d3fea92f | |||
| 12556bf10f | |||
| 7d4329f773 | |||
| 59bd83403f | |||
| 91915b9d90 | |||
| 436596e786 |
@@ -87,7 +87,7 @@ v0.1.22 采用「庭院书卷」视觉:宣纸白底、黛青导航、朱砂点
|
||||
|
||||
**录像机原有历史录像回放尚未实现。** 需要取得具体型号及合法设备账号,接入其录像检索和回放接口;实时 RTSP 地址不能代替录像检索接口。驱动选项目前仅表示路径模板与接入类型,不能视为某个品牌全系列已经兼容。实际通道号需要由设备确认,不能根据三台双镜头直接猜成通道 1–6。
|
||||
|
||||
本机录像默认关闭,用户逐通道开启。默认保留 7 天、容量 40 GB、磁盘预留 8 GB,界面可调整。保留期限到达后 MediaMTX 自动删除本机录像;配额达到后暂停录制,不删除录像机中的数据。配额每 20 秒观察一次,允许少量超出。文件路径及录像索引使用 UTC,界面按浏览器时区显示。
|
||||
本机录像默认关闭,用户逐通道开启。默认最长保留 30 天、容量 40 GB、磁盘预留 8 GB,界面可调整。保留期限到达后 MediaMTX 自动删除本机录像;配额达到后暂停录制,不删除录像机中的数据。配额每 20 秒观察一次,允许少量超出。保留天数是时间上限,不保证在容量限制内存满该天数。文件路径及录像索引使用 UTC,界面按浏览器时区显示。
|
||||
|
||||
HLS 会有数秒延迟。网页清晰度仅提供“主码流”和“子码流”两个选项,默认主码流。主码流预览使用实际主码流,通过 Intel VAAPI 硬件解码、缩放及 H.264 Main 编码,最高 1920×1080、15 帧/秒。子码流预览使用实际子码流,由 FFmpeg 按需生成 H.264 Baseline / AAC 兼容画面,最高 768×432、10 帧/秒。高清预览需要可用的 Intel 核显、驱动及 render 设备权限,不自动退回高负载的软件高清转码。首开需要等待取流与缓冲。没有观看者后会停止转码;同一镜头的观看者共享一路转码。网页不提供原始编码直出的预览选项。本机录像保留原始主码流编码,兼容预览不改变录像及摄像头设置。网页回放按需转换为 H.264/AAC,最多同时两个会话,每段最多一小时;使用时间轴或定位时间跳转。关闭回放或切换页面后终止转换,不生成额外缓存文件。有可用 VAAPI 时回放最高 1080p/15 帧,否则使用 768×432/10 帧软件转换。下载保留原始录像编码,需支持该编码的播放器。设备状态基于 MediaMTX 实际码流状态;“正在录像”还要求观察到近期写入的本机录像文件。离线不会生成假画面或假录像。
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# v0.1.37 — Vue 与 Bootstrap 界面升级
|
||||
|
||||
## 外观与体验
|
||||
|
||||
- 基于现有 Vue 3、Bootstrap 5 架构升级:深色导航、墨绿主色、浅色内容区,统一卡片、按钮、表单、弹窗与信息层次。
|
||||
- 新增 Vue 场所概览组件,显示已授权场所的设备总量、区域数量与场所类型环形图。统计直接取自服务端已授权记录。
|
||||
- 家庭照片卡片增加清晰的封面文字遮罩与统计分区,保留个人排序、行列、分页和城市分组。
|
||||
- 网络拓扑新增可缩放、可点击的 Vue SVG 连接图;支持鼠标和键盘进入设备档案。只绘制已登记且通过现有层级校验的连接,不推测未确认的布线。
|
||||
- 手机端使用单列卡片、可收起的布局设置和触控表单;弹窗保留可滚动内容与可见保存按钮。
|
||||
- 保留个人配色、顶部或侧边导航、内容疏密及标题字体偏好;修正深色主题的按钮对比度。
|
||||
- 全屏监控使用独立的深色工具栏与名称底色,避免浅色后台样式影响名称可读性。
|
||||
- 图表在浏览器中绘制,不增加外部图表服务或新的后端数据采集。继续复用现有监控播放器。
|
||||
|
||||
## 验证
|
||||
|
||||
- Vite 生产构建通过;169 项 Python、138 项 JavaScript 回归测试通过。
|
||||
- Edge Computer Use 在隔离数据下验证家庭分页、布局保存、档案弹窗、网络图缩放、键盘跳转及手机菜单。
|
||||
- 390 与 320 像素视口检查无页面横向溢出,手机表单输入为 16px;检查浅色和深色主题。
|
||||
|
||||
本版未迁移业务数据库。公开源码不含用户照片、数据库或设备凭据。
|
||||
@@ -0,0 +1,13 @@
|
||||
# v0.1.38 — 录像留存与回放修复
|
||||
|
||||
- 新安装默认最长保留 30 天,保留现有 40 GB 容量上限、8 GB 磁盘预留;既有安装的自定义策略不会因升级被覆盖。
|
||||
- 容量不足时暂停写入,空间恢复后继续;过期录像由 MediaMTX 自动清理。保留天数是上限,实际时长取决于码率、路数与可用容量。
|
||||
- 回放页显示实际写入、未开启、设备离线、存储保护等状态;管理员可直接进入当前镜头的录像设置。后台状态刷新不重建播放器。
|
||||
- 修正首次录像前目录不存在被误报为服务故障;仅匹配当前镜头的缺失目录,权限、损坏文件与真实服务错误仍报错。
|
||||
- 修正微秒时间转换为网页毫秒时精度丢失,避免查询起点落在片段之前导致 404。查询边界向录像范围内收敛,不填补无录像空档。
|
||||
- 回放响应关闭反向代理缓冲,并减少 FFmpeg 输入探测等待;保留双路转换并发限制与退出清理。
|
||||
- “持续录像”开关明确说明存储于服务器并受保留策略管理。
|
||||
|
||||
验证:173 项 Python 与 140 项 JavaScript 回归测试;Vue / Bootstrap 生产构建。包含时间边界、空录像目录、权限错误、容量暂停、状态显示及代理缓冲回归。
|
||||
|
||||
升级不重建业务数据库,不批量启用摄像头录制。已关闭录制期间的历史画面无法补录。
|
||||
@@ -0,0 +1,7 @@
|
||||
# v0.1.39 — 手机录像筛选布局
|
||||
|
||||
在 v0.1.38 录像修复基础上调整小屏幕回放表单:镜头、录像来源、日期和查询按钮纵向排列,控件保持完整宽度,避免三个选择框挤在一行。
|
||||
|
||||
本版仅调整前端;保留 v0.1.38 的 30 天默认留存、容量保护、录像状态与时间精度修复。设备数据及录像配置不迁移。生产更新仅重启网页服务,持续录像的 MediaMTX 进程保留。
|
||||
|
||||
验证:141 项 JavaScript 回归测试与 Vue / Bootstrap 生产构建通过;后端沿用已通过 173 项回归的 v0.1.38 实现。
|
||||
@@ -0,0 +1,10 @@
|
||||
# v0.1.40 · 家谱画布稳定性与连续回放修复
|
||||
|
||||
- 修复全屏家谱因小数像素取整而反复产生滚动条、重算居中的抖动。
|
||||
- 合并画布尺寸通知,尺寸不变时不重复适配;手动缩放与拖动位置保持。
|
||||
- 修复浏览器不支持原生全屏时,兼容全屏画布被侧栏遮挡的问题。
|
||||
- 保留手机端家谱画布及人物档案的独立滚动区域。
|
||||
- 修复录像回放以直播速度读取历史 HTTP 文件,造成长片段上游写入超时而提前截断的问题;保留转换并发、线程和生命周期上限。
|
||||
- 新增画布小数像素、尺寸通知合并、手动视角、隐藏和重置回归测试。
|
||||
|
||||
录像保留策略仍以当前平台设置为准:30 天为最长保留时间;录像容量上限和磁盘预留可提前触发暂停,不能据此保证存满 30 天。
|
||||
@@ -0,0 +1,10 @@
|
||||
# v0.1.41 · 录像按需缓冲与连续回放
|
||||
|
||||
- 修复浏览器减慢读取时,长录像源 HTTP 连接超时而提前结束的问题。
|
||||
- 回放以最多 5 分钟为一段,沿用自动续播和真实录像空档规则;原始片段下载仍可选择最多一小时。
|
||||
- 每段录像在服务器私有临时目录缓冲,转换结束、失败或离开页面后清理;最多两个转换、每份缓存最大 256 MiB,受磁盘预留空间及下载时限保护。
|
||||
- 转换进程仅访问临时文件,按播放速度读取并限制线程,不携带录像服务认证信息。
|
||||
- 长时间暂停后从当前播放位置重新接入,无需刷新整个页面。
|
||||
- 保留 v0.1.40 家谱全屏抖动、尺寸通知循环与侧栏遮挡修复。
|
||||
|
||||
30 天为录像最长保留时间。实际可保留时长仍受总录像容量上限、磁盘预留、码率和路数限制。
|
||||
@@ -0,0 +1,5 @@
|
||||
# v0.1.42 · 回放预缓冲调整
|
||||
|
||||
- 允许有限录像片段提前完成转换,减少逐秒限速造成的播放器缓冲等待。
|
||||
- 继续使用最多 5 分钟的分段播放、自动续播、两路转换并发、单线程处理及有界临时缓存。
|
||||
- 保留家谱全屏稳定性修复、30 天录像保留上限、磁盘容量保护和长暂停后的原位置恢复。
|
||||
@@ -0,0 +1,28 @@
|
||||
# v0.1.43 · 本地图表与五代维护边界
|
||||
|
||||
## 界面与图表
|
||||
|
||||
- Vue 页面统一使用本地 Bootstrap 5.3.8;新增本地 Apache ECharts 6.1.0,生产页面不依赖远程 CDN、字体或地图资源。
|
||||
- 首页展示已授权场所、设备及区域数量,以及空间分布和各场所设备柱图。场所总览展示设备类型和网络接入方式;不推算没有数据依据的在线率或历史趋势。
|
||||
- 平台总拓扑仅展示已授权家庭、办公与工厂;场所内部网络图根据已登记上级关系生成,支持平移、缩放、重置及点击进入设备档案。详情列表保留键盘操作入口。
|
||||
- 图表按需加载、离开页面释放,相同数据刷新不重新布局。手机首页默认收起详细统计,可展开;表单、卡片和导航沿用 Bootstrap 响应式布局。
|
||||
- 视频与家谱等既有业务控制器保留兼容层,避免重建播放节点;本版没有宣称全部业务已改为 Vue 状态管理。
|
||||
|
||||
## 族谱维护权限
|
||||
|
||||
- 所有角色(包括超级管理员)均以账号关联的本人为准,只能维护本人及上下各五代以内的已连接亲属资料。
|
||||
- 例如第 32 代可维护第 27 至第 37 代,第 26、38 代及第 5 代不能修改;原有查看权限不变,不截断远代人物。
|
||||
- 人物、亲属关系、关联人物记事、归档和历史恢复统一经后端范围检查。切换查看参照人物不改变维护范围。
|
||||
- 本人关联设置后固定;不允许通过解除关联、更换本人、断开再重接世系或改变已确认代际位置扩大维护范围。代际冲突时暂停维护。
|
||||
- 没有关联本人的账号先关联已有本人人物;本人尚未录入时,可建立自己的档案并绑定。其他新增人物须关联可维护亲属,人物与关系原子保存,超出第六代时不会留下孤立人物。
|
||||
- 平台账号与各家庭成员结构的全面重构不在本次发布内。
|
||||
|
||||
## 验证
|
||||
|
||||
- 后端 190 项测试、前端 154 项测试通过。
|
||||
- Edge 本机测试:第五代边界编辑保存、远代只读、变更参照人物不扩权、ECharts 渲染及节点进入设备、390 像素手机显示。
|
||||
- 本地开发数据与生产资料分离,未替用户指定或更换真实人物关联。
|
||||
|
||||
## 发布
|
||||
|
||||
部署前创建一致性数据库备份;原子切换版本,仅重启 Web 服务,保留视频服务。无数据库结构迁移。
|
||||
@@ -73,6 +73,7 @@ SCAN = {'running': False, 'items': [], 'error': '', 'network': '', 'at': None}
|
||||
ATTEMPTS = {}
|
||||
API_PORT, HLS_PORT, PLAYBACK_PORT = 19997, 18888, 19996
|
||||
MEDIA_AUTH = None
|
||||
DEFAULT_STORAGE = {'retentionDays': 30, 'maxGB': 40, 'reserveGB': 8}
|
||||
|
||||
|
||||
class Problem(Exception):
|
||||
@@ -329,7 +330,7 @@ def source(c, quality):
|
||||
def write_media_config():
|
||||
with LOCK:
|
||||
paths = {}
|
||||
policy = setting('storage', {'retentionDays': 7, 'maxGB': 40, 'reserveGB': 8})
|
||||
policy = setting('storage', DEFAULT_STORAGE)
|
||||
for c in objects('cameras'):
|
||||
for quality in ('main', 'sub'):
|
||||
paths[stream_name(c, quality)] = {
|
||||
@@ -381,16 +382,24 @@ def media_json(path, playback=False):
|
||||
return json.load(r)
|
||||
except urllib.error.HTTPError as exc:
|
||||
with exc:
|
||||
if playback and path.startswith('/list?') and exc.code == 404:
|
||||
if playback and path.startswith('/list?') and exc.code in (400, 404):
|
||||
try:
|
||||
detail = json.loads(exc.read(4096))
|
||||
if detail.get('error') == 'no recording segments found':
|
||||
message = detail.get('error')
|
||||
if exc.code == 404 and message == 'no recording segments found':
|
||||
return []
|
||||
# MediaMTX 1.21 returns 400 before this camera's first recording.
|
||||
# Match only the requested camera directory, never permissions,
|
||||
# another path, a corrupt file, or an unavailable service.
|
||||
name = url.parse_qs(url.urlsplit(path).query).get('path', [''])[0]
|
||||
if (exc.code == 400 and re.fullmatch(r'cam_[a-f0-9]{16}_main', name)
|
||||
and message == 'lstat ' + str(RECORDINGS / name) + ': no such file or directory'):
|
||||
return []
|
||||
except (ValueError, AttributeError):
|
||||
pass
|
||||
raise Problem('视频服务暂不可用,或该时段尚无可回放录像', 503)
|
||||
raise Problem('录像服务暂不可用,请稍后重试或联系管理员检查服务', 503)
|
||||
except Exception:
|
||||
raise Problem('视频服务暂不可用,或该时段尚无可回放录像', 503)
|
||||
raise Problem('录像服务暂不可用,请稍后重试或联系管理员检查服务', 503)
|
||||
|
||||
|
||||
def media_config_watch():
|
||||
@@ -417,6 +426,22 @@ def media_config_watch():
|
||||
time.sleep(5)
|
||||
|
||||
|
||||
def recording_state(camera, ready, media_online):
|
||||
if not camera.get('record'):
|
||||
return 'off'
|
||||
if not camera.get('enabled'):
|
||||
return 'disabled'
|
||||
if STORAGE['paused']:
|
||||
return 'paused'
|
||||
if not media_online:
|
||||
return 'unavailable'
|
||||
if not ready:
|
||||
return 'offline'
|
||||
if time.time() - RECENT_RECORDS.get(stream_name(camera), 0) < 45:
|
||||
return 'recording'
|
||||
return 'waiting'
|
||||
|
||||
|
||||
def status():
|
||||
try:
|
||||
data = media_json('/v3/paths/list?itemsPerPage=200')
|
||||
@@ -432,10 +457,10 @@ def status():
|
||||
if endpoint:
|
||||
c = dict(c, host=endpoint['host'], port=endpoint['port'])
|
||||
main = ready.get(stream_name(c), {})
|
||||
recording = recording_state(c, main.get('ready', False), media)
|
||||
cameras.append({**public_camera(c), 'ready': main.get('ready', False), 'tracks': main.get('tracks', []),
|
||||
'recordingRequested': c['enabled'] and c['record'] and not STORAGE['paused'],
|
||||
'recordingActive': bool(c['enabled'] and c['record'] and not STORAGE['paused'] and main.get('ready', False)
|
||||
and time.time() - RECENT_RECORDS.get(stream_name(c), 0) < 45)})
|
||||
'recordingState': recording, 'recordingActive': recording == 'recording'})
|
||||
with LOCK:
|
||||
storage = dict(STORAGE)
|
||||
scan = dict(SCAN)
|
||||
@@ -860,13 +885,15 @@ class Handler(BaseHTTPRequestHandler):
|
||||
started = False
|
||||
old_timeout = self.connection.gettimeout()
|
||||
try:
|
||||
with playback.stream('http://127.0.0.1:' + str(PLAYBACK_PORT) + path, MEDIA_AUTH, duration) as output:
|
||||
reserve_bytes = int(setting('storage', DEFAULT_STORAGE).get('reserveGB', 8) * 1024**3)
|
||||
with playback.stream('http://127.0.0.1:' + str(PLAYBACK_PORT) + path, MEDIA_AUTH, duration, reserve_bytes=reserve_bytes) as output:
|
||||
first = output.read1(65536)
|
||||
if not first:
|
||||
raise Problem('录像转换失败,请检查录像是否完整及服务器视频驱动', 503)
|
||||
self.connection.settimeout(15)
|
||||
self.send_response(200)
|
||||
self.send_header('Content-Type', 'video/mp4')
|
||||
self.send_header('X-Accel-Buffering', 'no')
|
||||
self.send_header('Cache-Control', 'no-store')
|
||||
self.send_header('Accept-Ranges', 'none')
|
||||
self.send_header('X-Content-Type-Options', 'nosniff')
|
||||
@@ -1107,7 +1134,7 @@ def initialize():
|
||||
HERITAGE.initialize()
|
||||
JOURNAL.initialize()
|
||||
if not setting('storage'):
|
||||
set_setting('storage', {'retentionDays': 7, 'maxGB': 40, 'reserveGB': 8})
|
||||
set_setting('storage', DEFAULT_STORAGE)
|
||||
if not setting('mediaSecret'):
|
||||
set_setting('mediaSecret', secrets.token_hex(32))
|
||||
MEDIA_AUTH = 'Basic ' + base64.b64encode(('vision:' + setting('mediaSecret')).encode()).decode()
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Generation-based write boundaries. Viewing and role grants are separate."""
|
||||
from collections import deque
|
||||
|
||||
LIMIT = 5
|
||||
|
||||
|
||||
def generations(people, links, self_id):
|
||||
ids = {p['id'] for p in people}
|
||||
if self_id not in ids:
|
||||
return {}, False
|
||||
graph = {key: [] for key in ids}
|
||||
for edge in links:
|
||||
a, b = edge.get('fromId'), edge.get('toId')
|
||||
if not edge.get('active') or a not in ids or b not in ids:
|
||||
continue
|
||||
delta = 1 if edge.get('kind') == 'parent' else 0
|
||||
if edge.get('kind') not in ('parent', 'spouse'):
|
||||
continue
|
||||
graph[a].append((b, delta))
|
||||
graph[b].append((a, -delta))
|
||||
levels, pending, conflict = {self_id: 0}, deque([self_id]), False
|
||||
while pending:
|
||||
current = pending.popleft()
|
||||
for other, delta in graph[current]:
|
||||
level = levels[current] + delta
|
||||
if other in levels:
|
||||
conflict |= levels[other] != level
|
||||
else:
|
||||
levels[other] = level
|
||||
pending.append(other)
|
||||
return levels, conflict
|
||||
|
||||
|
||||
def within(levels, person_id):
|
||||
return person_id in levels and abs(levels[person_id]) <= LIMIT
|
||||
|
||||
|
||||
def targets(kind, item):
|
||||
if kind == 'person':
|
||||
return [item['id']]
|
||||
if kind == 'link':
|
||||
return [item['fromId'], item['toId']]
|
||||
return item.get('personIds', [])
|
||||
+5
-1
@@ -1,6 +1,6 @@
|
||||
# 赵府 Vue 前端
|
||||
|
||||
Vue 3 + Vite + Bootstrap 5。Python 服务提供 API 和本地静态资源;生产主机无需安装 Node。
|
||||
Vue 3 + Vite + Bootstrap 5 + Apache ECharts。Python 服务提供 API 和本地静态资源;生产主机无需安装 Node。
|
||||
|
||||
## 构建
|
||||
|
||||
@@ -19,12 +19,16 @@ pnpm --dir frontend build
|
||||
- `HomeExplorer`:账号独立的卡片布局、分页、排序及场所总拓扑。
|
||||
- `DeviceCollection`、`NetworkMap`:同一设备目录的卡片和拓扑视图。
|
||||
- `NetworkStatus`:授权设备的实时网络检查与后台入口,清理定时器并丢弃过期响应。
|
||||
- `LocalChart`、`HomeInsights`、`ScopeInsights`:本地 ECharts 场所及设备统计;按需加载,关闭页面释放实例,相同数据刷新不重排。手机首页默认收起详细统计。
|
||||
- `NetworkDiagram`:固定坐标网络图,支持平移、缩放和点击设备;下方详情提供键盘及读屏操作。平台总拓扑与设备拓扑只使用当前账号已授权数据,不虚构在线率或历史曲线。
|
||||
- `Workspace`、`RuntimeOverlays`:现有业务页面与表单模板。
|
||||
- `composables/bridge.js`、`web/vue-bridge.js`:Vue 与现有业务控制器的状态边界。
|
||||
- `compat/scripts.json`:旧业务控制器依赖顺序,按顺序加载。视频播放器、家谱、记事等复杂交互暂时保留原控制器;尚未全部迁为 Vue 状态管理。
|
||||
|
||||
Vue 管理家庭卡片、设备列表、网络拓扑的 DOM;旧控制器只发布数据,不再覆盖这些容器。表单及播放器的兼容容器由原控制器管理,Vue 不重建其内部节点,避免轮询时重建视频。`web/index.html` 已移除,模板以 Vue 组件为准。
|
||||
|
||||
ECharts 使用 npm 包按需打包饼图、柱图、关系图和 Canvas 渲染器。生产 `/ui/assets/` 内包含全部框架、样式和图表代码;没有远程 CDN、远程字体或地图服务依赖。外部媒体与设备后台链接仍按业务配置访问。原有播放器和家谱关系图保留现有控制器。许可证及 NOTICE 收录于 `THIRD-PARTY-LICENSES.txt`。
|
||||
|
||||
## 网络状态
|
||||
|
||||
`GET /api/devices/network?source=device|camera|recorder&id=...` 只允许当前家庭管理员与超级管理员检查本归属下的已登记设备。端口探测与 Tailscale 节点状态分别显示,30 秒缓存、并发限制;用户输入不能指定任意检查目标。只连接 TCP 端口,不修改设备、不发送登录密码。
|
||||
|
||||
@@ -44,3 +44,279 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
echarts
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
========================================================================
|
||||
Apache ECharts Subcomponents:
|
||||
|
||||
The Apache ECharts project contains subcomponents with separate copyright
|
||||
notices and license terms. Your use of the source code for these
|
||||
subcomponents is also subject to the terms and conditions of the following
|
||||
licenses.
|
||||
|
||||
BSD 3-Clause (d3.js):
|
||||
The following files embed [d3.js](https://github.com/d3/d3) BSD 3-Clause:
|
||||
`/src/chart/treemap/treemapLayout.ts`,
|
||||
`/src/chart/tree/layoutHelper.ts`,
|
||||
`/src/chart/graph/forceHelper.ts`,
|
||||
`/src/util/number.ts`
|
||||
See `/licenses/LICENSE-d3` for details of the license.
|
||||
|
||||
Apache ECharts
|
||||
Copyright 2017-2026 The Apache Software Foundation
|
||||
|
||||
This product includes software developed at
|
||||
The Apache Software Foundation (https://www.apache.org/).
|
||||
|
||||
zrender
|
||||
BSD 3-Clause License
|
||||
|
||||
Copyright (c) 2017, Baidu Inc.
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
tslib
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
PERFORMANCE OF THIS SOFTWARE.
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "zhao-steward-ui",
|
||||
"private": true,
|
||||
"version": "0.1.35",
|
||||
"version": "0.1.43",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "vite build",
|
||||
@@ -9,6 +9,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"bootstrap": "5.3.8",
|
||||
"echarts": "6.1.0",
|
||||
"vue": "^3.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
Generated
+23
@@ -11,6 +11,9 @@ importers:
|
||||
bootstrap:
|
||||
specifier: 5.3.8
|
||||
version: 5.3.8(@popperjs/core@2.11.8)
|
||||
echarts:
|
||||
specifier: 6.1.0
|
||||
version: 6.1.0
|
||||
vue:
|
||||
specifier: ^3.5.0
|
||||
version: 3.5.43
|
||||
@@ -396,6 +399,9 @@ packages:
|
||||
csstype@3.2.3:
|
||||
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
|
||||
|
||||
echarts@6.1.0:
|
||||
resolution: {integrity: sha512-q0yaFPggC9FUdsWH4blavRWFmxdrIodbkoKNAjJudAI6CA9gNPxHtV2RcZNEepZVlk4yvBYkOkbk6HIVpIyHZA==}
|
||||
|
||||
entities@7.0.1:
|
||||
resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}
|
||||
engines: {node: '>=0.12'}
|
||||
@@ -454,6 +460,9 @@ packages:
|
||||
resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
|
||||
engines: {node: '>=12.0.0'}
|
||||
|
||||
tslib@2.3.0:
|
||||
resolution: {integrity: sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==}
|
||||
|
||||
vite@7.3.6:
|
||||
resolution: {integrity: sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
@@ -502,6 +511,9 @@ packages:
|
||||
typescript:
|
||||
optional: true
|
||||
|
||||
zrender@6.1.0:
|
||||
resolution: {integrity: sha512-oEGMDB6pOP2S6OwRR4PdVv610zrjnA3Bh+JnSG12fYJlBKjtNAoEb5fSUoCOOINlH96I2fU38/A2UpRKs67xYQ==}
|
||||
|
||||
snapshots:
|
||||
|
||||
'@babel/helper-string-parser@7.29.7': {}
|
||||
@@ -747,6 +759,11 @@ snapshots:
|
||||
|
||||
csstype@3.2.3: {}
|
||||
|
||||
echarts@6.1.0:
|
||||
dependencies:
|
||||
tslib: 2.3.0
|
||||
zrender: 6.1.0
|
||||
|
||||
entities@7.0.1: {}
|
||||
|
||||
esbuild@0.28.2:
|
||||
@@ -842,6 +859,8 @@ snapshots:
|
||||
fdir: 6.5.0(picomatch@4.0.7)
|
||||
picomatch: 4.0.7
|
||||
|
||||
tslib@2.3.0: {}
|
||||
|
||||
vite@7.3.6:
|
||||
dependencies:
|
||||
esbuild: 0.28.2
|
||||
@@ -860,3 +879,7 @@ snapshots:
|
||||
'@vue/runtime-dom': 3.5.43
|
||||
'@vue/server-renderer': 3.5.43
|
||||
'@vue/shared': 3.5.43
|
||||
|
||||
zrender@6.1.0:
|
||||
dependencies:
|
||||
tslib: 2.3.0
|
||||
|
||||
Vendored
+239
@@ -0,0 +1,239 @@
|
||||
/* Bootstrap presentation layer. Keep player geometry and account preferences intact. */
|
||||
:root {
|
||||
--ui-bg: #f3f6fa;
|
||||
--ui-surface: #fff;
|
||||
--ui-line: #e3e9ef;
|
||||
--ui-muted: #5e6f7e;
|
||||
--ui-sidebar: #172e35;
|
||||
--ui-accent: #217964;
|
||||
--ink: #253b46;
|
||||
--muted: #5e6f7e;
|
||||
--paper: var(--ui-surface);
|
||||
--line: var(--ui-line);
|
||||
--green: var(--ui-accent);
|
||||
--bs-primary: #217964;
|
||||
--bs-primary-rgb: 33, 121, 100;
|
||||
--bs-body-color: var(--ink);
|
||||
--bs-body-bg: var(--ui-bg);
|
||||
--bs-border-color: var(--ui-line);
|
||||
--ui-shadow: 0 3px 16px #223d5010;
|
||||
--ui-soft: #f5f8fa;
|
||||
}
|
||||
html[data-theme="paper"] { --ui-bg: #f5f6f4; --ui-soft: #f5f7f3; }
|
||||
html[data-theme="clean"] { --ui-bg: #f1f5f9; --ui-soft: #f4f7fb; }
|
||||
html[data-theme="ink"] {
|
||||
--ui-bg: #111e26; --ui-surface: #1a2b35; --ui-line: #30444e;
|
||||
--ui-soft: #21353f; --ink: #e0ecef; --ui-muted: #a8bdc5;
|
||||
--muted: #a8bdc5; --ui-shadow: 0 3px 16px #0002;
|
||||
--paper: #1a2b35; --line: #30444e;
|
||||
}
|
||||
html, body { min-width: 0; }
|
||||
body { -webkit-font-smoothing: antialiased; }
|
||||
#app > main { max-width: 2000px; padding: 30px 38px 24px !important; }
|
||||
main > header { margin-bottom: 26px !important; padding-bottom: 24px !important; }
|
||||
#page-title { font-size: clamp(24px, 2.3vw, 32px) !important; letter-spacing: -.7px !important; }
|
||||
html[data-font="serif"] #page-title { font-weight: 600 !important; }
|
||||
#brand-motto { color: var(--ui-accent) !important; letter-spacing: 2.4px; }
|
||||
#page-note { font-size: 13px !important; }
|
||||
.header-status { gap: 9px; }
|
||||
#clock { font-variant-numeric: tabular-nums; font-size: 11px; }
|
||||
#service-status { padding: 6px 10px; border-radius: 20px !important; }
|
||||
.sidebar { background: linear-gradient(165deg, #1d3940, #152b32 70%) !important; }
|
||||
.brand { padding-bottom: 26px !important; }
|
||||
.brand-icon { width: 46px !important; height: 46px !important; box-shadow: 0 3px 12px #071d2860; }
|
||||
.sidebar nav button { border-radius: 10px !important; min-height: 46px; transition: background .15s, color .15s; }
|
||||
.sidebar nav button.active { background: #e1f2eb !important; color: #155b48 !important; box-shadow: 0 2px 7px #0002 !important; }
|
||||
.sidebar nav button.active .app-icon { opacity: 1; }
|
||||
.sidebar #current-user { padding: 14px 9px 2px; }
|
||||
.section-head { align-items: center; margin-bottom: 18px; }
|
||||
.section-head h2 { font-size: 21px !important; }
|
||||
.count-pill { background: #e7f0ec; color: #286752; border: 0; border-radius: 7px; padding: 3px 9px; font-size: 12px; }
|
||||
.btn { border-radius: 9px !important; min-height: 38px; padding: 8px 14px; transition: background .15s, border-color .15s, box-shadow .15s; }
|
||||
.btn-primary { --bs-btn-bg: var(--ui-accent); --bs-btn-border-color: var(--ui-accent); box-shadow: 0 3px 8px #21796416; }
|
||||
.btn-primary:hover { box-shadow: 0 4px 12px #21796428; }
|
||||
.btn-outline-secondary { --bs-btn-color: var(--ink); --bs-btn-border-color: var(--ui-line); background: var(--ui-surface); }
|
||||
.btn-link { color: var(--ui-accent); }
|
||||
html:is([data-theme="clean"],[data-theme="ink"]) :is(main,dialog) .btn-primary:not(.steward-tile):not(.device-title):not(.platform-place-node) { background: var(--ui-accent) !important; color: #fff !important; border-color: var(--ui-accent) !important; }
|
||||
html:is([data-theme="clean"],[data-theme="ink"]) :is(main,dialog) .btn-outline-secondary { background: var(--ui-surface) !important; color: var(--ink) !important; }
|
||||
html:is([data-theme="clean"],[data-theme="ink"]) :is(main,dialog) .btn-outline-secondary:is(.active,[aria-pressed="true"]) { background: var(--ui-soft) !important; border-color: #629987 !important; }
|
||||
html:is([data-theme="clean"],[data-theme="ink"]) .btn-link { background: transparent !important; color: var(--ink) !important; }
|
||||
html[data-theme="ink"] #brand-motto { color: #a7d7c4 !important; }
|
||||
.btn:focus-visible, button:focus-visible, a:focus-visible { outline: 3px solid #529cce; outline-offset: 3px; }
|
||||
.form-control, .form-select { border-radius: 9px !important; border-color: var(--ui-line) !important; min-height: 40px; background-color: var(--ui-surface); color: var(--ink); }
|
||||
.form-control:focus, .form-select:focus { border-color: #51a18b !important; box-shadow: 0 0 0 3px #21856819 !important; }
|
||||
.card, .panel { border: 1px solid var(--ui-line) !important; border-radius: 14px !important; background: var(--ui-surface); box-shadow: var(--ui-shadow) !important; }
|
||||
.card { overflow: hidden; }
|
||||
.card-body { padding: 24px; }
|
||||
dialog { border-radius: 16px !important; box-shadow: 0 24px 100px #10293040 !important; }
|
||||
dialog::backdrop { background: #132a3670; backdrop-filter: blur(4px); }
|
||||
dialog h2 { font-size: 22px !important; }
|
||||
.household-context, .device-context { border: 1px solid var(--ui-line) !important; background: var(--ui-surface) !important; border-radius: 12px; box-shadow: var(--ui-shadow); }
|
||||
.home-insights { display: grid; grid-template-columns: 1.4fr .7fr 1fr; gap: 18px; margin: 22px 0 26px; }
|
||||
.home-insights > article { border-radius: 15px; padding: 24px; min-width: 0; }
|
||||
.insight-welcome { position: relative; overflow: hidden; color: #fff; background: linear-gradient(115deg,#20534d,#297562); box-shadow: 0 6px 22px #21594c1c; }
|
||||
.insight-welcome::after { content: ''; position: absolute; right: -28px; bottom: -64px; width: 200px; height: 200px; border: 32px solid #fff07; border-radius: 50%; pointer-events: none; }
|
||||
.insight-kicker { color: #cae4d9; font-size: 10px; letter-spacing: 2px; }
|
||||
.insight-welcome h2 { color: #fff !important; font-size: 23px !important; margin: 14px 0 8px !important; }
|
||||
.insight-welcome p { color: #d0e7df; font-size: 12px; margin-bottom: 22px; }
|
||||
.insight-scope { display: flex; gap: 7px; align-items: center; color: #d7ebe4; font-size: 10px; }
|
||||
.insight-scope .app-icon { width: 15px; height: 15px; flex-basis: 15px; }
|
||||
.insight-number, .insight-distribution { background: var(--ui-surface); border: 1px solid var(--ui-line); box-shadow: var(--ui-shadow); }
|
||||
.insight-number { position: relative; display: flex; flex-direction: column; justify-content: center; }
|
||||
.insight-icon { position: absolute; right: 20px; top: 22px; width: 36px; height: 36px; display: grid; place-items: center; background: #e8f1fb; color: #527ec0; border-radius: 11px; }
|
||||
.insight-label { color: var(--ui-muted); font-size: 12px; padding-right: 35px; }
|
||||
.insight-number > strong { font-size: 40px; line-height: 1.3; font-weight: 650; margin: 10px 0; color: var(--ink); font-variant-numeric: tabular-nums; }
|
||||
.insight-number strong small { font-size: 12px; font-weight: 400; margin-left: 10px; color: var(--ui-muted); }
|
||||
.insight-foot { color: var(--ui-muted); font-size: 11px; }
|
||||
.insight-distribution { display: flex; align-items: center; justify-content: center; gap: 20px; }
|
||||
.insight-donut { width: 126px; flex: 0 0 126px; position: relative; }
|
||||
.insight-donut svg { width: 100%; display: block; }
|
||||
.donut-track { stroke: var(--ui-line); }
|
||||
.insight-donut > div { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; pointer-events: none; }
|
||||
.insight-donut strong { font-size: 28px; line-height: 1.3; }
|
||||
.insight-donut small { font-size: 10px; color: var(--ui-muted); }
|
||||
.insight-legend { flex: 1; min-width: 60px; max-width: 145px; }
|
||||
.insight-legend h3 { font-size: 12px !important; margin-bottom: 13px; white-space: nowrap; }
|
||||
.insight-legend > span { display: flex; align-items: center; gap: 7px; font-size: 11px; margin-top: 7px; color: var(--ui-muted); }
|
||||
.insight-legend i { width: 7px; height: 7px; border-radius: 2px; flex-shrink: 0; }
|
||||
.insight-legend b { margin-left: auto; color: var(--ink); }
|
||||
.home-toolbar { padding: 13px 16px; border: 1px solid var(--ui-line); border-radius: 12px; background: var(--ui-surface); gap: 14px; }
|
||||
.home-layout-toggle { display: none; }
|
||||
#home-layout-status { margin: 10px 3px 18px; font-size: 11px; }
|
||||
.home-card-grid { gap: 24px; }
|
||||
.home-card { transition: box-shadow .18s, border-color .18s; }
|
||||
.home-card:hover { box-shadow: 0 8px 26px #223d5019 !important; border-color: #b4cac0 !important; }
|
||||
.home-cover { height: 220px; background: linear-gradient(120deg,#35595b,#193a40); }
|
||||
.home-cover .cover-shade { background: linear-gradient(180deg,#142b3830 0%,#10282b05 30%,#0a232bcc 100%); }
|
||||
.home-cover-content { padding: 22px 25px; }
|
||||
.home-cover-content h3 { font-size: 24px !important; font-weight: 600 !important; letter-spacing: .5px !important; }
|
||||
.home-cover-content .badge { border: 1px solid #ffffff38; background: #f6fffaed !important; color: #27594a !important; border-radius: 6px !important; font-size: 11px; }
|
||||
.home-location { font-size: 11px; color: #ebf3f0; }
|
||||
.cover-edit { background: #142a3560 !important; border: 1px solid #ffffff80 !important; color: #fff !important; backdrop-filter: blur(4px); }
|
||||
.home-summary { color: var(--ui-muted); font-size: 12px; }
|
||||
.home-numbers { background: var(--ui-soft); border: 0; border-radius: 10px; padding: 14px 0; margin: 16px 0 20px; }
|
||||
.home-numbers span { border-right: 1px solid var(--ui-line); color: var(--ui-muted); font-size: 11px; }
|
||||
.home-numbers span:last-child { border: 0; }
|
||||
.home-numbers b { font-size: 24px; color: var(--ink); }
|
||||
.home-card-actions { border-top: 1px solid var(--ui-line); padding-top: 18px; margin-top: 18px; }
|
||||
.compact-details dt { color: var(--ui-muted); }
|
||||
.compact-details dd { color: var(--ink); }
|
||||
.home-pagination { margin-top: 24px; font-size: 11px; }
|
||||
.metrics { gap: 16px; }
|
||||
.metrics > div { border: 1px solid var(--ui-line); border-radius: 12px; background: var(--ui-surface); box-shadow: var(--ui-shadow); border-top: 3px solid #438979; }
|
||||
.metrics > div:nth-child(2) { border-top-color: #658cd1; }
|
||||
.metrics > div:nth-child(3) { border-top-color: #b69c70; }
|
||||
.metrics > div:nth-child(4) { border-top-color: #8391b5; }
|
||||
.metrics strong { font-variant-numeric: tabular-nums; color: var(--ink); }
|
||||
.device-card-heading .device-symbol { background: #e9f3ef; color: #287e65; border-radius: 12px; width: 44px; height: 44px; }
|
||||
.device-card .card-footer { border-top: 1px solid var(--ui-line); background: var(--ui-soft); padding: 14px 22px; }
|
||||
.device-card-grid { gap: 20px; }
|
||||
.device-view-controls { padding: 20px 24px; }
|
||||
.device-search-row { border-bottom: 1px solid var(--ui-line); padding-bottom: 18px; margin-bottom: 15px; }
|
||||
.group-title { margin: 24px 0 14px; }
|
||||
.device-location { color: var(--ui-muted); }
|
||||
.network-map { padding: 24px; }
|
||||
.network-platform { background: var(--ui-soft); border: 1px solid var(--ui-line); border-radius: 12px; padding: 20px; }
|
||||
.network-platform > .app-icon { width: 30px; height: 30px; flex-basis: 30px; color: var(--ui-accent); }
|
||||
.network-diagram { margin: 20px 0 28px; border: 1px solid var(--ui-line); border-radius: 12px; overflow: hidden; }
|
||||
.diagram-toolbar { display: flex; justify-content: space-between; align-items: center; gap: 16px; padding: 14px 18px; background: var(--ui-surface); }
|
||||
.diagram-toolbar > div { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
|
||||
.diagram-toolbar strong { font-size: 13px; }
|
||||
.diagram-dot { width: 7px; height: 7px; border-radius: 50%; background: #4d8dbe; }
|
||||
.diagram-toolbar label { display: flex; align-items: center; gap: 8px; font-size: 11px; margin: 0; }
|
||||
.diagram-toolbar select { width: 86px; }
|
||||
.diagram-scroll { max-height: 480px; overflow: auto; background-color: var(--ui-soft); background-image: radial-gradient(var(--ui-line) 1px, transparent 1px); background-size: 18px 18px; border-block: 1px solid var(--ui-line); }
|
||||
.network-svg { display: block; }
|
||||
.network-edge { stroke: #82a79c; stroke-width: 2; }
|
||||
.diagram-node { cursor: pointer; outline: none; }
|
||||
.diagram-node-bg { fill: var(--ui-surface); stroke: var(--ui-line); stroke-width: 1.5; }
|
||||
.diagram-node:hover .diagram-node-bg, .diagram-node:focus .diagram-node-bg { stroke: #328d78; stroke-width: 2.5; }
|
||||
.diagram-node-type { fill: var(--ui-muted); font-size: 10px; }
|
||||
.diagram-node-title { fill: var(--ink); font-size: 14px; font-weight: 600; }
|
||||
.diagram-node-ip { fill: var(--ui-muted); font-size: 11px; font-family: ui-monospace, Consolas, monospace; }
|
||||
.diagram-note { margin: 0; padding: 11px 18px; font-size: 11px; color: var(--ui-muted); }
|
||||
.network-details-heading { margin: 20px 0 14px; }
|
||||
.platform-place-node { position: relative; text-align: left; padding: 24px; }
|
||||
.platform-place-node::before { content: ''; position: absolute; inset: 0 auto 0 0; width: 4px; background: #438979; }
|
||||
.platform-place-node:hover { border-color: #8db4a7 !important; background: var(--ui-soft); }
|
||||
.network-open { color: var(--ui-accent); font-weight: 600; }
|
||||
.scope-intro { border-bottom: 1px solid var(--ui-line); padding-bottom: 20px; }
|
||||
.steward-tile { border-radius: 14px !important; border: 1px solid var(--ui-line) !important; border-top: 3px solid #438979 !important; box-shadow: var(--ui-shadow) !important; padding: 28px !important; background: var(--ui-surface) !important; }
|
||||
.steward-tile:nth-child(2n) { border-top-color: #6c8fbc !important; }
|
||||
.steward-tile:nth-child(3n) { border-top-color: #b29a72 !important; }
|
||||
.steward-tile strong { font-size: 19px !important; }
|
||||
.steward-tile:hover { border-color: #9dbab0 !important; box-shadow: 0 8px 22px #223d5016 !important; }
|
||||
.journal-card { border-radius: 14px; box-shadow: var(--ui-shadow); }
|
||||
#page-live:is(:fullscreen,.wall-expanded) .camera-meta { background: #172e35 !important; color: #e8f3ef !important; }
|
||||
#page-live:is(:fullscreen,.wall-expanded) .camera-meta strong { color: #e8f3ef !important; }
|
||||
#page-live:is(:fullscreen,.wall-expanded) .wall-toolbar { background: #172e35 !important; border-color: #45616a !important; }
|
||||
#page-live:is(:fullscreen,.wall-expanded) .form-select { background-color: #213b44 !important; color: #e8f3ef !important; border-color: #64818b !important; }
|
||||
main > footer { color: var(--ui-muted); font-size: 10px; }
|
||||
html[data-density="compact"] .home-insights > article { padding: 18px; }
|
||||
html[data-density="compact"] .home-cover { height: 165px; }
|
||||
html[data-density="compact"] .card-body { padding: 18px; }
|
||||
@media (min-width: 1100px) { html[data-layout="top"] #app > main { padding-top: 28px !important; } }
|
||||
@media (max-width: 1250px) {
|
||||
.home-insights { grid-template-columns: 1.2fr .75fr 1fr; gap: 12px; }
|
||||
.home-insights > article { padding: 19px; }
|
||||
.insight-distribution { gap: 10px; }
|
||||
.insight-donut { width: 102px; flex-basis: 102px; }
|
||||
.insight-welcome h2 { font-size: 20px !important; }
|
||||
}
|
||||
@media (max-width: 1000px) and (min-width: 761px) {
|
||||
#app > main { padding: 26px 24px !important; }
|
||||
.home-insights { grid-template-columns: 1fr 1fr; }
|
||||
.insight-welcome { grid-column: 1/-1; }
|
||||
.insight-welcome p { margin-bottom: 12px; }
|
||||
}
|
||||
@media (max-width: 760px) {
|
||||
#app > main { padding: 20px 16px 20px !important; }
|
||||
.sidebar { background: #17353b !important; }
|
||||
main > header { margin-bottom: 20px !important; padding-bottom: 18px !important; }
|
||||
#page-title { font-size: 25px !important; }
|
||||
#page-note { font-size: 12px !important; }
|
||||
.home-insights { grid-template-columns: 1fr 1fr; gap: 12px; margin: 16px 0 20px; }
|
||||
.home-insights > article { padding: 18px; }
|
||||
.insight-welcome { grid-column: 1/-1; }
|
||||
.insight-welcome h2 { margin: 7px 0 0 !important; font-size: 20px !important; }
|
||||
.insight-welcome p, .insight-scope { display: none; }
|
||||
.insight-number > strong { font-size: 34px; }
|
||||
.insight-icon { width: 29px; height: 29px; top: 14px; right: 13px; }
|
||||
.insight-distribution { flex-direction: column; gap: 5px; }
|
||||
.insight-donut { width: 94px; flex-basis: auto; }
|
||||
.insight-legend { width: 100%; display: flex; flex-wrap: wrap; justify-content: center; gap: 6px; }
|
||||
.insight-legend h3 { display: none; }
|
||||
.insight-legend > span { margin: 0; font-size: 10px; gap: 4px; }
|
||||
.insight-number .insight-label { padding-right: 24px; font-size: 11px; }
|
||||
.insight-donut strong { font-size: 25px; }
|
||||
.insight-donut small { font-size: 9px; }
|
||||
.home-toolbar { padding: 12px; }
|
||||
.home-layout-toggle { display: inline-flex; margin-left: auto; }
|
||||
.home-toolbar .home-layout-controls { display: none; }
|
||||
.home-toolbar.home-options-open .home-layout-controls { display: flex; flex-basis: 100%; border-top: 1px solid var(--ui-line); padding-top: 12px; }
|
||||
.home-cover { height: 200px; }
|
||||
.home-cover-content { padding: 20px; }
|
||||
.home-cover-content h3 { font-size: 23px !important; }
|
||||
.card-body { padding: 20px; }
|
||||
.home-numbers { padding: 12px 0; }
|
||||
.home-card-grid { gap: 18px; }
|
||||
.home-card-actions { gap: 8px; flex-wrap: wrap; }
|
||||
.btn { min-height: 44px; }
|
||||
.form-control, .form-select { min-height: 44px; font-size: 16px; }
|
||||
#page-playback .playback-controls { display: grid; grid-template-columns: minmax(0, 1fr); gap: 14px; }
|
||||
#page-playback .playback-controls label { width: 100%; min-width: 0; }
|
||||
#page-playback .playback-controls input, #page-playback .playback-controls select { width: 100%; }
|
||||
#page-playback .playback-controls button { width: 100%; }
|
||||
#play-info { overflow-wrap: anywhere; }
|
||||
.device-view-controls { padding: 16px; }
|
||||
.network-map { padding: 14px; }
|
||||
.network-platform { padding: 16px; }
|
||||
.diagram-toolbar { padding: 12px; align-items: flex-start; }
|
||||
.diagram-toolbar > div { gap: 6px; }
|
||||
.diagram-toolbar > div .small { flex-basis: 100%; font-size: 10px; }
|
||||
.diagram-toolbar label { flex-direction: column; align-items: flex-start; }
|
||||
.diagram-toolbar select { width: 82px; }
|
||||
.diagram-scroll { max-height: 360px; }
|
||||
.steward-tile { padding: 22px !important; }
|
||||
main[data-page="live"] > header { margin-bottom: 10px !important; padding-bottom: 12px !important; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { *, *::before, *::after { transition: none !important; scroll-behavior: auto !important; } }
|
||||
@@ -15,6 +15,6 @@ export function enhance(root){
|
||||
export async function loadControllers(){
|
||||
enhance(document.getElementById('app'))
|
||||
new MutationObserver(records=>{for(const record of records)for(const node of record.addedNodes)enhance(node)}).observe(document.getElementById('app'),{childList:true,subtree:true})
|
||||
for(const path of [...scripts,'/vue-bridge.js'])await new Promise((resolve,reject)=>{const script=document.createElement('script');script.src=path+'?ui=0.1.36';script.onload=resolve;script.onerror=()=>reject(new Error('Could not load '+path));document.head.append(script)})
|
||||
for(const path of [...scripts,'/vue-bridge.js'])await new Promise((resolve,reject)=>{const script=document.createElement('script');script.src=path+'?ui=0.1.43';script.onload=resolve;script.onerror=()=>reject(new Error('Could not load '+path));document.head.append(script)})
|
||||
await window.ZhaoVue.boot()
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
<script setup>
|
||||
defineProps({ name: { type: String, default: "grid" } });
|
||||
const paths = {
|
||||
shield: "M12 2 3 6v6c0 5 9 10 9 10s9-5 9-10V6Z M8 12l3 3 5-6",
|
||||
location: "M20 10c0 6-8 12-8 12S4 16 4 10a8 8 0 1 1 16 0 M15 10a3 3 0 1 1-6 0 3 3 0 0 1 6 0",
|
||||
home: "m3 10 9-7 9 7v10H3Z M9 20v-7h6v7",
|
||||
journal: "M5 3h14v18H5Z M8 7h8 M8 11h8 M8 15h5",
|
||||
grid: "M3 3h7v7H3Z M14 3h7v7h-7Z M3 14h7v7H3Z M14 14h7v7h-7Z",
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { snapshot, bridge, accessLabel } from "../composables/bridge.js";
|
||||
import AppIcon from "./AppIcon.vue";
|
||||
import HomeInsights from "./HomeInsights.vue";
|
||||
import LocalChart from "./LocalChart.vue";
|
||||
import { platformChart } from "../composables/charts.mjs";
|
||||
const draft = ref({
|
||||
revision: 0,
|
||||
columns: 2,
|
||||
@@ -14,6 +17,7 @@ const draft = ref({
|
||||
page = ref(0),
|
||||
arrange = ref(false),
|
||||
mode = ref("cards"),
|
||||
layoutOptions = ref(false),
|
||||
drag = ref(""),
|
||||
message = ref("");
|
||||
let owner = "";
|
||||
@@ -28,6 +32,7 @@ watch(
|
||||
page.value = 0;
|
||||
arrange.value = false;
|
||||
mode.value = "cards";
|
||||
layoutOptions.value = false;
|
||||
drag.value = "";
|
||||
message.value = "";
|
||||
}
|
||||
@@ -144,7 +149,8 @@ async function enter(h, network = false) {
|
||||
+ 新建家庭或场所
|
||||
</button>
|
||||
</div>
|
||||
<div class="home-toolbar">
|
||||
<HomeInsights />
|
||||
<div class="home-toolbar" :class="{ 'home-options-open': layoutOptions }">
|
||||
<div class="btn-group" role="group" aria-label="场所显示方式">
|
||||
<button
|
||||
id="home-card-view"
|
||||
@@ -164,7 +170,8 @@ async function enter(h, network = false) {
|
||||
<AppIcon name="network" /> 整体拓扑
|
||||
</button>
|
||||
</div>
|
||||
<div v-show="mode === 'cards'" class="home-layout-controls">
|
||||
<button v-show="mode === 'cards'" class="btn btn-outline-secondary home-layout-toggle" :aria-expanded="layoutOptions" aria-controls="home-layout-options" @click="layoutOptions = !layoutOptions">{{ layoutOptions ? '收起设置' : '布局设置' }}</button>
|
||||
<div id="home-layout-options" v-show="mode === 'cards'" class="home-layout-controls">
|
||||
<label
|
||||
>每页
|
||||
<select
|
||||
@@ -364,6 +371,9 @@ async function enter(h, network = false) {
|
||||
<p class="description">
|
||||
平台与场所的管理关系;进入场所查看内部设备及网络。
|
||||
</p>
|
||||
<div v-if="homes.length" class="chart-network-surface mb-3">
|
||||
<LocalChart :option="platformChart(homes, snapshot.brandName || '赵府')" :active="snapshot.loggedIn && snapshot.page === 'households' && mode === 'topology'" :height="340" label="平台及已授权场所关系图;点击场所进入内部网络,下面也可通过卡片进入。" @select="id => enter({id}, true)" />
|
||||
</div>
|
||||
<div class="platform-place-grid">
|
||||
<button
|
||||
v-for="h in homes"
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
<script setup>
|
||||
import { computed, ref } from 'vue';
|
||||
import { snapshot } from '../composables/bridge.js';
|
||||
import { summarizeHomes } from '../composables/insights.mjs';
|
||||
import { distribution, bars } from '../composables/charts.mjs';
|
||||
import LocalChart from './LocalChart.vue';
|
||||
import AppIcon from './AppIcon.vue';
|
||||
const summary = computed(() => summarizeHomes(snapshot.value.state.households));
|
||||
const expanded = ref(false);
|
||||
const active = computed(() => snapshot.value.loggedIn && snapshot.value.page === 'households');
|
||||
const places = computed(() => (snapshot.value.state.households || []).map(h => ({ label: h.name, count: h.deviceCount || 0 })).sort((a,b) => b.count-a.count).slice(0, 8));
|
||||
</script>
|
||||
<template>
|
||||
<section class="dashboard-grid row g-3 mb-4" :class="{'charts-expanded':expanded}" aria-label="已授权场所概览">
|
||||
<div class="col-12 col-xl-4"><article class="dashboard-welcome h-100">
|
||||
<span class="insight-kicker">一处相连 · 各有归属</span>
|
||||
<h2>家与日常,尽在掌握</h2><p>从一处灯火,连接生活的每个空间。</p>
|
||||
<div class="dashboard-totals"><div><strong>{{ summary.total }}</strong><span>家庭与场所</span></div><div><strong>{{ summary.devices }}</strong><span>已登记设备</span></div><div><strong>{{ summary.areas }}</strong><span>区域空间</span></div></div>
|
||||
<div class="insight-scope"><AppIcon name="shield" /> 仅汇总你有权访问的家庭与场所</div>
|
||||
</article></div>
|
||||
<div class="col-12 d-md-none"><button class="btn btn-outline-secondary w-100" :aria-expanded="expanded" @click="expanded=!expanded">{{ expanded?'收起图表统计':'展开图表统计' }}</button></div>
|
||||
<div class="col-12 col-md-5 col-xl-3 dashboard-chart-column"><article class="chart-card h-100"><div class="chart-heading"><h3>空间分布</h3><span class="badge">{{ summary.total }} 处</span></div>
|
||||
<LocalChart v-if="summary.total" :option="distribution(summary.kinds)" :active="active" :height="160" :label="'场所分布:'+summary.kinds.map(k=>k.label+k.count+'个').join(',')" />
|
||||
<p v-else class="chart-empty">添加家庭或场所后显示分布</p>
|
||||
<div class="chart-legend"><span v-for="k in summary.kinds" :key="k.key"><i :style="{background:k.color}"></i>{{ k.label }} <b>{{ k.count }}</b></span></div>
|
||||
</article></div>
|
||||
<div class="col-12 col-md-7 col-xl-5 dashboard-chart-column"><article class="chart-card h-100"><div class="chart-heading"><h3>设备分布</h3><span class="small text-secondary">按场所 · 最多显示 8 处</span></div>
|
||||
<LocalChart v-if="places.length" :option="bars(places)" :active="active" :height="190" :label="'各场所已登记设备:'+places.map(x=>x.label+x.count+'台').join(',')" />
|
||||
<p v-else class="chart-empty">暂无已授权场所</p>
|
||||
<details v-if="places.length" class="chart-data"><summary>查看统计数字</summary><ul><li v-for="p in places" :key="p.label">{{ p.label }}:{{ p.count }} 台</li></ul></details>
|
||||
</article></div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,50 @@
|
||||
<script setup>
|
||||
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
|
||||
const props = defineProps({ option: { type: Object, required: true }, label: String, active: { type: Boolean, default: true }, height: { type: Number, default: 260 } });
|
||||
const emit = defineEmits(['select']);
|
||||
const host = ref(null), failed = ref(false);
|
||||
let chart, resizeObserver, themeObserver, frame, alive = true, loading = false, last = '', size = '';
|
||||
function dispose() { chart?.dispose(); chart = null; last = ''; size = ''; }
|
||||
function queue() { if (!frame && alive) frame = requestAnimationFrame(() => { frame = null; render(); }); }
|
||||
async function render() {
|
||||
if (!alive || !host.value || !props.active) { dispose(); return; }
|
||||
const width = Math.floor(host.value.clientWidth), height = Math.floor(host.value.clientHeight);
|
||||
if (!width || !height) return;
|
||||
if (!chart) {
|
||||
if (loading) return;
|
||||
loading = true;
|
||||
try {
|
||||
const runtime = await import('../composables/charts-runtime.js');
|
||||
if (!alive || !props.active || !host.value) return;
|
||||
chart = runtime.init(host.value, null, { renderer: 'canvas', devicePixelRatio: Math.min(window.devicePixelRatio || 1, 2) });
|
||||
chart.on('click', value => { if (value.data?.targetId) emit('select', value.data.targetId); });
|
||||
failed.value = false;
|
||||
} catch (error) { failed.value = true; console.error('Local chart unavailable', error); return; }
|
||||
finally { loading = false; }
|
||||
}
|
||||
const css = getComputedStyle(document.documentElement), ink = css.getPropertyValue('--ink').trim() || '#253b46', muted = css.getPropertyValue('--ui-muted').trim() || '#627485', line = css.getPropertyValue('--ui-line').trim() || '#e3e9ef';
|
||||
const fingerprint = JSON.stringify(props.option) + ink + muted + line;
|
||||
// Periodic status refreshes must not restart chart layout/animation.
|
||||
if (fingerprint !== last) {
|
||||
const option = { ...props.option, animation: false, backgroundColor: 'transparent', textStyle: { color: ink, fontFamily: 'system-ui, Microsoft YaHei, sans-serif' }, aria: { enabled: true, description: props.label }, tooltip: { trigger: 'item', renderMode: 'richText', confine: true, ...props.option.tooltip } };
|
||||
for (const axis of ['xAxis', 'yAxis']) if (option[axis]) option[axis] = { ...option[axis], axisLabel: { color: muted, ...option[axis].axisLabel }, splitLine: { lineStyle: { color: line } } };
|
||||
option.series = (option.series || []).map(series => ({ ...series, label: { color: ink, ...series.label } }));
|
||||
chart.setOption(option, { notMerge: true, lazyUpdate: false }); last = fingerprint;
|
||||
}
|
||||
const nextSize = width + ':' + height;
|
||||
if (nextSize !== size) { chart.resize({ width, height }); size = nextSize; }
|
||||
}
|
||||
watch(() => [props.option, props.active], queue, { deep: true, flush: 'post' });
|
||||
onMounted(() => {
|
||||
resizeObserver = new ResizeObserver(queue); resizeObserver.observe(host.value);
|
||||
themeObserver = new MutationObserver(queue); themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme', 'data-density'] });
|
||||
queue();
|
||||
});
|
||||
onBeforeUnmount(() => { alive = false; cancelAnimationFrame(frame); resizeObserver?.disconnect(); themeObserver?.disconnect(); dispose(); });
|
||||
</script>
|
||||
<template>
|
||||
<div class="local-chart-wrap">
|
||||
<div ref="host" class="local-chart" role="img" :aria-label="label" :style="{ height: height + 'px' }"></div>
|
||||
<p v-if="failed" class="small text-secondary px-3" role="status">图表暂未加载,可查看下方数据。</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,18 @@
|
||||
<script setup>
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { deviceView, snapshot, bridge } from '../composables/bridge.js';
|
||||
import { networkChart } from '../composables/charts.mjs';
|
||||
import LocalChart from './LocalChart.vue';
|
||||
const resetKey = ref(0);
|
||||
const option = computed(() => networkChart(deviceView.value.rows, bridge().location));
|
||||
const active = computed(() => snapshot.value.loggedIn && snapshot.value.page === 'objects' && deviceView.value.mode === 'topology');
|
||||
watch(() => snapshot.value.session + ':' + snapshot.value.state.familyId, () => resetKey.value++);
|
||||
function open(id) { const row = deviceView.value.rows.find(r => r.device.id === id); if (row) bridge().enterDevice(row.device.source, id, 'device'); }
|
||||
</script>
|
||||
<template>
|
||||
<div v-if="deviceView.rows.length" class="network-diagram">
|
||||
<div class="diagram-toolbar"><div><span class="diagram-dot"></span><strong>设备连接图</strong><span class="small text-secondary">{{ deviceView.rows.length }} 台设备 · {{ option.series[0].links.length }} 条已登记连接</span></div><button class="btn btn-sm btn-outline-secondary" @click="resetKey++">重置视图</button></div>
|
||||
<div class="chart-network-surface"><LocalChart :key="resetKey" :option="option" :active="active" :height="400" label="已登记设备连接图,可拖动缩放;下方设备详情提供相同信息及操作。" @select="open" /></div>
|
||||
<p class="diagram-note">拖动平移、滚轮或双指缩放;点击节点打开档案。未登记上级的设备独立显示;接入方式不代表在线状态。</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from "../composables/bridge.js";
|
||||
import AppIcon from "./AppIcon.vue";
|
||||
import NetworkStatus from "./NetworkStatus.vue";
|
||||
import NetworkDiagram from "./NetworkDiagram.vue";
|
||||
const home = computed(() =>
|
||||
(snapshot.value.state.households || []).find(
|
||||
(h) => h.id === snapshot.value.state.familyId,
|
||||
@@ -27,6 +28,8 @@ const home = computed(() =>
|
||||
<p class="description">
|
||||
连线来自已确认的上级设备关系。上级未填写时单独列出;不代表已自动发现所有交换机或布线。
|
||||
</p>
|
||||
<NetworkDiagram />
|
||||
<h3 class="network-details-heading">设备与连接详情</h3>
|
||||
<div class="topology-nodes">
|
||||
<article
|
||||
v-for="row in deviceView.rows"
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,14 @@
|
||||
<script setup>
|
||||
import { computed } from 'vue';
|
||||
import { snapshot } from '../composables/bridge.js';
|
||||
import { summarizeDevices, bars, distribution, palette } from '../composables/charts.mjs';
|
||||
import LocalChart from './LocalChart.vue';
|
||||
const summary = computed(() => summarizeDevices(snapshot.value.state));
|
||||
const active = computed(() => snapshot.value.loggedIn && snapshot.value.page === 'overview');
|
||||
</script>
|
||||
<template>
|
||||
<section class="row g-3 mb-4" aria-label="当前场所设备统计" v-if="active && summary.total">
|
||||
<div class="col-12 col-lg-7"><article class="chart-card h-100"><div class="chart-heading"><h3>设备类型</h3><span class="small text-secondary">{{ summary.total }} 台已授权设备</span></div><LocalChart :option="bars(summary.types.slice(0,8))" :height="220" :label="'设备类型:'+summary.types.map(x=>x.label+x.count+'台').join(',')" /><details class="chart-data"><summary>查看全部类型</summary><ul><li v-for="x in summary.types" :key="x.label">{{ x.label }}:{{ x.count }} 台</li></ul></details></article></div>
|
||||
<div class="col-12 col-lg-5"><article class="chart-card h-100"><div class="chart-heading"><h3>网络接入</h3><span class="small text-secondary">来自设备档案</span></div><LocalChart :option="distribution(summary.networks)" :height="190" :label="'登记的网络接入方式:'+summary.networks.map(x=>x.label+x.count+'台').join(',')" /><div class="chart-legend"><span v-for="(x,i) in summary.networks" :key="x.label"><i :style="{background:palette[i]}"></i>{{ x.label }} <b>{{ x.count }}</b></span></div><p class="small text-secondary mt-2 mb-0">接入方式不代表设备在线状态。</p></article></div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -3,6 +3,7 @@ import HomeExplorer from './HomeExplorer.vue'
|
||||
import DeviceCollection from './DeviceCollection.vue'
|
||||
import NetworkMap from './NetworkMap.vue'
|
||||
import DeviceNetworkPanel from './DeviceNetworkPanel.vue'
|
||||
import ScopeInsights from './ScopeInsights.vue'
|
||||
</script>
|
||||
<template>
|
||||
|
||||
@@ -29,11 +30,12 @@ import DeviceNetworkPanel from './DeviceNetworkPanel.vue'
|
||||
<form id="journal-filter" class="panel journal-filters"><label>查看方式<select id="journal-mode"><option value="feed">家庭/场所动态</option><option value="mine">我的个人阅历</option><option value="person">某个人的阅历</option></select></label><label id="journal-person-label" hidden>人物<select id="journal-person"></select></label><label>分类<select id="journal-category"><option value="">全部分类</option><option>日常</option><option>成长</option><option>家庭</option><option>旅行</option><option>工作</option><option>其他</option></select></label><label>关键词<input id="journal-search" type="search" maxlength="120" placeholder="在文字中查找"></label><label>开始日期<input id="journal-from" type="date"></label><label>结束日期<input id="journal-to" type="date"></label><button type="submit">查询阅历</button><button id="journal-filter-clear" type="button" class="quiet">清除筛选</button></form><p class="description">个人阅历保留同一条记事的文字、附件和互动;查看他人时只展示其分享给当前家庭/场所的内容。删除记事或移出附件列表不会删除网盘原文件。</p><div class="section-head"><p id="journal-query-status" role="status"></p><div><button id="journal-prev" class="quiet">上一页</button><button id="journal-next" class="quiet">下一页</button></div></div><div id="journal-list" class="journal-feed"></div>
|
||||
</section>
|
||||
|
||||
<section id="page-overview" class="page" hidden><div id="scope-overview"></div></section><section id="page-device" class="page" hidden><DeviceNetworkPanel /><div id="device-detail"></div></section><section id="page-heritage" class="page" hidden><div id="heritage-home"></div></section>
|
||||
<section id="page-overview" class="page" hidden><ScopeInsights /><div id="scope-overview"></div></section><section id="page-device" class="page" hidden><DeviceNetworkPanel /><div id="device-detail"></div></section><section id="page-heritage" class="page" hidden><div id="heritage-home"></div></section>
|
||||
<section id="page-live" class="page"><div class="section-head"><h2 id="live-heading">本场所监控墙</h2><div><label>清晰度 <select id="quality"><option value="hd">主码流</option><option value="compat">子码流</option></select></label></div></div><details class="live-help"><summary>画面与清晰度说明</summary><p id="wall-context" class="description">这里汇总当前场所内已授权的镜头;点击摄像头详情可进入单台设备。</p><p class="description" id="quality-note">主码流画面更清晰,最高 1920×1080;子码流更流畅,最高 768×432,适合网络较慢时使用。</p></details><div class="wall-toolbar"><label>分屏 <select id="wall-layout"><option value="auto">自适应</option><option value="1">1 画面</option><option value="2">2 画面</option><option value="4">4 画面</option><option value="6">6 画面</option><option value="9">9 画面</option><option value="16">16 画面</option></select></label><label class="check"><input id="wall-arrange" type="checkbox">调整顺序</label><div class="wall-paging"><button id="wall-prev" class="quiet" aria-label="上一组画面">‹</button><span id="wall-page"></span><button id="wall-next" class="quiet" aria-label="下一组画面">›</button></div><span id="wall-clock"></span><button id="wall-fullscreen">全屏监控</button></div><div id="live-grid" class="live-grid"></div><section id="ptz-panel" class="ptz-panel" hidden><div><strong id="ptz-title">云台</strong><p id="ptz-status" role="status"></p></div><div class="ptz-pad"><button data-ptz-action="up" aria-label="云台向上">↑</button><button data-ptz-action="left" aria-label="云台向左">←</button><button data-ptz-action="stop">停止</button><button data-ptz-action="right" aria-label="云台向右">→</button><button data-ptz-action="down" aria-label="云台向下">↓</button></div><div id="ptz-presets"><div class="section-head"><strong>常用位置 <small id="preset-count"></small></strong><button id="preset-reload" class="quiet">重新读取</button></div><p id="preset-status" role="status"></p><div id="preset-list"></div><p class="description">调整位置后可另存为新预置位。本版不覆盖已有位置,避免设备固件拒绝或误改。</p><form id="preset-form" hidden><label>当前位置名称<input id="preset-name" required maxlength="40" placeholder="例如:大门、院子"></label><button type="submit">保存当前位置</button></form><div id="preset-confirmation" hidden><p id="preset-confirm-text"></p><button id="preset-confirm-yes">确认</button><button id="preset-confirm-cancel" class="quiet">取消</button></div></div><button id="ptz-close" class="quiet">收起云台</button></section></section>
|
||||
<section id="page-playback" class="page" hidden>
|
||||
<div class="section-head"><h2>回到那一刻 <small>光阴</small></h2></div>
|
||||
<div class="panel playback-controls"><label>镜头 / 通道<select id="play-camera"></select></label><label>录像来源<select id="archive-source"><option value="recorder">录像机原有录像(待接入)</option><option value="local">小电脑本机录像</option></select></label><label>日期<input id="play-date" type="date"></label><button id="query-recordings">查找录像</button><span id="play-info">选择日期,查看实际录像时段</span></div>
|
||||
<aside id="recording-health" class="panel" aria-label="本机录像状态" hidden><div class="section-head"><strong id="recording-health-text" role="status"></strong><button id="recording-configure" class="quiet" hidden>录像设置</button></div><p id="recording-policy-note" class="description"></p><p id="recording-start-note" class="description"></p></aside>
|
||||
<div class="video-panel"><video id="play-video" controls playsinline></video><div id="play-empty" class="video-empty">选择一个有录像的时间段</div></div>
|
||||
<div class="panel"><div class="timeline-head"><strong>当日时间轴</strong><span><i class="legend"></i> 有录像的时段 · 点击定位</span></div><canvas id="timeline" height="76" aria-label="录像时间轴"></canvas><div class="time-labels"><span>00:00</span><span>06:00</span><span>12:00</span><span>18:00</span><span>24:00</span></div><div class="seek-row"><label>定位时间 <input id="seek-time" type="time" step="1" value="12:00:00"></label><button id="seek-button" class="secondary">定位播放</button><a id="download" class="button secondary" hidden>下载原始片段</a></div></div>
|
||||
<div class="panel"><div class="playback-tools"><label class="check"><input id="play-autonext" type="checkbox" checked>自动续播下一时段(跳过空档)</label><button id="play-snapshot" class="quiet">回放截图</button><span id="play-position" role="status"></span></div><details class="clip-editor"><summary>选取并下载指定片段</summary><form id="clip-form"><div class="form-grid"><label>开始时间<input id="clip-start" type="datetime-local" step="1" required></label><label>结束时间<input id="clip-end" type="datetime-local" step="1" required></label></div><div class="playback-tools"><button type="button" class="quiet" data-clip-mark="start">当前位置作起点</button><button type="button" class="quiet" data-clip-mark="end">当前位置作终点</button><button type="submit">生成下载链接</button><a id="clip-download" class="button secondary" hidden>下载所选片段</a></div><p id="clip-status" role="status" class="description"></p><p class="description">每段最多一小时,不可跨越无录像时段。下载保留原始编码,剪辑边界可能受设备关键帧影响。</p></form></details></div><div id="recording-list" class="recording-list"></div>
|
||||
@@ -42,12 +44,12 @@ import DeviceNetworkPanel from './DeviceNetworkPanel.vue'
|
||||
<section id="page-objects" class="page" hidden><div class="section-head"><h2>一物一档 <small>设备 · 归属</small></h2><div class="device-actions"><button class="quiet" data-page="sites" data-admin>管理区域</button><button data-action="new-asset">+ 摄像机</button><button data-action="new-recorder">+ 录像机</button><button id="new-device" data-admin>+ 其他设备</button></div></div><p class="description">同一设备可同时记录类型、区域、所有人、负责人和标签。分组顺序可自由组合,例如“灯 → 卧室”或“负责人 → 类型 → 区域”。人员归属不自动授予访问权限。</p><div class="panel device-view-controls"><div class="device-search-row"><label>设备类型<select id="device-type"><option value="">所有类型</option></select></label><label>搜索设备或人员<input id="device-search" type="search" placeholder="例如:卧室 灯;也可查 IP、品牌、型号、人员"></label><button id="device-clear" type="button" class="quiet" hidden>清除设备筛选</button></div><div class="device-actions view-presets" role="group" aria-label="设备分组方式"><button type="button" class="quiet" data-group-preset="space,type">按区域查看</button><button type="button" class="quiet" data-group-preset="type,space">按类型查看</button><button type="button" class="quiet" data-group-preset="manager,type,space">按负责人查看</button></div><details class="group-custom"><summary>自定义分组顺序</summary><p class="description">依次分组(前面的维度优先,区域按你定义的完整层级展示)</p><div id="device-group-order" class="device-group-order"></div><div class="device-actions"><button id="device-group-add" class="quiet">+ 增加分组维度</button><button data-admin id="device-view-save" class="secondary">保存为本归属的默认视图</button></div></details><p id="device-count" class="description"></p></div><div class="device-actions" role="group" aria-label="设备展示方式"><button id="devices-card-view" class="quiet" aria-pressed="true">设备卡片</button><button id="devices-topology-view" class="quiet" aria-pressed="false">网络拓扑</button></div><DeviceCollection /><NetworkMap /></section>
|
||||
<section id="page-recorders" class="page" hidden><div class="section-head"><h2>录像机 <small>存影</small></h2><button data-action="new-recorder">+ 添加录像机</button></div><p class="description">统一保存录像机地址与账号,镜头通道关联录像机。实时取流使用 RTSP;读取录像机已有历史录像,需要该型号的回放接口适配。</p><div id="recorder-list" class="site-grid"></div></section>
|
||||
<section id="page-sites" class="page" hidden><div class="section-head"><h2>区域与空间 <small>自定层级</small></h2><button data-action="new-site">+ 新建空间</button></div><p class="description">在当前家庭或场所下自行划分区域,不限定层级数量。例如“一楼 → 卧室”或“厂区 → 车间 → 产线”。名称和区域类别均由你定义,地址信息按需填写。</p><div id="site-list" class="site-grid"></div></section>
|
||||
<section id="page-storage" class="page" hidden><div class="section-head"><h2>录像与存储 <small>留存</small></h2></div><div class="storage-grid"><form id="storage-form" class="panel"><h3>录像保留策略</h3><label>保留天数<input name="retentionDays" type="number" min="1" max="365" required></label><label>录像容量上限(GB)<input name="maxGB" type="number" min="5" max="100000" required></label><label>磁盘预留空间(GB)<input name="reserveGB" type="number" min="2" max="1000" required></label><p class="description">超过保留天数的录像会自动删除。达到容量上限或预留空间不足时暂停录像;调整策略后自动恢复。容量每 20 秒检查一次,可能有少量超出。</p><button type="submit">保存策略</button><span class="form-error"></span></form><div class="panel"><h3>运行状态</h3><dl id="storage-status"></dl><p class="description">开启摄像头的“持续录像”后,服务会保存主码流。预览默认使用主码流高清画面(最高 1920×1080、15 帧/秒),也可切换子码流流畅画面(最高 768×432、10 帧/秒)。本机录像保留设备原始编码。</p><h3>最近操作</h3><div id="audit-list"></div></div></div></section>
|
||||
<section id="page-storage" class="page" hidden><div class="section-head"><h2>录像与存储 <small>留存</small></h2></div><div class="storage-grid"><form id="storage-form" class="panel"><h3>录像保留策略</h3><label>保留天数<input name="retentionDays" type="number" min="1" max="365" required></label><label>录像容量上限(GB)<input name="maxGB" type="number" min="5" max="100000" required></label><label>磁盘预留空间(GB)<input name="reserveGB" type="number" min="2" max="1000" required></label><p class="description">默认最长保留 30 天,超过设定天数的录像会自动删除。容量上限由全部摄像头共用;达到上限或预留空间不足时暂停录像,空间恢复后继续。实际可留时长取决于码率和路数,未必存满设定天数。容量每 20 秒检查一次,可能有少量超出。</p><button type="submit">保存策略</button><span class="form-error"></span></form><div class="panel"><h3>运行状态</h3><dl id="storage-status"></dl><p class="description">开启摄像头的“持续录像”后,服务会保存主码流。预览默认使用主码流高清画面(最高 1920×1080、15 帧/秒),也可切换子码流流畅画面(最高 768×432、10 帧/秒)。本机录像保留设备原始编码。</p><h3>最近操作</h3><div id="audit-list"></div></div></div></section>
|
||||
<section id="page-heritage-records" class="page" hidden><div class="section-head"><h2 id="heritage-records-title">文化与家风</h2><div><button class="quiet" data-page="heritage">返回家庭传承</button><button id="heritage-new">+ 新建档案</button></div></div><div class="panel heritage-controls"><label>查找档案<input id="heritage-search" type="search" placeholder="名称、内容、相关人员"></label><label class="check"><input id="heritage-archived" type="checkbox">包含归档资料</label><button id="heritage-reload" class="quiet">重新载入</button></div><p id="heritage-error" class="form-error" role="status"></p><div id="heritage-list" class="site-grid"></div><aside id="heritage-detail" class="panel" hidden></aside></section>
|
||||
<section id="page-family" class="page" hidden>
|
||||
<div class="section-head"><h2>家族的来处与延续 <small>世系 · 传承</small></h2><div><button id="family-reload" class="quiet">重新载入</button><button id="family-export" class="quiet">导出家谱</button><button id="new-person">+ 录入人物</button></div></div>
|
||||
<p class="description">从祖辈到后辈,一张图看全家。点击人物查看档案,暖金色卡片是当前账号关联的本人。</p>
|
||||
<div class="panel family-toolbar"><label>关系参照人物<select id="family-reference"></select></label><label>查找人物<input id="family-search" type="search" placeholder="姓名、别名或籍贯"></label><button id="family-find" class="quiet" hidden>定位搜索结果</button><label class="check"><input id="family-archived" type="checkbox">显示归档人物</label><span id="family-count"></span></div>
|
||||
<p id="family-edit-note" class="alert alert-info" role="status"></p><div class="panel family-toolbar"><label>关系参照人物<select id="family-reference"></select></label><label>查找人物<input id="family-search" type="search" placeholder="姓名、别名或籍贯"></label><button id="family-find" class="quiet" hidden>定位搜索结果</button><label class="check"><input id="family-archived" type="checkbox">显示归档人物</label><span id="family-count"></span></div>
|
||||
<div id="family-error" class="form-error" role="status"></div>
|
||||
<div id="family-workspace" class="family-workspace">
|
||||
<section id="family-canvas-panel" class="family-canvas-panel" aria-label="全家关系图">
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
// Bundled locally by Vite. No remote scripts, fonts, maps or CDN fallback.
|
||||
import { init, use } from 'echarts/core';
|
||||
import { PieChart, BarChart, GraphChart } from 'echarts/charts';
|
||||
import { TooltipComponent, GridComponent, AriaComponent } from 'echarts/components';
|
||||
import { CanvasRenderer } from 'echarts/renderers';
|
||||
use([PieChart, BarChart, GraphChart, TooltipComponent, GridComponent, AriaComponent, CanvasRenderer]);
|
||||
export { init };
|
||||
@@ -0,0 +1,32 @@
|
||||
// These builders accept only the current server-authorized snapshot.
|
||||
export const palette = ['#268575', '#648bcc', '#c49b5b', '#8e82b5', '#899aa5'];
|
||||
const count = value => Math.max(0, Math.floor(Number(value) || 0));
|
||||
export function distribution(items = []) {
|
||||
return { series: [{ type: 'pie', radius: ['62%', '84%'], center: ['50%', '50%'], avoidLabelOverlap: true, label: { show: false }, emphasis: { scale: false }, data: items.map((item, i) => ({ name: item.label, value: count(item.count), itemStyle: { color: item.color || palette[i % palette.length], borderRadius: 4 } })) }] };
|
||||
}
|
||||
export function bars(items = []) {
|
||||
return { grid: { left: 12, right: 35, top: 10, bottom: 12, containLabel: true }, xAxis: { type: 'value', minInterval: 1, axisTick: { show: false } }, yAxis: { type: 'category', inverse: true, axisTick: { show: false }, axisLine: { show: false }, axisLabel: { width: 90, overflow: 'truncate' }, data: items.map(x => x.label) }, series: [{ type: 'bar', barMaxWidth: 20, label: { show: true, position: 'right' }, data: items.map((x, i) => ({ value: count(x.count), itemStyle: { color: x.color || palette[i % palette.length], borderRadius: [0, 5, 5, 0] } })) }] };
|
||||
}
|
||||
export function summarizeDevices(state = {}) {
|
||||
const all = [...(state.assets || []).map(x => ({ ...x, deviceType: '摄像机' })), ...(state.recorders || []).map(x => ({ ...x, deviceType: '录像机' })), ...(state.devices || [])];
|
||||
const byType = new Map(), byNetwork = new Map();
|
||||
const names = { lan: '局域网', tailscale: 'Tailscale', public: '公网', unknown: '待登记' };
|
||||
for (const device of all) {
|
||||
const type = device.deviceType || '其他', network = names[device.networkAccess] || names.unknown;
|
||||
byType.set(type, (byType.get(type) || 0) + 1); byNetwork.set(network, (byNetwork.get(network) || 0) + 1);
|
||||
}
|
||||
const list = map => [...map].map(([label, count]) => ({ label, count })).sort((a,b) => b.count-a.count || a.label.localeCompare(b.label));
|
||||
return { total: all.length, types: list(byType), networks: list(byNetwork) };
|
||||
}
|
||||
export function graphOption(nodes, edges) {
|
||||
return { tooltip: { formatter: item => item.dataType === 'edge' ? '已登记的上级连接' : item.data.detail || item.name }, series: [{ type: 'graph', layout: 'none', roam: true, draggable: false, scaleLimit: { min: .2, max: 4 }, symbol: 'roundRect', symbolSize: [145, 60], edgeSymbol: ['none', 'arrow'], edgeSymbolSize: 6, label: { show: true, fontSize: 11, width: 128, overflow: 'truncate', formatter: item => item.data.caption || item.name }, lineStyle: { color: '#8aa99f', width: 2, curveness: .08 }, emphasis: { focus: 'adjacency', lineStyle: { width: 3 } }, data: nodes, links: edges }] };
|
||||
}
|
||||
export function networkChart(rows = [], location = () => '') {
|
||||
const ids = new Map(rows.map(r => [r.device.id, r]));
|
||||
const nodes = rows.map((r, i) => ({ id: r.device.id, targetId: r.device.id, name: r.device.name, caption: r.device.name + '\n' + ((r.device.networkHosts || [])[0] || 'IP 待填写'), detail: [r.device.name, r.device.deviceType, location(r.device.siteId) || '位置待登记', (r.device.networkHosts || []).join(' / ') || 'IP 待填写', { lan: '局域网', tailscale: 'Tailscale', public: '公网' }[r.device.networkAccess] || '接入待确认'].join('\n'), x: Math.max(0, r.depth || 0) * 280, y: i * 105, itemStyle: { color: r.device.source === 'camera' ? '#e1ebfb' : '#dceddf', borderColor: r.device.source === 'camera' ? '#648bcc' : '#468b73', borderWidth: 1 }, label: { color: '#213f48' } }));
|
||||
const edges = rows.flatMap(r => { const parent = ids.get(r.device.uplinkId); return parent && parent.depth + 1 === r.depth ? [{ source: parent.device.id, target: r.device.id }] : []; });
|
||||
return graphOption(nodes, edges);
|
||||
}
|
||||
export function platformChart(homes = [], name = '赵府') {
|
||||
return graphOption([{ id: 'platform', name, x: 0, y: 0, symbolSize: [160, 65], itemStyle: { color: '#286d5d' }, label: { color: '#fff' } }, ...homes.map((h, i) => ({ id: 'home:' + h.id, targetId: h.id, name: h.name, caption: h.name + '\n' + count(h.deviceCount) + ' 台设备', detail: [h.name, {home:'家庭',office:'办公',factory:'工厂'}[h.kind || 'home'] || '场所', [h.province,h.city,h.district].filter(Boolean).join(' · '), count(h.deviceCount) + ' 台已授权设备'].filter(Boolean).join('\n'), x: 300, y: (i - (homes.length-1)/2) * 120, itemStyle: { color: '#e3efe8', borderColor: '#8ebaa6', borderWidth: 1 }, label: { color: '#213f48' } }))], homes.map(h => ({ source: 'platform', target: 'home:' + h.id })));
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Display-only summaries of the records already authorized by the server.
|
||||
export function summarizeHomes(homes = []) {
|
||||
const kinds = [
|
||||
{ key: 'home', label: '家庭', color: '#258b76', count: 0 },
|
||||
{ key: 'office', label: '办公', color: '#5c83cb', count: 0 },
|
||||
{ key: 'factory', label: '工厂', color: '#c69a52', count: 0 },
|
||||
{ key: 'other', label: '其他', color: '#8997a9', count: 0 },
|
||||
];
|
||||
let devices = 0, areas = 0;
|
||||
for (const home of homes) {
|
||||
(kinds.find(k => k.key === (home.kind || 'home')) || kinds[3]).count++;
|
||||
devices += Math.max(0, Number(home.deviceCount) || 0);
|
||||
areas += Math.max(0, Number(home.sites) || 0);
|
||||
}
|
||||
let offset = 0;
|
||||
return { total: homes.length, devices, areas, kinds: kinds.filter(k => k.count).map(k => {
|
||||
const value = { ...k, share: k.count / homes.length * 100, offset };
|
||||
offset += value.share;
|
||||
return value;
|
||||
}) };
|
||||
}
|
||||
|
||||
export function layoutNetwork(rows = []) {
|
||||
const nodes = rows.map((row, index) => ({
|
||||
...row, x: 28 + Math.max(0, row.depth) * 300, y: 26 + index * 112,
|
||||
}));
|
||||
const byId = new Map(nodes.map(n => [n.device.id, n]));
|
||||
const edges = nodes.flatMap(node => {
|
||||
const parent = byId.get(node.device.uplinkId);
|
||||
// Only draw an edge when the validated hierarchy confirms the parent.
|
||||
if (!parent || parent.depth + 1 !== node.depth) return [];
|
||||
const x = parent.x + 244, y = parent.y + 40, endY = node.y + 40;
|
||||
return [{ id: node.device.id, path: `M${x},${y} H${x + 24} V${endY} H${node.x}` }];
|
||||
});
|
||||
return { nodes, edges, width: Math.max(640, ...nodes.map(n => n.x + 272)), height: Math.max(172, nodes.length * 112 + 26) };
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/* Shared local Bootstrap presentation for desktop and phones. */
|
||||
:root { --ui-shadow: 0 4px 22px #223d500a; --bs-body-font-family: system-ui,"Microsoft YaHei",sans-serif; }
|
||||
html[data-theme="paper"] { --ui-bg: #f5f5f1; --ui-soft: #f4f6f2; }
|
||||
.dashboard-grid { margin-top: 4px; }
|
||||
.dashboard-grid > div, .row > div { min-width: 0; }
|
||||
.dashboard-welcome { position: relative; overflow: hidden; padding: 28px; border-radius: 16px; background: linear-gradient(140deg,#234a49,#2e7964); color:#fff; }
|
||||
.dashboard-welcome::after { content:''; position:absolute; right:-85px; top:-95px; width:260px; height:260px; border:40px solid #ffffff07; border-radius:50%; pointer-events:none; }
|
||||
.dashboard-welcome h2 { font-size:clamp(21px,2vw,26px)!important; color:#fff!important; margin:16px 0 8px; letter-spacing:.2px; }
|
||||
.dashboard-welcome > p { color:#d3e7df; font-size:12px; }
|
||||
.dashboard-totals { display:flex; gap:28px; margin:22px 0; }
|
||||
.dashboard-totals > div { display:flex; flex-direction:column; }
|
||||
.dashboard-totals strong { color:#fff; font-size:32px; font-weight:600; line-height:1.3; font-variant-numeric:tabular-nums; }
|
||||
.dashboard-totals span { color:#d3e7df; font-size:11px; margin-top:5px; }
|
||||
.chart-card { padding:22px; border:1px solid var(--ui-line); border-radius:16px; background:var(--ui-surface); box-shadow:var(--ui-shadow); min-width:0; }
|
||||
.chart-heading { display:flex; gap:12px; align-items:center; justify-content:space-between; flex-wrap:wrap; margin-bottom:10px; }
|
||||
.chart-heading h3 { font-size:15px!important; font-weight:650; margin:0; }
|
||||
.chart-heading .small { font-size:11px; }
|
||||
.chart-legend { display:flex; gap:10px 18px; flex-wrap:wrap; justify-content:center; padding-top:8px; }
|
||||
.chart-legend span { display:flex; align-items:center; gap:6px; font-size:12px; color:var(--ui-muted); }
|
||||
.chart-legend i { width:8px; height:8px; border-radius:3px; }
|
||||
.chart-legend b { color:var(--ink); font-variant-numeric:tabular-nums; }
|
||||
.chart-data { color:var(--ui-muted); font-size:11px; margin-top:8px; }
|
||||
.chart-data summary { cursor:pointer; padding:6px 0; }
|
||||
.chart-data ul { padding-left:20px; margin:8px 0 0; }
|
||||
.chart-empty { min-height:150px; display:grid; place-items:center; color:var(--ui-muted); margin:0; font-size:13px; }
|
||||
.local-chart-wrap,.local-chart { width:100%; min-width:0; }
|
||||
.chart-network-surface { background:var(--ui-soft); border-radius:12px; background-image:radial-gradient(var(--ui-line) 1px,transparent 1px); background-size:20px 20px; overflow:hidden; }
|
||||
.chart-network-surface .local-chart { touch-action:none; }
|
||||
.household-context { border-left:3px solid #488b76!important; }
|
||||
.section-head > div > .description { margin-top:7px; }
|
||||
.home-toolbar,.device-view-controls,.playback-controls { box-shadow:var(--ui-shadow); }
|
||||
.home-card .card-body { padding:22px; }
|
||||
.home-cover { height:200px; }
|
||||
.form-grid label { align-items:stretch; }
|
||||
dialog .dialog-heading { position:sticky; top:0; background:var(--ui-surface); z-index:2; padding-block:12px; }
|
||||
dialog .dialog-footer { padding-top:18px; border-top:1px solid var(--ui-line); }
|
||||
html[data-theme="ink"] .chart-card { color:var(--ink); }
|
||||
html[data-theme="ink"] .chart-heading .badge { background:#2c493e!important; color:#c2e9d7!important; }
|
||||
@media(max-width:767px) {
|
||||
.dashboard-grid:not(.charts-expanded) .dashboard-chart-column { display:none; }
|
||||
.dashboard-welcome { padding:22px; }
|
||||
.dashboard-welcome h2 { font-size:22px!important; }
|
||||
.dashboard-totals { justify-content:space-between; gap:14px; margin:18px 0 14px; }
|
||||
.dashboard-welcome .insight-scope { display:flex; font-size:10px; }
|
||||
.chart-card { padding:18px; }
|
||||
.dashboard-grid .chart-card { height:auto!important; }
|
||||
.chart-network-surface .local-chart { max-height:340px; }
|
||||
.diagram-toolbar { flex-wrap:wrap; }
|
||||
.diagram-toolbar .btn { min-height:40px; }
|
||||
.household-context { padding:14px!important; }
|
||||
.section-head { gap:12px; flex-wrap:wrap; }
|
||||
.dialog-footer button { flex:1; }
|
||||
.table-wrap { overscroll-behavior-x:contain; }
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import '../../web/family-map.css'
|
||||
import '../../web/chinese-theme.css'
|
||||
import 'bootstrap/dist/css/bootstrap.min.css'
|
||||
import './theme.css'
|
||||
import './bootstrap-polish.css'
|
||||
import './dashboard.css'
|
||||
import App from './App.vue'
|
||||
import './composables/bridge.js'
|
||||
createApp(App).mount('#app')
|
||||
|
||||
+84
-4
@@ -3,6 +3,7 @@ import geography
|
||||
import datetime as dt
|
||||
import json
|
||||
import secrets
|
||||
import family_permissions as permissions
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
|
||||
@@ -34,14 +35,59 @@ class Family:
|
||||
with self.a.LOCK:
|
||||
can_edit = self.a.HOUSEHOLDS.manager(user) or user.get('familyAccess') == 'edit'
|
||||
people = self.a.HOUSEHOLDS.objects(user, 'people')
|
||||
links = self.a.HOUSEHOLDS.objects(user, 'family_links')
|
||||
scope = self.edit_scope(user, people, links)
|
||||
return {'revision': self.a.setting(self.a.HOUSEHOLDS.revision_key(user), 0), 'people': people,
|
||||
'links': self.a.HOUSEHOLDS.objects(user, 'family_links'),
|
||||
'links': links,
|
||||
'events': [e for e in self.a.HOUSEHOLDS.objects(user, 'family_events')
|
||||
if can_edit or (e.get('status') == 'published' and not e.get('archived'))],
|
||||
'canEdit': can_edit,
|
||||
'selfId': user.get('personId', '') if any(p['id'] == user.get('personId') for p in people) else '',
|
||||
'canEdit': can_edit and bool(scope['levels']) and not scope['conflict'],
|
||||
'editScope': scope,
|
||||
'selfId': scope['selfId'],
|
||||
'familyId': self.a.HOUSEHOLDS.scope(user)}
|
||||
|
||||
def edit_scope(self, user, people=None, links=None):
|
||||
a = self.a
|
||||
people = a.HOUSEHOLDS.objects(user, 'people') if people is None else people
|
||||
links = a.HOUSEHOLDS.objects(user, 'family_links') if links is None else links
|
||||
# Always use the account's binding, never a selected graph reference or submitted ID.
|
||||
account = a.get_object('users', user.get('id')) if user.get('id') else None
|
||||
self_id = (account or user).get('personId', '')
|
||||
levels, conflict = permissions.generations(people, links, self_id)
|
||||
granted = a.HOUSEHOLDS.manager(user) or user.get('familyAccess') == 'edit'
|
||||
editable = [key for key in levels if permissions.within(levels, key)] if granted and not conflict else []
|
||||
note = ('族谱维护限本人上下各五代,所有角色(含超级管理员)相同;远代仍可按权限查看。'
|
||||
if levels else '尚未关联本家庭族谱中的本人,暂不能维护。请在成员与权限中关联本人。')
|
||||
if conflict:
|
||||
note = '亲属关系存在代际冲突,无法可靠确定五代范围,已暂时锁定维护。'
|
||||
can_start = bool(granted and account and not account.get('personId')
|
||||
and a.HOUSEHOLDS.family_of(account) == a.HOUSEHOLDS.scope(user))
|
||||
return dict(limit=permissions.LIMIT, selfId=self_id if levels else '', levels=levels,
|
||||
conflict=conflict, editablePersonIds=editable, canCreateSelf=can_start, note=note)
|
||||
|
||||
def check_write(self, user, kind, item, old=None, proposed_people=None, proposed_links=None):
|
||||
scope = self.edit_scope(user)
|
||||
if not scope['levels'] or scope['conflict']:
|
||||
raise self.a.Problem(scope['note'], 403)
|
||||
levels = scope['levels']
|
||||
if old and any(not permissions.within(levels, key) for key in permissions.targets(kind, old)):
|
||||
raise self.a.Problem('该资料超出本人上下五代维护范围,所有角色均只能查看', 403)
|
||||
if (kind == 'person' and old is not None) or kind == 'event':
|
||||
if any(not permissions.within(levels, key) for key in permissions.targets(kind, item)):
|
||||
raise self.a.Problem('只能维护本人上下五代内且已连接的亲属资料', 403)
|
||||
if proposed_links is not None:
|
||||
next_levels, conflict = permissions.generations(proposed_people, proposed_links, scope['selfId'])
|
||||
if conflict:
|
||||
raise self.a.Problem('这条关系会产生代际冲突,不能据此确定维护范围', 409)
|
||||
# Prevent moving/disconnecting an existing branch and reattaching it closer
|
||||
# to oneself to circumvent the five-generation rule.
|
||||
if any(next_levels.get(key) != value for key, value in levels.items()):
|
||||
raise self.a.Problem('不能改变已确认人物的代际位置或断开其世系;请先补充同代的正确关系', 403)
|
||||
if any(not permissions.within(next_levels, key) for key in permissions.targets(kind, item)):
|
||||
raise self.a.Problem('新增关系或人物超出本人上下五代维护范围', 403)
|
||||
if kind == 'link' and not any(permissions.within(levels, key) for key in permissions.targets(kind, item)):
|
||||
raise self.a.Problem('请从本人上下五代内的已知亲属连接关系', 403)
|
||||
|
||||
def save(self, kind, data, user, restored_from=None):
|
||||
self.authorize(user, True)
|
||||
a = self.a
|
||||
@@ -63,6 +109,32 @@ class Family:
|
||||
raise a.Problem('家谱记录不存在', 404)
|
||||
item = {'person': self.person, 'link': self.link, 'event': self.event}[kind](data, old)
|
||||
item.update(familyId=family_id, updatedAt=dt.datetime.now(dt.timezone.utc).isoformat(), updatedBy=user['username'])
|
||||
added_link = None
|
||||
bind_self = data.get('asSelf', False)
|
||||
if not isinstance(bind_self, bool):
|
||||
raise a.Problem('本人关联设置不正确')
|
||||
if bind_self and (kind != 'person' or old or not self.edit_scope(user)['canCreateSelf']):
|
||||
raise a.Problem('已有本人关联,不能用另一个人物切换维护范围', 403)
|
||||
people = a.HOUSEHOLDS.objects(user, 'people')
|
||||
links = a.HOUSEHOLDS.objects(user, 'family_links')
|
||||
if kind == 'person' and not old and not bind_self:
|
||||
relative = data.get('relativeId')
|
||||
a.HOUSEHOLDS.owns(user, a.get_object('people', relative))
|
||||
relation = data.get('relativeKind')
|
||||
if relation not in ('parent', 'child', 'spouse'):
|
||||
raise a.Problem('新增人物时请选择与已有亲属的关系')
|
||||
if relative not in self.edit_scope(user)['editablePersonIds']:
|
||||
raise a.Problem('请选择本人上下五代内可维护的亲属', 403)
|
||||
added_link = dict(id=secrets.token_hex(8), fromId=item['id'] if relation == 'parent' else relative,
|
||||
toId=relative if relation == 'parent' else item['id'],
|
||||
kind='spouse' if relation == 'spouse' else 'parent', active=True,
|
||||
lineage='unspecified', note='', familyId=family_id,
|
||||
updatedAt=item['updatedAt'], updatedBy=user['username'])
|
||||
self.check_write(user, kind, item, proposed_people=people+[item], proposed_links=links+[added_link])
|
||||
elif kind == 'link':
|
||||
self.check_write(user, kind, item, old, people, [e for e in links if e['id'] != item['id']]+[item])
|
||||
elif not bind_self:
|
||||
self.check_write(user, kind, item, old)
|
||||
if kind == 'event':
|
||||
item.update(createdAt=old.get('createdAt', item['updatedAt']) if old else item['updatedAt'],
|
||||
createdBy=old.get('createdBy', user['username']) if old else user['username'])
|
||||
@@ -79,8 +151,16 @@ class Family:
|
||||
a.DB.execute('INSERT INTO family_changes VALUES (?,?,?,?,?,?,?,?)',
|
||||
(change_revision, kind, item['id'], json.dumps(old) if old else None,
|
||||
json.dumps(item), user['username'], item['updatedAt'], restored_from))
|
||||
if added_link:
|
||||
a.DB.execute('INSERT INTO family_links VALUES (?,?)', (added_link['id'], json.dumps(added_link)))
|
||||
a.DB.execute('INSERT INTO family_changes VALUES (?,?,?,?,?,?,?,?)',
|
||||
(change_revision+1, 'link', added_link['id'], None, json.dumps(added_link),
|
||||
user['username'], item['updatedAt'], None))
|
||||
if bind_self:
|
||||
account = dict(a.get_object('users', user['id']), personId=item['id'])
|
||||
a.DB.execute('UPDATE users SET body=? WHERE id=?', (json.dumps(account), user['id']))
|
||||
a.audit({'person': '更新家谱人物', 'link': '更新家谱关系', 'event': '更新家族记事'}[kind], user['username'])
|
||||
return {'item': item, 'revision': revision + 1}
|
||||
return {'item': item, 'revision': revision + 1, 'changeRevision': change_revision}
|
||||
|
||||
def history(self, user, kind, target_id, before=None):
|
||||
# Previous drafts and withdrawn text are visible only to family editors.
|
||||
|
||||
+4
-2
@@ -102,7 +102,9 @@ class Accounts:
|
||||
if actor and actor['id'] == uid and (disabled or role != actor['role']):
|
||||
raise a.Problem('不能停用或降低当前登录账号的管理权限')
|
||||
related = a.clean_text(data.get('relatedToId', ''), 32)
|
||||
person = a.clean_text(data.get('personId', ''), 32)
|
||||
person = a.clean_text(data.get('personId', (old or {}).get('personId', '')), 32)
|
||||
if old and old.get('personId') and person != old['personId']:
|
||||
raise a.Problem('本人关联已固定,不能通过更换或解除关联绕过五代维护范围', 403)
|
||||
if related and related != uid and not a.get_object('users', related):
|
||||
raise a.Problem('关系参照账号不存在')
|
||||
if related and related != uid:
|
||||
@@ -192,7 +194,7 @@ class Accounts:
|
||||
state['sites'] = [s for s in state['sites'] if s['id'] in permitted]
|
||||
state['assets'] = [s for s in state['assets'] if s['siteId'] in permitted]
|
||||
state['devices'] = [s for s in state['devices'] if s['siteId'] in permitted]
|
||||
fields = ('id', 'name', 'siteId', 'assetId', 'point', 'enabled', 'ready', 'recordingActive', 'archiveSource')
|
||||
fields = ('id', 'name', 'siteId', 'assetId', 'point', 'enabled', 'ready', 'recordingActive', 'recordingState', 'archiveSource')
|
||||
state['cameras'] = [{k: c.get(k) for k in fields} for c in state['cameras'] if c['siteId'] in permitted]
|
||||
state['recorders'] = []
|
||||
state['scan'] = {}
|
||||
|
||||
+68
-7
@@ -1,17 +1,60 @@
|
||||
"""Bounded, ephemeral H.264 playback; original recordings remain untouched."""
|
||||
from contextlib import contextmanager
|
||||
import http.client
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
SLOTS = threading.BoundedSemaphore(2)
|
||||
MAX_SOURCE_BYTES = 256 * 1024 * 1024
|
||||
MAX_SESSION_SECONDS = 300
|
||||
|
||||
|
||||
class PlaybackError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@contextmanager
|
||||
def cached_source(source, authorization, reserve_bytes):
|
||||
# A private, bounded scratch file decouples MediaMTX's HTTP write timeout
|
||||
# from browser buffering and pause. Use the data disk, not a small /tmp RAM disk.
|
||||
base = Path(os.environ.get('VISION_DATA', tempfile.gettempdir())) / 'playback-tmp'
|
||||
base.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
for old in base.glob('buffer-*'):
|
||||
try:
|
||||
if old.is_symlink() or not old.is_dir() or time.time() - old.stat().st_mtime < 3600:
|
||||
continue
|
||||
(old / 'source.mp4').unlink(missing_ok=True)
|
||||
old.rmdir()
|
||||
except OSError:
|
||||
pass
|
||||
with tempfile.TemporaryDirectory(prefix='buffer-', dir=base) as folder:
|
||||
if shutil.disk_usage(folder).free < reserve_bytes + MAX_SOURCE_BYTES:
|
||||
raise PlaybackError('磁盘剩余空间不足以缓冲回放,请先释放空间')
|
||||
request = urllib.request.Request(source, headers={'Authorization': authorization})
|
||||
target = Path(folder) / 'source.mp4'
|
||||
deadline = time.monotonic() + 30
|
||||
size = 0
|
||||
with urllib.request.urlopen(request, timeout=10) as response, target.open('wb') as output:
|
||||
while chunk := response.read(256 * 1024):
|
||||
size += len(chunk)
|
||||
if size > MAX_SOURCE_BYTES:
|
||||
raise PlaybackError('该录像片段过大,请缩短回放时段')
|
||||
if time.monotonic() > deadline:
|
||||
raise PlaybackError('回放缓冲超时,请稍后重试')
|
||||
if shutil.disk_usage(folder).free < reserve_bytes + len(chunk):
|
||||
raise PlaybackError('磁盘预留空间不足,已停止缓冲回放')
|
||||
output.write(chunk)
|
||||
if not size:
|
||||
raise PlaybackError('该时段没有可读取的录像')
|
||||
yield str(target)
|
||||
|
||||
|
||||
def command(source, authorization, duration):
|
||||
executable = shutil.which('ffmpeg')
|
||||
if not executable:
|
||||
@@ -29,10 +72,14 @@ def command(source, authorization, duration):
|
||||
'-c:v', 'libx264', '-threads', '1', '-preset', 'veryfast',
|
||||
'-tune', 'zerolatency', '-profile:v', 'baseline', '-pix_fmt', 'yuv420p',
|
||||
'-crf', '26', '-g', '20', '-bf', '0']
|
||||
input_options = (['-rw_timeout', '15000000', '-headers', 'Authorization: ' + authorization + '\r\n']
|
||||
if authorization else [])
|
||||
return [executable, '-hide_banner', '-loglevel', 'error', '-nostdin',
|
||||
'-threads', '1', '-filter_threads', '1'] + acceleration + [
|
||||
'-rw_timeout', '15000000', '-headers', 'Authorization: ' + authorization + '\r\n',
|
||||
'-readrate', '1', '-i', source, '-t', str(duration),
|
||||
'-threads', '1', '-filter_threads', '1'] + acceleration + input_options + [
|
||||
'-analyzeduration', '1000000', '-probesize', '1000000',
|
||||
# Recordings are finite HTTP downloads. Pacing their input like a
|
||||
# live source stalls upstream writes and truncates long responses.
|
||||
'-i', source, '-t', str(duration),
|
||||
'-map', '0:v:0', '-map', '0:a:0?', '-sn', '-dn'] + video + [
|
||||
'-c:a', 'aac', '-ar', '48000', '-ac', '1', '-b:a', '64k',
|
||||
'-movflags', '+frag_keyframe+empty_moov+default_base_moof',
|
||||
@@ -40,20 +87,34 @@ def command(source, authorization, duration):
|
||||
|
||||
|
||||
@contextmanager
|
||||
def stream(source, authorization, duration):
|
||||
def stream(source, authorization, duration, reserve_bytes=8 * 1024**3):
|
||||
if not 0 < duration <= MAX_SESSION_SECONDS:
|
||||
raise PlaybackError('请刷新页面,使用每段最多 5 分钟的自动连续回放')
|
||||
if not SLOTS.acquire(blocking=False):
|
||||
raise PlaybackError('已有两个回放正在进行,请关闭其他回放后重试')
|
||||
process = timer = None
|
||||
try:
|
||||
# No shell and no diagnostics containing authentication headers in logs.
|
||||
process = subprocess.Popen(command(source, authorization, duration),
|
||||
if not shutil.which('ffmpeg'):
|
||||
raise PlaybackError('回放转换需要服务器安装 FFmpeg')
|
||||
with cached_source(source, authorization, reserve_bytes) as local_source:
|
||||
# Credentials never appear in the converter's process arguments.
|
||||
process = subprocess.Popen(command(local_source, '', duration),
|
||||
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL)
|
||||
timer = threading.Timer(duration + 45, process.kill)
|
||||
timer.daemon = True
|
||||
timer.start()
|
||||
try:
|
||||
yield process.stdout
|
||||
except OSError as exc:
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=3)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait()
|
||||
except (OSError, http.client.HTTPException) as exc:
|
||||
raise PlaybackError('录像转换服务暂不可用') from exc
|
||||
finally:
|
||||
if timer:
|
||||
|
||||
+100
-30
@@ -25,6 +25,9 @@ class WebTests(unittest.TestCase):
|
||||
def setUpClass(cls):
|
||||
app.initialize()
|
||||
cls.admin = app.ACCOUNTS.save({'username': 'admin', 'password': 'test-password', 'role': 'admin'}, None)
|
||||
person = dict(app.FAMILY.person({'name': 'Test account self'}, None), familyId=cls.admin['familyId'])
|
||||
app.save_object('people', person)
|
||||
cls.admin = app.ACCOUNTS.save(dict(cls.admin, personId=person['id']), cls.admin)
|
||||
cls.server = app.ThreadingHTTPServer(('127.0.0.1', 0), app.Handler)
|
||||
cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
@@ -192,12 +195,11 @@ class WebTests(unittest.TestCase):
|
||||
|
||||
def test_family_graph_validation_and_revision(self):
|
||||
def save(kind,data):
|
||||
return app.FAMILY.save(kind,dict(data,revision=app.setting('familyRevision',0)),self.admin)['item']
|
||||
return self.family_save(kind,data)['item']
|
||||
p=save('person',{'name':'祖辈','biography':'第一行\n第二行'})
|
||||
q=save('person',{'name':'子辈'})
|
||||
r=save('person',{'name':'孙辈'})
|
||||
first=save('link',{'fromId':p['id'],'toId':q['id'],'kind':'parent'})
|
||||
save('link',{'fromId':q['id'],'toId':r['id'],'kind':'parent'})
|
||||
q=save('person',{'name':'子辈','relativeId':p['id']})
|
||||
r=save('person',{'name':'孙辈','relativeId':q['id']})
|
||||
first=next(e for e in app.objects('family_links') if e['fromId']==p['id'] and e['toId']==q['id'])
|
||||
for value in [{'fromId':r['id'],'toId':p['id'],'kind':'parent'},
|
||||
{'fromId':p['id'],'toId':p['id'],'kind':'parent'},
|
||||
{'fromId':p['id'],'toId':r['id'],'kind':'spouse'},
|
||||
@@ -209,9 +211,8 @@ class WebTests(unittest.TestCase):
|
||||
save('person',{'name':'错误日期','birthDate':'2026-02-30'})
|
||||
with self.assertRaises(app.Problem):
|
||||
save('person',{'name':'错误日期','birthDate':'2020-01-01','deathDate':'1900-01-01','lifeStatus':'deceased'})
|
||||
save('link',dict(first,active=False))
|
||||
self.assertFalse(app.get_object('family_links',first['id'])['active'])
|
||||
save('link',dict(first,active=True))
|
||||
with self.assertRaises(app.Problem):save('link',dict(first,active=False))
|
||||
self.assertTrue(app.get_object('family_links',first['id'])['active'])
|
||||
save('person',dict(p,archived=True))
|
||||
self.assertTrue(app.get_object('people',p['id'])['archived'])
|
||||
save('person',dict(p,archived=False))
|
||||
@@ -257,6 +258,9 @@ class WebTests(unittest.TestCase):
|
||||
self.assertEqual(command[command.index('-rc_mode') + 1], 'CQP')
|
||||
self.assertIn('h264_vaapi', command)
|
||||
self.assertIn('pipe:1', command)
|
||||
self.assertEqual(command[command.index('-analyzeduration') + 1], '1000000')
|
||||
self.assertNotIn('-readrate', command)
|
||||
self.assertNotIn('-re', command)
|
||||
|
||||
def test_ptz_requires_both_space_and_control_permission(self):
|
||||
app.save_object('sites', dict(id='permitted', name='Permitted'))
|
||||
@@ -278,7 +282,7 @@ class WebTests(unittest.TestCase):
|
||||
def test_family_event_draft_publish_archive_and_restore(self):
|
||||
def save(data):
|
||||
return app.FAMILY.save('event',dict(data,revision=app.setting('familyRevision',0)),self.admin)['item']
|
||||
p=app.FAMILY.save('person',{'name':'Event person','revision':app.setting('familyRevision',0)},self.admin)['item']
|
||||
p=self.family_save('person',{'name':'Event person'})['item']
|
||||
reader={'role':'member','familyAccess':'read','personId':p['id']}
|
||||
e=save({'title':'First event','eventDate':'2024-02-10','summary':'Summary','body':'Line one\nLine two','personIds':[p['id'],p['id']]})
|
||||
self.assertEqual(e['status'],'draft');self.assertEqual(e['personIds'],[p['id']])
|
||||
@@ -334,16 +338,18 @@ class WebTests(unittest.TestCase):
|
||||
self.assertEqual(event['publishedAt'],published);self.assertEqual(event['createdAt'],created)
|
||||
|
||||
def test_biological_birth_order_checked_on_link_and_person_changes(self):
|
||||
def save(kind,data):return app.FAMILY.save(kind,dict(data,revision=app.setting('familyRevision',0)),self.admin)['item']
|
||||
def save(kind,data):return self.family_save(kind,data)['item']
|
||||
parent=save('person',{'name':'Parent','birthDate':'1980-01-01'})
|
||||
child=save('person',{'name':'Child','birthDate':'2000-01-01'})
|
||||
relation=save('link',{'fromId':parent['id'],'toId':child['id'],'kind':'parent','lineage':'biological'})
|
||||
child=save('person',{'name':'Child','birthDate':'2000-01-01','relativeId':parent['id']})
|
||||
edge=next(e for e in app.objects('family_links') if e['toId']==child['id'])
|
||||
relation=save('link',dict(edge,lineage='biological'))
|
||||
for person,date in [(parent,'2000-01-01'),(parent,'2001-01-01'),(child,'1979-01-01')]:
|
||||
revision=app.setting('familyRevision',0)
|
||||
with self.assertRaises(app.Problem):save('person',dict(person,birthDate=date))
|
||||
self.assertEqual(app.setting('familyRevision',0),revision)
|
||||
self.assertEqual(app.get_object('people',person['id'])['birthDate'],person['birthDate'])
|
||||
save('link',dict(relation,active=False))
|
||||
# Legacy inactive data can exist; seed it to exercise current birth validation.
|
||||
app.save_object('family_links',dict(relation,lineage='adoptive'))
|
||||
save('person',dict(parent,birthDate='2001-01-01'))
|
||||
with self.assertRaises(app.Problem):save('link',dict(relation,active=True))
|
||||
save('link',dict(relation,active=True,lineage='adoptive'))
|
||||
@@ -378,29 +384,89 @@ class WebTests(unittest.TestCase):
|
||||
app.media_json('/list?path=example', playback=True)
|
||||
self.assertTrue(error.fp.closed)
|
||||
|
||||
def test_first_recording_missing_directory_is_empty_only_for_requested_camera(self):
|
||||
name = 'cam_' + 'a' * 16 + '_main'
|
||||
path = '/list?path=' + name
|
||||
expected = 'lstat ' + str(app.RECORDINGS / name) + ': no such file or directory'
|
||||
for message, empty in [(expected, True), (expected.replace(name, 'other'), False),
|
||||
(expected.replace('no such file or directory', 'permission denied'), False),
|
||||
('invalid start timestamp', False)]:
|
||||
error = app.urllib.error.HTTPError('http://localhost/list', 400, 'Bad Request', {},
|
||||
io.BytesIO(json.dumps({'error': message}).encode()))
|
||||
with self.subTest(message=message), patch('app.urllib.request.urlopen', side_effect=error):
|
||||
if empty:
|
||||
self.assertEqual(app.media_json(path, playback=True), [])
|
||||
else:
|
||||
with self.assertRaises(app.Problem):
|
||||
app.media_json(path, playback=True)
|
||||
self.assertTrue(error.fp.closed)
|
||||
|
||||
def test_playback_disables_reverse_proxy_buffering(self):
|
||||
with patch.object(playback, 'stream', return_value=io.BytesIO(b'test-mp4')):
|
||||
code, headers, body = self.request('/media/playback?camera='+'a'*16+'&start=2026-01-01T00:00:00Z&duration=10')
|
||||
self.assertEqual(code, 200)
|
||||
self.assertEqual(headers['X-Accel-Buffering'], 'no')
|
||||
self.assertEqual(headers['Cache-Control'], 'no-store')
|
||||
self.assertEqual(body, b'test-mp4')
|
||||
|
||||
def test_default_retention_is_30_days_and_keeps_space_guards(self):
|
||||
self.assertEqual(app.DEFAULT_STORAGE, dict(retentionDays=30, maxGB=40, reserveGB=8))
|
||||
camera = dict(id='e'*16, enabled=True, record=True)
|
||||
def setting(key, default=None):
|
||||
return 'test-secret' if key == 'mediaSecret' else default
|
||||
with tempfile.TemporaryDirectory() as folder, patch.object(app, 'CONFIG', app.Path(folder)/'media.json'), \
|
||||
patch.object(app, 'objects', return_value=[camera]), patch.object(app, 'setting', side_effect=setting), \
|
||||
patch.object(app, 'source', return_value='rtsp://test/stream'), patch.dict(app.STORAGE, paused=False):
|
||||
app.write_media_config()
|
||||
config=json.loads(app.CONFIG.read_text())
|
||||
main=config['paths'][app.stream_name(camera)]
|
||||
self.assertEqual(main['recordDeleteAfter'], '720h')
|
||||
self.assertTrue(main['record'])
|
||||
self.assertFalse(config['paths'][app.stream_name(camera, 'sub')]['record'])
|
||||
app.STORAGE['paused']=True
|
||||
app.write_media_config()
|
||||
self.assertFalse(json.loads(app.CONFIG.read_text())['paths'][app.stream_name(camera)]['record'])
|
||||
|
||||
def test_recording_status_requires_recent_writes_and_distinguishes_protection(self):
|
||||
camera=dict(id='e'*16, enabled=True, record=True)
|
||||
with patch.dict(app.STORAGE, paused=False), patch.dict(app.RECENT_RECORDS, {}, clear=True):
|
||||
self.assertEqual(app.recording_state(camera, True, True), 'waiting')
|
||||
app.RECENT_RECORDS[app.stream_name(camera)]=time.time()
|
||||
self.assertEqual(app.recording_state(camera, True, True), 'recording')
|
||||
self.assertEqual(app.recording_state(dict(camera,record=False), True, True), 'off')
|
||||
self.assertEqual(app.recording_state(dict(camera,enabled=False), True, True), 'disabled')
|
||||
self.assertEqual(app.recording_state(camera, False, True), 'offline')
|
||||
self.assertEqual(app.recording_state(camera, True, False), 'unavailable')
|
||||
app.RECENT_RECORDS[app.stream_name(camera)]=time.time()-60
|
||||
self.assertEqual(app.recording_state(camera, True, True), 'waiting')
|
||||
app.STORAGE['paused']=True
|
||||
self.assertEqual(app.recording_state(camera, True, True), 'paused')
|
||||
|
||||
def family_save(self, kind, data):
|
||||
if kind == 'person' and not data.get('id'):
|
||||
data = dict({'relativeId':self.admin['personId'], 'relativeKind':'child'}, **data)
|
||||
return app.FAMILY.save(kind, dict(data, revision=app.setting('familyRevision', 0)), self.admin)
|
||||
|
||||
def test_history_records_before_after_and_restore_as_new_version(self):
|
||||
first = self.family_save('person', {'name': 'History original', 'biography': 'Original story'})
|
||||
second = self.family_save('person', dict(first['item'], name='History changed'))
|
||||
change = app.FAMILY.change(self.admin, second['revision'])
|
||||
change = app.FAMILY.change(self.admin, second['changeRevision'])
|
||||
self.assertEqual(change['before']['name'], 'History original')
|
||||
self.assertEqual(change['after']['name'], 'History changed')
|
||||
restored = app.FAMILY.restore({'changeRevision': second['revision'], 'side': 'before',
|
||||
restored = app.FAMILY.restore({'changeRevision': second['changeRevision'], 'side': 'before',
|
||||
'revision': app.setting('familyRevision')}, self.admin)
|
||||
self.assertEqual(restored['item']['name'], 'History original')
|
||||
self.assertGreater(restored['revision'], second['revision'])
|
||||
entries = app.FAMILY.history(self.admin, 'person', first['item']['id'])['items']
|
||||
self.assertEqual(len(entries), 3)
|
||||
self.assertEqual(entries[0]['restoredFrom'], second['revision'])
|
||||
self.assertEqual(app.FAMILY.change(self.admin, second['revision']), change)
|
||||
self.assertEqual(entries[0]['restoredFrom'], second['changeRevision'])
|
||||
self.assertEqual(app.FAMILY.change(self.admin, second['changeRevision']), change)
|
||||
|
||||
def test_history_rejects_stale_restore_without_writing(self):
|
||||
first = self.family_save('person', {'name': 'Stale restore'})
|
||||
second = self.family_save('person', dict(first['item'], name='Latest'))
|
||||
with self.assertRaises(app.Problem) as caught:
|
||||
app.FAMILY.restore(dict(changeRevision=first['revision'], side='after', revision=first['revision']), self.admin)
|
||||
app.FAMILY.restore(dict(changeRevision=first['changeRevision'], side='after', revision=first['revision']), self.admin)
|
||||
self.assertEqual(caught.exception.status, 409)
|
||||
self.assertEqual(app.get_object('people', first['item']['id'])['name'], 'Latest')
|
||||
self.assertEqual(app.setting('familyRevision'), second['revision'])
|
||||
@@ -408,32 +474,36 @@ class WebTests(unittest.TestCase):
|
||||
def test_restore_revalidates_current_birth_order(self):
|
||||
old = self.family_save('person', {'name': 'Restore parent', 'birthDate': '1980-01-01'})
|
||||
parent = self.family_save('person', dict(old['item'], birthDate='1960-01-01'))['item']
|
||||
child = self.family_save('person', {'name': 'Restore child', 'birthDate': '1970-01-01'})['item']
|
||||
self.family_save('link', dict(fromId=parent['id'], toId=child['id'], kind='parent', lineage='biological'))
|
||||
child = self.family_save('person', {'name': 'Restore child', 'birthDate': '1970-01-01', 'relativeId':parent['id']})['item']
|
||||
edge=next(e for e in app.objects('family_links') if e['toId']==child['id'])
|
||||
self.family_save('link', dict(edge, lineage='biological'))
|
||||
with self.assertRaises(app.Problem):
|
||||
app.FAMILY.restore(dict(changeRevision=old['revision'], side='after', revision=app.setting('familyRevision')), self.admin)
|
||||
app.FAMILY.restore(dict(changeRevision=old['changeRevision'], side='after', revision=app.setting('familyRevision')), self.admin)
|
||||
self.assertEqual(app.get_object('people', parent['id'])['birthDate'], '1960-01-01')
|
||||
|
||||
def test_restore_link_cannot_create_new_cycle(self):
|
||||
a = self.family_save('person', {'name': 'Cycle A'})['item']
|
||||
b = self.family_save('person', {'name': 'Cycle B'})['item']
|
||||
old = self.family_save('link', dict(fromId=a['id'], toId=b['id'], kind='parent'))
|
||||
self.family_save('link', dict(old['item'], active=False))
|
||||
self.family_save('link', dict(fromId=b['id'], toId=a['id'], kind='parent'))
|
||||
b = self.family_save('person', {'name': 'Cycle B','relativeId':a['id']})['item']
|
||||
edge=next(e for e in app.objects('family_links') if e['toId']==b['id'])
|
||||
old = self.family_save('link', dict(edge, note='History'))
|
||||
# Seed a changed legacy graph; the current API disallows this displacement.
|
||||
app.save_object('family_links',dict(old['item'],active=False))
|
||||
inverse=app.FAMILY.link(dict(fromId=b['id'],toId=a['id'],kind='parent'),None)
|
||||
app.save_object('family_links',dict(inverse,familyId=self.admin['familyId']))
|
||||
with self.assertRaises(app.Problem):
|
||||
app.FAMILY.restore(dict(changeRevision=old['revision'], side='after', revision=app.setting('familyRevision')), self.admin)
|
||||
app.FAMILY.restore(dict(changeRevision=old['changeRevision'], side='after', revision=app.setting('familyRevision')), self.admin)
|
||||
self.assertFalse(app.get_object('family_links', old['item']['id'])['active'])
|
||||
|
||||
def test_restore_event_preserves_first_publication_and_validates_scope(self):
|
||||
draft = self.family_save('event', dict(title='Restored story', eventDate='2020-01-01', body='Draft', status='draft'))
|
||||
published = self.family_save('event', dict(draft['item'], body='Published', status='published'))
|
||||
restored = app.FAMILY.restore(dict(changeRevision=draft['revision'], side='after', revision=app.setting('familyRevision')), self.admin)
|
||||
restored = app.FAMILY.restore(dict(changeRevision=draft['changeRevision'], side='after', revision=app.setting('familyRevision')), self.admin)
|
||||
self.assertEqual(restored['item']['status'], 'draft')
|
||||
self.assertEqual(restored['item']['publishedAt'], published['item']['publishedAt'])
|
||||
self.assertNotIn(draft['item']['id'], [e['id'] for e in app.FAMILY.snapshot(dict(role='member', familyAccess='read'))['events']])
|
||||
for side in ['before', 'invalid']:
|
||||
with self.assertRaises(app.Problem):
|
||||
app.FAMILY.restore(dict(changeRevision=draft['revision'], side=side, revision=app.setting('familyRevision')), self.admin)
|
||||
app.FAMILY.restore(dict(changeRevision=draft['changeRevision'], side=side, revision=app.setting('familyRevision')), self.admin)
|
||||
|
||||
def test_history_pagination_is_complete_and_omits_story_bodies(self):
|
||||
item = self.family_save('person', {'name': 'Pagination', 'biography': 'Private full story'})['item']
|
||||
@@ -454,7 +524,7 @@ class WebTests(unittest.TestCase):
|
||||
app.DB.execute('INSERT INTO sessions VALUES (?,?,?)', (hashlib.sha256(token.encode()).hexdigest(), time.time()+3600, reader['id']))
|
||||
app.DB.commit()
|
||||
path = '/api/family/history?kind=person&id=' + item['item']['id']
|
||||
for target in [path, '/api/family/change?revision=' + str(item['revision'])]:
|
||||
for target in [path, '/api/family/change?revision=' + str(item['changeRevision'])]:
|
||||
self.assertEqual(self.request(target, token=token)[0], 403)
|
||||
self.assertEqual(self.request(target, authenticated=False)[0], 401)
|
||||
self.assertEqual(self.request(target)[0], 200)
|
||||
@@ -480,7 +550,7 @@ class WebTests(unittest.TestCase):
|
||||
revision = app.setting('familyRevision', 0); barrier = threading.Barrier(2)
|
||||
def save(index):
|
||||
barrier.wait()
|
||||
try:app.FAMILY.save('person', dict(name='Concurrent '+str(index), revision=revision), self.admin);return 200
|
||||
try:app.FAMILY.save('person', dict(name='Concurrent '+str(index), revision=revision, relativeId=self.admin['personId'], relativeKind='child'), self.admin);return 200
|
||||
except app.Problem as e:return e.status
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:self.assertEqual(sorted(pool.map(save, range(2))), [200, 409])
|
||||
self.assertEqual(app.setting('familyRevision'), revision+1)
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs');
|
||||
const charts=()=>import('./frontend/src/composables/charts.mjs');
|
||||
test('dashboard counts physical devices once, not lenses; handles missing network metadata',async()=>{
|
||||
const {summarizeDevices}=await charts();
|
||||
assert.equal(summarizeDevices().total,0);
|
||||
const result=summarizeDevices({assets:[{id:'camera',networkAccess:'tailscale'}],cameras:[{assetId:'camera'},{assetId:'camera'}],recorders:[{networkAccess:'lan'}],devices:[{deviceType:'灯'}, {deviceType:'灯',networkAccess:'lan'}]});
|
||||
assert.equal(result.total,4); assert.equal(result.types.find(x=>x.label==='灯').count,2);
|
||||
assert.equal(result.networks.find(x=>x.label==='待登记').count,1);
|
||||
});
|
||||
test('chart aggregates remain numerical and empty charts are valid',async()=>{
|
||||
const {bars,distribution}=await charts();
|
||||
assert.deepEqual(bars().series[0].data,[]);
|
||||
assert.equal(distribution([{label:'a',count:-2}]).series[0].data[0].value,0);
|
||||
assert.equal(bars([{label:'a',count:'3'}]).series[0].data[0].value,3);
|
||||
});
|
||||
test('network chart cannot draw phantom parent or cyclic connections',async()=>{
|
||||
const {networkChart}=await charts();
|
||||
const option=networkChart([{device:{id:'r',name:'路由',source:'device'},depth:0},{device:{id:'c',name:'摄像头',uplinkId:'r',networkHosts:['192.168.8.160']},depth:1},{device:{id:'x',name:'独立',uplinkId:'missing'},depth:0}]);
|
||||
assert.deepEqual(option.series[0].links,[{source:'r',target:'c'}]);
|
||||
assert.equal(option.series[0].data.length,3);assert.equal(option.series[0].data[1].targetId,'c');
|
||||
assert.match(option.series[0].data[1].caption,/192\.168\.8\.160/);
|
||||
assert.equal(option.series[0].layout,'none');
|
||||
});
|
||||
test('platform graph only includes supplied authorized households and no device leakage',async()=>{
|
||||
const {platformChart}=await charts();
|
||||
const series=platformChart([{id:'one',name:'家庭A',deviceCount:2}],'本平台').series[0];
|
||||
assert.deepEqual(series.data.map(x=>x.id),['platform','home:one']);
|
||||
assert.equal(series.data[1].targetId,'one');assert.equal(series.links.length,1);
|
||||
});
|
||||
test('ECharts runtime is local, lazy, deterministic and releases resources',()=>{
|
||||
const runtime=fs.readFileSync('frontend/src/composables/charts-runtime.js','utf8'),widget=fs.readFileSync('frontend/src/components/LocalChart.vue','utf8');
|
||||
assert.match(runtime,/echarts\/core/);assert.doesNotMatch(runtime,/https?:\/\//);
|
||||
assert.match(widget,/import\('\.\.\/composables\/charts-runtime\.js'\)/);
|
||||
assert.match(widget,/animation: false/);assert.match(widget,/fingerprint !== last/);
|
||||
assert.match(widget,/renderMode: 'richText'/);assert.match(widget,/onBeforeUnmount/);
|
||||
assert.match(widget,/resizeObserver\?\.disconnect/);assert.match(widget,/chart\?\.dispose/);
|
||||
});
|
||||
test('deployed entry and controller dependencies have no remote CDN references',()=>{
|
||||
const html=fs.readFileSync('web/ui/index.html','utf8');
|
||||
for(const match of html.matchAll(/(?:src|href)="([^"]+)"/g))assert.ok(match[1].startsWith('/'),match[1]);
|
||||
const scripts=JSON.parse(fs.readFileSync('frontend/src/compat/scripts.json','utf8'));
|
||||
for(const script of scripts){assert.ok(script.startsWith('/')&&!script.startsWith('//'));assert.ok(fs.existsSync('web'+script));}
|
||||
for(const file of ['frontend/src/main.js','frontend/src/dashboard.css','frontend/src/theme.css','frontend/src/bootstrap-polish.css'])assert.doesNotMatch(fs.readFileSync(file,'utf8'),/(?:@import\s+|(?:src|href)\s*=\s*|url\(\s*['"]?)https?:\/\//);
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm');
|
||||
function fixture(){
|
||||
const space={style:{}},surface={style:{}},label={},frames=new Map();let next=0,observer;
|
||||
const viewport={clientWidth:1550,clientHeight:601,rect:{width:1550,height:600.5234375},scrollLeft:0,scrollTop:0,
|
||||
addEventListener(){},getBoundingClientRect(){return this.rect;},
|
||||
querySelector(s){return s==='.family-map-space'?space:surface;},replaceChildren(){},
|
||||
scrollTo(x,y){this.scrollLeft=x;this.scrollTop=y;}};
|
||||
const scope=vm.createContext({$:()=>label,ResizeObserver:class{constructor(fn){observer=fn;}observe(){}},
|
||||
requestAnimationFrame(fn){frames.set(++next,fn);return next;},cancelAnimationFrame(id){frames.delete(id);}});
|
||||
vm.runInContext(fs.readFileSync('web/family-map.js','utf8')+';this.MapClass=FamilyMap',scope);
|
||||
const map=new scope.MapClass(viewport,()=>{});map.graph={width:400,height:264,nodes:[]};
|
||||
return {map,viewport,space,surface,frames,resize:()=>observer(),flush(){const jobs=[...frames.values()];frames.clear();jobs.forEach(fn=>fn());}};
|
||||
}
|
||||
test('fractional fullscreen size never creates a too-tall scroll surface',()=>{
|
||||
const f=fixture();for(let i=0;i<20;i++){f.map.fit();assert.equal(f.space.style.height,'600px');assert.ok(parseFloat(f.space.style.height)<=f.viewport.rect.height);}
|
||||
assert.equal(f.surface.style.transform,'translate(575px,168px) scale(1)');
|
||||
});
|
||||
test('resize notifications coalesce and unchanged dimensions do not refit',()=>{
|
||||
const f=fixture();let calls=0;const fit=f.map.fit.bind(f.map);f.map.fit=()=>{calls++;fit();};
|
||||
f.resize();f.resize();assert.equal(f.frames.size,1);f.flush();assert.equal(calls,1);
|
||||
f.resize();f.flush();assert.equal(calls,1);
|
||||
f.viewport.rect.height=700.7;f.viewport.clientHeight=701;f.resize();f.flush();assert.equal(calls,2);
|
||||
});
|
||||
test('manual zoom and scroll survive a resize notification',()=>{
|
||||
const f=fixture();f.map.autoFit=false;f.map.scale=1.5;f.viewport.scrollLeft=15;f.viewport.scrollTop=30;
|
||||
f.resize();f.flush();assert.equal(f.map.scale,1.5);assert.equal(f.map.autoFit,false);
|
||||
assert.equal(f.viewport.scrollLeft,15);assert.equal(f.viewport.scrollTop,30);
|
||||
});
|
||||
test('hidden canvas does not resize and pending work is cancelled on reset',()=>{
|
||||
const f=fixture();f.viewport.clientWidth=0;f.resize();f.flush();assert.equal(f.space.style.width,undefined);
|
||||
f.resize();f.map.reset();assert.equal(f.frames.size,0);assert.equal(f.map.graph,null);
|
||||
});
|
||||
test('scaled map clips unscaled overflow and fullscreen fallback clears the sidebar',()=>{
|
||||
const css=fs.readFileSync('web/family-map.css','utf8');
|
||||
assert.match(css,/\.family-map-space\{min-width:0;min-height:0;overflow:clip\}/);
|
||||
assert.match(css,/scrollbar-gutter:stable/);assert.match(css,/\.family-workspace\.family-expanded\{z-index:1100\}/);
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Real storage and HTTP regressions for the universal five-generation boundary."""
|
||||
import hashlib
|
||||
import http.client
|
||||
import json
|
||||
import secrets
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
from test_app import app
|
||||
from family_permissions import generations
|
||||
|
||||
|
||||
class FamilyPermissionTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(); self.addCleanup(self.temp.cleanup)
|
||||
db = sqlite3.connect(':memory:', check_same_thread=False); db.row_factory = sqlite3.Row
|
||||
self.addCleanup(db.close)
|
||||
db.executescript('CREATE TABLE settings (key TEXT PRIMARY KEY,value TEXT NOT NULL);'
|
||||
'CREATE TABLE sessions (hash TEXT PRIMARY KEY,expires REAL NOT NULL);'
|
||||
'CREATE TABLE audit (id INTEGER PRIMARY KEY,at TEXT,action TEXT,name TEXT);')
|
||||
for table in ('sites', 'assets', 'recorders', 'cameras'):
|
||||
db.execute('CREATE TABLE '+table+' (id TEXT PRIMARY KEY,body TEXT NOT NULL)')
|
||||
for key, value in [('DB', db), ('DATA', Path(self.temp.name)), ('write_media_config', lambda: None)]:
|
||||
p = patch.object(app, key, value); p.start(); self.addCleanup(p.stop)
|
||||
app.initialize()
|
||||
self.actor = app.ACCOUNTS.save(dict(username='admin', password='fixture-only', role='admin'), None)
|
||||
self.home = self.actor['familyId']
|
||||
self.people = {}
|
||||
for generation in range(5, 40):
|
||||
person = dict(app.FAMILY.person(dict(name='第'+str(generation)+'代'), None), familyId=self.home)
|
||||
app.save_object('people', person); self.people[generation] = person
|
||||
for generation in range(5, 39):
|
||||
edge = dict(id=secrets.token_hex(8), fromId=self.people[generation]['id'],
|
||||
toId=self.people[generation+1]['id'], kind='parent', lineage='unspecified',
|
||||
active=True, note='', familyId=self.home)
|
||||
app.save_object('family_links', edge)
|
||||
self.actor = app.ACCOUNTS.save(dict(self.actor, personId=self.people[32]['id']), self.actor)
|
||||
|
||||
def save(self, kind, item, **extra):
|
||||
return app.FAMILY.save(kind, dict(item, revision=app.setting('familyRevision', 0), **extra), self.actor)
|
||||
|
||||
def test_all_roles_can_edit_fifth_but_not_sixth_or_ancient_generation(self):
|
||||
for role in ('admin', 'family_admin', 'member'):
|
||||
self.actor = dict(self.actor, role=role, familyAccess='edit')
|
||||
for generation in (27, 32, 37):
|
||||
self.save('person', dict(self.people[generation], note=role))
|
||||
for generation in (5, 26, 38):
|
||||
with self.subTest(role=role, generation=generation), self.assertRaises(app.Problem) as caught:
|
||||
self.save('person', dict(self.people[generation], note='denied'))
|
||||
self.assertEqual(caught.exception.status, 403)
|
||||
self.assertEqual(app.get_object('people', self.people[generation]['id'])['note'], '')
|
||||
|
||||
def test_view_contains_all_generations_and_reference_cannot_change_scope(self):
|
||||
view = app.FAMILY.snapshot(self.actor)
|
||||
self.assertEqual(len(view['people']), 35)
|
||||
self.assertEqual(view['editScope']['levels'][self.people[5]['id']], -27)
|
||||
self.assertNotIn(self.people[5]['id'], view['editScope']['editablePersonIds'])
|
||||
self.assertEqual(len(view['editScope']['editablePersonIds']), 11)
|
||||
with self.assertRaises(app.Problem):
|
||||
app.FAMILY.save('person', dict(self.people[5], note='forged', revision=0, selfId=self.people[5]['id']),
|
||||
dict(self.actor, personId=self.people[5]['id']))
|
||||
|
||||
def test_new_relative_is_atomic_and_sixth_leaves_no_orphan(self):
|
||||
before = len(app.objects('people'))
|
||||
for relative, kind in ((27, 'parent'), (37, 'child')):
|
||||
with self.assertRaises(app.Problem) as caught:
|
||||
self.save('person', dict(name='Outside'), relativeId=self.people[relative]['id'], relativeKind=kind)
|
||||
self.assertEqual(caught.exception.status, 403)
|
||||
self.assertEqual(len(app.objects('people')), before)
|
||||
result = self.save('person', dict(name='A sibling'), relativeId=self.people[31]['id'], relativeKind='child')
|
||||
self.assertEqual(app.FAMILY.snapshot(self.actor)['editScope']['levels'][result['item']['id']], 0)
|
||||
self.assertTrue(any(e['toId'] == result['item']['id'] for e in app.objects('family_links')))
|
||||
|
||||
def test_relationship_rewrite_and_disconnect_cannot_launder_scope(self):
|
||||
with self.assertRaises(app.Problem):
|
||||
self.save('link', dict(fromId=self.people[32]['id'], toId=self.people[5]['id'], kind='spouse'))
|
||||
edge = next(e for e in app.objects('family_links') if e['fromId'] == self.people[30]['id'])
|
||||
with self.assertRaises(app.Problem): self.save('link', dict(edge, active=False))
|
||||
self.assertTrue(app.get_object('family_links', edge['id'])['active'])
|
||||
with self.assertRaises(app.Problem):
|
||||
self.save('link', dict(fromId=self.people[28]['id'], toId=self.people[30]['id'], kind='parent'))
|
||||
|
||||
def test_old_event_cannot_be_retargeted_to_self_to_gain_write_access(self):
|
||||
event = dict(app.FAMILY.event(dict(title='Old ancestor', eventDate='1900-01-01',
|
||||
body='untouched', personIds=[self.people[5]['id']], status='published'), None), familyId=self.home)
|
||||
app.save_object('family_events', event)
|
||||
with self.assertRaises(app.Problem): self.save('event', dict(event, personIds=[self.people[32]['id']], body='denied'))
|
||||
self.assertEqual(app.get_object('family_events', event['id'])['body'], 'untouched')
|
||||
self.assertIn(event['id'], [e['id'] for e in app.FAMILY.snapshot(self.actor)['events']])
|
||||
|
||||
def test_history_restore_cannot_change_far_person(self):
|
||||
person = self.people[5]
|
||||
app.DB.execute('INSERT INTO family_changes VALUES (?,?,?,?,?,?,?,?)',
|
||||
(1, 'person', person['id'], None, json.dumps(dict(person, note='old text')), 'fixture', '2026-10-01', None))
|
||||
app.DB.commit()
|
||||
with self.assertRaises(app.Problem) as caught:
|
||||
app.FAMILY.restore(dict(changeRevision=1, side='after', revision=0), self.actor)
|
||||
self.assertEqual(caught.exception.status, 403)
|
||||
self.assertEqual(app.get_object('people', person['id'])['note'], '')
|
||||
|
||||
def test_binding_cannot_be_cleared_or_changed_even_by_super_admin(self):
|
||||
for person in ('', self.people[5]['id']):
|
||||
with self.assertRaises(app.Problem) as caught:
|
||||
app.ACCOUNTS.save(dict(self.actor, personId=person), self.actor)
|
||||
self.assertEqual(caught.exception.status, 403)
|
||||
|
||||
def test_unbound_account_can_create_only_its_own_starting_record(self):
|
||||
account = app.ACCOUNTS.save(dict(username='unbound', password='fixture-only', familyAccess='edit'), self.actor)
|
||||
self.assertFalse(app.FAMILY.snapshot(account)['canEdit'])
|
||||
with self.assertRaises(app.Problem):
|
||||
app.FAMILY.save('person', dict(self.people[32], note='denied', revision=0), account)
|
||||
result = app.FAMILY.save('person', dict(name='New self', asSelf=True, revision=0), account)
|
||||
self.assertEqual(app.get_object('users', account['id'])['personId'], result['item']['id'])
|
||||
with self.assertRaises(app.Problem):
|
||||
app.FAMILY.save('person', dict(name='Another self', asSelf=True, revision=1), account)
|
||||
|
||||
def test_conflicting_generations_fail_closed(self):
|
||||
edge = dict(id=secrets.token_hex(8), fromId=self.people[27]['id'], toId=self.people[29]['id'],
|
||||
kind='parent', active=True, familyId=self.home)
|
||||
app.save_object('family_links', edge)
|
||||
self.assertTrue(app.FAMILY.snapshot(self.actor)['editScope']['conflict'])
|
||||
self.assertFalse(app.FAMILY.snapshot(self.actor)['canEdit'])
|
||||
with self.assertRaises(app.Problem): self.save('person', dict(self.people[32], note='denied'))
|
||||
|
||||
def test_http_direct_write_is_denied_for_super_admin(self):
|
||||
token = 'a'*64
|
||||
app.DB.execute('INSERT INTO sessions VALUES (?,?,?)', (hashlib.sha256(token.encode()).hexdigest(), time.time()+60, self.actor['id']))
|
||||
app.DB.commit()
|
||||
server = app.ThreadingHTTPServer(('127.0.0.1', 0), app.Handler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True); thread.start()
|
||||
try:
|
||||
c = http.client.HTTPConnection(*server.server_address, timeout=3)
|
||||
c.request('POST', '/api/family/person', json.dumps(dict(self.people[5], note='denied', revision=0)),
|
||||
{'Cookie': 'vision='+token, 'Content-Type': 'application/json'})
|
||||
response = c.getresponse(); response.read(); c.close()
|
||||
self.assertEqual(response.status, 403)
|
||||
finally:
|
||||
server.shutdown(); server.server_close(); thread.join()
|
||||
|
||||
def test_offsets_are_generation_difference_not_number_of_clicks(self):
|
||||
spouse = dict(app.FAMILY.person({'name':'spouse'}, None), familyId=self.home)
|
||||
app.save_object('people', spouse)
|
||||
app.save_object('family_links', dict(id=secrets.token_hex(8), fromId=self.people[32]['id'],
|
||||
toId=spouse['id'], kind='spouse', active=True, familyId=self.home))
|
||||
levels, conflict = generations(app.objects('people'), app.objects('family_links'), self.people[32]['id'])
|
||||
self.assertFalse(conflict); self.assertEqual(levels[spouse['id']], 0)
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
+2
-2
@@ -157,8 +157,8 @@ class HouseholdTests(unittest.TestCase):
|
||||
self.assertEqual(self.request('/api/households',self.members[self.aid],{'name':'unauthorized'})[0],403)
|
||||
|
||||
def test_genealogy_revisions_history_restore_and_refs_isolated(self):
|
||||
a = app.FAMILY.save('person',dict(name='A private',revision=0),self.owner)['item']
|
||||
b = app.FAMILY.save('person',dict(name='B private',revision=0),self.other)['item']
|
||||
a = app.FAMILY.save('person',dict(name='A private',revision=0,asSelf=True),self.owner)['item']
|
||||
b = app.FAMILY.save('person',dict(name='B private',revision=0,asSelf=True),self.other)['item']
|
||||
self.assertEqual(self.request('/api/family')[1]['revision'],1)
|
||||
self.assertEqual([p['name'] for p in self.request('/api/family')[1]['people']],['A private'])
|
||||
revision=app.FAMILY.history(self.other,'person',b['id'])['items'][0]['revision']
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
import playback
|
||||
|
||||
|
||||
class PlaybackCacheTests(unittest.TestCase):
|
||||
def test_private_cache_removed_after_use_and_abort(self):
|
||||
for abort in (False, True):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
with patch.dict('os.environ', {'VISION_DATA':folder}), patch('playback.shutil.disk_usage', return_value=SimpleNamespace(free=10**12)), patch('playback.urllib.request.urlopen', return_value=io.BytesIO(b'video')) as opening:
|
||||
try:
|
||||
with playback.cached_source('http://127.0.0.1/source', 'Basic private', 8) as path:
|
||||
self.assertEqual(Path(path).read_bytes(), b'video')
|
||||
self.assertEqual(opening.call_args.args[0].get_header('Authorization'), 'Basic private')
|
||||
if abort:
|
||||
raise RuntimeError('browser left')
|
||||
except RuntimeError:
|
||||
self.assertTrue(abort)
|
||||
self.assertEqual(list((Path(folder)/'playback-tmp').iterdir()), [])
|
||||
|
||||
def test_oversize_and_empty_sources_leave_no_cache(self):
|
||||
for contents in (b'', b'123456789'):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
with patch.dict('os.environ', {'VISION_DATA':folder}), patch('playback.MAX_SOURCE_BYTES', 8), patch('playback.shutil.disk_usage', return_value=SimpleNamespace(free=1000)), patch('playback.urllib.request.urlopen', return_value=io.BytesIO(contents)):
|
||||
with self.assertRaises(playback.PlaybackError):
|
||||
with playback.cached_source('http://127.0.0.1/source', 'private', 8):
|
||||
self.fail('invalid cache accepted')
|
||||
self.assertEqual(list((Path(folder)/'playback-tmp').iterdir()), [])
|
||||
|
||||
def test_disk_reserve_checked_before_download(self):
|
||||
with patch('playback.shutil.disk_usage', return_value=SimpleNamespace(free=1)), patch('playback.urllib.request.urlopen') as opening:
|
||||
with self.assertRaises(playback.PlaybackError):
|
||||
with playback.cached_source('unused', 'private', 8):
|
||||
self.fail('low space accepted')
|
||||
opening.assert_not_called()
|
||||
|
||||
def test_stale_buffers_are_removed_but_current_and_unrelated_files_remain(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
base=Path(folder)/'playback-tmp';base.mkdir()
|
||||
old=base/'buffer-old';old.mkdir();(old/'source.mp4').write_bytes(b'old')
|
||||
os.utime(old,(time.time()-7200,time.time()-7200))
|
||||
fresh=base/'buffer-active';fresh.mkdir();(fresh/'source.mp4').write_bytes(b'active')
|
||||
unrelated=base/'keep.txt';unrelated.write_text('keep')
|
||||
with patch.dict('os.environ',{'VISION_DATA':folder}), patch('playback.shutil.disk_usage',return_value=SimpleNamespace(free=10**12)), patch('playback.urllib.request.urlopen',return_value=io.BytesIO(b'video')):
|
||||
with playback.cached_source('http://127.0.0.1/source','private',8):
|
||||
self.assertFalse(old.exists())
|
||||
self.assertEqual((fresh/'source.mp4').read_bytes(),b'active')
|
||||
self.assertEqual(unrelated.read_text(),'keep')
|
||||
|
||||
def test_local_converter_can_buffer_ahead_and_has_no_credentials(self):
|
||||
with patch('playback.shutil.which', return_value='ffmpeg'), patch('playback.os.access', return_value=False):
|
||||
cmd=playback.command('/tmp/private/source.mp4', '', 300)
|
||||
self.assertNotIn('-readrate', cmd)
|
||||
self.assertNotIn('-headers', cmd)
|
||||
self.assertIn('libx264', cmd)
|
||||
self.assertEqual(cmd[cmd.index('-threads')+1], '1')
|
||||
|
||||
def test_sessions_are_bounded_before_consuming_a_slot(self):
|
||||
for duration in (0, 301, float('nan')):
|
||||
with self.assertRaises(playback.PlaybackError):
|
||||
with playback.stream('unused', 'private', duration):
|
||||
self.fail('unbounded playback accepted')
|
||||
self.assertTrue(playback.SLOTS.acquire(blocking=False))
|
||||
playback.SLOTS.release()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
+33
-3
@@ -4,9 +4,18 @@ test('ranges clip to selected day and merge overlaps without filling gaps',()=>{
|
||||
const items=[{start:date(-10),duration:40},{start:date(20),duration:30},{start:date(60),duration:100},{start:'invalid',duration:20},{start:date(3),duration:-4},{start:date(3),duration:Infinity}];
|
||||
assert.deepEqual(Ranges.normalize(items,date(0),date(100)),[{start:+date(0),end:+date(50)},{start:+date(60),end:+date(100)}]);
|
||||
});
|
||||
test('long recording continues after each one-hour session',()=>{
|
||||
const ranges=[{start:+date(0),end:+date(8000)}];assert.deepEqual(Ranges.at(ranges,date(0)),{start:+date(0),end:+date(3600)});
|
||||
assert.deepEqual(Ranges.next(ranges,date(3600)),{start:+date(3600),end:+date(7200)});assert.equal(Ranges.next(ranges,date(8000)),null);
|
||||
test('microsecond recording starts round inward and never seek into the preceding gap',()=>{
|
||||
const raw='2026-10-04T00:00:00.340240Z';
|
||||
const ranges=Ranges.normalize([{start:raw,duration:41.1355}],date(0),date(100));
|
||||
assert.equal(new Date(ranges[0].start).toISOString(),'2026-10-04T00:00:00.341Z');
|
||||
assert.equal(new Date(ranges[0].end).toISOString(),'2026-10-04T00:00:41.475Z');
|
||||
const exact=Ranges.normalize([{start:'2026-10-04T00:00:00.340000Z',duration:10}],date(0),date(100));
|
||||
assert.equal(exact[0].start,Date.parse(raw));
|
||||
assert.deepEqual(Ranges.normalize([{start:raw,duration:0.0001}],date(0),date(1)),[]);
|
||||
});
|
||||
test('long recording continues in bounded five-minute sessions',()=>{
|
||||
const ranges=[{start:+date(0),end:+date(8000)}];assert.deepEqual(Ranges.at(ranges,date(0)),{start:+date(0),end:+date(300)});
|
||||
assert.deepEqual(Ranges.next(ranges,date(300)),{start:+date(300),end:+date(600)});assert.equal(Ranges.next(ranges,date(8000)),null);
|
||||
});
|
||||
test('next segment skips the actual gap and does not replay the previous end',()=>{
|
||||
const ranges=[{start:+date(0),end:+date(10)},{start:+date(30),end:+date(40)}];assert.equal(Ranges.at(ranges,date(10)),null);
|
||||
@@ -20,6 +29,19 @@ test('clip requires valid, positive, fully recorded interval up to one hour',()=
|
||||
function section(file,a,b){const s=fs.readFileSync('web/'+file,'utf8'),i=s.indexOf(a),j=s.indexOf(b,i+a.length);assert.ok(i>=0&&j>i);return s.slice(i,j);}
|
||||
function deferred(){let resolve;const promise=new Promise(r=>resolve=r);return{promise,resolve};}
|
||||
function ui(extra={}){const elements=new Map();const $=s=>{if(!elements.has(s))elements.set(s,{replaceChildren(){},reset(){},value:'',hidden:false});return elements.get(s);};return vm.createContext({$,Number,Date,URLSearchParams,loggedIn:true,activePage:'playback',RecordingRanges:Ranges,...extra});}
|
||||
test('recording health distinguishes configured from writing and never changes the player',()=>{
|
||||
const c=ui({state:{cameras:[{id:'camera',recordingState:'off'}],storage:{retentionDays:30,maxGB:40,reserveGB:8}},isAdmin:()=>true});
|
||||
c.$('#play-camera').value='camera';c.$('#archive-source').value='local';c.$('#recording-configure').dataset={};
|
||||
c.$('#play-video').src='keep-playing';
|
||||
vm.runInContext(section('recording-ui.js','function renderRecordingStatus(','function localDateTime('),c);
|
||||
for(const [status,text] of [['off','未开启'],['waiting','等待文件写入'],['recording','正在录像'],['paused','磁盘保护'],['offline','等待摄像头'],['unavailable','服务未连接'],['disabled','设备连接已停用']]){
|
||||
c.state.cameras[0].recordingState=status;c.renderRecordingStatus();assert.ok(c.$('#recording-health-text').textContent.includes(text));
|
||||
}
|
||||
assert.match(c.$('#recording-policy-note').textContent,/30 天/);assert.equal(c.$('#recording-configure').dataset.editCamera,'camera');
|
||||
assert.equal(c.$('#play-video').src,'keep-playing');
|
||||
c.isAdmin=()=>false;c.state.storage={};c.renderRecordingStatus();assert.equal(c.$('#recording-configure').hidden,true);assert.doesNotMatch(c.$('#recording-policy-note').textContent,/undefined|40 GB/);
|
||||
c.$('#archive-source').value='recorder';c.renderRecordingStatus();assert.equal(c.$('#recording-health').hidden,true);
|
||||
});
|
||||
test('auto-continue preserves user choice, stops short clips and ends at last segment',()=>{
|
||||
const c=ui({playbackRange:{start:0,end:10000},spans:[{start:0,end:10000},{start:20000,end:30000}],playAt:d=>c.played=+d});
|
||||
vm.runInContext(section('recording-ui.js','function continuePlayback(','function makeClip('),c);
|
||||
@@ -34,6 +56,14 @@ test('late recording list cannot replace another camera or a logged-out view',as
|
||||
vm.runInContext(section('recording-ui.js','async function queryRecordings(','function drawTimeline('),c);
|
||||
const work=c.queryRecordings();c.playbackGeneration++;p.resolve({items:[]});await work;assert.equal(c.spans,undefined);
|
||||
});
|
||||
test('resuming a long pause reopens the recorded position without a page refresh',()=>{
|
||||
const c=ui({playbackRange:{start:10000,end:300000},playbackPausedAt:Date.now()-20000,playAt:(date,preserve)=>c.played={time:+date,preserve}});
|
||||
c.$('#play-video').currentTime=45;
|
||||
vm.runInContext(section('recording-ui.js','function pausePlayback(','function makeClip('),c);
|
||||
c.resumePlayback();assert.deepEqual(c.played,{time:55000,preserve:true});assert.equal(c.playbackPausedAt,0);
|
||||
c.played=null;c.playbackPausedAt=Date.now();c.resumePlayback();assert.equal(c.played,null);
|
||||
c.playbackPausedAt=Date.now()-20000;c.loggedIn=false;c.resumePlayback();assert.equal(c.played,null);
|
||||
});
|
||||
test('download generation refuses gaps and invalidates old links first',()=>{
|
||||
const c=ui({queryCamera:'camera',spans:[{start:+date(0),end:+date(60)}],playbackParams:()=>new URLSearchParams({start:'test'}),Error});
|
||||
vm.runInContext(section('recording-ui.js','function makeClip(',"$('#query-recordings')"),c);
|
||||
|
||||
@@ -21,6 +21,22 @@ test('Vue theme builds locally after Bootstrap without remote fonts', () => {
|
||||
assert.doesNotMatch(fs.readFileSync('frontend/src/theme.css','utf8'), /@import|https?:|@font-face/i);
|
||||
assert.match(fs.readFileSync('frontend/index.html','utf8'), /name="viewport"/);
|
||||
});
|
||||
|
||||
test('Bootstrap polish keeps readable light and dark foregrounds and avoids remote assets', () => {
|
||||
const polish=fs.readFileSync('frontend/src/bootstrap-polish.css','utf8');
|
||||
const light=polish.match(/:root\s*\{([^}]+)\}/)[1];
|
||||
const value=name=>light.match(new RegExp('--'+name+':\\s*(#[0-9a-f]{6})'))[1];
|
||||
for(const bg of ['#ffffff','#f3f6fa','#f5f6f4']) {
|
||||
assert.ok(contrast(value('ink'),bg)>=4.5);
|
||||
assert.ok(contrast(value('ui-muted'),bg)>=4.5);
|
||||
}
|
||||
for(const bg of [value('ui-accent'),'#397359'])assert.ok(contrast('#ffffff',bg)>=4.5);
|
||||
assert.ok(contrast('#a8bdc5','#1a2b35')>=4.5);
|
||||
assert.doesNotMatch(polish,/@import|https?:|@font-face/);
|
||||
assert.match(polish,/prefers-reduced-motion/);
|
||||
assert.match(polish,/home-options-open/);
|
||||
assert.match(polish,/#page-live:is\(:fullscreen,\.wall-expanded\) \.camera-meta \{[^}]+background: #172e35 !important; color: #e8f3ef !important/);
|
||||
});
|
||||
test('primary text, muted text and actions have at least 4.5:1 contrast', () => {
|
||||
for (const [fg, bg] of [
|
||||
[token('ink'), token('paper')], [token('muted'), token('paper')],
|
||||
@@ -58,3 +74,9 @@ test('recording timeline paints with theme tokens and keeps range geometry', ()
|
||||
]);
|
||||
assert.equal(ctx.strokeStyle, '#d3ccbc');
|
||||
});
|
||||
|
||||
test('mobile playback filters keep full-width readable controls',()=>{
|
||||
const css=fs.readFileSync('frontend/src/bootstrap-polish.css','utf8');
|
||||
assert.match(css,/#page-playback \.playback-controls \{ display: grid; grid-template-columns: minmax\(0, 1fr\)/);
|
||||
assert.match(css,/#page-playback \.playback-controls input, #page-playback \.playback-controls select \{ width: 100%/);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const model=()=>import('./frontend/src/composables/insights.mjs');
|
||||
test('home summary uses only supplied authorized records and handles empty values',async()=>{
|
||||
const {summarizeHomes}=await model();
|
||||
assert.deepEqual(summarizeHomes(),{total:0,devices:0,areas:0,kinds:[]});
|
||||
const value=summarizeHomes([{kind:'home',deviceCount:4,sites:1},{kind:'office',deviceCount:2,sites:3},{kind:'home',deviceCount:-1}]);
|
||||
assert.equal(value.devices,6);assert.equal(value.areas,4);assert.equal(value.total,3);
|
||||
assert.equal(value.kinds.reduce((n,k)=>n+k.count,0),3);
|
||||
assert.ok(Math.abs(value.kinds.reduce((n,k)=>n+k.share,0)-100)<0.001);
|
||||
assert.equal(value.kinds[1].offset,value.kinds[0].share);
|
||||
});
|
||||
test('network diagram draws only known parent connections',async()=>{
|
||||
const {layoutNetwork}=await model();
|
||||
const rows=[{device:{id:'r'},depth:0},{device:{id:'c',uplinkId:'r'},depth:1},{device:{id:'x',uplinkId:'missing'},depth:0},{device:{id:'cycle',uplinkId:'cycle'},depth:0}];
|
||||
const graph=layoutNetwork(rows);
|
||||
assert.equal(graph.nodes.length,4);assert.deepEqual(graph.edges.map(e=>e.id),['c']);
|
||||
assert.ok(graph.nodes.every(n=>n.x>=0&&n.y>=0&&n.x+244<=graph.width&&n.y+88<=graph.height));
|
||||
assert.deepEqual(layoutNetwork().edges,[]);
|
||||
});
|
||||
+9
-1
@@ -4,6 +4,14 @@ const source=name=>fs.readFileSync('web/'+name,'utf8');
|
||||
function section(file,start,end){const s=source(file),a=s.indexOf(start),b=s.indexOf(end,a+start.length);assert.ok(a>=0&&b>a);return s.slice(a,b);}
|
||||
const apiSource=section('app.js','async function api(','function toast(');
|
||||
const refreshSource=section('app.js','async function refresh(','async function auth(');
|
||||
test('genealogy UI applies write scope independently of viewing reference',()=>{
|
||||
const family={canEdit:true,editScope:{limit:5,levels:{self:0,near:-5,far:-6},editablePersonIds:['self','near']},links:[{id:'edge',fromId:'near',toId:'far'}],events:[{id:'event',personIds:['far']}]};
|
||||
const c=vm.createContext({family});vm.runInContext(section('family.js','function familyEditable(','function editablePeopleOptions('),c);
|
||||
assert.equal(c.familyEditable('person','near'),true);assert.equal(c.familyEditable('person','far'),false);
|
||||
assert.equal(c.familyEditable('link','edge'),false);assert.equal(c.familyEditable('event','event'),false);
|
||||
assert.match(c.familyScopeLabel('far'),/只读/);family.selfId='far';assert.equal(c.familyEditable('person','far'),false);
|
||||
family.canEdit=false;assert.equal(c.familyEditable('person','near'),false);
|
||||
});
|
||||
function context(extra={}){return vm.createContext({sessionGeneration:0,refreshGeneration:0,authGeneration:0,loggedIn:true,currentUser:{id:'a'},state:{},Error,...extra});}
|
||||
function deferred(){let resolve,reject;const promise=new Promise((a,b)=>{resolve=a;reject=b;});return {promise,resolve,reject};}
|
||||
|
||||
@@ -57,7 +65,7 @@ test('archived person reached from an event is revealed before graph location',(
|
||||
test('event default save preserves published state and exposes explicit withdrawal',()=>{
|
||||
const controls=new Map(),form={dataset:{},querySelector:s=>{if(!controls.has(s))controls.set(s,{});return controls.get(s);}};
|
||||
const elements=new Map([['#event-form',form]]);const $=s=>{if(!elements.has(s))elements.set(s,{showModal(){},close(){}});return elements.get(s);};
|
||||
const c=context({family:{canEdit:true,revision:3,people:[],events:[{id:'published',status:'published',personIds:[]}]},$,fillForm:()=>{},initDateFields:()=>{},esc:String});
|
||||
const c=context({family:{canEdit:true,revision:3,people:[],events:[{id:'published',status:'published',personIds:[]}]},familyEditable:()=>true,$,fillForm:()=>{},initDateFields:()=>{},esc:String});
|
||||
vm.runInContext(section('family-events.js','function editFamilyEvent(',"$('#event-form').addEventListener"),c);
|
||||
c.editFamilyEvent('published');assert.equal(form.querySelector('[data-save-event]').value,'published');assert.equal(form.querySelector('[data-save-event]').textContent,'保存修改');assert.equal(form.querySelector('[data-publish-event]').hidden,true);assert.equal(form.querySelector('[data-withdraw-event]').hidden,false);
|
||||
c.editFamilyEvent();assert.equal(form.querySelector('[data-save-event]').value,'draft');assert.equal(form.querySelector('[data-withdraw-event]').hidden,true);
|
||||
|
||||
@@ -107,6 +107,7 @@ function render() {
|
||||
if (activePage === 'recorders') renderRecorders();
|
||||
if (activePage === 'playback') {
|
||||
setOptions($('#play-camera'), filtered().map(c=>`<option value="${c.id}">${esc(siteName(c.siteId)+' / '+c.name)}</option>`).join(''));
|
||||
renderRecordingStatus();
|
||||
drawTimeline();
|
||||
}
|
||||
if (activePage === 'storage') renderStorage();
|
||||
|
||||
@@ -29,22 +29,22 @@ function renderFamilyEvents(){
|
||||
function showPersonEvents(id){familyView='timeline';renderFamily();$('#family-event-person').value=id;$('#family-event-year').value='';$('#family-event-search').value='';$('#family-event-relatives').checked=false;$('#family-event-state').value='published';renderFamilyEvents();$('#family-events').scrollIntoView({behavior:'smooth',block:'start'});}
|
||||
function personEventSummary(id){
|
||||
const events=(family.events||[]).filter(e=>e.personIds.includes(id)&&!e.archived&&e.status==='published').sort((a,b)=>b.eventDate.localeCompare(a.eventDate));
|
||||
return `<section class="person-events"><div class="section-head"><h3>相关重大记事 <small>${events.length}</small></h3>${family.canEdit?`<button class="quiet" data-new-person-event="${id}">+ 记一件事</button>`:''}</div>${(familyView==='timeline'?events.slice(0,3):[]).map(e=>`<button class="person-event-link" data-view-event="${e.id}"><time>${esc(e.eventDate)}</time><span>${esc(e.title)}</span></button>`).join('')||(familyView==='timeline'?'<p class="description">尚无已发布的相关记事。</p>':'')}<button class="quiet" data-person-events="${id}">在时间线追溯 →</button></section>`;
|
||||
return `<section class="person-events"><div class="section-head"><h3>相关重大记事 <small>${events.length}</small></h3>${familyEditable('person',id)?`<button class="quiet" data-new-person-event="${id}">+ 记一件事</button>`:''}</div>${(familyView==='timeline'?events.slice(0,3):[]).map(e=>`<button class="person-event-link" data-view-event="${e.id}"><time>${esc(e.eventDate)}</time><span>${esc(e.title)}</span></button>`).join('')||(familyView==='timeline'?'<p class="description">尚无已发布的相关记事。</p>':'')}<button class="quiet" data-person-events="${id}">在时间线追溯 →</button></section>`;
|
||||
}
|
||||
function openFamilyEvent(id){
|
||||
const e=(family.events||[]).find(e=>e.id===id);if(!e)return;
|
||||
// All content is plain text. External reports are links, never embedded HTML.
|
||||
const safeSource=/^https?:\/\//i.test(e.sourceUrl||'')?e.sourceUrl:'';
|
||||
$('#event-detail-content').innerHTML=`<div class="event-detail-meta"><time>${esc(ZhaoCalendar.describe(e.eventDate))}</time><span class="badge">${esc(eventStatus(e))}</span></div><h2 id="event-detail-title">${esc(e.title)}</h2>${e.summary?`<p class="event-lead">${esc(e.summary)}</p>`:''}<div class="event-associated"><span class="description">关联人物</span>${e.personIds.length?e.personIds.map(id=>`<button class="quiet" data-event-person="${esc(id)}">${esc(personName(id))} ↗</button>`).join(''):'<span>全家记事</span>'}</div><div class="family-prose event-article">${esc(e.body||'此条记事暂未填写详细正文。')}</div>${safeSource?`<a class="button secondary event-source" href="${esc(safeSource)}" target="_blank" rel="noopener noreferrer">阅读原始报道${e.sourceName?' · '+esc(e.sourceName):''} ↗</a>`:e.sourceName?`<p class="description">资料来源:${esc(e.sourceName)}</p>`:''}<p class="description event-updated">最近整理:${esc(new Date(e.updatedAt).toLocaleString())}</p>${family.canEdit?`<button data-edit-event="${e.id}">编辑这条记事</button><button class="quiet" data-history-kind="event" data-history-id="${e.id}">修改记录</button>`:''}`;
|
||||
$('#event-detail-content').innerHTML=`<div class="event-detail-meta"><time>${esc(ZhaoCalendar.describe(e.eventDate))}</time><span class="badge">${esc(eventStatus(e))}</span></div><h2 id="event-detail-title">${esc(e.title)}</h2>${e.summary?`<p class="event-lead">${esc(e.summary)}</p>`:''}<div class="event-associated"><span class="description">关联人物</span>${e.personIds.length?e.personIds.map(id=>`<button class="quiet" data-event-person="${esc(id)}">${esc(personName(id))} ↗</button>`).join(''):'<span>全家记事</span>'}</div><div class="family-prose event-article">${esc(e.body||'此条记事暂未填写详细正文。')}</div>${safeSource?`<a class="button secondary event-source" href="${esc(safeSource)}" target="_blank" rel="noopener noreferrer">阅读原始报道${e.sourceName?' · '+esc(e.sourceName):''} ↗</a>`:e.sourceName?`<p class="description">资料来源:${esc(e.sourceName)}</p>`:''}<p class="description event-updated">最近整理:${esc(new Date(e.updatedAt).toLocaleString())}</p>${familyEditable('event',e.id)?`<button data-edit-event="${e.id}">编辑这条记事</button><button class="quiet" data-history-kind="event" data-history-id="${e.id}">修改记录</button>`:''}`;
|
||||
$('#event-detail-dialog').showModal();
|
||||
}
|
||||
function editFamilyEvent(id,personId=''){
|
||||
if(!family.canEdit)return;
|
||||
if(!family.canEdit||id&&!familyEditable('event',id))return;
|
||||
const e=(family.events||[]).find(e=>e.id===id),f=$('#event-form');
|
||||
fillForm(f,{...(e||{}),revision:family.revision});
|
||||
$('#event-editor-title').textContent=e?'编辑家族记事':'写一则家族记事';
|
||||
const selected=new Set(e?.personIds||(personId?[personId]:[]));
|
||||
$('#event-person-choices').innerHTML=family.people.map(p=>`<label class="check"><input type="checkbox" name="personIds" value="${esc(p.id)}" ${selected.has(p.id)?'checked':''}>${esc(p.name)}${p.archived?'(已归档)':''}</label>`).join('')||'<p class="description">家谱尚无人名,此条记事将记为全家记事。</p>';
|
||||
$('#event-person-choices').innerHTML=family.people.filter(p=>familyEditable('person',p.id)).map(p=>`<label class="check"><input type="checkbox" name="personIds" value="${esc(p.id)}" ${selected.has(p.id)?'checked':''}>${esc(p.name)}${p.archived?'(已归档)':''}</label>`).join('')||'<p class="description">家谱尚无人名,此条记事将记为全家记事。</p>';
|
||||
$('#event-person-search').value='';f.dataset.status=e?.status||'draft';
|
||||
f.querySelector('[data-save-event]').value=f.dataset.status;f.querySelector('[data-save-event]').textContent=e?'保存修改':'保存草稿';
|
||||
f.querySelector('[data-publish-event]').hidden=f.dataset.status==='published';f.querySelector('[data-withdraw-event]').hidden=f.dataset.status!=='published';
|
||||
|
||||
@@ -7,6 +7,18 @@
|
||||
|
||||
.family-workspace.family-expanded{position:fixed;inset:0;z-index:8;}
|
||||
|
||||
/* Keep scaled descendants and fractional fullscreen sizes out of the
|
||||
scrollable overflow calculation. Reserve one gutter instead of alternating. */
|
||||
.family-map-viewport{scrollbar-gutter:stable;overflow-anchor:none}
|
||||
.family-map-space{min-width:0;min-height:0;overflow:clip}
|
||||
.family-workspace:is(:fullscreen,.family-expanded){min-height:0;grid-template-rows:minmax(0,1fr)}
|
||||
.family-workspace:is(:fullscreen,.family-expanded) .family-canvas-panel{min-height:0}
|
||||
.family-workspace:is(:fullscreen,.family-expanded) .family-map-heading,
|
||||
.family-workspace:is(:fullscreen,.family-expanded) .family-map-controls,
|
||||
.family-workspace:is(:fullscreen,.family-expanded) .family-map-footer{flex-shrink:0}
|
||||
.family-workspace.family-expanded{z-index:1100}
|
||||
@media(max-width:1000px){.family-workspace:is(:fullscreen,.family-expanded) .family-canvas-panel{min-height:65vh}}
|
||||
|
||||
/* Versions remain readable on a small screen, including long family narratives. */
|
||||
#history-dialog{width:min(1040px,94vw)}
|
||||
#history-list{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:10px;max-height:260px;overflow:auto;margin:16px 0}
|
||||
|
||||
+21
-6
@@ -10,9 +10,24 @@ class FamilyMap {
|
||||
viewport.addEventListener('pointermove',e=>{if(!this.drag)return;viewport.scrollLeft=this.drag.left+this.drag.x-e.clientX;viewport.scrollTop=this.drag.top+this.drag.y-e.clientY;});
|
||||
const release=()=>{this.drag=null;viewport.classList.remove('panning');};
|
||||
viewport.addEventListener('pointerup',release);viewport.addEventListener('pointercancel',release);viewport.addEventListener('lostpointercapture',release);
|
||||
this.resize=new ResizeObserver(()=>{if(this.autoFit)this.fit();else this.applyScale();});this.resize.observe(viewport);
|
||||
this.resizeFrame=0;this.resizeSize='';
|
||||
this.resize=new ResizeObserver(()=>this.scheduleResize());this.resize.observe(viewport,{box:'border-box'});
|
||||
}
|
||||
reset(){cancelAnimationFrame(this.resizeFrame);this.resizeFrame=0;this.resizeSize='';this.key='';this.data=null;this.graph=null;this.viewport.replaceChildren();this.autoFit=true;this.drag=null;$('#family-zoom-value').textContent='100%';}
|
||||
viewportSize(){
|
||||
const v=this.viewport,r=v.getBoundingClientRect();
|
||||
// clientHeight rounds fractional pixels up; using it as a child height can
|
||||
// create a scrollbar, remove it on the next fit, and repeat indefinitely.
|
||||
return {width:Math.floor(Math.min(v.clientWidth,r.width)),height:Math.floor(Math.min(v.clientHeight,r.height))};
|
||||
}
|
||||
scheduleResize(){
|
||||
if(this.resizeFrame)return;
|
||||
this.resizeFrame=requestAnimationFrame(()=>{
|
||||
this.resizeFrame=0;const {width,height}=this.viewportSize(),key=width+':'+height;
|
||||
if(!width||!height||key===this.resizeSize)return;
|
||||
this.resizeSize=key;if(this.autoFit)this.fit();else this.applyScale();
|
||||
});
|
||||
}
|
||||
reset(){this.key='';this.data=null;this.viewport.replaceChildren();this.autoFit=true;this.drag=null;$('#family-zoom-value').textContent='100%';}
|
||||
render(data) {
|
||||
this.data=data;
|
||||
const key=JSON.stringify([data.people,data.links,data.showArchived,data.selfId]);
|
||||
@@ -46,16 +61,16 @@ class FamilyMap {
|
||||
}
|
||||
applyScale() {
|
||||
const v=this.viewport,g=this.graph,space=v.querySelector('.family-map-space'),surface=v.querySelector('.family-map-surface');
|
||||
if(!g||!space||!v.clientWidth)return;
|
||||
const w=Math.max(v.clientWidth,g.width*this.scale+32),h=Math.max(v.clientHeight,g.height*this.scale+32);
|
||||
const {width,height}=this.viewportSize();if(!g||!space||!width||!height)return;
|
||||
const w=Math.max(width,Math.ceil(g.width*this.scale+32)),h=Math.max(height,Math.ceil(g.height*this.scale+32));
|
||||
space.style.width=w+'px';space.style.height=h+'px';
|
||||
this.left=(w-g.width*this.scale)/2;this.top=(h-g.height*this.scale)/2;
|
||||
surface.style.transform=`translate(${this.left}px,${this.top}px) scale(${this.scale})`;
|
||||
$('#family-zoom-value').textContent=Math.round(this.scale*100)+'%';
|
||||
}
|
||||
fit() {
|
||||
const v=this.viewport,g=this.graph;if(!g||!v.clientWidth||!v.clientHeight)return;
|
||||
this.autoFit=true;this.scale=Math.max(.001,Math.min(1,(v.clientWidth-40)/g.width,(v.clientHeight-40)/g.height));
|
||||
const v=this.viewport,g=this.graph,{width,height}=this.viewportSize();if(!g||!width||!height)return;
|
||||
this.autoFit=true;this.scale=Math.max(.001,Math.min(1,(width-40)/g.width,(height-40)/g.height));
|
||||
this.applyScale();v.scrollTo(0,0);
|
||||
}
|
||||
zoom(factor) {
|
||||
|
||||
+36
-8
@@ -9,6 +9,20 @@ function clearFamilyState(){if(typeof clearFamilyHistory==='function')clearFamil
|
||||
function personLocation(p,prefix){return [ZhaoGeography.describe(p,prefix),...['Town','Community','Address'].map(k=>p[prefix+k])].filter(Boolean).join(' · ');}
|
||||
function personSearch(p){return [p.name,p.alias,p.birthplace,personLocation(p,'native'),personLocation(p,'birth')].join(' ').toLowerCase();}
|
||||
function personName(id){return family.people.find(p=>p.id===id)?.name||'未关联';}
|
||||
function familyEditable(kind,id){
|
||||
if(!family.canEdit)return false;
|
||||
if(!family.editScope)return true;
|
||||
const allowed=new Set(family.editScope.editablePersonIds||[]);
|
||||
if(kind==='person')return allowed.has(id);
|
||||
const row=(kind==='link'?family.links:family.events||[]).find(x=>x.id===id);
|
||||
return !!row&&(kind==='link'?[row.fromId,row.toId]:row.personIds||[]).every(key=>allowed.has(key));
|
||||
}
|
||||
function familyScopeLabel(id){
|
||||
const scope=family.editScope;if(!scope)return '';
|
||||
const n=scope.levels?.[id],position=n===0?'与本人同代':n<0?`本人上 ${-n} 代`:n>0?`本人下 ${n} 代`:'与本人的世系尚未连接';
|
||||
return position+' · '+(familyEditable('person',id)?'可维护':Number.isFinite(n)&&Math.abs(n)>scope.limit?'只读,超出五代范围':'只读');
|
||||
}
|
||||
function editablePeopleOptions(){return family.people.filter(p=>familyEditable('person',p.id)).map(p=>`<option value="${p.id}">${esc(p.name)}</option>`).join('');}
|
||||
function peopleOptions(blank=true){return (blank?'<option value="">尚未关联</option>':'')+family.people.map(p=>`<option value="${p.id}">${esc(p.name+(p.archived?'(已归档)':''))}</option>`).join('');}
|
||||
function fillForm(form,data){resetEditorForm(form);form.querySelector('.form-error').textContent='';for(const [k,v]of Object.entries(data)){const e=form.elements[k];if(!e)continue;if(e.type==='checkbox')e.checked=!!v;else e.value=v??'';}}
|
||||
function familyFormError(form,error){
|
||||
@@ -35,14 +49,17 @@ function renderFamily(){
|
||||
const people=family.people.filter(p=>($('#family-archived').checked||!p.archived)&&personSearch(p).includes(term));
|
||||
$('#family-count').textContent=family.people.filter(p=>!p.archived).length+' 位人物 · '+family.links.filter(e=>e.active).length+' 条关系'+(term?' · 找到 '+people.length+' 位':'');
|
||||
$('#family-find').hidden=!term;$('#family-find').disabled=!people.length;
|
||||
$('#new-person').hidden=!family.canEdit;
|
||||
$('#new-person').hidden=!family.canEdit&&!family.editScope?.canCreateSelf;
|
||||
$('#new-person').textContent=family.editScope?.canCreateSelf?'+ 建立我的人物档案':'+ 录入亲属';
|
||||
$('#family-edit-note').textContent=family.editScope?.note||'';
|
||||
$('#family-people').innerHTML=people.map(p=>`<button class="person-card ${p.id===focusPerson?'selected':''} ${p.id===family.selfId?'self':''}" data-person="${p.id}" aria-pressed="${p.id===focusPerson}"><strong>${esc(p.name)} ${p.id===family.selfId?'<span class="self-badge">本人</span>':''}</strong><span>${esc(p.id===reference&&p.id!==family.selfId?'参照人物':ZhaoKinship.describe(family.people,family.links,reference,p.id))}</span><small>${esc(p.birthDate||'出生待考')}${p.archived?' · 已归档':''}</small></button>`).join('')||empty(term?'没有找到这个人物':'从一个人物开始',term?'可换用姓名、别名或籍贯查找。':'可先录入自己,再逐步补齐父母、祖先和后辈。');
|
||||
renderFamilyTree();
|
||||
const p=family.people.find(p=>p.id===focusPerson);
|
||||
$('#family-detail').classList.toggle('is-self',p?.id===family.selfId&&!!p);
|
||||
if(!p){$('#family-detail').innerHTML='<h3>人物档案</h3><p class="description">点击图中的人物查看生平,或录入第一位人物。</p>';return;}
|
||||
const edges=family.links.filter(e=>e.fromId===p.id||e.toId===p.id);
|
||||
$('#family-detail').innerHTML=`<div class="section-head"><div><span class="eyebrow">人物档案</span><h2>${esc(p.name)}</h2></div>${family.canEdit?`<button data-edit-person="${p.id}" class="quiet">编辑人物</button><button class="quiet" data-history-kind="person" data-history-id="${p.id}">修改记录</button>`:''}</div><p class="description">相对于 ${esc(personName(reference))}:${esc(p.id===reference&&p.id!==family.selfId?'参照人物':ZhaoKinship.describe(family.people,family.links,reference,p.id))}</p><dl>${[['别名',p.alias],['性别',{male:'男',female:'女',unknown:'待确认'}[p.gender]],['在世情况',{alive:'在世',deceased:'已故',unknown:'待确认'}[p.lifeStatus]],['出生日期',ZhaoCalendar.describe(p.birthDate)],...(p.lifeStatus==='deceased'?[['去世日期',ZhaoCalendar.describe(p.deathDate)]]:[]),['籍贯(祖籍)',personLocation(p,'native')],['出生地',personLocation(p,'birth')],...(p.birthplace?[['原地域记录',p.birthplace]]:[])].map(([k,v])=>`<div><dt>${k}</dt><dd>${esc(v||'待补充')}</dd></div>`).join('')}</dl><h3>生平与记载</h3><p class="family-prose">${esc(p.biography||'尚未记录生平')}</p><p class="description family-prose">${esc(p.note||'')}</p><div class="section-head"><h3>亲属关系</h3>${family.canEdit?'<button id="add-relation" class="quiet">+ 连接亲属</button>':''}</div>${edges.map(e=>`<div class="family-link"><span>${esc(relationText(e))}<small>${esc(({biological:'亲生',adoptive:'收养',step:'继亲',unspecified:''}[e.lineage]||'')+' '+(e.note||''))}</small></span>${family.canEdit?`<button class="quiet" data-edit-relation="${e.id}">编辑</button><button class="quiet" data-history-kind="link" data-history-id="${e.id}">历史</button>`:''}</div>`).join('')||'<p class="description">尚未连接亲属。</p>'}`;
|
||||
$('#family-detail').innerHTML=`<div class="section-head"><div><span class="eyebrow">人物档案</span><h2>${esc(p.name)}</h2></div>${familyEditable('person',p.id)?`<button data-edit-person="${p.id}" class="quiet">编辑人物</button><button class="quiet" data-history-kind="person" data-history-id="${p.id}">修改记录</button>`:''}</div><p class="description">相对于 ${esc(personName(reference))}:${esc(p.id===reference&&p.id!==family.selfId?'参照人物':ZhaoKinship.describe(family.people,family.links,reference,p.id))}</p><dl>${[['别名',p.alias],['性别',{male:'男',female:'女',unknown:'待确认'}[p.gender]],['在世情况',{alive:'在世',deceased:'已故',unknown:'待确认'}[p.lifeStatus]],['出生日期',ZhaoCalendar.describe(p.birthDate)],...(p.lifeStatus==='deceased'?[['去世日期',ZhaoCalendar.describe(p.deathDate)]]:[]),['籍贯(祖籍)',personLocation(p,'native')],['出生地',personLocation(p,'birth')],...(p.birthplace?[['原地域记录',p.birthplace]]:[])].map(([k,v])=>`<div><dt>${k}</dt><dd>${esc(v||'待补充')}</dd></div>`).join('')}</dl><h3>生平与记载</h3><p class="family-prose">${esc(p.biography||'尚未记录生平')}</p><p class="description family-prose">${esc(p.note||'')}</p><div class="section-head"><h3>亲属关系</h3>${familyEditable('person',p.id)?'<button id="add-relation" class="quiet">+ 连接亲属</button>':''}</div>${edges.map(e=>`<div class="family-link"><span>${esc(relationText(e))}<small>${esc(({biological:'亲生',adoptive:'收养',step:'继亲',unspecified:''}[e.lineage]||'')+' '+(e.note||''))}</small></span>${familyEditable('link',e.id)?`<button class="quiet" data-edit-relation="${e.id}">编辑</button><button class="quiet" data-history-kind="link" data-history-id="${e.id}">历史</button>`:''}</div>`).join('')||'<p class="description">尚未连接亲属。</p>'}`;
|
||||
$('#family-detail').insertAdjacentHTML('afterbegin',`<p class="alert alert-light border">${esc(familyScopeLabel(p.id))}</p>`);
|
||||
if(typeof personEventSummary==='function')$('#family-detail').insertAdjacentHTML('beforeend',personEventSummary(p.id));
|
||||
$('#family-detail').insertAdjacentHTML('afterbegin',`${p.id===family.selfId?'<div class="family-self-heading">◎ 本人 · 当前账号关联人物</div>':''}<button type="button" id="family-show-person" class="quiet family-back-to-map">在图中定位</button>`);
|
||||
}
|
||||
@@ -56,27 +73,38 @@ function renderFamilyTree(){
|
||||
familyMap.render({...family,focusId:focusPerson,reference:$('#family-reference').value,term:$('#family-search').value.trim().toLowerCase(),showArchived:$('#family-archived').checked});
|
||||
}
|
||||
function selectFamilyPerson(id,locate=false){focusPerson=id;if(locate){familyView='tree';if(family.people.find(p=>p.id===id)?.archived)$('#family-archived').checked=true;}renderFamily();if(locate)familyMap.locate(id);if(window.innerWidth<=1000&&!document.fullscreenElement)$('#family-detail').scrollIntoView({behavior:'smooth',block:'start'});}
|
||||
function openPerson(id){if(!family.canEdit)return;const p=family.people.find(p=>p.id===id)||{};fillForm($('#person-form'),{...p,revision:family.revision});ZhaoGeography.fill($('#person-form'),p);$('#person-legacy-place').hidden=!p.birthplace;initDateFields();$('#person-dialog').showModal();}
|
||||
function openRelation(id){if(!family.canEdit)return;if(family.people.length<2){toast('请先录入另一位亲属,再连接关系');return;}const f=$('#relation-form');f.elements.fromId.innerHTML=peopleOptions(false);f.elements.toId.innerHTML=peopleOptions(false);const edge=family.links.find(e=>e.id===id);fillForm(f,{...(edge||{fromId:focusPerson,active:true}),revision:family.revision});if(!edge)f.elements.toId.value=family.people.find(p=>p.id!==focusPerson)?.id||'';$('#relation-dialog').showModal();}
|
||||
function openPerson(id){
|
||||
const self=!id&&family.editScope?.canCreateSelf;
|
||||
if(id?!familyEditable('person',id):!family.canEdit&&!self)return;
|
||||
const p=family.people.find(p=>p.id===id)||{},f=$('#person-form');
|
||||
f.elements.relativeId.innerHTML=editablePeopleOptions();
|
||||
fillForm(f,{...p,revision:family.revision});f.dataset.asSelf=String(!!self);
|
||||
$('#person-relative-fields').hidden=!!id||!!self;f.elements.relativeId.required=!id&&!self;
|
||||
if(!id&&!self)f.elements.relativeId.value=familyEditable('person',focusPerson)?focusPerson:family.selfId;
|
||||
$('#person-self-note').hidden=!self;
|
||||
if(self)f.elements.name.value=currentUser?.name||'';
|
||||
ZhaoGeography.fill(f,p);$('#person-legacy-place').hidden=!p.birthplace;initDateFields();$('#person-dialog').showModal();
|
||||
}
|
||||
function openRelation(id){if(!family.canEdit||id&&!familyEditable('link',id))return;if(family.people.length<2){toast('请先录入另一位亲属,再连接关系');return;}const f=$('#relation-form');f.elements.fromId.innerHTML=peopleOptions(false);f.elements.toId.innerHTML=peopleOptions(false);const edge=family.links.find(e=>e.id===id);fillForm(f,{...(edge||{fromId:focusPerson,active:true}),revision:family.revision});if(!edge)f.elements.toId.value=family.people.find(p=>p.id!==focusPerson)?.id||'';$('#relation-dialog').showModal();}
|
||||
for(const [name,path]of [['person','person'],['relation','link']]){
|
||||
$('#'+name+'-form').addEventListener('submit',async e=>{
|
||||
e.preventDefault();const f=e.currentTarget,b=f.querySelector('[type=submit]');b.disabled=true;
|
||||
try{const d=formValues(f);d.revision=Number(d.revision);if(name==='person'){syncDateFields(true);Object.assign(d,formValues(f));d.revision=Number(d.revision);d.archived=f.elements.archived.checked;}else d.active=f.elements.active.checked;
|
||||
const result=await api('/api/family/'+path,d);if(name==='person')focusPerson=result.item.id;f.closest('dialog').close();const loaded=await loadFamily();if(loggedIn)toast(loaded?'家谱已保存':'家谱已保存,读取最新资料失败,请重新载入');
|
||||
try{const d=formValues(f);d.revision=Number(d.revision);if(name==='person'){syncDateFields(true);Object.assign(d,formValues(f));d.revision=Number(d.revision);d.archived=f.elements.archived.checked;d.asSelf=f.dataset.asSelf==='true';}else d.active=f.elements.active.checked;
|
||||
const result=await api('/api/family/'+path,d);if(name==='person')focusPerson=result.item.id;f.closest('dialog').close();if(d.asSelf){await auth();if(loggedIn){showPage('family');toast('本人人物已建立,维护范围已生效');}}else{const loaded=await loadFamily();if(loggedIn)toast(loaded?'家谱已保存':'家谱已保存,读取最新资料失败,请重新载入');}
|
||||
}catch(err){familyFormError(f,err);}finally{b.disabled=false;}
|
||||
});
|
||||
}
|
||||
async function loadUsers(){
|
||||
if(!isAdmin())return;const id=currentUser.id;
|
||||
try{const [u,f]=await Promise.all([api('/api/users'),api('/api/family')]);if(!loggedIn||currentUser?.id!==id)return;users=u.users;family=f;
|
||||
$('#user-list').innerHTML=`<div class="table-wrap"><table class="device-table"><thead><tr><th>账号</th><th>角色 / 状态</th><th>人物关系</th><th>家谱 / 传承资料</th><th>摄像头空间</th><th></th></tr></thead><tbody>${users.map(u=>`<tr><td>${esc(u.name)}<small>${esc(u.username)}</small></td><td>${roleName(u)}${u.disabled?' · 已停用':''}</td><td>${u.relationship==='本人'&&u.relatedToId===u.id?'本人':u.relationship?esc(u.name+' 是 '+(users.find(x=>x.id===u.relatedToId)?.name||'(参照待指定)')+' 的 '+u.relationship):'未设置'}<small>家谱:${esc(personName(u.personId))}</small></td><td>${u.role!=='member'?'管理本归属':({none:'不可访问',read:'查看',edit:'录入和维护'}[u.familyAccess])}<small>文化与财产:${u.role!=='member'?'管理':({none:'不可访问',read:'查看',edit:'维护'}[u.heritageAccess||'none'])}</small></td><td>${u.role!=='member'?'本归属全部区域':esc((u.siteIds.map(siteName).join('、')||'未授权')+(u.includeSubspaces?'(含下级区域)':''))}</td><td><button class="quiet" data-edit-user="${u.id}">编辑账号</button></td></tr>`).join('')}</tbody></table></div>`;
|
||||
$('#user-list').innerHTML=`<div class="table-wrap"><table class="device-table"><thead><tr><th>账号</th><th>角色 / 状态</th><th>人物关系</th><th>家谱 / 传承资料</th><th>摄像头空间</th><th></th></tr></thead><tbody>${users.map(u=>`<tr><td>${esc(u.name)}<small>${esc(u.username)}</small></td><td>${roleName(u)}${u.disabled?' · 已停用':''}</td><td>${u.relationship==='本人'&&u.relatedToId===u.id?'本人':u.relationship?esc(u.name+' 是 '+(users.find(x=>x.id===u.relatedToId)?.name||'(参照待指定)')+' 的 '+u.relationship):'未设置'}<small>家谱:${esc(personName(u.personId))}</small></td><td>${u.role!=='member'||u.familyAccess==='edit'?(u.personId?'维护本人上下五代':'查看 · 待关联本人'):({none:'不可访问',read:'查看'}[u.familyAccess])}<small>文化与财产:${u.role!=='member'?'管理':({none:'不可访问',read:'查看',edit:'维护'}[u.heritageAccess||'none'])}</small></td><td>${u.role!=='member'?'本归属全部区域':esc((u.siteIds.map(siteName).join('、')||'未授权')+(u.includeSubspaces?'(含下级区域)':''))}</td><td><button class="quiet" data-edit-user="${u.id}">编辑账号</button></td></tr>`).join('')}</tbody></table></div>`;
|
||||
return true;
|
||||
}catch(e){if(!e.stale)toast(e.message);return false;}
|
||||
}
|
||||
function openUser(id){
|
||||
if(!isAdmin())return;const f=$('#user-form'),u=users.find(u=>u.id===id)||{};
|
||||
f.elements.personId.innerHTML=peopleOptions();f.elements.relatedToId.innerHTML='<option value="">尚未指定</option>'+users.map(u=>`<option value="${u.id}">${esc(u.name+' / '+u.username)}</option>`).join('');
|
||||
fillForm(f,u);f.elements.password.required=!u.id;
|
||||
fillForm(f,u);f.elements.password.required=!u.id;f.elements.personId.disabled=!!u.personId;
|
||||
f.elements.role.querySelector('[value=admin]').hidden=!isPlatformAdmin();
|
||||
$('#user-sites').innerHTML=state.sites.map(s=>`<label class="check"><input type="checkbox" name="siteIds" value="${s.id}" ${(u.siteIds||[]).includes(s.id)?'checked':''}>${esc(siteName(s.id))}</label>`).join('');$('#user-dialog').showModal();
|
||||
}
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
'use strict';
|
||||
// Pure range logic shared by the UI and regression tests. All ranges are [start,end).
|
||||
const RecordingRanges=(()=>{
|
||||
// Date truncates fractional milliseconds. Round the query start inward so
|
||||
// MediaMTX never receives a time before this segment's microsecond timestamp.
|
||||
function firstMillisecond(value){
|
||||
const time=+new Date(value),fraction=typeof value==='string'&&value.match(/\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/);
|
||||
return time+(fraction&&/[1-9]/.test(fraction[1].slice(3))?1:0);
|
||||
}
|
||||
function normalize(items,start,end){
|
||||
const lo=+start,hi=+end;if(!Number.isFinite(lo)||!Number.isFinite(hi)||hi<=lo)return [];
|
||||
const ranges=(Array.isArray(items)?items:[]).filter(s=>s&&Number.isFinite(+new Date(s.start))&&Number.isFinite(Number(s.duration))&&Number(s.duration)>0).map(s=>({start:Math.max(lo,+new Date(s.start)),end:Math.min(hi,+new Date(s.start)+Number(s.duration)*1000)}))
|
||||
const ranges=(Array.isArray(items)?items:[]).filter(s=>s&&Number.isFinite(+new Date(s.start))&&Number.isFinite(Number(s.duration))&&Number(s.duration)>0).map(s=>({start:Math.max(lo,firstMillisecond(s.start)),end:Math.min(hi,Math.floor(+new Date(s.start)+Number(s.duration)*1000))}))
|
||||
.filter(s=>Number.isFinite(s.start)&&Number.isFinite(s.end)&&s.end>s.start).sort((a,b)=>a.start-b.start);
|
||||
const result=[];for(const r of ranges){const last=result.at(-1);if(last&&r.start<=last.end)last.end=Math.max(last.end,r.end);else result.push({...r});}return result;
|
||||
}
|
||||
function at(ranges,time){const t=+time,s=ranges.find(s=>t>=s.start&&t<s.end);return s?{start:t,end:Math.min(s.end,t+3600000)}:null;}
|
||||
function at(ranges,time){const t=+time,s=ranges.find(s=>t>=s.start&&t<s.end);return s?{start:t,end:Math.min(s.end,t+300000)}:null;}
|
||||
function next(ranges,end){const s=ranges.find(s=>s.end>+end);return s?at(ranges,Math.max(s.start,+end)):null;}
|
||||
function clip(ranges,start,end){
|
||||
const a=+start,b=+end;
|
||||
|
||||
+27
-6
@@ -1,10 +1,21 @@
|
||||
'use strict';
|
||||
let playbackRange=null;
|
||||
function playbackSourceHint(){if($('#archive-source').value==='recorder')$('#play-info').textContent='录像机原有录像待接入;查看本系统保存的录像请选择“小电脑本机录像”。';}
|
||||
let playbackRange=null,playbackPausedAt=0;
|
||||
function playbackSourceHint(){renderRecordingStatus();if($('#archive-source').value==='recorder')$('#play-info').textContent='录像机原有录像待接入;查看本系统保存的录像请选择“小电脑本机录像”。';}
|
||||
|
||||
function renderRecordingStatus(){
|
||||
const camera=state.cameras.find(c=>c.id===$('#play-camera').value),box=$('#recording-health');
|
||||
box.hidden=!camera||$('#archive-source').value==='recorder';if(box.hidden)return;
|
||||
const messages={recording:'正在录像 · 主码流持续保存',off:'未开启本机录像 · 实时画面接通不代表已保存录像',disabled:'录像已暂停 · 设备连接已停用',paused:'录像已暂停 · 已触发容量或磁盘保护',unavailable:'录像服务未连接 · 请联系管理员检查服务',offline:'等待摄像头接通 · 当前没有新录像写入',waiting:'已开启录像 · 等待文件写入,请稍候;若持续等待请检查存储'};
|
||||
$('#recording-health-text').textContent=messages[camera.recordingState]||'正在读取录像状态';
|
||||
const policy=state.storage||{};
|
||||
$('#recording-policy-note').textContent=policy.retentionDays?`最长保留 ${policy.retentionDays} 天,过期自动清理;全平台录像上限 ${policy.maxGB} GB,磁盘预留 ${policy.reserveGB} GB。容量不足会提前暂停,实际可留时长取决于码率和路数。`:'录像由服务器按保留策略自动管理。';
|
||||
$('#recording-start-note').textContent='本机只保存开启录像期间的画面。新录像按 5 分钟分段保存,回放查询可能稍有延迟。';
|
||||
const button=$('#recording-configure');button.hidden=!isAdmin();button.dataset.editCamera=camera.id;
|
||||
}
|
||||
|
||||
function localDateTime(value){const d=new Date(value);return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}T${d.toTimeString().slice(0,8)}`;}
|
||||
function resetPlayback(){
|
||||
playbackGeneration++;playbackRange=null;const v=$('#play-video');v.pause();v.removeAttribute('src');v.load();
|
||||
playbackGeneration++;playbackRange=null;playbackPausedAt=0;const v=$('#play-video');v.pause();v.removeAttribute('src');v.load();
|
||||
$('#play-empty').hidden=false;$('#download').hidden=true;$('#clip-download').hidden=true;$('#clip-status').textContent='';$('#clip-form').reset();
|
||||
spans=[];queryCamera='';queryStart=null;queryEnd=null;$('#play-info').textContent='选择日期,查看实际录像时段';$('#play-position').textContent='';drawTimeline();$('#recording-list').innerHTML='';
|
||||
}
|
||||
@@ -31,8 +42,8 @@ function drawTimeline(){
|
||||
function playbackParams(range){return new URLSearchParams({camera:queryCamera,start:new Date(range.start).toISOString(),duration:String((range.end-range.start)/1000)});}
|
||||
function playAt(date,preserveClip=false){
|
||||
const range=RecordingRanges.at(spans,date);if(!range){toast('这个时间没有录像,请选择绿色时段');return;}
|
||||
playbackRange=range;const params=playbackParams(range),v=$('#play-video');v.src='/media/playback?'+params;v.play().catch(()=>{});
|
||||
$('#play-info').textContent='回放起点 '+new Date(range.start).toLocaleString()+' · 每次最多一小时,结束后按续播选项处理';$('#play-empty').hidden=true;
|
||||
playbackPausedAt=0;playbackRange=range;const params=playbackParams(range),v=$('#play-video');v.src='/media/playback?'+params;v.play().catch(()=>{});
|
||||
$('#play-info').textContent='回放起点 '+new Date(range.start).toLocaleString()+' · 每段最多 5 分钟,按续播选项连续播放';$('#play-empty').hidden=true;
|
||||
$('#download').href='/media/playback?'+params+'&download=1';$('#download').setAttribute('download','recording.mp4');$('#download').hidden=false;
|
||||
if(!preserveClip){$('#clip-start').value=localDateTime(range.start);$('#clip-end').value=localDateTime(range.end);$('#clip-download').hidden=true;$('#clip-status').textContent='可修改起止时间后生成下载链接';}
|
||||
}
|
||||
@@ -44,6 +55,15 @@ function continuePlayback(){
|
||||
if(!next){$('#play-info').textContent='所选日期的已查询录像播放完毕';return;}
|
||||
playAt(new Date(next.start),true);if(next.start>end)$('#play-info').textContent=`已跳过无录像时段,续播 ${new Date(next.start).toLocaleString()}`;
|
||||
}
|
||||
function pausePlayback(){
|
||||
const v=$('#play-video');if(playbackRange&&!v.ended)playbackPausedAt=Date.now();
|
||||
}
|
||||
function resumePlayback(){
|
||||
const elapsed=playbackPausedAt?Date.now()-playbackPausedAt:0;playbackPausedAt=0;
|
||||
if(elapsed<12000||!loggedIn||activePage!=='playback'||!playbackRange)return;
|
||||
const time=playbackRange.start+$('#play-video').currentTime*1000;
|
||||
if(time<playbackRange.end)playAt(new Date(time),true);
|
||||
}
|
||||
function makeClip(){
|
||||
$('#clip-download').hidden=true;
|
||||
try{if(!queryCamera)throw Error('请先查询录像');const range=RecordingRanges.clip(spans,new Date($('#clip-start').value),new Date($('#clip-end').value));
|
||||
@@ -51,11 +71,12 @@ function makeClip(){
|
||||
}catch(e){$('#clip-status').textContent=e.message;}
|
||||
}
|
||||
$('#query-recordings').onclick=queryRecordings;
|
||||
$('#play-camera').onchange=()=>{resetPlayback();const c=state.cameras.find(c=>c.id===$('#play-camera').value);$('#archive-source').value=c?.archiveSource||'local';};$('#archive-source').onchange=()=>{resetPlayback();playbackSourceHint();};$('#play-date').onchange=resetPlayback;
|
||||
$('#play-camera').onchange=()=>{resetPlayback();const c=state.cameras.find(c=>c.id===$('#play-camera').value);$('#archive-source').value=c?.archiveSource||'local';playbackSourceHint();};$('#archive-source').onchange=()=>{resetPlayback();playbackSourceHint();};$('#play-date').onchange=resetPlayback;
|
||||
$('#seek-button').onclick=()=>{if(!queryCamera){toast('请先查询录像');return;}playAt(new Date($('#play-date').value+'T'+$('#seek-time').value));};
|
||||
$('#timeline').onclick=e=>{if(!queryStart)return;const r=e.currentTarget.getBoundingClientRect();playAt(new Date(+queryStart+(queryEnd-queryStart)*(e.clientX-r.left)/r.width));};
|
||||
$('#play-video').onerror=()=>{if($('#play-video').getAttribute('src'))$('#play-info').textContent='回放失败:请稍后重试,或下载原始片段;服务器最多同时转换两个回放。';};
|
||||
$('#play-video').onplaying=()=>{$('#play-empty').hidden=true;};$('#play-video').onended=continuePlayback;
|
||||
$('#play-video').onpause=pausePlayback;$('#play-video').onplay=resumePlayback;
|
||||
$('#play-video').ontimeupdate=()=>{if(playbackRange)$('#play-position').textContent='录像时间 '+new Date(Math.min(playbackRange.end,playbackRange.start+$('#play-video').currentTime*1000)).toLocaleString();};
|
||||
$('#clip-form').onsubmit=e=>{e.preventDefault();makeClip();};
|
||||
for(const id of ['clip-start','clip-end'])$('#'+id).oninput=()=>{$('#clip-download').hidden=true;$('#clip-status').textContent='起止时间已修改,请重新生成链接';};
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+2
-2
@@ -1,3 +1,3 @@
|
||||
<!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-BbCjyE-W.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/index-r3VkLczt.css">
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#244d43"><link rel="icon" href="/zhao-icon.png"><link rel="apple-touch-icon" href="/zhao-icon.png"><title>赵府 · 智能数字管家</title> <script type="module" crossorigin src="/ui/assets/index-OX4XEEVF.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/ui/assets/index-BOIfNXlB.css">
|
||||
</head><body><div id="app"></div></body></html>
|
||||
|
||||
Reference in New Issue
Block a user