1"""
2    Slixmpp: The Slick XMPP Library
3    Copyright (C) 2012 Nathanael C. Fritz, Lance J.T. Stout
4    This file is part of Slixmpp.
5
6    See the file LICENSE for copying permission.
7"""
8
9import logging
10
11from slixmpp import Iq
12from slixmpp.plugins import BasePlugin
13from slixmpp.xmlstream.handler import Callback
14from slixmpp.xmlstream.matcher import StanzaPath
15from slixmpp.xmlstream import register_stanza_plugin, JID
16from slixmpp.plugins.xep_0191 import stanza, Block, Unblock, BlockList
17
18
19log = logging.getLogger(__name__)
20
21
22class XEP_0191(BasePlugin):
23
24    name = 'xep_0191'
25    description = 'XEP-0191: Blocking Command'
26    dependencies = {'xep_0030'}
27    stanza = stanza
28
29    def plugin_init(self):
30        register_stanza_plugin(Iq, BlockList)
31        register_stanza_plugin(Iq, Block)
32        register_stanza_plugin(Iq, Unblock)
33
34        self.xmpp.register_handler(
35                Callback('Blocked Contact',
36                    StanzaPath('iq@type=set/block'),
37                    self._handle_blocked))
38
39        self.xmpp.register_handler(
40                Callback('Unblocked Contact',
41                    StanzaPath('iq@type=set/unblock'),
42                    self._handle_unblocked))
43
44    def plugin_end(self):
45        self.xmpp.remove_handler('Blocked Contact')
46        self.xmpp.remove_handler('Unblocked Contact')
47
48    def get_blocked(self, ifrom=None, timeout=None, callback=None,
49                          timeout_callback=None):
50        iq = self.xmpp.Iq()
51        iq['type'] = 'get'
52        iq['from'] = ifrom
53        iq.enable('blocklist')
54        return iq.send(timeout=timeout, callback=callback,
55                       timeout_callback=timeout_callback)
56
57    def block(self, jids, ifrom=None, timeout=None, callback=None,
58                          timeout_callback=None):
59        iq = self.xmpp.Iq()
60        iq['type'] = 'set'
61        iq['from'] = ifrom
62
63        if not isinstance(jids, (set, list)):
64            jids = [jids]
65
66        iq['block']['items'] = jids
67        return iq.send(timeout=timeout, callback=callback,
68                       timeout_callback=timeout_callback)
69
70    def unblock(self, jids=None, ifrom=None, timeout=None, callback=None,
71                      timeout_callback=None):
72        iq = self.xmpp.Iq()
73        iq['type'] = 'set'
74        iq['from'] = ifrom
75
76        if jids is None:
77            jids = []
78        if not isinstance(jids, (set, list)):
79            jids = [jids]
80
81        iq['unblock']['items'] = jids
82        return iq.send(timeout=timeout, callback=callback,
83                       timeout_callback=timeout_callback)
84
85    def _handle_blocked(self, iq):
86        self.xmpp.event('blocked', iq)
87
88    def _handle_unblocked(self, iq):
89        self.xmpp.event('unblocked', iq)
90