Part of Slepp's ProjectsPastebinTURLImagebinFilebin
Feedback -- English French German Japanese
Create Upload Newest Tools Donate
Sign In | Create Account

Paste Description for XMPP Atomstream

Extend the Atomsteam.py script to publish ATOM feeds into XHTML-IM messages.

To fix, to enhance, to optimize, etc...

XMPP Atomstream
Wednesday, September 3rd, 2008 at 12:38:13pm MDT 

  1. # coding: utf-8
  2.  
  3. """
  4. Extending Atomstream.py with XMPP support
  5.  
  6. author : xmpp:kael@jabber.org
  7. """
  8.  
  9.  
  10. """
  11. atomstream: a more efficient way to get feed updates
  12. http://www.aaronsw.com/2002/atomstream/
  13.  
  14.     >>> import atomstream
  15.     >>> for update in atomstream.connect():
  16.     ...     print "'%s...'" % update[:20]
  17.     >>> import feedparser
  18.     >>> from itertools import imap
  19.     >>> for update in imap(feedparser.parse, atomstream.connect()):
  20.             print update.entries[0].title.encode('utf8')
  21.     Валєрій Нуґатов / З циклу "ФРІЛАНС"
  22.  
  23.     Ну и зайчик...
  24.  
  25.     Squee.
  26.     линейная графика
  27.     Как я боролась с павианами
  28.  
  29.     And you thought I was obsessed....
  30.     一个比利时的 dapper 源
  31.     Видеоподборка
  32.     Synchronisma Promotional Video... and More
  33.  
  34.     ^C
  35. """
  36. __author__ = "Aaron Swartz <http://www.aaronsw.com/>"
  37. __version__ = "1.1"
  38. __license__ = "public domain"
  39.  
  40. import urllib, logging
  41. from xml.sax.handler import EntityResolver, DTDHandler, ContentHandler, ErrorHandler
  42. from xml.sax.saxutils import XMLGenerator
  43. from xml.sax import make_parser
  44. from StringIO import StringIO
  45. import feedparser
  46. from itertools import imap
  47. import xmpp
  48.  
  49. JID = JID
  50. PWD = PWD
  51.  
  52. options = {
  53.     'JID': JID,
  54.     'Password': PWD,
  55. }
  56.  
  57.  
  58. class Streamer(EntityResolver, DTDHandler, ContentHandler, ErrorHandler):
  59.     def __init__(self):
  60.         self.time = 0
  61.         self.reset()
  62.    
  63.     def reset(self):
  64.         self.mode = None
  65.         self.chr = []
  66.         self.results = []
  67.        
  68.     def startElement(self, name, attr):
  69.         if name == 'atomStream':
  70.             self.mode = 'atomStream'
  71.            
  72.         elif self.mode == 'atomStream' and name == 'time':
  73.             self.mode = 'time'
  74.             self.chr = []
  75.  
  76.         elif name == 'sorryTooSlow':
  77.             logging.warn('too slow, you missed'+dict(attr)['youMissed'])
  78.        
  79.         elif name == 'feed':
  80.             self.mode = 'feed'
  81.             self.feeddata = StringIO()
  82.             self.feedster = XMLGenerator(self.feeddata)
  83.        
  84.         if self.mode == 'feed':
  85.             self.feedster.startElement(name, attr)
  86.    
  87.     def characters(self, ch):
  88.         if self.mode == 'feed':
  89.             self.feedster.characters(ch)
  90.         else:
  91.             self.chr.append(ch)
  92.    
  93.     def endElement(self, name):
  94.         if self.mode == 'feed':
  95.             self.feedster.endElement(name)
  96.        
  97.         if self.mode == 'time' and name == 'time':
  98.             self.mode = 'atomStream'
  99.             self.time = int(''.join(self.chr))
  100.             self.chr = []
  101.         elif self.mode == 'feed' and name == 'feed':
  102.             self.results.append(self.feeddata.getvalue())
  103.             self.mode = 'atomStream'
  104.  
  105.  
  106. class RunProcess:
  107.  
  108.     def __init__(self, conn):
  109.         self.conn = conn
  110.  
  111.     def connect(self, feed="http://updates.sixapart.com/atom-stream.xml"):
  112.         print "start"
  113.         s = Streamer()
  114.         p = make_parser()
  115.         p.setContentHandler(s)
  116.         while 1:
  117.             print "yes"
  118.             try:
  119.                 d = urllib.urlopen(feed+'?since='+str(s.time))
  120.                 for line in iter(d.readline, None):
  121.                     p.feed(line)
  122.                     while s.results: yield s.results.pop(0)
  123.             except:
  124.                 raise
  125.                 s.reset()
  126.                
  127.     def get_stream(self):
  128.         for update in imap(feedparser.parse, self.connect()):
  129.             title =  update.entries[0].title
  130.             content = update.entries[0].content[0].value
  131.             self.send_xhtml(title,content)
  132.            
  133.     def send_xhtml(self, title, content):
  134.         try :
  135.             message=xmpp.protocol.Message(to=JID, subject=title.encode('utf-8'), typ='chat', body='foo')
  136.             payload=xmpp.simplexml.XML2Node("<body xmlns='http://www.w3.org/1999/xhtml'><center><h2>%s</h2></center>%s</body>" % (title.encode('utf-8'), content.encode('utf-8')))
  137.             message.addChild('html', {}, [payload], xmpp.NS_XHTML_IM)
  138.             self.conn.send(message)
  139.         except:
  140.             pass
  141.            
  142. class XmppConn(RunProcess):
  143.  
  144.     def __init__(self, JID, Password):
  145.         jid = xmpp.JID(JID)
  146.         self.conn = xmpp.Client(jid.getDomain(), debug=['always', 'nodebuilder'])
  147.         result = self.conn.connect()
  148.         if result is None:
  149.             raise ConnectionError
  150.         result = self.conn.auth(jid.getNode(), Password,'SixApart')
  151.         if result is None:
  152.             raise AuthorizationError
  153.         self.conn.sendInitPresence(requestRoster=1)
  154.         self.bot = RunProcess(self.conn)
  155.         self.bot.get_stream()
  156.  
  157.     def loop(self):
  158.         try:
  159.             while self.conn.Process(1):
  160.                 self.conn.send(' ')
  161.                 pass
  162.         except KeyboardInterrupt:
  163.             return 0
  164.         return 1
  165.      
  166. bot = XmppConn(**options)
  167. bot.loop()

Paste Details

Tags: xmpp atom

advertising

Update the Post

Either update this post and resubmit it with changes, or make a new post.

You may also comment on this post.

update paste below
details of the post (optional)

Note: Only the paste content is required, though the following information can be useful to others.

Save name / title?

(space separated, optional)



Please note that information posted here will expire by default in one month. If you do not want it to expire, please set the expiry time above. If it is set to expire, web search engines will not be allowed to index it prior to it expiring. Items that are not marked to expire will be indexable by search engines. Be careful with your passwords. All illegal activities will be reported and any information will be handed over to the authorities, so be good.