Receive works!

This commit is contained in:
Alicia
2024-04-11 13:12:54 -07:00
parent 14c0812d96
commit e4f3c150cf

View File

@@ -5,11 +5,14 @@ User actions
import aiohttp import aiohttp
import asyncio import asyncio
from datetime import datetime, timedelta from datetime import datetime, timedelta
import logging
from pathlib import Path from pathlib import Path
from pytz import timezone from pytz import timezone
from typing import TYPE_CHECKING, Optional, Union from typing import TYPE_CHECKING, Optional, Union
from slidge import BaseSession, GatewayUser, LegacyContact, LegacyRoster from slidge import BaseSession, GatewayUser, LegacyContact, LegacyRoster
log = logging.getLogger(__name__)
class Contact(LegacyContact[str]): class Contact(LegacyContact[str]):
session: "Session" session: "Session"
@@ -38,10 +41,12 @@ ASSETS_DIR = Path(__file__).parent / "assets"
class Session(BaseSession[str, Contact]): class Session(BaseSession[str, Contact]):
def __init__(self, user: GatewayUser): def __init__(self, user: GatewayUser):
self.httpsession = aiohttp.ClientSession() self.httpsession = aiohttp.ClientSession()
self.stop_loop = False
super().__init__(user) super().__init__(user)
def shutdown(self): async def logout(self):
super().shutdown() self.stop_loop = True
await asyncio.sleep(10) # ensure the loop is dead
self.httpsession.close() self.httpsession.close()
async def login(self): async def login(self):
@@ -55,22 +60,30 @@ class Session(BaseSession[str, Contact]):
}) as response: }) as response:
json = await response.json() json = await response.json()
if json['status'] == 'success': if json['status'] == 'success':
self.xmpp.loop.create_task(self.poll_loop())
return f"Connected as {json['dids'][0]['did']}" return f"Connected as {json['dids'][0]['did']}"
else: else:
return f"Failure! {json['status']}" return f"Failure! {json['status']}"
async def poll_loop(): async def poll_loop(self):
while True: last_run_ids = []
last_15s = datetime.now() - timedelta(seconds=15) last_run_time = datetime.now() - timedelta(seconds=10)
messages = await get_messages(last_15s) log.debug('poll loop initiated')
while not self.stop_loop:
current_run_time = datetime.now()
messages = await self.get_messages(last_run_time - timedelta(seconds=2))
for message in messages: new_messages = [message for message in messages if message['id'] not in last_run_ids]
if 'col_media1' in message: last_run_ids = [message['id'] for message in messages]
self.xmpp.send_file(file_url=message['col1_media'], legacy_message_id=message['id'])
elif 'message' in message: for message in new_messages:
self.xmpp.send_text(message['message'], legacy_msg_id=message['id']) contact = await self.contacts.by_legacy_id(message['contact'])
await asyncio.sleep(15) if message['col_media1'] != '':
contact.send_file(file_url=message['col1_media'], legacy_message_id=message['id'])
elif message['message'] != '':
contact.send_text(message['message'], legacy_msg_id=message['id'])
last_run_time = current_run_time
await asyncio.sleep(10)
# See this issue for timezone explanation https://github.com/michaelkourlas/voipms-sms-client/issues/35 # See this issue for timezone explanation https://github.com/michaelkourlas/voipms-sms-client/issues/35
async def get_messages(self, from_time: datetime): async def get_messages(self, from_time: datetime):
@@ -87,16 +100,13 @@ class Session(BaseSession[str, Contact]):
'content_type': 'json', 'content_type': 'json',
}) as response: }) as response:
json = await response.json() json = await response.json()
log.debug(f"received messages from voipms {json}")
if json['status'] != 'success': if json['status'] != 'success':
return [] return []
else: else:
return json['sms'] return json['sms']
# SMS doesn't care about presence
async def on_presence(resource: str, show, status: str, resources, merged_resource):
pass
async def on_file(self, chat: Contact, url: str, **_kwargs): async def on_file(self, chat: Contact, url: str, **_kwargs):
f = self.user.registration_form f = self.user.registration_form
async with self.httpsession.get(API_URL, params={ async with self.httpsession.get(API_URL, params={