hermes_pairing.py 5.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. """Bot-owned WhatsApp pairing, without the Hermes Dashboard dependency graph."""
  2. import atexit
  3. import json
  4. import os
  5. from pathlib import Path
  6. import secrets
  7. import shutil
  8. import subprocess
  9. import threading
  10. import time
  11. class PairingManager:
  12. def __init__(self):
  13. self.lock=threading.RLock();self.flows={}
  14. def public(self,f):return {k:v for k,v in f.items() if k in ('pairing_id','status','qr_payload','error','expires_at','user')}
  15. def start(self,home,bridge,session,reset=False):
  16. home,bridge,session=map(lambda p:Path(p).resolve(),(home,bridge,session))
  17. with self.lock:
  18. self.flows={k:v for k,v in self.flows.items() if v['status'] in ('starting','waiting','finishing') or v['expires_at']>int((time.time()-600)*1000)}
  19. for f in self.flows.values():
  20. if f['home']==str(home) and f['status'] in ('starting','waiting','finishing'):return self.public(f)
  21. for previous in self.flows.values():
  22. if previous['home']==str(home):previous.update(status='cancelled',qr_payload=None)
  23. if (session/'creds.json').exists():
  24. if not reset:raise ValueError('已有WhatsApp会话;重新关联前请明确选择清除旧会话。')
  25. backup=home/'platforms/whatsapp/session-backups'/str(time.time_ns());backup.parent.mkdir(parents=True,exist_ok=True,mode=0o700);os.replace(session,backup)
  26. session.mkdir(parents=True,exist_ok=True,mode=0o700)
  27. identity=secrets.token_hex(16)
  28. f={'pairing_id':identity,'status':'starting','home':str(home),'expires_at':int((time.time()+600)*1000),'qr_payload':None}
  29. process=subprocess.Popen([shutil.which('node') or 'node',str(bridge/'bridge.js'),'--pair-only','--pair-json','--session',str(session)],cwd=bridge,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,encoding='utf8',start_new_session=os.name!='nt',env={**os.environ,'HERMES_HOME':str(home),'WHATSAPP_MODE':'bot','WHATSAPP_DM_POLICY':'pairing'})
  30. f['process']=process;self.flows[identity]=f
  31. timer=threading.Timer(600,lambda:self.cancel(identity,home,'expired'));timer.daemon=True;timer.start();f['timer']=timer
  32. thread=threading.Thread(target=self._watch,args=(f,process,session),daemon=True);f['thread']=thread;thread.start()
  33. return self.public(f)
  34. def _watch(self,f,process,session):
  35. connected=False
  36. try:
  37. for line in process.stdout:
  38. try:event=json.loads(line)
  39. except (ValueError,TypeError):continue
  40. with self.lock:
  41. if f['status'] not in ('starting','waiting','finishing'):continue
  42. kind=event.get('event')
  43. if kind=='qr':f.update(status='waiting',qr_payload=str(event.get('qr',''))[:20000])
  44. elif kind=='connected':connected=True;f.update(status='finishing',qr_payload=None,user=event.get('user'))
  45. elif kind=='error':f.update(status='error',error='WhatsApp关联失败,请核对账号和网络。',qr_payload=None)
  46. code=process.wait(timeout=5)
  47. with self.lock:
  48. if f['status'] in ('starting','waiting','finishing'):
  49. try:valid=isinstance(json.loads((session/'creds.json').read_text()),dict)
  50. except Exception:valid=False
  51. f.update(status='connected' if connected and code==0 and valid else 'error',qr_payload=None)
  52. if f['status']=='error':f['error']='WhatsApp关联未完成,请重试。'
  53. finally:
  54. if process.poll() is None:self._stop(process)
  55. process.stdout.close()
  56. f['timer'].cancel()
  57. def _stop(self,process):
  58. try:
  59. process.terminate();process.wait(timeout=3)
  60. except subprocess.TimeoutExpired:process.kill();process.wait(timeout=3)
  61. except ProcessLookupError:pass
  62. def get(self,identity,home):
  63. with self.lock:
  64. f=self.flows.get(identity)
  65. if not f or f['home']!=str(Path(home).resolve()):raise ValueError('关联操作不存在或已结束。')
  66. return self.public(f)
  67. def cancel(self,identity,home,status='cancelled',invalidate=False):
  68. with self.lock:
  69. self.get(identity,home);f=self.flows[identity]
  70. if invalidate or f['status'] in ('starting','waiting','finishing') or f['status']=='connected' and not f.get('applied'):f.update(status=status,qr_payload=None)
  71. process=f['process'];f['timer'].cancel()
  72. if process.poll() is None:self._stop(process)
  73. if f.get('thread') is not threading.current_thread():f['thread'].join(timeout=4)
  74. return self.public(f)
  75. def apply(self,identity,home,callback):
  76. with self.lock:
  77. self.get(identity,home);f=self.flows[identity]
  78. if f['status']!='connected':raise ValueError('关联已取消或尚未完成,请重新读取状态。')
  79. if f.get('applied'):return {'ok':True,'alreadyApplied':True}
  80. result=callback();f['applied']=True
  81. return result
  82. def invalidate_home(self,home):
  83. for identity,f in list(self.flows.items()):
  84. if f['home']==str(Path(home).resolve()):self.cancel(identity,home,invalidate=True)
  85. def close(self):
  86. for identity,f in list(self.flows.items()):self.cancel(identity,f['home'])
  87. manager=PairingManager()
  88. atexit.register(manager.close)