aboutsummaryrefslogtreecommitdiff
path: root/xmpp-vala/src/module/xep/0231_bits_of_binary.vala
blob: 7e811045d2dad3ebe8b039f34393fb4ff907f3c7 (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
60
61
62
63
64
65
66
using Gee;

namespace Xmpp.Xep.BitsOfBinary {

    public const string NS_URI = "urn:xmpp:bob";

    public static HashMap<string, Bytes> known_bobs = null;

    public class Module : XmppStreamModule {
        public static ModuleIdentity<Module> IDENTITY = new ModuleIdentity<Module>(NS_URI, "bits_of_binary");

        private ReceivedPipelineListener received_pipeline_listener = new ReceivedPipelineListener();

        public override void attach(XmppStream stream) {
            known_bobs = new HashMap<string, Bytes>();
            var message_module = stream.get_module(MessageModule.IDENTITY);
            if (message_module != null) {
                message_module.received_pipeline.connect(received_pipeline_listener);
            }
            stream.received_iq_stanza.connect(on_received_iq_stanza);
        }

        public override void detach(XmppStream stream) {
            var message_module = stream.get_module(MessageModule.IDENTITY);
            if (message_module != null) {
                message_module.received_pipeline.disconnect(received_pipeline_listener);
            }

            stream.received_iq_stanza.disconnect(on_received_iq_stanza);
        }

        private async void on_received_iq_stanza(XmppStream stream, StanzaNode node) {
            if (node.sub_nodes == null || node.sub_nodes.size == 0) return;
            Gee.List<StanzaNode> data_nodes = node.sub_nodes[0].get_subnodes("data", NS_URI);
            foreach (var data_node in data_nodes) {
                string cid = data_node.get_attribute("cid", NS_URI);
                if (cid == null) continue;

                known_bobs[cid] = new Bytes.take(Base64.decode(data_node.get_string_content()));
            }
        }

        public override string get_ns() { return NS_URI; }
        public override string get_id() { return IDENTITY.id; }
    }

    public class ReceivedPipelineListener : StanzaListener<MessageStanza> {

        private const string[] after_actions_const = {};

        public override string action_group { get { return ""; } }
        public override string[] after_actions { get { return after_actions_const; } }

        public override async bool run(XmppStream stream, MessageStanza message) {
            Gee.List<StanzaNode> data_nodes = message.stanza.get_subnodes("data", NS_URI);
            foreach (var data_node in data_nodes) {
                string cid = data_node.get_attribute("cid", NS_URI);
                if (cid == null) continue;

                known_bobs[cid] = new Bytes.take(Base64.decode(data_node.get_string_content()));
            }

            return false;
        }
    }
}