mam.py 6.2 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
import asyncio
10
import random
11
from datetime import datetime, timedelta, timezone
12
from slixmpp.exceptions import IqError, IqTimeout
13
from poezio.theming import get_theme
14
from poezio import tabs
15 16
from poezio import xhtml
from poezio.config import config
17 18
from poezio.text_buffer import Message, TextBuffer

19
def add_line(tab, text_buffer: TextBuffer, text: str, str_time: str, nick: str, top: bool):
20 21 22 23
    """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')
24 25
    time = time.replace(tzinfo=timezone.utc).astimezone(tz=None)
    time = time.replace(tzinfo=None)
26 27 28 29 30 31 32 33 34 35 36 37
    if isinstance(tab, tabs.MucTab):
        nick = nick.split('/')[1]
        user = tab.get_user_by_name(nick)
        if user:
            color = user.color
        else:
            color = random.choice(list(xhtml.colors))
            color = xhtml.colors.get(color)
            color = (color, -1)
    else:
        nick = nick.split('/')[0]
        color = get_theme().COLOR_OWN_NICK
38 39 40 41 42 43 44 45 46 47 48 49 50 51
    text_buffer.add_message(
        text,
        time,
        nick,
        color,
        True,  # History
        None,  # User
        False,  # Highlight
        top, #Top
        None,  # Identifier
        None,  # str_time
        None,  # Jid
    )

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

128 129 130
def mam_scroll(tab):
    remote_jid = tab.jid
    text_buffer = tab._text_buffer
131 132 133
    try:
        before = tab.stanza_id
    except:
134
        before = None
135
        end = datetime.now()
136 137 138 139 140 141
        if isinstance(tab, tabs.MucTab) is False:
            for message in text_buffer.messages:
                time = message.time
                if time < end:
                    end = time
        end = end + timedelta(seconds=-1)
142 143 144 145
        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')
146
    top = True
147 148 149
    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):
150 151 152 153
        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))
154 155 156 157 158
        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