summaryrefslogtreecommitdiff
path: root/slixmpp/plugins/xep_0444/stanza.py
blob: 02684df10b9b2a3f72472c71d2c3e03021b9283b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

# Slixmpp: The Slick XMPP Library
# Copyright (C) 2020 Mathieu Pasquet
# This file is part of Slixmpp.
# See the file LICENSE for copying permission.
from typing import Set, Iterable
from slixmpp.xmlstream import ElementBase
try:
    from emoji import UNICODE_EMOJI
    if UNICODE_EMOJI.get('en'):
        UNICODE_EMOJI = UNICODE_EMOJI['en']
except ImportError:
    UNICODE_EMOJI = None


NS = 'urn:xmpp:reactions:0'

class Reactions(ElementBase):
    name = 'reactions'
    plugin_attrib = 'reactions'
    namespace = NS
    interfaces = {'id', 'values'}

    def get_values(self, *, all_chars=False) -> Set[str]:
        """"Get all reactions as str"""
        reactions = set()
        for reaction in self:
            value = reaction['value']
            if UNICODE_EMOJI and not all_chars:
                if value in UNICODE_EMOJI:
                    reactions.add(reaction['value'])
            else:
                reactions.add(reaction['value'])
        return reactions

    def set_values(self, values: Iterable[str], *, all_chars=False):
        """"Set all reactions as str"""
        for element in self.xml.findall('reaction'):
            self.xml.remove(element)
        for reaction_txt in values:
            reaction = Reaction()
            reaction.set_value(reaction_txt, all_chars=all_chars)
            self.append(reaction)


class Reaction(ElementBase):
    name = 'reaction'
    namespace = NS
    interfaces = {'value'}

    def get_value(self) -> str:
        return self.xml.text

    def set_value(self, value: str, *, all_chars=False):
        if UNICODE_EMOJI and not all_chars:
            if not value in UNICODE_EMOJI:
                raise ValueError("%s is not a valid emoji" % value)
        self.xml.text = value