mam.py 4.08 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
    iq = await self.core.xmpp.plugin['xep_0030'].get_info(jid=remote_jid)
    if 'urn:xmpp:mam:2' not in iq['disco_info'].get_features():
        return self.core.information("This MUC doesn't support MAM.", "Error")
48 49 50 51 52 53
    if top:
        results = self.core.xmpp['xep_0313'].retrieve(jid=self.remote_jid,
        iterator=True, reverse=top, end=self.end_date)
    else:
        results = self.core.xmpp['xep_0313'].retrieve(jid=self.remote_jid,
        iterator=True, reverse=top, start=self.start_date, end=self.end_date)
54 55
    msg_count = 0
    msgs = []
56 57
    timestamp = datetime.now()
    add_line(text_buffer, 'Start of MAM query: ', timestamp, 'MAM', top)
58
    async for rsm in results:
59 60 61 62
        if top:
            for msg in rsm['mam']['results']:
                msgs.append(msg)
                if msg_count == 10:
63
                    self.query_id = 0
Madhur Garg's avatar
Madhur Garg committed
64 65
                    timestamp = datetime.now()
                    add_line(text_buffer, 'End of MAM query: ', timestamp, 'MAM', top)
Madhur Garg's avatar
Madhur Garg committed
66
                    self.core.refresh_window()
67 68 69 70 71 72 73
                    return
                msg_count += 1
            msgs.reverse()
            for msg in msgs:
                forwarded = msg['mam_result']['forwarded']
                timestamp = forwarded['delay']['stamp']
                message = forwarded['stanza']
74
                add_line(text_buffer, message['body'], timestamp, str(message['from']), top)
75 76 77 78 79 80
                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']
81
                add_line(text_buffer, message['body'], timestamp, str(message['from']), top)
82
                self.core.refresh_window()
83
    self.query_id = 0
84 85
    timestamp = datetime.now()
    add_line(text_buffer, 'End of MAM query: ', timestamp, 'MAM', top)
86 87 88 89 90 91 92 93 94 95 96


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
97 98 99
    tzone = datetime.now().astimezone().tzinfo
    end = end.replace(tzinfo=tzone).astimezone(tz=timezone.utc)
    end = end.replace(tzinfo=None)
100
    end = datetime.strftime(end, '%Y-%m-%dT%H:%M:%SZ')
101
    start = False
102
    top = True
Madhur Garg's avatar
Madhur Garg committed
103 104 105 106
    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))
107
        self.query_id = 1
Madhur Garg's avatar
Madhur Garg committed
108 109 110 111
        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