Files
ecs-relay-service/deployable/relay/notification_client.py
T

70 lines
3.6 KiB
Python

"""Small add-on compatible with existing WorkClient; never stores or sends recipient IDs."""
import hashlib
import httpx
def push(client, *, request_id, kind='text', text='', title='', oauth_state=''):
from .work_client import WorkError
payload = {'request_id': request_id, 'kind': kind, 'text': text,
'title': title, 'oauth_state': oauth_state, 'binding_owner': client.owner}
try:
response = client.http.post('/device/notifications', json={
**payload, 'host_id': client.config['host_id'],
'proof': client.proof('work-notify-v1', payload)})
except httpx.HTTPError:
raise WorkError('通知发送状态未知;未自动重试。请核对机器人消息,勿换新request_id重发。') from None
if response.status_code != 200:
raise WorkError(f'通知请求失败(HTTP {response.status_code}),未自动重试。')
return response.json()
def notify_authorization(client, data):
"""Best effort once per local OAuth transaction. Local authorization remains usable."""
from .work_client import atomic_secret, WorkError
if data.get('notification_attempted'):
return
data['notification_attempted'] = True
data['notification_status'] = 'unknown'
atomic_secret(client.pending, data)
try:
result = push(client, request_id='oauth_' + hashlib.sha256(data['state'].encode()).hexdigest(),
kind='authorization', oauth_state=data['state'])
data['notification_status'] = result.get('previous_status', result['status'])
except (WorkError, ValueError):
# Older ECS returns 404; direct user authorization URL remains the fallback.
data['notification_status'] = 'unconfirmed'
atomic_secret(client.pending, data)
def register_notification_tool(directory):
import json
import os
from tools.registry import registry
import toolsets
name = 'work_notification'
description = '按用户要求向本机绑定用户的Work机器人私聊发送文本或通知卡片;不能指定其他收件人。request_id须稳定,状态未知不得换ID重试。'
parameters = {'type': 'object', 'additionalProperties': False,
'properties': {'request_id': {'type':'string'}, 'kind': {'type':'string', 'enum':['text','notice']},
'text': {'type':'string'}, 'title': {'type':'string'}},
'required': ['request_id','text']}
def handle(args, **kwargs):
from .work_client import WorkClient, WorkError
client = None
try:
if set(args) - {'request_id','kind','text','title'}:
raise WorkError('不支持指定收件人或自定义卡片。')
client = WorkClient(directory, os.environ.get('HN_WORK_RELAY_URL','https://10.77.76.13'))
return json.dumps(push(client, **args), ensure_ascii=False)
except WorkError as error:
return json.dumps({'status':'unconfirmed','message':str(error)},ensure_ascii=False)
except Exception:
return json.dumps({'status':'unknown','message':'通知状态未确认,未自动重试。'},ensure_ascii=False)
finally:
if client:client.close()
registry.register(name=name,toolset='hainuo_work',schema={'name':name,'description':description,'parameters':parameters},
handler=handle,description=description)
if name not in toolsets.TOOLSETS['hainuo_work']['tools']:
toolsets.TOOLSETS['hainuo_work']['tools'].append(name)
if name not in toolsets._HERMES_CORE_TOOLS:
toolsets._HERMES_CORE_TOOLS.append(name)