mam.py 4.66 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
from poezio.theming import get_theme
12
from poezio import tabs
13 14
from poezio.text_buffer import Message, TextBuffer

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

44
async def query(self, remote_jid, start, end, top):
45 46 47 48
    self.remote_jid = remote_jid
    self.start_date = start
    self.end_date = end
    text_buffer = self._text_buffer
49 50 51
    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")
52
    if top:
53 54 55 56 57 58
        if isinstance(self, tabs.MucTab):
            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(with_jid=self.remote_jid,
            iterator=True, reverse=top, end=self.end_date)
59
    else:
60 61 62 63 64 65
        if isinstance(self, tabs.MucTab):
            results = self.core.xmpp['xep_0313'].retrieve(jid=self.remote_jid,
            iterator=True, reverse=top, start=self.start_date, end=self.end_date)
        else:
            results = self.core.xmpp['xep_0313'].retrieve(with_jid=self.remote_jid,
            iterator=True, reverse=top, start=self.start_date, end=self.end_date)
66 67
    msg_count = 0
    msgs = []
68
    timestamp = datetime.now()
69
    add_line(self, text_buffer, 'Start of MAM query: ', timestamp, 'MAM', top)
70
    async for rsm in results:
71 72 73 74
        if top:
            for msg in rsm['mam']['results']:
                msgs.append(msg)
                if msg_count == 10:
75
                    self.query_id = 0
Madhur Garg's avatar
Madhur Garg committed
76
                    timestamp = datetime.now()
77
                    add_line(self, text_buffer, 'End of MAM query: ', timestamp, 'MAM', top)
Madhur Garg's avatar
Madhur Garg committed
78
                    self.core.refresh_window()
79 80 81 82 83 84 85
                    return
                msg_count += 1
            msgs.reverse()
            for msg in msgs:
                forwarded = msg['mam_result']['forwarded']
                timestamp = forwarded['delay']['stamp']
                message = forwarded['stanza']
86
                add_line(self, text_buffer, message['body'], timestamp, str(message['from']), top)
87 88 89 90 91 92
                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']
93
                add_line(self, text_buffer, message['body'], timestamp, str(message['from']), top)
94
                self.core.refresh_window()
95
    self.query_id = 0
96
    timestamp = datetime.now()
97
    add_line(self, text_buffer, 'End of MAM query: ', timestamp, 'MAM', top)
98 99 100 101 102 103 104 105 106 107 108


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
109 110 111
    tzone = datetime.now().astimezone().tzinfo
    end = end.replace(tzinfo=tzone).astimezone(tz=timezone.utc)
    end = end.replace(tzinfo=None)
112
    end = datetime.strftime(end, '%Y-%m-%dT%H:%M:%SZ')
113
    start = False
114
    top = True
Madhur Garg's avatar
Madhur Garg committed
115 116 117 118
    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))
119
        self.query_id = 1
Madhur Garg's avatar
Madhur Garg committed
120 121 122 123
        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