"""Send one fixed test message exclusively to the signed-in account itself.""" import argparse import datetime as dt import json from pathlib import Path import uuid from .live import run_math from .zip_export import evaluate PROBE = r'''(async () => { const prefs=require('WAWebUserPrefsMeUser'); const me=prefs.getMaybeMeLidUser()??prefs.getMaybeMePnUser(); if(!me||!prefs.isMeAccount(me))throw Error('Own account identity unavailable'); const {chat}=await require('WAWebFindChatAction').findOrCreateLatestChat(me,'sendSelfTest'); if(!chat||!prefs.isMeAccount(chat.id))throw Error('Refusing to send outside own account'); const action=require('WAWebSendTextMsgChatAction'); const body=__BODY__; const data=await action.createTextMsgData(chat,body,{}); if(!data?.id||!prefs.isMeAccount(data.id.remote))throw Error('Outgoing message is not addressed to self'); const id=data.id.toString(); await action.addAndSendTextMsg(chat,data); const model=chat.msgs.get(data.id)??require('WAWebMsgCollection').MsgCollection.get(data.id); const row=await require('WAWebSchemaMessage').getMessageTable().get(id); const decoded=row?require('WAWebDBMessageSerialization').messageFromDbRow(row):null; return {recipient_is_self:true,message_id:id,ack:model?.ack??null, send_completed:true,persisted:!!row,plaintext_matches:decoded?.body===body, timestamp:decoded?.t??null,body_length:body.length,cdp:false,ui_automation:false}; })()''' def send_self(output, pid=None): output=Path(output) if output.exists(): raise ValueError('Receipt exists; choose a new output. Sending is never retried automatically.') output.parent.mkdir(parents=True,exist_ok=True) body='WhatsApp JS-Sendetest an mich selbst — '+dt.datetime.now().isoformat(timespec='seconds')+' — '+uuid.uuid4().hex[:8] # Reserve the receipt before sending; a failed/uncertain attempt must be inspected before retrying. output.write_text(json.dumps({'status':'reserved','test_message':body}),encoding='utf-8') def operation(execute,session,report): result=evaluate(execute,PROBE.replace('__BODY__',json.dumps(body)),session) report['send_result']=result if not (result.get('recipient_is_self') and result.get('send_completed') and result.get('persisted') and result.get('plaintext_matches')): raise RuntimeError('Self-message send/readback verification failed; do not retry without checking the receipt') report=run_math(pid,'send-self',_operation=operation) report['test_message']=body output.write_text(json.dumps(report,indent=2),encoding='utf-8') return report def main(argv=None): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--pid',type=int) parser.add_argument('--output',type=Path,default=Path('analysis/whatsapp-suite')/('self-message-'+dt.datetime.now().strftime('%Y%m%d-%H%M%S')+'.json')) args=parser.parse_args(argv) report=send_self(args.output,args.pid) print(json.dumps({'passed':report['passed'],'error':report.get('error'),'send_result':report.get('send_result'),'receipt':str(args.output)})) return 0 if report['passed'] else 1