mam.py 5.48 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 slixmpp.exceptions import IqError, IqTimeout
12
from poezio.theming import get_theme
13
from poezio import tabs
14 15
from poezio.text_buffer import Message, TextBuffer

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

45
async def query(self, remote_jid, start, end, top):
46 47 48 49
    self.remote_jid = remote_jid
    self.start_date = start
    self.end_date = end
    text_buffer = self._text_buffer
50 51 52 53
    try:
        iq = await self.core.xmpp.plugin['xep_0030'].get_info(jid=remote_jid)
    except (IqError, IqTimeout):
        return self.information('Failed to retrieve messages', 'Error')
54 55
    if 'urn:xmpp:mam:2' not in iq['disco_info'].get_features():
        return self.core.information("This MUC doesn't support MAM.", "Error")
56
    if top:
57
        if isinstance(self, tabs.MucTab):
58 59 60 61 62
            try:
                results = self.core.xmpp['xep_0313'].retrieve(jid=self.remote_jid,
                iterator=True, reverse=top, end=self.end_date)
            except (IqError, IqTimeout):
                return self.information('Failed to retrieve messages', 'Error')
63
        else:
64 65 66 67 68
            try:
                results = self.core.xmpp['xep_0313'].retrieve(with_jid=self.remote_jid,
                iterator=True, reverse=top, end=self.end_date)
            except (IqError, IqTimeout):
                return self.information('Failed to retrieve messages', 'Error')
69
    else:
70
        if isinstance(self, tabs.MucTab):
71 72 73 74 75
            try:
                results = self.core.xmpp['xep_0313'].retrieve(jid=self.remote_jid,
                iterator=True, reverse=top, start=self.start_date, end=self.end_date)
            except (IqError, IqTimeout):
                return self.information('Failed to retrieve messages', 'Error')
76
        else:
77 78 79 80 81
            try:
                results = self.core.xmpp['xep_0313'].retrieve(with_jid=self.remote_jid,
                iterator=True, reverse=top, start=self.start_date, end=self.end_date)
            except (IqError, IqTimeout):
                return self.information('Failed to retrieve messages', 'Error')
82 83
    msg_count = 0
    msgs = []
84
    timestamp = datetime.now()
85
    add_line(self, text_buffer, 'Start of MAM query: ', timestamp, 'MAM', top)
86
    async for rsm in results:
87 88
        if top:
            for msg in rsm['mam']['results']:
89 90
                if msg['mam_result']['forwarded']['stanza']['body'] is not '':
                    msgs.append(msg)
91
                if msg_count == 10:
92
                    self.query_id = 0
Madhur Garg's avatar
Madhur Garg committed
93
                    timestamp = datetime.now()
94
                    add_line(self, text_buffer, 'End of MAM query: ', timestamp, 'MAM', top)
Madhur Garg's avatar
Madhur Garg committed
95
                    self.core.refresh_window()
96 97 98 99 100 101 102
                    return
                msg_count += 1
            msgs.reverse()
            for msg in msgs:
                forwarded = msg['mam_result']['forwarded']
                timestamp = forwarded['delay']['stamp']
                message = forwarded['stanza']
103
                add_line(self, text_buffer, message['body'], timestamp, str(message['from']), top)
104 105 106 107 108 109
                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']
110
                add_line(self, text_buffer, message['body'], timestamp, str(message['from']), top)
111
                self.core.refresh_window()
112
    self.query_id = 0
113
    timestamp = datetime.now()
114
    add_line(self, text_buffer, 'End of MAM query: ', timestamp, 'MAM', top)
115 116 117 118 119 120 121 122 123 124 125


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
126 127 128
    tzone = datetime.now().astimezone().tzinfo
    end = end.replace(tzinfo=tzone).astimezone(tz=timezone.utc)
    end = end.replace(tzinfo=None)
129
    end = datetime.strftime(end, '%Y-%m-%dT%H:%M:%SZ')
130
    start = False
131
    top = True
Madhur Garg's avatar
Madhur Garg committed
132 133 134 135
    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))
136
        self.query_id = 1
Madhur Garg's avatar
Madhur Garg committed
137 138 139 140
        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