Skip to content
This repository has been archived by the owner on Apr 30, 2021. It is now read-only.

Commit

Permalink
Launch plugins in a deferred thread, remove pydispatcher, tidy up/enh…
Browse files Browse the repository at this point in the history
…ance plugin api
  • Loading branch information
wrboyce committed Nov 29, 2011
1 parent 0c6c963 commit ac32a26
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 47 deletions.
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
description='Tampering Siri Proxy',
license="BSD",
url='https://github.com/wrboyce/sirious',
install_requires=['biplist', 'pydispatcher', 'pyopenssl', 'twisted'],
install_requires=['biplist', 'pyopenssl', 'twisted'],
packages=['sirious', 'sirious.plugins'],
package_data={
'sirious': ['scripts/gen_certs.zsh'],
Expand Down
55 changes: 26 additions & 29 deletions sirious/plugins/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from pydispatch import dispatcher

from sirious import SiriObjects


Expand Down Expand Up @@ -32,46 +30,45 @@ def respond(self, text, speakableText=None, dialogueIdentifier='Misc#ident', lis
root.views.append(SiriObjects.Utterance(text=text, speakableText=speakableText, dialogueIdentifier=dialogueIdentifier, listenAfterSpeaking=listenAfterSpeaking))
self.send_object(root)

def ask(self, handler, text, speakableText=None, dialogueIdentifier='Misc#ident', handler_kwargs={}):
def ask(self, text, speakableText=None, dialogueIdentifier='Misc#ident'):
""" Respond with an `Utterance` and send the response to `handler`. """
root = SiriObjects.AddViews()
root.views.append(SiriObjects.Utterance(text=text, speakableText=speakableText, dialogueIdentifier=dialogueIdentifier, listenAfterSpeaking=True))
root.make_root(ref_id=self.proxy.ref_id)
self.ask_views(handler, root, handler_kwargs)
return self.ask_views(root)

def get_next_phrase(self):
def _handler(phrase):
self.__response = phrase
self.proxy.get_next_phrase(_handler)

def ask_views(self, handler, views, handler_kwargs={}):
def ask_views(self, views):
""" Underlying power behind `SiriPlugin.ask` to send request and register for response. """
self.block_session()
self.send_object(views)
def handle_answer(*a, **kw):
del(kw['sender'])
del(kw['signal'])
handler_kwargs.update(kw)
handler(*a, **handler_kwargs)
dispatcher.disconnect(handle_answer, signal='consume_phrase')
dispatcher.connect(handle_answer, signal='consume_phrase')
self.__response = None
self.get_next_phrase()
while self.__response is None:
pass
response, self.__response = self.__response, None
return response

def confirm(self, handler, text, speakableText=None, dialogueIdentifier='Misc#ident', handler_kwargs={}):
def confirm(self, text, speakableText=None, dialogueIdentifier='Misc#ident'):
root = SiriObjects.AddViews()
root.views.append(SiriObjects.Utterance(text=text, speakableText=speakableText, dialogueIdentifier=dialogueIdentifier, listenAfterSpeaking=True))
root.make_root(ref_id=self.proxy.ref_id)
self.confirm_views(handler, root, handler_kwargs)
return self.confirm_views(root)

def confirm_views(self, views):
return self._confirm(self.ask_views(views))

def confirm_views(self, handler, views, handler_kwargs={}):
""" Wrapper around `SiriPlugin.ask` which handles yes/no responses. """
def handle_confirm(phrase, **kwargs):
phrase = phrase.lower().strip()
print 'confirm: "%s"' % phrase
confirmed = None
if phrase in ['yes', 'ok']:
confirmed = True
elif phrase in ['no', 'cancel']:
confirmed = False
if confirmed is None:
self.confirm(handler, "Please respond yes or no.", views, handler_kwargs)
else:
handler(confirmed, phrase, **kwargs)
self.ask_views(handle_confirm, views, handler_kwargs)
def _confirm(self, phrase):
phrase = phrase.lower().strip()
if phrase in ['yes', 'ok']:
return True
elif phrase in ['no', 'cancel']:
return False
return self.confirm("Please respond yes or no.")

def complete(self):
""" Sends a `RequestCompleted` response. """
Expand Down
18 changes: 9 additions & 9 deletions sirious/plugins/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,17 @@ def respond_test(self, phrase):
respond_test.triggers = ['Are you serious']

def ask_test(self, phrase):
self.ask(self.ask_test_response, "Do you think this is a test?")
ask_test.triggers = ['Is this a test']

def ask_test_handler(self, phrase):
self.logger.info('Asking question...')
response = self.ask("Do you think this is a test?")
self.logger.info('Got answer: %s' % response)
self.respond("Well, you've failed.")
self.complete()
ask_test.triggers = ['Is this a test']

def confirm_test(self, phrase):
self.confirm(self.confirm_test_handler, "Please confirm")
confirm_test.triggers = ['Do something']

def confirm_test_handler(self, confirmed, phrase):
self.respond('Confirmed.' if confirmed else 'OK, cancelled.')
if self.confirm("Please confirm"):
self.respond("Confirmed.")
else:
self.respond("Ok, cancelled.")
self.complete()
confirm_test.triggers = ['Do something']
19 changes: 11 additions & 8 deletions sirious/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
import zlib

from biplist import readPlistFromString, writePlistToString
from pydispatch import dispatcher
from twisted.internet import protocol, reactor, ssl
from twisted.internet import protocol, reactor, ssl, threads
from twisted.protocols.basic import LineReceiver
from twisted.protocols.portforward import ProxyClientFactory

Expand All @@ -19,6 +18,7 @@ class SiriProxy(LineReceiver, object):
blocking = False
ref_id = None # last refId seen
ace_host = None # The X-Ace-Host of the current user
consumer = None

def __init__(self, plugins=[], triggers=[]):
self.zlib_d = zlib.decompressobj()
Expand Down Expand Up @@ -142,6 +142,9 @@ def inject_plist(self, plist):
self.peer.transport.write(data)
self.peer.transport.write(self.zlib_c.flush(zlib.Z_FULL_FLUSH))

def get_next_phrase(self, consumer):
self.consumer = consumer

def process_speech(self, plist):
phrase = ''
for phrase_plist in plist['properties']['recognition']['properties']['phrases']:
Expand All @@ -153,11 +156,11 @@ def process_speech(self, plist):
phrase += ' '
if phrase:
self.logger.info('[Speech Recognised] "%s"' % phrase)
try:
dispatcher.getAllReceivers(signal='consume_phrase').next()
self.logger.debug('Dispatching `consume_phrase` signal')
dispatcher.send('consume_phrase', phrase=phrase)
except StopIteration:
if self.consumer:
self.logger.info("Sending phrase to consumer")
self.consumer(phrase)
self.consumer = None
else:
for trigger, function in self.triggers:
match = trigger.search(phrase)
if match:
Expand All @@ -167,7 +170,7 @@ def process_speech(self, plist):
args = [phrase]
if groups:
args.append(groups)
function(*args)
threads.deferToThread(function, *args)

def connectionLost(self, reason):
""" Reset ref_id and disconnect peer """
Expand Down

0 comments on commit ac32a26

Please sign in to comment.