Fix bridging and refactor

This commit is contained in:
2025-03-13 17:26:26 +00:00
parent f802b96c24
commit 52506f86a3
14 changed files with 1264 additions and 202 deletions

View File

@@ -1,46 +0,0 @@
from signalbot import SignalBot
import aiohttp
from core.util import logs
log = logs.get_logger("signalbot")
class NewSignalBot(SignalBot):
def __init__(self, config):
super().__init__(config)
self.bot_uuid = None # Initialize with None
async def get_own_uuid(self) -> str:
"""Fetch bot's UUID by checking contacts, groups, or profile."""
async with aiohttp.ClientSession() as session:
uri_contacts = f"http://{self._signal.signal_service}/v1/contacts/{self._signal.phone_number}"
try:
resp = await session.get(uri_contacts)
if resp.status == 200:
contacts_data = await resp.json()
if isinstance(contacts_data, list):
for contact in contacts_data:
if contact.get("number") == self._phone_number:
return contact.get("uuid")
except Exception as e:
log.error(f"Failed to get UUID from contacts: {e}")
async def initialize_bot(self):
"""Fetch bot's UUID and store it in self.bot_uuid."""
try:
self.bot_uuid = await self.get_own_uuid()
if self.bot_uuid:
log.info(f"Own UUID: {self.bot_uuid}")
else:
log.warning("Unable to fetch bot UUID.")
except Exception as e:
log.error(f"Failed to initialize bot UUID: {e}")
def start(self):
"""Start bot without blocking event loop."""
self._event_loop.create_task(self.initialize_bot()) # Fetch UUID first
self._event_loop.create_task(self._detect_groups()) # Sync groups
self._event_loop.create_task(self._produce_consume_messages()) # Process messages
self.scheduler.start() # Start async job scheduler

View File

@@ -32,6 +32,33 @@ class DeferredRequest(BaseModel):
detail: Optional[DeferredDetail] = None
attachments: Optional[list] = None
async def send_message(db_obj):
recipient_uuid = db_obj.session.identifier.identifier
text = db_obj.text
send = lambda x: signalapi.send_message_raw(recipient_uuid, x) # returns ts
start_t = lambda: signalapi.start_typing(recipient_uuid)
stop_t = lambda: signalapi.stop_typing(recipient_uuid)
tss = await natural.natural_send_message(
text,
send,
start_t,
stop_t,
) # list of ts
#result = await send_message_raw(recipient_uuid, text)
await sync_to_async(db_obj.delete)()
result = [x for x in tss if x] # all trueish ts
if result: # if at least one message was sent
ts1 = result.pop() # pick a time
log.info(f"signal message create {text}")
await sync_to_async(Message.objects.create)(
user=db_obj.session.user,
session=db_obj.session,
custom_author="BOT",
text=text,
ts=ts1, # use that time in db
)
async def process_deferred(data: dict, **kwargs):
try:
@@ -59,7 +86,7 @@ async def process_deferred(data: dict, **kwargs):
return
if message.session.identifier.service == "signal":
await signal.send_message(message)
await send_message(message)
else:
log.warning(f"Protocol not supported: {message.session.identifier.service}")
@@ -76,6 +103,7 @@ async def process_deferred(data: dict, **kwargs):
service=service,
)
xmpp_attachments = []
# attachments = []
# Asynchronously fetch all attachments
tasks = [signalapi.fetch_signal_attachment(att["id"]) for att in attachments]
@@ -95,9 +123,10 @@ async def process_deferred(data: dict, **kwargs):
})
for identifier in identifiers:
#recipient_jid = f"{identifier.user.username}@{settings.XMPP_ADDRESS}"
user = identifier.user
log.info(f"Sending {len(xmpp_attachments)} attachments from Signal to XMPP.")
await xmpp.send_from_external(identifier, msg, validated_data.detail, attachments=xmpp_attachments)
await xmpp.send_from_external(user, identifier, msg, validated_data.detail, attachments=xmpp_attachments)
else:
log.warning(f"Method not yet supported: {method}")
return