mam.py 5.85 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(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
    color = get_theme().COLOR_OWN_NICK
24 25 26 27 28 29 30 31 32 33 34 35 36 37
    text_buffer.add_message(
        text,
        time,
        nick,
        color,
        True,  # History
        None,  # User
        False,  # Highlight
        top, #Top
        None,  # Identifier
        None,  # str_time
        None,  # Jid
    )

38
async def query(tab, remote_jid, top, start=None, end=None, before=None):
39
    text_buffer = tab._text_buffer
40
    try:
41
        iq = await tab.core.xmpp.plugin['xep_0030'].get_info(jid=remote_jid)
42
    except (IqError, IqTimeout):
43
        return tab.information('Failed to retrieve messages', 'Error')
44
    if 'urn:xmpp:mam:2' not in iq['disco_info'].get_features():
45
        return tab.core.information("This MUC doesn't support MAM.", "Error")
46
    if top:
47
        if isinstance(tab, tabs.MucTab):
48
            try:
49
                if before is not None:
50
                    results = tab.core.xmpp['xep_0313'].retrieve(jid=remote_jid,
51 52
                    iterator=True, reverse=top, before=before)
                else:
53
                    results = tab.core.xmpp['xep_0313'].retrieve(jid=remote_jid,
54
                    iterator=True, reverse=top, end=end)
55
            except (IqError, IqTimeout):
56
                return tab.core.information('Failed to retrieve messages', 'Error')
57
        else:
58
            try:
59
                if before is not None:
60
                    results = tab.core.xmpp['xep_0313'].retrieve(with_jid=remote_jid,
61 62
                    iterator=True, reverse=top, before=before)
                else:
63
                    results = tab.core.xmpp['xep_0313'].retrieve(with_jid=remote_jid,
64
                    iterator=True, reverse=top, end=end)
65
            except (IqError, IqTimeout):
66
                return tab.core.information('Failed to retrieve messages', 'Error')
67
    else:
68
        if 'conference' in list(iq['disco_info']['identities'])[0]:
69
            try:
70
                results = tab.core.xmpp['xep_0313'].retrieve(jid=remote_jid,
71
                iterator=True, reverse=top, start=start_date, end=end)
72
            except (IqError, IqTimeout):
73
                return tab.core.information('Failed to retrieve messages', 'Error')
74
        else:
75
            try:
76
                results = tab.core.xmpp['xep_0313'].retrieve(with_jid=remote_jid,
77
                iterator=True, reverse=top, start=start_date, end=end)
78
            except (IqError, IqTimeout):
79
                return tab.core.information('Failed to retrieve messages', 'Error')
80 81
    msg_count = 0
    msgs = []
82
    async for rsm in results:
83 84
        if top:
            for msg in rsm['mam']['results']:
85 86
                if msg['mam_result']['forwarded']['stanza'].xml.find(
                    '{%s}%s' % ('jabber:client', 'body')) is not None:
87
                    msgs.append(msg)
88
                if msg_count == 10:
89 90
                    tab.query_id = 0
                    tab.core.refresh_window()
91 92 93 94 95 96 97
                    return
                msg_count += 1
            msgs.reverse()
            for msg in msgs:
                forwarded = msg['mam_result']['forwarded']
                timestamp = forwarded['delay']['stamp']
                message = forwarded['stanza']
98
                tab.stanza_id = msg['mam_result']['id']
99
                nick = str(message['from'])
100
                if isinstance(tab, tabs.MucTab):
101 102 103
                    nick = nick.split('/')[1]
                else:
                    nick = nick.split('/')[0]
104
                add_line(text_buffer, message['body'], timestamp, nick, top)
105
                tab.text_win.scroll_up(len(tab.text_win.built_lines))
106 107 108 109 110
        else:
            for msg in rsm['mam']['results']:
                forwarded = msg['mam_result']['forwarded']
                timestamp = forwarded['delay']['stamp']
                message = forwarded['stanza']
111 112 113 114 115
                nick = str(message['from'])
                if 'conference' in list(iq['disco_info']['identities'])[0]:
                    nick = nick.split('/')[1]
                else:
                    nick = nick.split('/')[0]
116
                add_line(text_buffer, message['body'], timestamp, nick, top)
117
                tab.core.refresh_window()
118
    if len(msgs) == 0:
119 120
        return tab.core.information('No more messages left to retrieve', 'Info')
    tab.query_id = 0
121

122 123 124
def mam_scroll(tab):
    remote_jid = tab.jid
    text_buffer = tab._text_buffer
125 126 127
    try:
        before = tab.stanza_id
    except:
128
        before = None
129
        end = datetime.now()
130 131 132 133
        tzone = datetime.now().astimezone().tzinfo
        end = end.replace(tzinfo=tzone).astimezone(tz=timezone.utc)
        end = end.replace(tzinfo=None)
        end = datetime.strftime(end, '%Y-%m-%dT%H:%M:%SZ')
134
    top = True
135 136 137
    pos = tab.text_win.pos
    tab.text_win.pos += tab.text_win.height - 1
    if tab.text_win.pos + tab.text_win.height > len(tab.text_win.built_lines):
138 139 140 141
        if before is None:
            asyncio.ensure_future(query(tab, remote_jid, top, end=end))
        else:
            asyncio.ensure_future(query(tab, remote_jid, top, before=before))
142 143 144 145 146
        tab.query_id = 1
        tab.text_win.pos = len(tab.text_win.built_lines) - tab.text_win.height
        if tab.text_win.pos < 0:
            tab.text_win.pos = 0
    return tab.text_win.pos != pos