Commits

Anonymous committed 1f2b917

AutoClient, a wrapper for jabber client which connects only when necessary.

Comments (0)

Files changed (1)

 
 MAXLENGTH=2048
 SENTFILE="~/.rss2xmpp.sent"
+RCFILE="~/.rss2xmpp"
 
 # jabber settings in ~/.rss2xmpp
 samplerc="""jid = mylogin@gmail.com
 def usage():
     print 'usage:', basename(argv[0]), 'feed', 'tojid'
 
-def readrc():
-    """Read XMPP settings from ~/.rss2xmpp."""
-    rcfile=expanduser("~/.rss2xmpp")
-    try:
-        lines=file(rcfile).readlines()
-        lines=[sub('#.*','',l).strip() for l in lines]
-        lines=[l for l in lines if len(l) > 0]
-        settings=[l.split('=',1) for l in lines]
-        settings=[ [ v.strip() for v in s ] for s in settings ]
-    except IOError, e:
-        file(rcfile,'w').write(samplerc)
-        raise e
-    return dict(settings)
-
 def get_sent_ids():
     sentfile=expanduser(SENTFILE)
     try:
         sentids=[]
     return sentids
 
-def rememberid(entryid):
+def remember_id(entryid):
     """Save crossposted feed entry ID in file."""
     sentids=get_sent_ids()
     sentids.append(entryid)
     pickle.dump(sentids,file(expanduser(SENTFILE),'w'))
 
-def issent(entryid):
+def is_sent(entryid):
     """Check if entryid is sent already."""
     sentids=get_sent_ids()
     return entryid in sentids
 
-def connect_jid_client():
-    try:
-        cfg=readrc()
-    except IOError:
-        print 'please edit XMPP account settings in ~/.rss2xmpp'
-        exit(1)
-    jid=xmpp.protocol.JID(cfg['jid'])
-    cl=xmpp.Client(jid.getDomain(),debug=[])
-    if cfg.has_key('server'):
-        con=cl.connect(server=(cfg['server'],cfg['port']))
-    else:
-        con=cl.connect(jid.getDomain())
-    if not con:
-        print 'cannot connect'
-        exit(1)
-    auth=cl.auth(jid.getNode(),cfg['pass'],resource=jid.getResource())
-    if not auth:
-        print 'cannot authenticate'
-        exit(1)
-    return cl
+class AutoClient:
+    """An XMPP client wrapper which autoconnects only if necessary (on send).
 
-def send_message(client,tojid,message):
-    client.send(xmpp.protocol.Message(tojid,message))
+    Example:
+
+    cl = AutoClient(rcfile) # AutoClient does not connect yet
+    cl.send('send-to@example.com','Hello!') # AutoClient connects automatically
+    cl.disconnect() # disconnect manually
+    """
+
+    def readrc(self):
+        """Read XMPP settings from rc-file."""
+        rcfile=expanduser(self.rcfile)
+        try:
+            lines=file(rcfile).readlines()
+            lines=[sub('#.*','',l).strip() for l in lines]
+            lines=[l for l in lines if len(l) > 0]
+            settings=[l.split('=',1) for l in lines]
+            settings=[ [ v.strip() for v in s ] for s in settings ]
+        except IOError, e:
+            file(rcfile,'w').write(samplerc)
+            raise e
+        return dict(settings)
+
+    def connect_jid_client(self):
+        try:
+            cfg=self.readrc()
+        except IOError:
+            raise Exception('please edit XMPP account settings in ~/.rss2xmpp')
+        jid=xmpp.protocol.JID(cfg['jid'])
+        cl=xmpp.Client(jid.getDomain(),debug=[])
+        if cfg.has_key('server'):
+            con=cl.connect(server=(cfg['server'],cfg['port']))
+        else:
+            con=cl.connect(jid.getDomain())
+        if not con:
+            raise Exception('cannot connect')
+        auth=cl.auth(jid.getNode(),cfg['pass'],resource=jid.getResource())
+        if not auth:
+            raise Exception('cannot authenticate')
+        return cl
+
+    def get_client(self):
+        "connect on demand"
+        if not self.client:
+            self.client=self.connect_jid_client()
+        return self.client
+
+    def __init__(self, rcfile=RCFILE):
+        self.client=None
+        self.rcfile=rcfile
+
+    def send(self,tojid,message):
+        self.get_client().send(xmpp.protocol.Message(tojid,message))
+
+    def disconnect(self):
+        if self.client:
+            self.client.disconnect()
+
 
 if __name__ == '__main__':
     if len(argv) != 3:
     feed  = argv[1]
     tojid = argv[2]
 
-    cl=connect_jid_client()
+    cl = AutoClient()
 
     d=parse(feed)
     for i in reversed(d['entries']):
-        if not issent(i.id):
+        if not is_sent(i.id):
             title,text,link,msg=i.title,html2text(i.summary),i.link,''
             if title:
                 msg += title + '\n'
-            msg += text[:MAXLENGTH] + '\n' + link
-            send_message(cl,tojid,msg)
-            rememberid(i.id)
+            # msg += text[:MAXLENGTH]
+            msg +='\n' + link.strip()
+            cl.send(tojid,msg)
+            remember_id(i.id)
             sleep(5)
 
     cl.disconnect()