Skip to content

Instantly share code, notes, and snippets.

@weaver
Created March 1, 2010 16:20
Show Gist options
  • Save weaver/318501 to your computer and use it in GitHub Desktop.
Save weaver/318501 to your computer and use it in GitHub Desktop.
XMPP client/server that use JSON info queries.
#!/usr/bin/env python
"""demo-client.py -- query the demo server
Example:
## In one terminal:
> python demo-server.py
## In another terminal:
> python demo-client.py '*'
"""
import os, sys, xmpp, base64, json
from xmpp import xml
def usage():
print __doc__
print 'usage: %s torrent-id timeframe' % sys.argv[0]
sys.exit(1)
def main(torrent_id, timeframe):
query = { 'id': torrent_id, 'timeframe': timeframe }
client = xmpp.Client({
'plugins': [(QueryClient, { 'query': query })],
'username': 'user',
'password': 'secret',
'host': 'localhost'
})
xmpp.start([xmpp.TCPClient(client).connect('127.0.0.1', 5222)])
class QueryClient(xmpp.Plugin):
def __init__(self, query):
self.send(query)
def send(self, query):
self.iq('get', self.on_reply, self.E(
'torrent-detail'
{ 'xmlns': 'urn:NRK' },
dumps(query)
))
def on_reply(self, iq):
assert iq.get('type') == 'result'
data = loads(xml.child(iq, '{urn:NRK}query/text()'))
print 'Got reply:', data
xmpp.loop().stop()
def dumps(obj):
return base64.b64encode(json.dumps(obj))
def loads(obj):
return json.loads(base64.base64decode(obj))
if __name__ == '__main__':
if len(sys.argv) != 3:
usage()
main(*sys.argv[1:])
#!/usr/bin/env python
"""demo-server.py -- listen for torrent-detail requests"""
import os, sys, json, xmpp, base64
from xmpp import xml
def main():
server = xmpp.Server({
'plugins': [QueryServer],
'users': { 'user': 'secret' },
'host': 'localhost'
})
print 'Waiting for clients...'
xmpp.start([xmpp.TCPServer(server).bind('127.0.0.1', 5222)])
class QueryServer(xmpp.Plugin):
@xmpp.iq('{urn:NRK}torrent-detail')
def torrent_detail(self, iq):
assert iq.get('type') == 'get'
data = loads(xml.child(iq, '{urn:NRK}torrent-detail/text()'))
result = torrent_detail(**data)
self.iq('result', iq, self.E(
'torrent-detail',
{ 'xmlns': 'urn:NRK'},
dumps(result)
)
def dumps(obj):
return base64.b64encode(json.dumps(obj))
def loads(obj):
return json.loads(base64.base64decode(obj))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment