Improve XEP-0070 and examples

This commit is contained in:
mathieui
2016-08-19 23:45:24 +02:00
parent 9019e2bc71
commit 39ee833c29
3 changed files with 64 additions and 54 deletions

View File

@@ -29,18 +29,33 @@ class AnswerConfirm(slixmpp.ClientXMPP):
def __init__(self, jid, password, trusted):
slixmpp.ClientXMPP.__init__(self, jid, password)
self.trusted = trusted
self.api.register(self.confirm, 'xep_0070', 'get_confirm')
self.add_event_handler("http_confirm", self.confirm)
self.add_event_handler("session_start", self.start)
def confirm(self, jid, id, url, method):
log.info('Received confirm request %s from %s to access %s using '
'method %s' % (id, jid, url, method))
if jid not in self.trusted:
log.info('Denied')
return False
log.info('Confirmed')
return True
def start(self, *args):
self.make_presence().send()
def prompt(self, stanza):
confirm = stanza['confirm']
print('Received confirm request %s from %s to access %s using '
'method %s' % (
confirm['id'], stanza['from'], confirm['url'],
confirm['method'])
)
result = input("Do you accept (y/N)? ")
return 'y' == result.lower()
def confirm(self, stanza):
if self.prompt(stanza):
reply = stanza.reply()
else:
reply = stanza.reply()
reply.enable('error')
reply['error']['type'] = 'auth'
reply['error']['code'] = '401'
reply['error']['condition'] = 'not-authorized'
reply.append(stanza['confirm'])
reply.send()
if __name__ == '__main__':
# Setup the command line arguments.

View File

@@ -16,7 +16,7 @@ from getpass import getpass
from argparse import ArgumentParser
import slixmpp
from slixmpp.exceptions import XMPPError
from slixmpp.exceptions import XMPPError, IqError
from slixmpp import asyncio
log = logging.getLogger(__name__)
@@ -37,24 +37,40 @@ class AskConfirm(slixmpp.ClientXMPP):
self.method = method
# Will be used to set the proper exit code.
self.confirmed = None
self.confirmed = asyncio.Future()
self.add_event_handler("session_start", self.start)
self.add_event_handler("message", self.start)
self.add_event_handler("http_confirm_message", self.confirm)
def confirm(self, message):
print(message)
if message['confirm']['id'] == self.id:
if message['type'] == 'error':
self.confirmed.set_result(False)
else:
self.confirmed.set_result(True)
@asyncio.coroutine
def start(self, event):
log.info('Sending confirm request %s to %s who wants to access %s using '
'method %s...' % (self.id, self.recipient, self.url, self.method))
confirmed = yield from self['xep_0070'].ask_confirm(self.recipient,
id=self.id,
url=self.url,
method=self.method,
message='Plz say yes or no for {method} {url} ({id}).')
try:
confirmed = yield from self['xep_0070'].ask_confirm(self.recipient,
id=self.id,
url=self.url,
method=self.method,
message='Plz say yes or no for {method} {url} ({id}).')
if isinstance(confirmed, slixmpp.Message):
confirmed = yield from self.confirmed
else:
confirmed = True
except IqError:
confirmed = False
if confirmed:
print('Confirmed')
else:
print('Denied')
self.confirmed = confirmed
self.disconnect()