2026-10-04 11:19:14 +08:00
|
|
|
|
"""Common device responsibility fields and non-video device records."""
|
2026-10-05 19:07:19 +08:00
|
|
|
|
import ipaddress
|
|
|
|
|
|
import re
|
2026-10-16 00:35:17 +08:00
|
|
|
|
import json
|
2026-10-04 11:19:14 +08:00
|
|
|
|
class Inventory:
|
|
|
|
|
|
def __init__(self, app):
|
|
|
|
|
|
self.a = app
|
|
|
|
|
|
|
2026-10-05 19:07:19 +08:00
|
|
|
|
def candidates(self, user):
|
|
|
|
|
|
if not self.a.HOUSEHOLDS.manager(user):
|
|
|
|
|
|
return []
|
|
|
|
|
|
a = self.a
|
|
|
|
|
|
users = a.HOUSEHOLDS.objects(user, 'users')
|
|
|
|
|
|
if user['role'] == 'admin' and not any(u['id'] == user['id'] for u in users):
|
|
|
|
|
|
users.append(user)
|
2026-10-18 20:00:43 +08:00
|
|
|
|
members = a.MEMBERS.snapshot(user)['items']
|
|
|
|
|
|
eligible = {m['personId'] for m in members if m['status'] != 'historical' and m['lifeStatus'] != 'deceased'}
|
|
|
|
|
|
result = [dict(ref='person:'+p['id'], name=p['name'], label=p['name']+' · '+p['id'][-4:], kind='家庭成员')
|
|
|
|
|
|
for p in a.HOUSEHOLDS.objects(user, 'people') if p['id'] in eligible and not p.get('archived')]
|
|
|
|
|
|
# Preserve optional account contacts for offices/external maintainers; a login
|
|
|
|
|
|
# grant does not make that account a real household member.
|
|
|
|
|
|
result += [dict(ref='user:'+u['id'], name=u['name'], label=u['name']+' / '+u['username'], kind='授权账号联系人')
|
|
|
|
|
|
for u in users if not u.get('disabled') and u.get('personId') not in eligible]
|
2026-10-05 19:07:19 +08:00
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
def display(self, item):
|
|
|
|
|
|
result = dict(item)
|
2026-10-25 14:35:24 +08:00
|
|
|
|
result['powerManaged'] = self.a.POWER.managed(item)
|
|
|
|
|
|
if self.a.get_object('devices',item['id']):
|
|
|
|
|
|
result.update(self.a.TYPES.instance(item))
|
|
|
|
|
|
if result['fbType']=='computer.power.v1':
|
|
|
|
|
|
state=self.a.POWER.power(item['id'])
|
|
|
|
|
|
result['dataInstance']['values'].update(RUN=None if state['run'] is None else bool(state['run']),
|
|
|
|
|
|
OP=state['op'],BUSY=bool(state['op']),RESULT=(state['last'] or {}).get('result',''))
|
|
|
|
|
|
result['dataInstance']['checkedAt']=state['checkedAt']
|
|
|
|
|
|
result['dataInstance']['quality']=state['state']
|
2026-10-05 19:07:19 +08:00
|
|
|
|
for prefix in ('owner', 'manager'):
|
|
|
|
|
|
ref = item.get(prefix+'Ref', '')
|
|
|
|
|
|
kind, _, key = ref.partition(':')
|
|
|
|
|
|
target = self.a.get_object({'user':'users','person':'people'}.get(kind, 'users'), key) if key else None
|
2026-10-18 20:00:43 +08:00
|
|
|
|
family = self.a.HOUSEHOLDS.family_of(item)
|
|
|
|
|
|
valid = target and (self.a.HOUSEHOLDS.family_of(target) == family or
|
|
|
|
|
|
kind == 'user' and self.a.HOUSEHOLDS.grant(target, family) or
|
|
|
|
|
|
kind == 'person' and any(m['personId'] == key for m in self.a.MEMBERS.rows(family)))
|
|
|
|
|
|
if valid:
|
2026-10-05 19:07:19 +08:00
|
|
|
|
result[prefix+'Name'] = target['name']
|
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
def metadata(self, data, old=None, user=None):
|
2026-10-04 11:19:14 +08:00
|
|
|
|
old = old or {}
|
|
|
|
|
|
result = {k: self.a.clean_text(data.get(k, old.get(k, '')), 80)
|
|
|
|
|
|
for k in ('ownerName', 'managerName')}
|
2026-10-05 19:07:19 +08:00
|
|
|
|
candidates = {p['ref']:p for p in self.candidates(user)}
|
|
|
|
|
|
for prefix in ('owner', 'manager'):
|
|
|
|
|
|
field = prefix+'Ref'
|
|
|
|
|
|
ref = self.a.clean_text(data.get(field, old.get(field, '')), 64)
|
|
|
|
|
|
if ref:
|
|
|
|
|
|
if ref in candidates:
|
|
|
|
|
|
result[prefix+'Name'] = candidates[ref]['name']
|
|
|
|
|
|
elif ref == old.get(field):
|
|
|
|
|
|
result[prefix+'Name'] = self.display(old).get(prefix+'Name', '')
|
|
|
|
|
|
else:
|
|
|
|
|
|
raise self.a.Problem('请选择当前家庭/场所的人员,或选择手动填写')
|
|
|
|
|
|
result[field] = ref
|
|
|
|
|
|
for field in ('managementHost','tailscaleHost'):
|
|
|
|
|
|
value = self.a.clean_text(data.get(field,old.get(field,'')),253)
|
|
|
|
|
|
if value:
|
|
|
|
|
|
try: ipaddress.ip_address(value)
|
|
|
|
|
|
except ValueError:
|
|
|
|
|
|
if re.fullmatch(r'[0-9.]+',value) or not all(re.fullmatch(r'[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?',part) for part in value.split('.')):
|
|
|
|
|
|
raise self.a.Problem('设备地址请填写 IP 或域名,不含账号、路径及端口')
|
|
|
|
|
|
result[field]=value
|
|
|
|
|
|
for field,choices in [('networkAccess',('unknown','lan','tailscale','public')),('connectionType',('unknown','wired','wifi'))]:
|
|
|
|
|
|
result[field]=data.get(field,old.get(field,'unknown'))
|
|
|
|
|
|
if result[field] not in choices:raise self.a.Problem('网络接入类型不正确')
|
|
|
|
|
|
cidr=self.a.clean_text(data.get('networkCidr',old.get('networkCidr','')),64)
|
|
|
|
|
|
if cidr:
|
|
|
|
|
|
try:cidr=str(ipaddress.ip_network(cidr,strict=True))
|
|
|
|
|
|
except ValueError:raise self.a.Problem('网段请使用 CIDR 格式,例如 192.168.8.0/24')
|
|
|
|
|
|
result['networkCidr']=cidr
|
|
|
|
|
|
uplink=self.a.clean_text(data.get('uplinkId',old.get('uplinkId','')),32)
|
|
|
|
|
|
if uplink:
|
|
|
|
|
|
records={x['id']:x for table in ('assets','recorders','devices') for x in self.a.HOUSEHOLDS.objects(user,table)}
|
|
|
|
|
|
if uplink not in records:raise self.a.Problem('上级设备不属于当前家庭/场所')
|
|
|
|
|
|
seen={data.get('id')};node=uplink
|
|
|
|
|
|
while node:
|
|
|
|
|
|
if node in seen:raise self.a.Problem('上级设备不能指向自己或形成循环')
|
|
|
|
|
|
seen.add(node);node=records.get(node,{}).get('uplinkId')
|
|
|
|
|
|
result['uplinkId']=uplink
|
2026-10-04 11:19:14 +08:00
|
|
|
|
tags = data.get('tags', old.get('tags', []))
|
|
|
|
|
|
if not isinstance(tags, list) or len(tags) > 12:
|
|
|
|
|
|
raise self.a.Problem('自定义标签最多 12 个')
|
|
|
|
|
|
result['tags'] = sorted({self.a.clean_text(tag, 40, True) for tag in tags})
|
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
def save(self, data, user):
|
|
|
|
|
|
a = self.a
|
|
|
|
|
|
with a.LOCK:
|
|
|
|
|
|
family = a.HOUSEHOLDS.prepare(user, 'devices', data, (('sites', 'siteId'),))
|
|
|
|
|
|
key = a.object_key('devices', data)
|
|
|
|
|
|
old = a.get_object('devices', key)
|
|
|
|
|
|
item = {k: a.clean_text(data.get(k, ''), 300 if k == 'note' else 120, k in ('name', 'deviceType'))
|
|
|
|
|
|
for k in ('name', 'deviceType', 'brand', 'model', 'serial', 'note')}
|
|
|
|
|
|
if item['deviceType'] in ('摄像头', '摄像机', '录像机'):
|
|
|
|
|
|
raise a.Problem('视频设备请使用摄像机或录像机档案,以保留取流与通道配置')
|
|
|
|
|
|
item.update(id=key, familyId=family, siteId=a.clean_text(data.get('siteId', ''), 32),
|
2026-10-25 14:35:24 +08:00
|
|
|
|
**self.metadata(data, old, user), **a.TYPES.preserve(data, old, user))
|
2026-10-04 11:19:14 +08:00
|
|
|
|
a.save_object('devices', item)
|
|
|
|
|
|
a.audit('保存设备档案', item['name'])
|
|
|
|
|
|
return item
|
2026-10-16 00:35:17 +08:00
|
|
|
|
|
|
|
|
|
|
def transfer(self, data, user):
|
|
|
|
|
|
a = self.a
|
|
|
|
|
|
if user.get('role') != 'admin':
|
|
|
|
|
|
raise a.Problem('跨家庭转移需要超级管理员同时管理双方家庭',403)
|
|
|
|
|
|
table = {'device':'devices','camera':'assets','recorder':'recorders'}.get(data.get('source'))
|
|
|
|
|
|
if not table: raise a.Problem('请选择设备类型')
|
|
|
|
|
|
with a.LOCK:
|
|
|
|
|
|
item = a.HOUSEHOLDS.owns(user, a.get_object(table,data.get('id')))
|
|
|
|
|
|
target = a.get_object('households',data.get('targetFamilyId'))
|
|
|
|
|
|
if not target: raise a.Problem('目标家庭不存在',404)
|
|
|
|
|
|
if target['id'] == a.HOUSEHOLDS.family_of(item): raise a.Problem('设备已经属于这个家庭')
|
|
|
|
|
|
site = a.get_object('sites',data.get('targetSiteId')) if data.get('targetSiteId') else None
|
|
|
|
|
|
if data.get('targetSiteId') and (not site or a.HOUSEHOLDS.family_of(site)!=target['id']):
|
|
|
|
|
|
raise a.Problem('目标区域不属于所选家庭')
|
|
|
|
|
|
channels = [c for c in a.objects('cameras') if table=='assets' and c.get('assetId')==item['id']
|
|
|
|
|
|
or table=='recorders' and (c.get('recorderId')==item['id'] or c.get('archiveRecorderId')==item['id'])]
|
|
|
|
|
|
if table=='recorders' and channels:
|
|
|
|
|
|
raise a.Problem('录像机仍关联摄像头,请先在镜头设置解除取流及录像来源关联,再转移')
|
|
|
|
|
|
if table=='assets' and any(c.get('recorderId') or c.get('archiveRecorderId') for c in channels):
|
|
|
|
|
|
raise a.Problem('摄像头仍关联原家庭录像机,请先解除录像机关联,再转移')
|
|
|
|
|
|
old_family = a.HOUSEHOLDS.family_of(item)
|
|
|
|
|
|
with a.DB:
|
|
|
|
|
|
for row_table, row in [(table,item)]+[('cameras',c) for c in channels]:
|
|
|
|
|
|
updated = dict(row,familyId=target['id'],siteId=site['id'] if site else '',
|
|
|
|
|
|
uplinkId='',ownerRef='',ownerName='',managerRef='',managerName='')
|
|
|
|
|
|
a.DB.execute('UPDATE '+row_table+' SET body=? WHERE id=?',(json.dumps(updated),row['id']))
|
|
|
|
|
|
# Do not leave topology links crossing family boundaries.
|
|
|
|
|
|
for other_table in ('devices','assets','recorders'):
|
|
|
|
|
|
for child in a.objects(other_table):
|
|
|
|
|
|
if child.get('uplinkId') == item['id']:
|
|
|
|
|
|
child['uplinkId']=''
|
|
|
|
|
|
a.DB.execute('UPDATE '+other_table+' SET body=? WHERE id=?',(json.dumps(child),child['id']))
|
|
|
|
|
|
a.DB.execute('UPDATE household_displays SET revoked=1 WHERE device_id=?',(item['id'],))
|
2026-10-25 14:35:24 +08:00
|
|
|
|
# Views are household-owned presentations, not portable device data.
|
|
|
|
|
|
# Remove the old household's bindings atomically with the transfer.
|
|
|
|
|
|
if table == 'devices':
|
|
|
|
|
|
for view in a.objects('device_views'):
|
|
|
|
|
|
if view.get('familyId') == old_family and view.get('dataInstanceId',view.get('deviceId')) == item['id']:
|
|
|
|
|
|
a.DB.execute('DELETE FROM device_views WHERE id=?',(view['id'],))
|
2026-10-16 00:35:17 +08:00
|
|
|
|
a.audit('转移设备家庭',item['name']+':'+old_family+' → '+target['name'])
|
|
|
|
|
|
if channels: a.write_media_config()
|
|
|
|
|
|
return {'ok':True,'id':item['id'],'familyId':target['id']}
|