mam.py 4.01 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).
"""

9 10
import asyncio
from datetime import datetime, timedelta, timezone
11 12 13
from poezio.theming import get_theme
from poezio.text_buffer import Message, TextBuffer

14 15 16 17 18
def add_line(text_buffer: TextBuffer, text: str, str_time: str, nick: str, top: bool):
    """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')
19 20 21
    if '/' in nick:
        nick = nick.split('/')[1]
        color = get_theme().COLOR_OWN_NICK
Madhur Garg's avatar
Madhur Garg committed
22 23
        time = time.replace(tzinfo=timezone.utc).astimezone(tz=None)
        time = time.replace(tzinfo=None)
24 25
    else:
        color = get_theme().COLOR_ME_MESSAGE
26 27 28 29 30 31 32 33 34 35 36 37 38 39
    text_buffer.add_message(
        text,
        time,
        nick,
        color,
        True,  # History
        None,  # User
        False,  # Highlight
        top, #Top
        None,  # Identifier
        None,  # str_time
        None,  # Jid
    )

40
async def query(self, remote_jid, start, end, top):
41 42 43 44
    self.remote_jid = remote_jid
    self.start_date = start
    self.end_date = end
    text_buffer = self._text_buffer
45 46 47 48
    def callback(iq):
        if 'urn:xmpp:mam:2' not in iq['disco_info'].get_features():
            return self.core.information("This MUC doesn't support MAM.", "Error")
    self.core.xmpp.plugin['xep_0030'].get_info(jid=remote_jid, callback=callback)
49
    results = self.core.xmpp['xep_0313'].retrieve(jid=self.remote_jid,
50 51 52
    iterator=True, reverse=top, start=self.start_date, end=self.end_date)
    msg_count = 0
    msgs = []
53 54
    timestamp = datetime.now()
    add_line(text_buffer, 'Start of MAM query: ', timestamp, 'MAM', top)
55
    async for rsm in results:
56 57 58 59
        if top:
            for msg in rsm['mam']['results']:
                msgs.append(msg)
                if msg_count == 10:
Madhur Garg's avatar
Madhur Garg committed
60 61
                    timestamp = datetime.now()
                    add_line(text_buffer, 'End of MAM query: ', timestamp, 'MAM', top)
Madhur Garg's avatar
Madhur Garg committed
62
                    self.core.refresh_window()
63 64 65 66 67 68 69
                    return
                msg_count += 1
            msgs.reverse()
            for msg in msgs:
                forwarded = msg['mam_result']['forwarded']
                timestamp = forwarded['delay']['stamp']
                message = forwarded['stanza']
70
                add_line(text_buffer, message['body'], timestamp, str(message['from']), top)
71 72 73 74 75 76
                self.text_win.scroll_up(len(self.text_win.built_lines))
        else:
            for msg in rsm['mam']['results']:
                forwarded = msg['mam_result']['forwarded']
                timestamp = forwarded['delay']['stamp']
                message = forwarded['stanza']
77
                add_line(text_buffer, message['body'], timestamp, str(message['from']), top)
78
                self.core.refresh_window()
79 80
    timestamp = datetime.now()
    add_line(text_buffer, 'End of MAM query: ', timestamp, 'MAM', top)
81 82 83 84 85 86 87 88 89 90 91


def mam_scroll(self):
    remote_jid = self.jid
    text_buffer = self._text_buffer
    end = datetime.now()
    for message in text_buffer.messages:
        time = message.time
        if time < end:
            end = time
    end = end + timedelta(seconds=-1)
Madhur Garg's avatar
Madhur Garg committed
92 93 94
    tzone = datetime.now().astimezone().tzinfo
    end = end.replace(tzinfo=tzone).astimezone(tz=timezone.utc)
    end = end.replace(tzinfo=None)
95 96
    end = datetime.strftime(end, '%Y-%m-%dT%H:%M:%SZ')
    start = datetime.strptime(end, '%Y-%m-%dT%H:%M:%SZ')
97
    start = start + timedelta(days=-360)
98 99
    start = datetime.strftime(start, '%Y-%m-%dT%H:%M:%SZ')
    top = True
Madhur Garg's avatar
Madhur Garg committed
100 101 102 103 104 105 106 107
    pos = self.text_win.pos
    self.text_win.pos += self.text_win.height - 1
    if self.text_win.pos + self.text_win.height > len(self.text_win.built_lines):
        asyncio.ensure_future(query(self, remote_jid, start, end, top))
        self.text_win.pos = len(self.text_win.built_lines) - self.text_win.height
        if self.text_win.pos < 0:
            self.text_win.pos = 0
    return self.text_win.pos != pos