mam.py 1.82 KB
Newer Older
1 2 3 4 5 6 7 8
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
    Query and control an archive of messages stored on a server using
    XEP-0313: Message Archive Management(MAM).
"""

Madhur Garg's avatar
Madhur Garg committed
9
import asyncio
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
from datetime import datetime, timezone
from poezio.theming import get_theme
from poezio.text_buffer import Message, TextBuffer


def add_line(text_buffer: TextBuffer, text: str, str_time: str, nick: str):
    """Adds a textual entry in the TextBuffer"""

    time = datetime.strftime(str_time, '%Y-%m-%d %H:%M:%S')
    time = datetime.strptime(time, '%Y-%m-%d %H:%M:%S')
    time = time.replace(tzinfo=timezone.utc).astimezone(tz=None)
    nick = nick.split('/')[1]
    color = get_theme().COLOR_OWN_NICK
    text_buffer.add_message(
        text,
        time,
        nick,
        color,
        True,  # History
        None,  # User
        False,  # Highlight
        None,  # Identifier
        None,  # str_time
        None,  # Jid
    )


Madhur Garg's avatar
Madhur Garg committed
37
class MAM:
38 39 40 41
    """
    A basic client fetching mam archive messages
    """

42
    def __init__(self, remote_jid, start, end, tab):
43 44 45 46
        self.remote_jid = remote_jid
        self.start_date = start
        self.end_date = end
        self.tab = tab
Madhur Garg's avatar
Madhur Garg committed
47
        asyncio.ensure_future(self.start())
48

Madhur Garg's avatar
Madhur Garg committed
49
    async def start(self):
50
        text_buffer = self.tab._text_buffer
Madhur Garg's avatar
Madhur Garg committed
51
        results = self.tab.core.xmpp.plugin['xep_0313'].retrieve(jid=self.remote_jid,
52 53 54 55 56 57 58 59 60 61
        iterator=True, start=self.start_date, end=self.end_date)
        async for rsm in results:
            for msg in rsm['mam']['results']:
                forwarded = msg['mam_result']['forwarded']
                timestamp = forwarded['delay']['stamp']
                message = forwarded['stanza']
                add_line(text_buffer, '%s' % message['body'], timestamp, str(message['from']))

        self.tab.text_win.pos = 0
        self.tab.core.refresh_window()