Add device-bound robot notifications and automatic OAuth cards

This commit is contained in:
ex_tianzy
2026-10-28 16:33:14 +08:00
parent b774941890
commit f5a38e0808
19 changed files with 837 additions and 2 deletions
@@ -0,0 +1,64 @@
"""Apply only the notification integration, preserving installed TLS/document fixes."""
import argparse
import shutil
from datetime import datetime, timezone
from pathlib import Path
def prepare(relay_dir, source_root=None):
relay_dir=Path(relay_dir)
source_root=Path(source_root or Path(__file__).resolve().parents[1])
client=(relay_dir/'work_client.py').read_text(encoding='utf-8-sig')
tools=(relay_dir/'work_tools.py').read_text(encoding='utf-8-sig')
if 'from .notification_client import notify_authorization' not in client:
start=client.index(' def authorize(self):')
end=client.index(' def save_tokens(',start)
block=client[start:end]
old1=' return data["authorization_url"]'
old2=' return data["authorization_url"]'
if block.count(old1)!=1 or block.count('\n'+old2)!=1:
raise ValueError('Unknown authorize implementation; stopped without modifying files')
block=block.replace(old1,' from .notification_client import notify_authorization\n'
' notify_authorization(self, data)\n'+old1)
block=block.replace('\n'+old2,'\n from .notification_client import notify_authorization\n'
' notify_authorization(self, data)\n'+old2)
client=client[:start]+block+client[end:]
if 'register_notification_tool(directory)' not in tools:
marker='\ndef calendar(client, args):'
if tools.count(marker)!=1 or 'def register(directory):' not in tools:
raise ValueError('Unknown tool registration implementation; stopped without modifying files')
tools=tools.replace(marker,' from .notification_client import register_notification_tool\n'
' register_notification_tool(directory)\n\n'+marker)
updates={'work_client.py':client,'work_tools.py':tools}
for name in ['notification_client.py','notification_cli.py']:
updates[name]=(source_root/'relay'/name).read_text(encoding='utf-8-sig')
for name,text in updates.items():compile(text,name,'exec')
return updates
def apply(relay_dir, source_root=None):
relay_dir=Path(relay_dir)
updates=prepare(relay_dir,source_root)
backup=relay_dir.parent/('notification-backup-'+datetime.now(timezone.utc).strftime('%Y%m%d-%H%M%S-%f'))
backup.mkdir()
for name in updates:
target=relay_dir/name
if target.exists():shutil.copy2(target,backup/name)
for name,text in updates.items():
target=relay_dir/name
temporary=target.with_suffix('.notification-tmp')
temporary.write_text(text,encoding='utf-8')
temporary.replace(target)
print('Client integration applied. Backup:',backup)
print('Restart the native Agent after the ECS upgrade. No credentials were read or printed.')
if __name__=='__main__':
parser=argparse.ArgumentParser()
parser.add_argument('--relay-dir',type=Path,required=True)
parser.add_argument('--apply',action='store_true')
args=parser.parse_args()
if args.apply:apply(args.relay_dir)
else:
prepare(args.relay_dir)
print('Compatible client source detected; dry run only. Use --apply to write with backup.')
@@ -0,0 +1,35 @@
"""Install server source only after verifying it matches the exported baseline."""
import argparse
import hashlib
import json
import shutil
from datetime import datetime, timezone
from pathlib import Path
def install(root, package):
root,package=Path(root),Path(package)
manifest=json.loads((package/'manifest.json').read_text(encoding='utf-8'))
for name,entry in manifest.items():
incoming=package/'relay'/name
assert hashlib.sha256(incoming.read_bytes()).hexdigest()==entry['new'], 'Package checksum mismatch'
target=root/'relay'/name
current=hashlib.sha256(target.read_bytes()).hexdigest() if target.exists() else None
if current not in {entry['old'],entry['new']}:
raise ValueError('Server source differs from reviewed baseline: '+name+'; nothing modified')
backup=root/'backups'/('before-notifications-'+datetime.now(timezone.utc).strftime('%Y%m%d-%H%M%S-%f'))
backup.mkdir(parents=True)
for name in manifest:
target=root/'relay'/name
if target.exists():shutil.copy2(target,backup/name)
shutil.copy2(package/'relay'/name,target)
print('Server source backup:',backup)
print('Source updated; running containers are unchanged until image rebuild/recreation.')
if __name__=='__main__':
parser=argparse.ArgumentParser()
parser.add_argument('--root',type=Path,required=True)
parser.add_argument('--package',type=Path,required=True)
args=parser.parse_args()
install(args.root,args.package)
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env bash
set -euo pipefail
umask 077
package=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
root=$(cd "${1:?Provide the existing ECS project directory}" && pwd)
cd "$root"
test -f .env && test -f Dockerfile.offline && test -d wheelhouse
image=hainuo-relay:0.1.0
rollback="hainuo-relay:before-notifications-$(date +%Y%m%d-%H%M%S)"
docker image tag "$image" "$rollback"
echo "Rollback image: $rollback"
docker run --rm --user 0:0 --entrypoint python \
-v "$root:/work" -v "$package:/patch:ro" "$image" \
/patch/scripts/apply_notification_server.py --root /work --package /patch
docker build --network none --pull=false -f Dockerfile.offline -t "$image" .
args=(-f compose.yaml)
for extra in compose.offline.yaml compose.edge-fix.yaml compose.h5.yaml compose.work.yaml compose.feishu.yaml compose.autoreg.yaml compose.userapi.yaml; do
if [[ -f "$extra" ]]; then args+=(-f "$extra"); fi
done
# Keep existing overrides, key material, binding database and container networking.
docker compose "${args[@]}" up -d --no-build --pull never --no-deps --force-recreate connector
docker compose "${args[@]}" exec -T connector python -c 'import time,urllib.request
for _ in range(30):
try:
urllib.request.urlopen("http://127.0.0.1:8000/ready",timeout=2)
print("Connector ready; proceed with notification business acceptance.")
break
except Exception: time.sleep(1)
else: raise SystemExit("Connector not ready; preserve logs and use the recorded rollback image.")'
echo 'Only connector was recreated. Ready is not proof that the platform accepted a card.'