mam.py 5.86 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 22
    time = time.replace(tzinfo=timezone.utc).astimezone(tz=None)
    time = time.replace(tzinfo=None)
23
    if '/' in nick:
24
        if isinstance(self, tabs.MucTab) or self.chat_category == 'conference':
25 26 27
            nick = nick.split('/')[1]
        else:
            nick = nick.split('/')[0]
28 29 30
        color = get_theme().COLOR_OWN_NICK
    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
    self.remote_jid = remote_jid
    self.start_date = start
    self.end_date = end
49
    self.chat_category = 'account'
50
    text_buffer = self._text_buffer
51 52 53 54
    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')
55 56
    if 'urn:xmpp:mam:2' not in iq['disco_info'].get_features():
        return self.core.information("This MUC doesn't support MAM.", "Error")
57
    if top:
58
        if isinstance(self, tabs.MucTab):
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):
63
                return self.core.information('Failed to retrieve messages', 'Error')
64
        else:
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):
69
                return self.core.information('Failed to retrieve messages', 'Error')
70
    else:
71 72
        if 'conference' in list(iq['disco_info']['identities'])[0]:
            self.chat_category = 'conference'
73 74 75 76
            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):
77
                return self.core.information('Failed to retrieve messages', 'Error')
78
        else:
79 80 81 82
            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):
83
                return self.core.information('Failed to retrieve messages', 'Error')
84 85
    msg_count = 0
    msgs = []
86
    async for rsm in results:
87 88
        if top:
            for msg in rsm['mam']['results']:
89 90
                if msg['mam_result']['forwarded']['stanza'].xml.find(
                    '{%s}%s' % ('jabber:client', 'body')) is not None:
91
                    msgs.append(msg)
92
                if msg_count == 10:
93
                    self.query_id = 0
Madhur Garg's avatar
Madhur Garg committed
94
                    self.core.refresh_window()
95 96 97 98
                    return
                msg_count += 1
            msgs.reverse()
            for msg in msgs:
99 100 101
                if msg is msgs[0]:
                    timestamp = msg['mam_result']['forwarded']['delay']['stamp']
                    add_line(self, text_buffer, 'Start of MAM query: ', timestamp, 'MAM', top)
102 103 104
                forwarded = msg['mam_result']['forwarded']
                timestamp = forwarded['delay']['stamp']
                message = forwarded['stanza']
105
                add_line(self, text_buffer, message['body'], timestamp, str(message['from']), top)
106 107 108
                if msg is msgs[len(msgs)-1]:
                    timestamp = msg['mam_result']['forwarded']['delay']['stamp']
                    add_line(self, text_buffer, 'End of MAM query: ', timestamp, 'MAM', top)
109 110 111 112 113 114
                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']
115
                add_line(self, text_buffer, message['body'], timestamp, str(message['from']), top)
116
                self.core.refresh_window()
117 118
    if len(msgs) == 0:
        return self.core.information('No more messages left to retrieve', 'Info')
119
    self.query_id = 0
120 121 122 123 124 125 126 127 128 129

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