foafbot-0.5/0042775000016500001440000000000007671462514012360 5ustar edmunddusersfoafbot-0.5/oracle.py0100775000016500001440000004204007671462512014173 0ustar edmunddusers#!/usr/bin/python2.2 # $Id: oracle.py,v 1.21 2002/08/02 17:38:37 edmundd Exp $ # # Copyright (C) 2002 Edd Dumbill # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. import RDF import AttributedModel import scutter import FOAF import DC import string import re import mbox_sha1_hook import plan_hook class Oracle: def __init__(self, name, start_anew=1, keyids=[]): if start_anew: new_param=",new='yes'" else: new_param=",new='no'" self._storage=RDF.Storage(storage_name="hashes", name=name, options_string="hash-type='bdb',index-subjects='yes',index-objects='yes',contexts='yes',index-predicates='yes',dir='.'%s" % new_param) self.model=AttributedModel.AttributedModel(self._storage) self.model.register_hook(FOAF.mboxNode, mbox_sha1_hook.hook) self.model.register_hook(FOAF.rdfTypeNode, plan_hook.hook) if start_anew==0: self._loaded=1 else: self._loaded=0 self._scutter=scutter.Scutter(self.model, keyids) def close(self): """perform any necessary cleanup""" print "Closing down Oracle" RDF.debug(1) # note how nasty this is # TODO: get changes in RDF.py to make this # be much better. self.model.__del__() self.model._model=None self.model=None self._storage.__del__() self._storage._storage=None self._storage=None RDF.debug(0) def load(self, uristring): """spider, starting with the seeAlso links at the URI uristring""" if not self._loaded: self._scutter.load_plan(uristring) self._scutter.scutter() print "Merging..." self.model.merge_attributed(FOAF.mboxsha1Node) # print "Merging nicks..." # self.mergeNicks() print "Merging complete." else: print "Not loading more than once." self.model.dump() def lookupNick(self, nick): """find a person's node that matches this nick. braindead, returns first match only.""" folk=self.model.attributed_sources_explain(FOAF.nickNode, RDF.Node(literal=nick)) # we now need to find one of these descriptions tha # has an mbox node for f in folk: (p,c)=f m=self.model.attributed_targets(p, FOAF.mboxNode) if len(m)>0: return f return None def lookupEmail(self, mbox): """find a person's node that matches this mbox. returns first match.""" folk=self.model.attributed_sources_explain(FOAF.mboxNode, RDF.Node(uri_string="mailto:"+mbox)) if len(folk)>0: return folk[0] else: return None def lookupName(self, name): """find a person's node that matches this name. brainded, returns first match only""" folk=self.model.attributed_sources_explain(FOAF.nameNode, RDF.Node(literal=name)) # we now need to find one of these descriptions that # has an mbox node for f in folk: (p,c)=f m=self.model.attributed_targets(p, FOAF.mboxNode) if len(m)>0: return f return None def findProperty(self, subject, property): return self.model.attributed_targets_explain(subject, property) def quickAndDirtyProperty(self, subject, property): res=self.model.attributed_targets(subject, property) if len(res)>0: return res[0] else: return None def degradingQuickAndDirtyProperty(self, person, proplist): for p in proplist: r=self.quickAndDirtyProperty(person, p) if r != None: return r return None def planURLStatus(self, urlnode): scode=self._scutter.get_url_status(urlnode) if scode==scutter.SCUTTER_STATUS_OK: return "OK" elif scode==scutter.SCUTTER_STATUS_NEW: return "NEW" elif scode==scutter.SCUTTER_STATUS_ERROR: return "ERROR" else: return "UNKNOWN" def planURLsFrom(self, person): """returns a list of tuples (uri, referring uri, referring uri owner, status) for all URIs owned by 'person'""" print "looking for plan nodes from",person urllist=[] for u in self._scutter.get_urls_from(person): referrer=self._scutter.get_url_referrer(u) status=self.planURLStatus(u) if referrer==scutter.dynPlanNode: # for now, make base plan URLs have no referrer referrer=None if referrer!=None: refowner=self._scutter.get_url_owner(referrer) else: refowner=None urllist.append((u, referrer, refowner, status)) return urllist def datedCreations(self, person): print "looking for datedCreations by",person chatevents=[] eventtimes={} ctxts={} createdThings=self.model.attributed_sources_explain(DC.creatorNode, person) for (e,p) in createdThings: print "this is, by",e,person,'ctxt',p chatevents.append(e) ctxts[e]=p times=self.model.attributed_targets(e, DC.dateNode) if len(times)>0: eventtimes[e]=times[0] r=[] for unode in chatevents: if eventtimes.has_key(unode): r.append((unode, ctxts[unode], str(eventtimes[unode]))) r.sort(lambda (n1,c1,t1),(n2,c2,t2): cmp(t2,t1)) return r def chatEvents2(self, person): print "looking for chatEvents created by",person if 1: return None nicklist=self.model.attributed_targets(person, FOAF.nickNode) chatevents=[] eventtimes={} ctxts={} print "looking at these nicks" nmap={} for n in nicklist: print n nmap[n]=1 preds=self.model.attributed_preds(DC.creatorNode) for p in preds: ns=self.model.find_statements(RDF.Statement(subject=None, predicate=p, object=None)) while not ns.end(): st=ns.current() knickers=self.model.attributed_targets(st.object, FOAF.nickNode) if (knickers!=None and len(knickers)>0 and nmap.has_key(knickers[0])): # got our creator, let's continue # and see if the created object is # a chatEvent print "node is, by",st.subject,knickers[0] if self.model.attributed_contains_statement( RDF.Statement(subject=st.subject, predicate=FOAF.rdfTypeNode, object=FOAF.chatEventNode)): print "chat is, by",st.subject,knickers[0] chatevents.append(st.subject) if ctxts.has_key(st.subject): ctxts[st.subject].append(p) else: ctxts[st.subject]=[p] times=self.model.attributed_targets(st.subject, DC.dateNode) if times != None and len(times)>0: eventtimes[st.subject]=times[0] ns.next() r=[] for unode in chatevents: if eventtimes.has_key(unode): r.append((unode, ctxts[unode], str(eventtimes[unode]))) r.sort(lambda (n1,c1,t1),(n2,c2,t2): cmp(t2,t1)) return r def chumpContributions(self, person): print "looking for chump items from",person nicklist=self.model.attributed_targets(person, FOAF.nickNode) chumpings=[] chumptimes={} ctxts={} nmap={} for n in nicklist: nmap[n]=1 potentials={} contributorNode=RDF.Node(uri_string="http://usefulinc.com/ns/chump#contributor") contribAtNode=RDF.Node(uri_string="http://usefulinc.com/ns/chump#contributedAt") for n in nmap.keys(): print "looking at nick",n qs=RDF.Statement(subject=None, predicate=FOAF.nickNode, object=n) stream=self.model.find_statements(qs) while not stream.end(): s=RDF.Node(node=stream.current().subject) potentials[s]=1 stream.next() # two strategies: we either hunt through all chumpings, # and manually match for contributor, or we search for all # contributor/chumping pairings. i choose the latter for now for cont in potentials.keys(): print "contributor",cont qs=RDF.Statement(subject=None, predicate=contributorNode, object=cont) stream=self.model.find_statements(qs) while not stream.end(): s=RDF.Node(node=stream.current().subject) print "Found",stream.current() if not ctxts.has_key(s): chumpings.append(s) ctxts[s]=[RDF.Node(node=stream.context())] times=self.model.attributed_targets(s, contribAtNode) if times!= None and len(times)>0: chumptimes[s]=times[0] stream.next() r=[] for unode in chumpings: if chumptimes.has_key(unode): r.append((unode, ctxts[unode], str(chumptimes[unode]))) r.sort(lambda (n1,c1,t1),(n2,c2,t2): cmp(t2,t1)) return r def mergeNicks(self): # cos chatlogs aren't that cool and don't have mboxes rtable={} omap={} ncache={} # first, find sources that request to be merged on nick # for p in self.model.attributed_preds(scutter.planMergePropertyNode): print 'attributed pred',p ns=self.model.find_statements(RDF.Statement(subject=None, predicate=p, object=None)) while not ns.end(): st=ns.current() print st.subject,st.object if st.object==FOAF.nickNode: for o in self.model.attributed_targets(st.subject, scutter.planOwnerNode): omap[o]=1 ns.next() print "Resolving nicks to names..." for v in self.model.attributed_preds(FOAF.nickNode): #print v for sayer in self.model.sayers([v]): if omap.has_key(sayer): ns=self.model.find_statements(RDF.Statement( subject=None, predicate=v, object=None)) if not ns.end(): qq=ns.current() # qq is n=str(qq.object) if ncache.has_key(n): person=ncache[n] else: person=self.lookupNick(n) ncache[n]=person if person: (rtable[qq.subject],chuk)=person print 'scheduling',qq.subject,'->',rtable[qq.subject] ns.next() # for sayer in omap.keys(): # print 'sayer',sayer # for v in self.model.sources(AttributedModel.attrNode, sayer): # preds=self.model.targets(v, AttributedModel.predNode) # if preds[0]==FOAF.nickNode: # ns=self.model.find_statements(RDF.Statement(subject=None, # predicate=v, object=None)) # if not ns.end(): # qq=ns.next() # # qq is # person=self.lookupNick(str(qq.object)) # if person: # (rtable[qq.subject],chuk)=person # print 'scheduling',qq.subject,'->',rtable[qq.subject] print "Canonicalizing nicks..." for sayer in omap.keys(): for v in self.model.sources(AttributedModel.attrNode, sayer): ns=self.model.find_statements(RDF.Statement(subject=None, predicate=v, object=None)) if not ns.end(): st=ns.current() new_s=RDF.Statement(statement=st) clean=1 if rtable.has_key(st.subject): new_s.subject=rtable[st.subject] #print st.subject,'-s>',new_s.subject clean=0 if rtable.has_key(st.object): new_s.object=rtable[st.object] #print st.object,'-o>',new_s.object clean=0 if not clean: self.model.remove_statement(st) self.model.add_statement(new_s) ns.next() def sayers(self, contextlist): # we get a list of context URIs. it's now nice to # resolve those into nicer names; nicks or realnames rlist=[] arlist=[] found={} seen={} for sp in contextlist: if not seen.has_key(sp): owner=self._scutter.get_url_owner(sp) seen[sp]=1 n=None if owner!=None and not found.has_key(owner): found[owner]=1 n=str(self.degradingQuickAndDirtyProperty(owner, [FOAF.nameNode, FOAF.nickNode, FOAF.mboxNode])) if n[0:4]=='Anon': arlist.append(n) else: rlist.append(n) s="" rlist.sort(lambda a,b: cmp (a,b)) arlist.sort(lambda a,b: cmp (a,b)) if len(rlist): s=string.join(rlist, ", ") if len(arlist): s=s+"; and anonymous sources " if len(arlist): s=s+string.join(arlist, ", ") return s def findCodepiction(self, nodelist): print "codepict nodelist is",nodelist pics={} ctxts={} findmap={} num=len(nodelist) for (f, c) in nodelist: findmap[f]=1 qs=RDF.Statement(subject=None, predicate=FOAF.depictionNode, object=None) stream=self.model.find_statements(qs) while not stream.end(): st=stream.current() o=RDF.Node(node=st.object) s=RDF.Node(node=st.subject) if findmap.has_key(s): if pics.has_key(o): pics[o][s]=1 ctxts[o].append(RDF.Node(node=stream.context())) else: pics[o]={s: 1} ctxts[o]=[RDF.Node(node=stream.context())] stream.next() qs=RDF.Statement(subject=None, predicate=FOAF.depictsNode, object=None) stream=self.model.find_statements(qs) while not stream.end(): st=stream.current() o=RDF.Node(node=st.object) s=RDF.Node(node=st.subject) if findmap.has_key(o): if pics.has_key(s): pics[s][o]=1 ctxts[s].append(RDF.Node(node=stream.context())) else: pics[s]={o: 1} ctxts[s]=[RDF.Node(node=stream.context())] stream.next() # now we have a list of the pictures with people we're # interested in. now go to look for ones which have all 3 res=[] for pic in pics.keys(): if len(pics[pic].keys())==num: # matching setsize means we win res.append((pic, ctxts[pic])) return res def forgetFrom(self, sayer): for n in self._scutter.get_urls_from(sayer): print "Forgetting", n self.model.delete_by_sayer(n) def reloadFrom(self, sayer): for n in self._scutter.get_urls_from(sayer): self._scutter.set_url_status(n, scutter.SCUTTER_STATUS_NEW) self._scutter.scutter() print "Merging..." self.model.merge_attributed(FOAF.mboxsha1Node) foafbot-0.5/foafbot.py0100775000016500001440000003466507671462512014364 0ustar edmunddusers#!/usr/bin/python2.2 # $Id: foafbot.py,v 1.11 2002/08/02 21:58:00 edmundd Exp $ # # Copyright (C) 2002 Edd Dumbill # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. import RDF import urllib2 import os import FOAF import DC import string import re import time import profile import getopt import sys from oracle import Oracle from ircbot import SingleServerIRCBot from irclib import nm_to_n, irc_lower query_pat=re.compile(r'([A-Za-z_ @\.\-0-9]+)\'s\s+(.+)\??') depiction_pat=re.compile(r'picture\s+of\s+([A-Za-z_ @\.\-0-9]+)\??', re.IGNORECASE) forget_pat=re.compile(r'(reload|forget)\s+from\s+([A-Za-z_ @\.\-0-9]+)', re.IGNORECASE) status_pat=re.compile(r'status\s+of\s+(.+)', re.IGNORECASE) and_pat=re.compile(r'\s+and\s+', re.IGNORECASE) space_pat=re.compile(r'\s+') def squish_space(s): return string.join(space_pat.split(s), " ") class OracleBotQuitException(Exception): pass class OracleBot(SingleServerIRCBot): def __init__(self, connection, nick, name, start_anew=1, keyids=[]): SingleServerIRCBot.__init__(self, connection, nick, name) self.oracle=Oracle(self._nickname, start_anew, keyids) def quit(self): self.oracle.close() SingleServerIRCBot.disconnect(self, "aagh! a well!") raise OracleBotQuitException("On user request") def on_welcome(self, c, e): for chan in self.join_channels: c.join(chan) self.nick_pat=re.compile(self._nickname+"[:,]\s*(.*)") def give_help(self, c, target): c.privmsg(target, "Ask me things like \"foo's email\", where foo is the nick of someone") c.privmsg(target, "Read more about me at http://usefulinc.com/foaf/foafbot") def on_privmsg(self, c, e): msg = e.arguments()[0] nick = nm_to_n(e.source()) print e.target(), "::", msg, "from",nick self.handle_instruction(c, e, msg, nick) def on_pubmsg(self, c, e): msg = e.arguments()[0] nick = nm_to_n(e.source()) print e.target(), "::", msg, "from",nick m = self.nick_pat.match(msg) if m: instruction=m.group(1) self.handle_instruction(c, e, instruction, e.target()) def lookup_target(self, who): target=self.oracle.lookupNick(who) if target==None: target=self.oracle.lookupEmail(who) if target==None: target=self.oracle.lookupName(who) return target def make_reply(self, c, replyto, replylines): for r in replylines: print "> %s: %s" % (replyto, r) if replyto!=None: c.privmsg(replyto, r) def handle_instruction(self, c, e, instruction, replyto): if instruction[-1]=='?': instruction=instruction[:-1] if instruction=="help": self.give_help(c, replyto) elif instruction=="quit" or instruction=="die": self.quit() else: m = query_pat.match(instruction) p = depiction_pat.match(instruction) if m: who=m.group(1) what=m.group(2) target=self.lookup_target(who) if target==None: c.privmsg(replyto, "Can't identify '%s', sorry." % who) else: (person, psayers)=target replylines=self.answer_query(person, who, what) self.make_reply(c, replyto, replylines) elif p: who=and_pat.split(p.group(1)) who_nodes=[] for p in who: target=self.lookup_target(p) if target==None: c.privmsg(replyto, "Can't identify '%s', sorry." % p) else: who_nodes.append(target) if len(who)==len(who_nodes): replylines=self.find_codepiction(who_nodes) self.make_reply(c, replyto, replylines) else: f=forget_pat.match(instruction) if f: what=f.group(1) who=f.group(2) target=self.lookup_target(who) if target==None: c.privmsg(replyto, "Can't identify '%s', sorry." % who) elif string.lower(what)=='reload': replylines=self.forget_from(target, who) self.make_reply(c, replyto, replylines) replylines=["Reloading and merging..."] self.make_reply(c, replyto, replylines) replylines=self.reload_from(target, who) self.make_reply(c, replyto, replylines) else: replylines=self.forget_from(target, who) self.make_reply(c, replyto, replylines) f=status_pat.match(instruction) if f: url=f.group(1) replylines=self.url_status(url) self.make_reply(c, replyto, replylines) def query_simple_property(self, person, who, what, rdfnode): r=[] res=self.oracle.findProperty(person, rdfnode) if len(res): for (result, ctxt) in res: r.append("%s's %s is '%s', according to %s" % (who, what, str(result), self.oracle.sayers(ctxt))) else: r.append("Sorry, I don't know %s's %s" % (who,what)) return r def query_image(self, person, who): r=[] res=self.oracle.findProperty(person, FOAF.imageNode) if len(res): for (result, ctxt) in res: desc=self.oracle.degradingQuickAndDirtyProperty(result, [DC.descriptionNode, DC.titleNode]) r.append("%s's photo is at %s -- according to %s" % (who, str(result.uri), self.oracle.sayers(ctxt))) if desc: r.append("Caption: %s" % squish_space(str(desc))) else: r.append("Sorry, I can't find %s's photo. You could try asking me 'picture of %s'" % (who,who)) return r def answer_query(self, person, who, what): r=[] if what=="email": r=self.query_simple_property(person, who, what, FOAF.mboxNode) elif what=="nick" or what=="handle" or what=="nickname": r=self.query_simple_property(person, who, what, FOAF.nickNode) elif what=="name": r=self.query_simple_property(person, who, what, FOAF.nameNode) elif what=="photo" or what=="image": r=self.query_image(person, who) elif what=="workplace" or what=="office": r=self.query_simple_property(person, who, what, FOAF.workplaceHomepageNode) elif what=="phone": r=self.query_simple_property(person, who, what, FOAF.phoneNode) elif (what=="homepage" or what=="web site" or what=="website"): r=self.query_simple_property(person, who, what, FOAF.homepageNode) elif (what=="bookmarks" or what=="chumpings"): r=self.find_chumpings(person, who) elif (what=="urls" or what=="uris" or what=="files"): r=self.find_plan_urls(person, who) elif (what=="utterings" or what=="mumblings" or what=="sayings" or what=="words" or what=="chatevents" or what=="chat"): r=self.find_chatevents(person, who) else: r=["I don't know how to find the property '%s'" % what] return r def find_codepiction(self, nodelist): r=[] pics=self.oracle.findCodepiction(nodelist) if pics==None or len(pics)==0: r.append("Sorry, couldn't find any appropriate pictures.") else: n=len(pics) if n>3: r.append("Found %d pictures, just showing 3." % n) n=3 i=0 while i3: r.append("Found %d entries, reporting the most recent 3." % n) n=3 i=0 while i3: r.append("Found %d entries, reporting the most recent 3." % n) n=3 i=0 while i filename of default scutterplan -s, --server specify IRC server to connect -n, --nick nickname to connect to IRC with -c, --channel name of IRC channel (omit leading #) (can have more than one channel) -f, --fresh respider, even if database exists -k, --keyid 8-digit hex ID of PGP key to decrypt with (can have more than one)""" % \ (sys.argv[0]) def main(): channel=None server=None nickname=None planfile=None channels=[] keyids=[] start_fresh=0 try: opts, args = getopt.getopt(sys.argv[1:], "hp:s:n:c:fk:", ["help", "plan=", "server=", "nick=", "channel=", "fresh", "keyid="]) except getopt.GetoptError: usage() sys.exit(2) for o, a in opts: if o in ("-h", "--help"): usage() sys.exit(0) elif o in ("-p", "--plan"): planfile=a elif o in ("-s", "--server"): server=a elif o in ("-n", "--nickname"): nickname=a elif o in ("-c", "--channel"): channels.append(a) elif o in ("-f", "--fresh"): start_fresh=1 elif o in ("-k", "--keyid"): keyids.append(a) if len(channels)==0: print "Error: need to specify at least one IRC channel" usage() sys.exit(2) elif server==None: print "Error: need to specify IRC server" usage() sys.exit(2) elif nickname==None: nickname='foafbot' elif planfile==None: planfile='./plan.rdf' obot=OracleBot([(server, 6667)], nickname, nickname, start_fresh, keyids) obot.join_channels=[] for c in channels: if c[0]!='#' and c[0]!='&': c='#'+c obot.join_channels.append(c) obot.planfile=("file:%s" % planfile) if start_fresh: obot.load_oracle() obot.oracle.model.dump() print 'Joining channels %s on %s' % (str(channels), server) try: obot.start() except OracleBotQuitException, e: print "Quitting (%s)" % e if __name__=="__main__": main() foafbot-0.5/irclib.py0100664000016500001440000011506707671462512014201 0ustar edmunddusers# Copyright (C) 1999, 2000 Joel Rosdahl # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # Joel Rosdahl # # $Id: irclib.py,v 1.1 2002/06/03 20:48:22 edmundd Exp $ """irclib -- Internet Relay Chat (IRC) protocol client library. This library is intended to encapsulate the IRC protocol at a quite low level. It provides an event-driven IRC client framework. It has a fairly thorough support for the basic IRC protocol and CTCP, but DCC connection support is not yet implemented. In order to understand how to make an IRC client, I'm afraid you more or less must understand the IRC specifications. They are available here: [IRC specifications]. The main features of the IRC client framework are: * Abstraction of the IRC protocol. * Handles multiple simultaneous IRC server connections. * Handles server PONGing transparently. * Messages to the IRC server are done by calling methods on an IRC connection object. * Messages from an IRC server triggers events, which can be caught by event handlers. * Reading from and writing to IRC server sockets are normally done by an internal select() loop, but the select()ing may be done by an external main loop. * Functions can be registered to execute at specified times by the event-loop. * Decodes CTCP tagging correctly (hopefully); I haven't seen any other IRC client implementation that handles the CTCP specification subtilties. * A kind of simple, single-server, object-oriented IRC client class that dispatches events to instance methods is included. Current limitations: * The IRC protocol shines through the abstraction a bit too much. * Data is not written asynchronously to the server, i.e. the write() may block if the TCP buffers are stuffed. * There are no support for DCC connections. * The author haven't even read RFC 2810, 2811, 2812 and 2813. * Like most projects, documentation is lacking... Since I seldom use IRC anymore, I will probably not work much on the library. If you want to help or continue developing the library, please contact me (Joel Rosdahl ). .. [IRC specifications] http://www.irchelp.org/irchelp/rfc/ """ import bisect import re import select import socket import string import sys import time import types VERSION = 0, 3, 1 DEBUG = 0 # TODO # ---- # DCC # (maybe) thread safety # (maybe) color parser convenience functions # documentation (including all event types) # (maybe) add awareness of different types of ircds # send data asynchronously to the server # NOTES # ----- # connection.quit() only sends QUIT to the server. # ERROR from the server triggers the error event and the disconnect event. # dropping of the connection triggers the disconnect event. class IRCError(Exception): """Represents an IRC exception.""" pass class IRC: """Class that handles one or several IRC server connections. When an IRC object has been instantiated, it can be used to create Connection objects that represent the IRC connections. The responsibility of the IRC object is to provide an event-driven framework for the connections and to keep the connections alive. It runs a select loop to poll each connection's TCP socket and hands over the sockets with incoming data for processing by the corresponding connection. The methods of most interest for an IRC client writer are server, add_global_handler, remove_global_handler, execute_at, execute_delayed, process_once and process_forever. Here is an example: irc = irclib.IRC() server = irc.server() server.connect(\"irc.some.where\", 6667, \"my_nickname\") server.privmsg(\"a_nickname\", \"Hi there!\") server.process_forever() This will connect to the IRC server irc.some.where on port 6667 using the nickname my_nickname and send the message \"Hi there!\" to the nickname a_nickname. """ def __init__(self, fn_to_add_socket=None, fn_to_remove_socket=None, fn_to_add_timeout=None): """Constructor for IRC objects. Optional arguments are fn_to_add_socket, fn_to_remove_socket and fn_to_add_timeout. The first two specify functions that will be called with a socket object as argument when the IRC object wants to be notified (or stop being notified) of data coming on a new socket. When new data arrives, the method process_data should be called. Similarly, fn_to_add_timeout is called with a number of seconds (a floating point number) as first argument when the IRC object wants to receive a notification (by calling the process_timeout method). So, if e.g. the argument is 42.17, the object wants the process_timeout method to be called after 42 seconds and 170 milliseconds. The three arguments mainly exist to be able to use an external main loop (for example Tkinter's or PyGTK's main app loop) instead of calling the process_forever method. An alternative is to just call ServerConnection.process_once() once in a while. """ if fn_to_add_socket and fn_to_remove_socket: self.fn_to_add_socket = fn_to_add_socket self.fn_to_remove_socket = fn_to_remove_socket else: self.fn_to_add_socket = None self.fn_to_remove_socket = None self.fn_to_add_timeout = fn_to_add_timeout self.connections = [] self.handlers = {} self.delayed_commands = [] # list of tuples in the format (time, function, arguments) self.add_global_handler("ping", _ping_ponger, -42) def server(self): """Creates and returns a ServerConnection object.""" c = ServerConnection(self) self.connections.append(c) return c def process_data(self, sockets): """Called when there is more data to read on connection sockets. Arguments: sockets -- A list of socket objects. See documentation for IRC.__init__. """ for s in sockets: for c in self.connections: if s == c._get_socket(): c.process_data() def process_timeout(self): """Called when a timeout notification is due. See documentation for IRC.__init__. """ t = time.time() while self.delayed_commands: if t >= self.delayed_commands[0][0]: apply(self.delayed_commands[0][1], self.delayed_commands[0][2]) del self.delayed_commands[0] else: break def process_once(self, timeout=0): """Process data from connections once. Arguments: timeout -- How long the select() call should wait if no data is available. This method should be called periodically to check and process incoming data, if there are any. If that seems boring, look at the process_forever method. """ sockets = map(lambda x: x._get_socket(), self.connections) sockets = filter(lambda x: x != None, sockets) if sockets: (i, o, e) = select.select(sockets, [], [], timeout) self.process_data(i) else: time.sleep(timeout) self.process_timeout() def process_forever(self, timeout=0.2): """Run an infinite loop, processing data from connections. This method repeatedly calls process_once. Arguments: timeout -- Parameter to pass to process_once. """ while 1: self.process_once(timeout) def disconnect_all(self, message=""): """Disconnects all connections.""" for c in self.connections: c.quit(message) c.disconnect(message) def add_global_handler(self, event, handler, priority=0): """Adds a global handler function for a specific event type. Arguments: event -- Event type (a string). Check the values of the numeric_events dictionary in irclib.py for possible event types. handler -- Callback function. priority -- A number (the lower number, the higher priority). The handler function is called whenever the specified event is triggered in any of the connections. See documentation for the Event class. The handler functions are called in priority order (lowest number is highest priority). If a handler function returns \"NO MORE\", no more handlers will be called. """ if not self.handlers.has_key(event): self.handlers[event] = [] bisect.insort(self.handlers[event], ((priority, handler))) def remove_global_handler(self, event, handler): """Removes a global handler function. Arguments: event -- Event type (a string). handler -- Callback function. Returns 1 on success, otherwise 0. """ if not self.handlers.has_key(event): return 0 for h in self.handlers[event]: if handler == h[1]: self.handlers[event].remove(h) return 1 def execute_at(self, at, function, arguments=()): """Execute a function at a specified time. Arguments: at -- Execute at this time (standard \"time_t\" time). function -- Function to call. arguments -- Arguments to give the function. """ self.execute_delayed(at-time.time(), function, arguments) def execute_delayed(self, delay, function, arguments=()): """Execute a function after a specified time. Arguments: delay -- How many seconds to wait. function -- Function to call. arguments -- Arguments to give the function. """ bisect.insort(self.delayed_commands, (delay+time.time(), function, arguments)) if self.fn_to_add_timeout: self.fn_to_add_timeout(delay) def _handle_event(self, connection, event): """[Internal]""" h = self.handlers for handler in h.get("all_events", []) + h.get(event.eventtype(), []): if handler[1](connection, event) == "NO MORE": return def _remove_connection(self, connection): """[Internal]""" self.connections.remove(connection) if self.fn_to_remove_socket: self.fn_to_remove_socket(connection._get_socket()) _rfc_1459_command_regexp = re.compile("^(:(?P[^ ]+) +)?(?P[^ ]+)( *(?P .+))?") class Connection: """Base class for IRC connections. Must be overridden. """ def __init__(self, irclibobj): self.irclibobj = irclibobj def _get_socket(): raise IRCError, "Not overridden" ############################## ### Convenience wrappers. def execute_at(self, at, function, arguments=()): self.irclibobj.execute_at(at, function, arguments) def execute_delayed(self, delay, function, arguments=()): self.irclibobj.execute_delayed(delay, function, arguments) class ServerConnectionError(IRCError): pass # Huh!? Crrrrazy EFNet doesn't follow the RFC: their ircd seems to # use \n as message separator! :P _linesep_regexp = re.compile("\r?\n") class ServerConnection(Connection): """This class represents an IRC server connection. ServerConnection objects are instantiated by calling the server method on an IRC object. """ def __init__(self, irclibobj): Connection.__init__(self, irclibobj) self.connected = 0 # Not connected yet. def connect(self, server, port, nickname, password=None, username=None, ircname=None): """Connect/reconnect to a server. Arguments: server -- Server name. port -- Port number. nickname -- The nickname. password -- Password (if any). username -- The username. ircname -- The IRC name. This function can be called to reconnect a closed connection. Returns the ServerConnection object. """ if self.connected: self.quit("Changing server") self.socket = None self.previous_buffer = "" self.handlers = {} self.real_server_name = "" self.real_nickname = nickname self.server = server self.port = port self.nickname = nickname self.username = username or nickname self.ircname = ircname or nickname self.password = password self.localhost = socket.gethostname() self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.socket.connect((self.server, self.port)) except socket.error, x: raise ServerConnectionError, "Couldn't connect to socket: %s" % x self.connected = 1 if self.irclibobj.fn_to_add_socket: self.irclibobj.fn_to_add_socket(self.socket) # Log on... if self.password: self.pass_(self.password) self.nick(self.nickname) self.user(self.username, self.localhost, self.server, self.ircname) return self def close(self): """Close the connection. This method closes the connection permanently; after it has been called, the object is unusable. """ self.disconnect("Closing object") self.irclibobj._remove_connection(self) def _get_socket(self): """[Internal]""" if self.connected: return self.socket else: return None def get_server_name(self): """Get the (real) server name. This method returns the (real) server name, or, more specifically, what the server calls itself. """ if self.real_server_name: return self.real_server_name else: return "" def get_nickname(self): """Get the (real) nick name. This method returns the (real) nickname. The library keeps track of nick changes, so it might not be the nick name that was passed to the connect() method. """ return self.real_nickname def process_data(self): """[Internal]""" try: new_data = self.socket.recv(2**14) except socket.error, x: # The server hung up. self.disconnect("Connection reset by peer") return if not new_data: # Read nothing: connection must be down. self.disconnect("Connection reset by peer") return lines = _linesep_regexp.split(self.previous_buffer + new_data) # Save the last, unfinished line. self.previous_buffer = lines[-1] lines = lines[:-1] for line in lines: if DEBUG: print "FROM SERVER:", line prefix = None command = None arguments = None self._handle_event(Event("all_raw_messages", self.get_server_name(), None, [line])) m = _rfc_1459_command_regexp.match(line) if m.group("prefix"): prefix = m.group("prefix") if not self.real_server_name: self.real_server_name = prefix if m.group("command"): command = string.lower(m.group("command")) if m.group("argument"): a = string.split(m.group("argument"), " :", 1) arguments = string.split(a[0]) if len(a) == 2: arguments.append(a[1]) if command == "nick": if nm_to_n(prefix) == self.real_nickname: self.real_nickname = arguments[0] if command in ["privmsg", "notice"]: target, message = arguments[0], arguments[1] messages = _ctcp_dequote(message) if command == "privmsg": if is_channel(target): command = "pubmsg" else: if is_channel(target): command = "pubnotice" else: command = "privnotice" for m in messages: if type(m) is types.TupleType: if command in ["privmsg", "pubmsg"]: command = "ctcp" else: command = "ctcpreply" m = list(m) if DEBUG: print "command: %s, source: %s, target: %s, arguments: %s" % ( command, prefix, target, m) self._handle_event(Event(command, prefix, target, m)) else: if DEBUG: print "command: %s, source: %s, target: %s, arguments: %s" % ( command, prefix, target, [m]) self._handle_event(Event(command, prefix, target, [m])) else: target = None if command == "quit": arguments = [arguments[0]] elif command == "ping": target = arguments[0] else: target = arguments[0] arguments = arguments[1:] if command == "mode": if not is_channel(target): command = "umode" # Translate numerics into more readable strings. if numeric_events.has_key(command): command = numeric_events[command] if DEBUG: print "command: %s, source: %s, target: %s, arguments: %s" % ( command, prefix, target, arguments) self._handle_event(Event(command, prefix, target, arguments)) def _handle_event(self, event): """[Internal]""" self.irclibobj._handle_event(self, event) if self.handlers.has_key(event.eventtype()): for fn in self.handlers[event.eventtype()]: fn(self, event) def is_connected(self): """Return connection status. Returns true if connected, otherwise false. """ return self.connected def add_global_handler(self, *args): """Add global handler. See documentation for IRC.add_global_handler. """ apply(self.irclibobj.add_global_handler, args) def action(self, target, action): """Send a CTCP ACTION command.""" self.ctcp("ACTION", target, action) def admin(self, server=""): """Send an ADMIN command.""" self.send_raw(string.strip(string.join(["ADMIN", server]))) def ctcp(self, ctcptype, target, parameter=""): """Send a CTCP command.""" ctcptype = string.upper(ctcptype) self.privmsg(target, "\001%s%s\001" % (ctcptype, parameter and (" " + parameter) or "")) def ctcp_reply(self, target, parameter): """Send a CTCP REPLY command.""" self.notice(target, "\001%s\001" % parameter) def disconnect(self, message=""): """Hang up the connection. Arguments: message -- Quit message. """ if self.connected == 0: return self.connected = 0 try: self.socket.close() except socket.error, x: pass self.socket = None self._handle_event(Event("disconnect", self.server, "", [message])) def globops(self, text): """Send a GLOBOPS command.""" self.send_raw("GLOBOPS :" + text) def info(self, server=""): """Send an INFO command.""" self.send_raw(string.strip(string.join(["INFO", server]))) def invite(self, nick, channel): """Send an INVITE command.""" self.send_raw(string.strip(string.join(["INVITE", nick, channel]))) def ison(self, nicks): """Send an ISON command. Arguments: nicks -- List of nicks. """ self.send_raw("ISON " + string.join(nicks, ",")) def join(self, channel, key=""): """Send a JOIN command.""" self.send_raw("JOIN %s%s" % (channel, (key and (" " + key)))) def kick(self, channel, nick, comment=""): """Send a KICK command.""" self.send_raw("KICK %s %s%s" % (channel, nick, (comment and (" :" + comment)))) def links(self, remote_server="", server_mask=""): """Send a LINKS command.""" command = "LINKS" if remote_server: command = command + " " + remote_server if server_mask: command = command + " " + server_mask self.send_raw(command) def list(self, channels=None, server=""): """Send a LIST command.""" command = "LIST" if channels: command = command + " " + string.join(channels, ",") if server: command = command + " " + server self.send_raw(command) def lusers(self, server=""): """Send a LUSERS command.""" self.send_raw("LUSERS" + (server and (" " + server))) def mode(self, target, command): """Send a MODE command.""" self.send_raw("MODE %s %s" % (target, command)) def motd(self, server=""): """Send an MOTD command.""" self.send_raw("MOTD" + (server and (" " + server))) def names(self, channels=None): """Send a NAMES command.""" self.send_raw("NAMES" + (channels and (" " + string.join(channels, ",")) or "")) def nick(self, newnick): """Send a NICK command.""" self.send_raw("NICK " + newnick) def notice(self, target, text): """Send a NOTICE command.""" # Should limit len(text) here! self.send_raw("NOTICE %s :%s" % (target, text)) def oper(self, nick, password): """Send an OPER command.""" self.send_raw("OPER %s %s" % (nick, password)) def part(self, channels): """Send a PART command.""" if type(channels) == types.StringType: self.send_raw("PART " + channels) else: self.send_raw("PART " + string.join(channels, ",")) def pass_(self, password): """Send a PASS command.""" self.send_raw("PASS " + password) def ping(self, target, target2=""): """Send a PING command.""" self.send_raw("PING %s%s" % (target, target2 and (" " + target2))) def pong(self, target, target2=""): """Send a PONG command.""" self.send_raw("PONG %s%s" % (target, target2 and (" " + target2))) def privmsg(self, target, text): """Send a PRIVMSG command.""" # Should limit len(text) here! self.send_raw("PRIVMSG %s :%s" % (target, text)) def privmsg_many(self, targets, text): """Send a PRIVMSG command to multiple targets.""" # Should limit len(text) here! self.send_raw("PRIVMSG %s :%s" % (string.join(targets, ","), text)) def quit(self, message=""): """Send a QUIT command.""" self.send_raw("QUIT" + (message and (" :" + message))) def sconnect(self, target, port="", server=""): """Send an SCONNECT command.""" self.send_raw("CONNECT %s%s%s" % (target, port and (" " + port), server and (" " + server))) def send_raw(self, string): """Send raw string to the server. The string will be padded with appropriate CR LF. """ try: self.socket.send(string + "\r\n") if DEBUG: print "TO SERVER:", string except socket.error, x: # Aouch! self.disconnect("Connection reset by peer.") def squit(self, server, comment=""): """Send an SQUIT command.""" self.send_raw("SQUIT %s%s" % (server, comment and (" :" + comment))) def stats(self, statstype, server=""): """Send a STATS command.""" self.send_raw("STATS %s%s" % (statstype, server and (" " + server))) def time(self, server=""): """Send a TIME command.""" self.send_raw("TIME" + (server and (" " + server))) def topic(self, channel, new_topic=None): """Send a TOPIC command.""" if new_topic == None: self.send_raw("TOPIC " + channel) else: self.send_raw("TOPIC %s :%s" % (channel, new_topic)) def trace(self, target=""): """Send a TRACE command.""" self.send_raw("TRACE" + (target and (" " + target))) def user(self, username, localhost, server, ircname): """Send a USER command.""" self.send_raw("USER %s %s %s :%s" % (username, localhost, server, ircname)) def userhost(self, nicks): """Send a USERHOST command.""" self.send_raw("USERHOST " + string.join(nicks, ",")) def users(self, server=""): """Send a USERS command.""" self.send_raw("USERS" + (server and (" " + server))) def version(self, server=""): """Send a VERSION command.""" self.send_raw("VERSION" + (server and (" " + server))) def wallops(self, text): """Send a WALLOPS command.""" self.send_raw("WALLOPS :" + text) def who(self, target="", op=""): """Send a WHO command.""" self.send_raw("WHO%s%s" % (target and (" " + target), op and (" o"))) def whois(self, targets): """Send a WHOIS command.""" self.send_raw("WHOIS " + string.join(targets, ",")) def whowas(self, nick, max=None, server=""): """Send a WHOWAS command.""" self.send_raw("WHOWAS %s%s%s" % (nick, max and (" " + max), server and (" " + server))) class DCCConnection(Connection): """Unimplemented.""" def __init__(self): raise IRCError, "Unimplemented." class SimpleIRCClient: """A simple single-server IRC client class. This is an example of an object-oriented wrapper of the IRC framework. A real IRC client can be made by subclassing this class and adding appropriate methods. The method on_join will be called when a "join" event is created (which is done when the server sends a JOIN messsage/command), on_privmsg will be called for "privmsg" events, and so on. The handler methods get two arguments: the connection object (same as self.connection) and the event object. Instance attributes that can be used by sub classes: ircobj -- The IRC instance. connection -- The ServerConnection instance. """ def __init__(self): self.ircobj = IRC() self.connection = self.ircobj.server() self.ircobj.add_global_handler("all_events", self._dispatcher, -10) def _dispatcher(self, c, e): """[Internal]""" m = "on_" + e.eventtype() if hasattr(self, m): getattr(self, m)(c, e) def connect(self, server, port, nickname, password=None, username=None, ircname=None): """Connect/reconnect to a server. Arguments: server -- Server name. port -- Port number. nickname -- The nickname. password -- Password (if any). username -- The username. ircname -- The IRC name. This function can be called to reconnect a closed connection. """ self.connection.connect(server, port, nickname, password, username, ircname) def start(self): """Start the IRC client.""" self.ircobj.process_forever() class Event: """Class representing an IRC event.""" def __init__(self, eventtype, source, target, arguments=None): """Constructor of Event objects. Arguments: eventtype -- A string describing the event. source -- The originator of the event (a nick mask or a server). XXX Correct? target -- The target of the event (a nick or a channel). XXX Correct? arguments -- Any event specific arguments. """ self._eventtype = eventtype self._source = source self._target = target if arguments: self._arguments = arguments else: self._arguments = [] def eventtype(self): """Get the event type.""" return self._eventtype def source(self): """Get the event source.""" return self._source def target(self): """Get the event target.""" return self._target def arguments(self): """Get the event arguments.""" return self._arguments _LOW_LEVEL_QUOTE = "\020" _CTCP_LEVEL_QUOTE = "\134" _CTCP_DELIMITER = "\001" _low_level_mapping = { "0": "\000", "n": "\n", "r": "\r", _LOW_LEVEL_QUOTE: _LOW_LEVEL_QUOTE } _low_level_regexp = re.compile(_LOW_LEVEL_QUOTE + "(.)") def mask_matches(nick, mask): """Check if a nick matches a mask. Returns true if the nick matches, otherwise false. """ nick = irc_lower(nick) mask = irc_lower(mask) mask = string.replace(mask, "\\", "\\\\") for ch in ".$|[](){}+": mask = string.replace(mask, ch, "\\" + ch) mask = string.replace(mask, "?", ".") mask = string.replace(mask, "*", ".*") r = re.compile(mask, re.IGNORECASE) return r.match(nick) _alpha = "abcdefghijklmnopqrstuvxyz" _special = "-[]\\`^{}" nick_characters = _alpha + string.upper(_alpha) + string.digits + _special _ircstring_translation = string.maketrans(string.upper(_alpha) + "[]\\^", _alpha + "{}|~") def irc_lower(s): """Returns a lowercased string. The definition of lowercased comes from the IRC specification (RFC 1459). """ return string.translate(s, _ircstring_translation) def _ctcp_dequote(message): """[Internal] Dequote a message according to CTCP specifications. The function returns a list where each element can be either a string (normal message) or a tuple of one or two strings (tagged messages). If a tuple has only one element (ie is a singleton), that element is the tag; otherwise the tuple has two elements: the tag and the data. Arguments: message -- The message to be decoded. """ def _low_level_replace(match_obj): ch = match_obj.group(1) # If low_level_mapping doesn't have the character as key, we # should just return the character. return _low_level_mapping.get(ch, ch) if _LOW_LEVEL_QUOTE in message: # Yup, there was a quote. Release the dequoter, man! message = _low_level_regexp.sub(_low_level_replace, message) if _CTCP_DELIMITER not in message: return [message] else: # Split it into parts. (Does any IRC client actually *use* # CTCP stacking like this?) chunks = string.split(message, _CTCP_DELIMITER) messages = [] i = 0 while i < len(chunks)-1: # Add message if it's non-empty. if len(chunks[i]) > 0: messages.append(chunks[i]) if i < len(chunks)-2: # Aye! CTCP tagged data ahead! messages.append(tuple(string.split(chunks[i+1], " ", 1))) i = i + 2 if len(chunks) % 2 == 0: # Hey, a lonely _CTCP_DELIMITER at the end! This means # that the last chunk, including the delimiter, is a # normal message! (This is according to the CTCP # specification.) messages.append(_CTCP_DELIMITER + chunks[-1]) return messages def is_channel(string): """Check if a string is a channel name. Returns true if the argument is a channel name, otherwise false. """ return string and string[0] in "#&+!" def nm_to_n(s): """Get the nick part of a nickmask. (The source of an Event is a nickmask.) """ return string.split(s, "!")[0] def nm_to_uh(s): """Get the userhost part of a nickmask. (The source of an Event is a nickmask.) """ return string.split(s, "!")[1] def nm_to_h(s): """Get the host part of a nickmask. (The source of an Event is a nickmask.) """ return string.split(s, "@")[1] def nm_to_u(s): """Get the user part of a nickmask. (The source of an Event is a nickmask.) """ s = string.split(s, "!")[1] return string.split(s, "@")[0] def parse_nick_modes(mode_string): """Parse a nick mode string. The function returns a list of lists with three members: sign, mode and argument. The sign is \"+\" or \"-\". The argument is always None. Example: >>> irclib.parse_nick_modes(\"+ab-c\") [['+', 'a', None], ['+', 'b', None], ['-', 'c', None]] """ return _parse_modes(mode_string, "") def parse_channel_modes(mode_string): """Parse a channel mode string. The function returns a list of lists with three members: sign, mode and argument. The sign is \"+\" or \"-\". The argument is None if mode isn't one of \"b\", \"k\", \"l\", \"v\" or \"o\". Example: >>> irclib.parse_channel_modes(\"+ab-c foo\") [['+', 'a', None], ['+', 'b', 'foo'], ['-', 'c', None]] """ return _parse_modes(mode_string, "bklvo") def _parse_modes(mode_string, unary_modes=""): """[Internal]""" modes = [] arg_count = 0 # State variable. sign = "" a = string.split(mode_string) if len(a) == 0: return [] else: mode_part, args = a[0], a[1:] if mode_part[0] not in "+-": return [] for ch in mode_part: if ch in "+-": sign = ch elif ch == " ": collecting_arguments = 1 elif ch in unary_modes: modes.append([sign, ch, args[arg_count]]) arg_count = arg_count + 1 else: modes.append([sign, ch, None]) return modes def _ping_ponger(connection, event): """[Internal]""" connection.pong(event.target()) # Numeric table mostly stolen from the Perl IRC module (Net::IRC). numeric_events = { "001": "welcome", "002": "yourhost", "003": "created", "004": "myinfo", "005": "featurelist", # XXX "200": "tracelink", "201": "traceconnecting", "202": "tracehandshake", "203": "traceunknown", "204": "traceoperator", "205": "traceuser", "206": "traceserver", "208": "tracenewtype", "209": "traceclass", "211": "statslinkinfo", "212": "statscommands", "213": "statscline", "214": "statsnline", "215": "statsiline", "216": "statskline", "217": "statsqline", "218": "statsyline", "219": "endofstats", "221": "umodeis", "231": "serviceinfo", "232": "endofservices", "233": "service", "234": "servlist", "235": "servlistend", "241": "statslline", "242": "statsuptime", "243": "statsoline", "244": "statshline", "250": "luserconns", "251": "luserclient", "252": "luserop", "253": "luserunknown", "254": "luserchannels", "255": "luserme", "256": "adminme", "257": "adminloc1", "258": "adminloc2", "259": "adminemail", "261": "tracelog", "262": "endoftrace", "265": "n_local", "266": "n_global", "300": "none", "301": "away", "302": "userhost", "303": "ison", "305": "unaway", "306": "nowaway", "311": "whoisuser", "312": "whoisserver", "313": "whoisoperator", "314": "whowasuser", "315": "endofwho", "316": "whoischanop", "317": "whoisidle", "318": "endofwhois", "319": "whoischannels", "321": "liststart", "322": "list", "323": "listend", "324": "channelmodeis", "329": "channelcreate", "331": "notopic", "332": "topic", "333": "topicinfo", "341": "inviting", "342": "summoning", "351": "version", "352": "whoreply", "353": "namreply", "361": "killdone", "362": "closing", "363": "closeend", "364": "links", "365": "endoflinks", "366": "endofnames", "367": "banlist", "368": "endofbanlist", "369": "endofwhowas", "371": "info", "372": "motd", "373": "infostart", "374": "endofinfo", "375": "motdstart", "376": "endofmotd", "377": "motd2", # 1997-10-16 -- tkil "381": "youreoper", "382": "rehashing", "384": "myportis", "391": "time", "392": "usersstart", "393": "users", "394": "endofusers", "395": "nousers", "401": "nosuchnick", "402": "nosuchserver", "403": "nosuchchannel", "404": "cannotsendtochan", "405": "toomanychannels", "406": "wasnosuchnick", "407": "toomanytargets", "409": "noorigin", "411": "norecipient", "412": "notexttosend", "413": "notoplevel", "414": "wildtoplevel", "421": "unknowncommand", "422": "nomotd", "423": "noadmininfo", "424": "fileerror", "431": "nonicknamegiven", "432": "erroneusnickname", # Thiss iz how its speld in thee RFC. "433": "nicknameinuse", "436": "nickcollision", "441": "usernotinchannel", "442": "notonchannel", "443": "useronchannel", "444": "nologin", "445": "summondisabled", "446": "usersdisabled", "451": "notregistered", "461": "needmoreparams", "462": "alreadyregistered", "463": "nopermforhost", "464": "passwdmismatch", "465": "yourebannedcreep", # I love this one... "466": "youwillbebanned", "467": "keyset", "471": "channelisfull", "472": "unknownmode", "473": "inviteonlychan", "474": "bannedfromchan", "475": "badchannelkey", "476": "badchanmask", "481": "noprivileges", "482": "chanoprivsneeded", "483": "cantkillserver", "491": "nooperhost", "492": "noservicehost", "501": "umodeunknownflag", "502": "usersdontmatch", } generated_events = [ # Generated events "disconnect", "ctcp", "ctcpreply" ] protocol_events = [ # IRC protocol events "error", "join", "kick", "mode", "part", "ping", "privmsg", "privnotice", "pubmsg", "pubnotice", "quit" ] all_events = generated_events + protocol_events + numeric_events.values() foafbot-0.5/ircbot.py0100664000016500001440000003071607671462513014215 0ustar edmunddusers# Copyright (C) 1999, 2000 Joel Rosdahl # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # Joel Rosdahl # # $Id: ircbot.py,v 1.1 2002/06/03 20:48:22 edmundd Exp $ """ircbot -- Simple IRC bot library. This module contains a single-server IRC bot class that can be used to write simpler bots. """ import sys import string from UserDict import UserDict from irclib import SimpleIRCClient from irclib import nm_to_n, irc_lower, all_events from irclib import parse_channel_modes, is_channel, is_channel from irclib import ServerConnectionError class SingleServerIRCBot(SimpleIRCClient): """A single-server IRC bot class. The bot tries to reconnect if it is disconnected. The bot keeps track of the channels it has joined, the other clients that are present in the channels and which of those that have operator or voice modes. The "database" is kept in the self.channels attribute, which is an IRCDict of Channels. """ def __init__(self, server_list, nickname, realname, reconnection_interval=60): """Constructor for SingleServerIRCBot objects. Arguments: server_list -- A list of tuples (server, port) that defines which servers the bot should try to connect to. nickname -- The bot's nickname. realname -- The bot's realname. reconnection_interval -- How long the bot should wait before trying to reconnect. """ SimpleIRCClient.__init__(self) self.channels = IRCDict() self.server_list = server_list if not reconnection_interval or reconnection_interval < 0: reconnection_interval = 2**31 self.reconnection_interval = reconnection_interval self._nickname = nickname self._realname = realname for i in ["disconnect", "join", "kick", "mode", "namreply", "nick", "part", "quit"]: self.connection.add_global_handler(i, getattr(self, "_on_" + i), -10) def _connected_checker(self): """[Internal]""" if not self.connection.is_connected(): self.connection.execute_delayed(self.reconnection_interval, self._connected_checker) self.jump_server() def _connect(self): """[Internal]""" password = None if len(self.server_list[0]) > 2: password = self.server_list[0][2] try: self.connect(self.server_list[0][0], self.server_list[0][1], self._nickname, password, ircname=self._realname) except ServerConnectionError: pass def _on_disconnect(self, c, e): """[Internal]""" self.channels = IRCDict() self.connection.execute_delayed(self.reconnection_interval, self._connected_checker) def _on_join(self, c, e): """[Internal]""" ch = e.target() nick = nm_to_n(e.source()) if nick == self._nickname: self.channels[ch] = Channel() self.channels[ch].add_user(nick) def _on_kick(self, c, e): """[Internal]""" nick = e.arguments()[0] channel = e.target() if nick == self._nickname: del self.channels[channel] else: self.channels[channel].remove_user(nick) def _on_mode(self, c, e): """[Internal]""" modes = parse_channel_modes(string.join(e.arguments())) t = e.target() if is_channel(t): ch = self.channels[t] for mode in modes: if mode[0] == "+": f = ch.set_mode else: f = ch.clear_mode f(mode[1], mode[2]) else: # Mode on self... XXX pass def _on_namreply(self, c, e): """[Internal]""" # e.arguments()[0] == "=" (why?) # e.arguments()[1] == channel # e.arguments()[2] == nick list ch = e.arguments()[1] for nick in string.split(e.arguments()[2]): if nick[0] == "@": nick = nick[1:] self.channels[ch].set_mode("o", nick) elif nick[0] == "+": nick = nick[1:] self.channels[ch].set_mode("v", nick) self.channels[ch].add_user(nick) def _on_nick(self, c, e): """[Internal]""" before = nm_to_n(e.source()) after = e.target() for ch in self.channels.values(): if ch.has_user(before): ch.change_nick(before, after) if nm_to_n(before) == self._nickname: self._nickname = after def _on_part(self, c, e): """[Internal]""" nick = nm_to_n(e.source()) channel = e.target() if nick == self._nickname: del self.channels[channel] else: self.channels[channel].remove_user(nick) def _on_quit(self, c, e): """[Internal]""" nick = nm_to_n(e.source()) for ch in self.channels.values(): if ch.has_user(nick): ch.remove_user(nick) def die(self, msg="Bye, cruel world!"): """Let the bot die. Arguments: msg -- Quit message. """ self.connection.quit(msg) sys.exit(0) def disconnect(self, msg="I'll be back!"): """Disconnect the bot. The bot will try to reconnect after a while. Arguments: msg -- Quit message. """ self.connection.quit(msg) def get_version(self): """Returns the bot version. Used when answering a CTCP VERSION request. """ return "ircbot.py by Joel Rosdahl " def jump_server(self): """Connect to a new server, possible disconnecting from the current. The bot will skip to next server in the server_list each time jump_server is called. """ if self.connection.is_connected(): self.connection.quit("Jumping servers") self.server_list.append(self.server_list.pop(0)) self._connect() def on_ctcp(self, c, e): """Default handler for ctcp events. Replies to VERSION and PING requests. """ if e.arguments()[0] == "VERSION": c.ctcp_reply(nm_to_n(e.source()), self.get_version()) elif e.arguments()[0] == "PING": if len(e.arguments()) > 1: c.ctcp_reply(nm_to_n(e.source()), "PING " + e.arguments()[1]) def start(self): """Start the bot.""" self._connect() SimpleIRCClient.start(self) class IRCDict: """A dictionary suitable for storing IRC-related things. Dictionary keys a and b are considered equal if and only if irc_lower(a) == irc_lower(b) Otherwise, it should behave exactly as a normal dictionary. """ def __init__(self, dict=None): self.data = {} self.canon_keys = {} # Canonical keys if dict is not None: self.update(dict) def __repr__(self): return repr(self.data) def __cmp__(self, dict): if isinstance(dict, IRCDict): return cmp(self.data, dict.data) else: return cmp(self.data, dict) def __len__(self): return len(self.data) def __getitem__(self, key): return self.data[self.canon_keys[irc_lower(key)]] def __setitem__(self, key, item): if self.has_key(key): del self[key] self.data[key] = item self.canon_keys[irc_lower(key)] = key def __delitem__(self, key): ck = irc_lower(key) del self.data[self.canon_keys[ck]] del self.canon_keys[ck] def clear(self): self.data.clear() self.canon_keys.clear() def copy(self): if self.__class__ is UserDict: return UserDict(self.data) import copy return copy.copy(self) def keys(self): return self.data.keys() def items(self): return self.data.items() def values(self): return self.data.values() def has_key(self, key): return self.canon_keys.has_key(irc_lower(key)) def update(self, dict): for k, v in dict.items(): self.data[k] = v def get(self, key, failobj=None): return self.data.get(key, failobj) class Channel: """A class for keeping information about an IRC channel. This class can be improved a lot. """ def __init__(self): self.userdict = IRCDict() self.operdict = IRCDict() self.voiceddict = IRCDict() self.modes = {} def users(self): """Returns an unsorted list of the channel's users.""" return self.userdict.keys() def opers(self): """Returns an unsorted list of the channel's operators.""" return self.operdict.keys() def voiced(self): """Returns an unsorted list of the persons that have voice mode set in the channel.""" return self.voiceddict.keys() def has_user(self, nick): """Check whether the channel has a user.""" return self.userdict.has_key(nick) def is_oper(self, nick): """Check whether a user has operator status in the channel.""" return self.operdict.has_key(nick) def is_voiced(self, nick): """Check whether a user has voice mode set in the channel.""" return self.voiceddict.has_key(nick) def add_user(self, nick): self.userdict[nick] = 1 def remove_user(self, nick): for d in self.userdict, self.operdict, self.voiceddict: if d.has_key(nick): del d[nick] def change_nick(self, before, after): self.userdict[after] = 1 del self.userdict[before] if self.operdict.has_key(before): self.operdict[after] = 1 del self.operdict[before] if self.voiceddict.has_key(before): self.voiceddict[after] = 1 del self.voiceddict[before] def set_mode(self, mode, value=None): """Set mode on the channel. Arguments: mode -- The mode (a single-character string). value -- Value """ if mode == "o": self.operdict[value] = 1 elif mode == "v": self.voiceddict[value] = 1 else: self.modes[mode] = value def clear_mode(self, mode, value=None): """Clear mode on the channel. Arguments: mode -- The mode (a single-character string). value -- Value """ try: if mode == "o": del self.operdict[value] elif mode == "v": del self.voiceddict[value] else: del self.modes[mode] except KeyError: pass def has_mode(self, mode): return mode in self.modes def is_moderated(self): return self.has_mode("m") def is_secret(self): return self.has_mode("s") def is_protected(self): return self.has_mode("p") def has_topic_lock(self): return self.has_mode("t") def is_invite_only(self): return self.has_mode("i") def has_message_from_outside_protection(self): # Eh... What should it be called, really? return self.has_mode("n") def has_limit(self): return self.has_mode("l") def limit(self): if self.has_limit(): return self.modes[l] else: return None def has_key(self): return self.has_mode("k") def key(self): if self.has_key(): return self.modes["k"] else: return None foafbot-0.5/scutter.py0100775000016500001440000004735007671462513014431 0ustar edmunddusers#!/usr/bin/python2.2 # $Id: scutter.py,v 1.22 2002/08/02 21:58:00 edmundd Exp $ # # Copyright (C) 2002 Edd Dumbill # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. import RDF import urllib2 import os import AttributedModel import FOAF import profile import commands import re import string import sys import timeoutsocket import mbox_sha1_hook import plan_hook # set default timeout on all operations to 20 seconds timeoutsocket.setDefaultSocketTimeout(20) planNode=RDF.Node(uri_string="http://usefulinc.com/ns/scutter/0.1#Resource") planOwnerNode=RDF.Node(uri_string="http://usefulinc.com/ns/scutter/0.1#owner") planMergePropertyNode=RDF.Node(uri_string="http://usefulinc.com/ns/scutter/0.1#mergeProperty") planReferrerNode=RDF.Node(uri_string="http://usefulinc.com/ns/scutter/0.1#referrer") planStatusNode=RDF.Node(uri_string="http://usefulinc.com/ns/scutter/0.1#status") parser=RDF.Parser('raptor') preprocessor="xsltproc getrdf.xsl '%s' >'%s'" gpgProgram="/usr/bin/gpg" gpgEmailRegexp=re.compile(r'<(.*)>', re.MULTILINE) gpgKeyIDRegexp=re.compile(r'key\s+ID\s+([A-F0-9]+)', re.IGNORECASE|re.MULTILINE) gpgPubKeyNotFoundRegexp=re.compile(r'public key not found', re.IGNORECASE|re.MULTILINE) sanitizeRegexp=re.compile(r'[/#:]') mboxCnt=0 mboxBase="http://usefulinc.com/tmp/anon#%d" pgpBase="http://usefulinc.com/tmp/pgpid#%d" dynPlanNode=RDF.Node(uri_string="http://usefulinc.com/ns/scutter/dynamic") anonCounterNode=RDF.Node(uri_string="http://usefulinc.com/ns/scutter/anoncount") urllib2.__version__ = urllib2.__version__+'-foaf-scutter-0.4 ' SCUTTER_STATUS_OK = 0 SCUTTER_STATUS_NEW = 1 SCUTTER_STATUS_ERROR = 2 def handler (type, message): if type == 0: print "Redland error - ",message else: print "Redland warning - ",message RDF.set_message_handler(handler) class ScutterError: def __init__(self, value): self.value = value def __str__(self): return `self.value` class Scutter: def __init__(self, model, keyids=[]): self._model=model self._status={} self._count=0 self._cache=0 self._keyids=keyids def get_email(self, subject): res=self._model.attributed_targets(subject, FOAF.mboxNode) if len(res)>0: return res[0] else: return None def own_keys(self, keylist): """return true if scutter should recognize any of the keys in keylist""" for k in keylist: if k in self._keyids: return 1 return 0 def load_plan(self, url): """load an RDF file in, attributed to the special owner dynPlanNode""" furi=RDF.Uri(string=url) print 'Consulting plan',furi self._model.parse_attributed(parser, dynPlanNode, furi) def _first_value(self, urlnode, propnode): """return the first matched value for the triple (urlnode, propnode, ?)""" nodes=self._model.attributed_targets(urlnode, propnode) if len(nodes): return nodes[0] return None def get_url_referrer(self, urinode): """retrieve the referrer of the urinode""" return self._first_value(urinode, planReferrerNode) def get_url_owner(self, urinode): """retrieve the owner of the urinode""" return self._first_value(urinode, planOwnerNode) def get_url_status(self, urinode): """retrieve the status of the urinode""" if self._status.has_key(urinode): return self._status[urinode] else: val=self._first_value(urinode, planStatusNode) if val: return int(str(val)) return SCUTTER_STATUS_NEW def _delete_value(self, urinode, propnode): """delete all statements made by scutter with urinode as subject and propnode as predicate""" qs=RDF.Statement(subject=urinode, predicate=propnode, object=None) stream=self._model.find_statements(qs) while not stream.end(): self._model.remove_statement(stream.current(), stream.context()) stream.next() def set_url_referrer(self, urinode, referrer): """set referrer of urinode""" self._delete_value(urinode, planReferrerNode) s=RDF.Statement(subject=urinode, predicate=planReferrerNode, object=referrer) self._model.add_attributed_statement(s, dynPlanNode) def set_url_owner(self, urinode, owner): """set owner of urinode""" self._delete_value(urinode, planOwnerNode) s=RDF.Statement(subject=urinode, predicate=planOwnerNode, object=owner) self._model.add_attributed_statement(s, dynPlanNode) def set_url_status(self, urinode, status): """record the status of the scuttering of this uri""" self._delete_value(urinode, planStatusNode) s=RDF.Statement(subject=urinode, predicate=planStatusNode, object=RDF.Node(literal=`status`)) self._model.add_attributed_statement(s, dynPlanNode) print '***** Setting status for %s to %s' % (str(urinode), str(status)) def set_anon_counter(self, count): """record the anon user number""" self._delete_value(anonCounterNode,FOAF.rdfValueNode) s=RDF.Statement(subject=anonCounterNode, predicate=FOAF.rdfValueNode, object=RDF.Node(literal=str(count))) self._model.add_attributed_statement(s, dynPlanNode) print "***** Setting anon counter to",count def get_anon_counter(self): """return the most recent value of the anon user counter""" v=self._first_value(anonCounterNode, FOAF.rdfValueNode) if v!=None: return int(str(v)) else: return 0 def get_url_assurance(self, urinode): return self._first_value(urinode, FOAF.assuranceNode) def get_urls_from(self, owner): return self._model.attributed_sources(planOwnerNode, owner) def check_encrypted(self, urinode): """checks to see if the document pointed at by urinode is encrypted and if so returns the list of keys we believe it to be encrypted for""" keys=self._model.attributed_targets( urinode, FOAF.encryptedToNode) key_id_strings=[] for k in keys: keyids=self._model.attributed_targets( k, FOAF.hexidNode) if len(keyids): key_id_strings.append(str(keyids[0])) print 'encrypted to',key_id_strings return key_id_strings def scutter_uri(self, urinode, referrer): """retrieves the FOAF file pointed to by urinode, updating the status, referrer and owner of that uri""" fname="%d.rdf" % self._count self._count=self._count+1 try: # first, drop anything we had from this uri self._model.delete_by_sayer(urinode) print "referrer",referrer # check to see if we're told it's encrypted keyids=self.check_encrypted(urinode) if len(keyids): if self.own_keys(keyids): # means encrupted and signed to us: special measures # required creator_mboxes=fetch_encrypted_into_file(str(urinode.uri), fname) else: raise ScutterError("Encrypted to someone else.") else: # look for prior knowledg of dig sig sigurlnode=self.get_url_assurance(urinode) if sigurlnode!=None: sigurl=str(sigurlnode.uri) else: sigurl=None creator_mboxes=fetch_into_file(str(urinode.uri), fname, sigurl) # create_mboxes now holds candidate information about # who owns the file we just fetched. cnt=self.get_anon_counter() owner=owner_from_creator_mboxes(self._model, creator_mboxes, cnt, urinode) self.set_anon_counter(cnt+1) print "owner",owner self._model.parse_attributed(parser, urinode, RDF.Uri(string="file:./"+fname)) if self._cache==0: os.unlink(fname) self.set_url_owner(urinode, owner) self.set_url_referrer(urinode, referrer) self.set_url_status(urinode, SCUTTER_STATUS_OK) except IOError, e: print "IO Error",e self.set_url_status(urinode, SCUTTER_STATUS_ERROR) except ValueError, e: # needed cos of urllib2 bug print "Value Error", e self.set_url_status(urinode, SCUTTER_STATUS_ERROR) except OSError, e: # if file: URIs are encountered # TODO: don't bother spidering file: URIs print "OSError", e self.set_url_status(urinode, SCUTTER_STATUS_ERROR) except ScutterError, e: print "Skipping due to error",e self.set_url_status(urinode, SCUTTER_STATUS_ERROR) except RDF.NodeTypeError, e: print "NodeTypeError",e self.set_url_status(urinode, SCUTTER_STATUS_ERROR) except timeoutsocket.Timeout, e: print "TimeOut",e self.set_url_status(urinode, SCUTTER_STATUS_ERROR) def scutter(self): """scutter the infonets for foaf information.""" done=0 files=0 while not done: done=1 qs=RDF.Statement(subject=None, predicate=FOAF.rdfsSeeAlsoNode, object=None) stream=self._model.find_statements(qs) while not stream.end(): # if files > 30: return referrer=stream.context() n=stream.current().object if self.get_url_status(n)==SCUTTER_STATUS_NEW: done=0 self.scutter_uri(n, referrer) files=files+1 stream.next() def dump_plan(self): qs=RDF.Statement(subject=None, predicate=planStatusNode, object=None) stream=self._model.find_statements(qs) while not stream.end(): n=stream.current().subject o=self.get_url_owner(n) r=self.get_url_referrer(n) s=self.get_url_status(n) e=None if o!=None: e=self.get_email(o) print "%s\n\tOwner\t%s (%s)\n\tRef'r\t%s\n\tStatus\t%d" % ( str(n), str(o), str(e), str(r), s) stream.next() def sanitize(str): return sanitizeRegexp.sub('_', str) def attributed_nodes_of_type(model, typeNode): return model.attributed_sources(FOAF.rdfTypeNode, typeNode) def attributed_nodes_for_mbox(model, mbox): return model.attributed_sources(FOAF.mboxNode, mbox) def is_anon_owner(urinode): if string.find(str(urinode), "usefulinc.com/tmp/anon")>=0: return 1 else: return 0 def gpg_decrypt_and_verify(fname, result): addrs=[] vcmd=gpgProgram+" -d -o '%s' '%s'" % (result, fname) print 'Executing',vcmd (rc, op)=commands.getstatusoutput(vcmd) if rc!=0: print 'Error verifying signature, investigating' if gpgPubKeyNotFoundRegexp.search(op): print 'Public key not found, trying to fetch' m=gpgKeyIDRegexp.search(op) if m: (keyID,)=m.groups() cmd=gpgProgram+" --keyserver pgp.mit.edu --recv-keys %s" % keyID print 'Executing',cmd print commands.getoutput(cmd) print 'Executing',vcmd (rc, op)=commands.getstatusoutput(vcmd) if rc==0: print 'Decryption and verification successful' addrs=[RDF.Node(uri_string="mailto:"+x) for x in gpgEmailRegexp.findall( op[string.find(op, 'Good signature'):])] else: print 'Error verifying signature' print op return addrs def gpg_verify_url(url, fname, sigurl=None): addrs=[] print 'Fetching signature from',sigurl if sigurl!=None: try: signame=fname+".asc" fp=open(signame, "wb") up=urllib2.urlopen(sigurl) fp.write(up.read()) up.close() fp.close() cmd=gpgProgram+" --no-tty --verify '%s' '%s'" % (signame, fname) print 'Executing',cmd (rc, op)=commands.getstatusoutput(cmd) if rc!=0: print 'Error verifying signature, investigating' if gpgPubKeyNotFoundRegexp.search(op): print 'Public key not found, trying to fetch' m=gpgKeyIDRegexp.search(op) if m: (keyID,)=m.groups() cmd=gpgProgram+" --keyserver pgp.mit.edu --recv-keys %s" % keyID print 'Executing',cmd print commands.getoutput(cmd) cmd=gpgProgram+" --no-tty --verify '%s' '%s'" % (signame, fname) print 'Executing',cmd (rc, op)=commands.getstatusoutput(cmd) if rc==0: print 'Verification successful' addrs=[RDF.Node(uri_string="mailto:"+x) for x in gpgEmailRegexp.findall(op)] else: print 'Error verifying signature' print op os.unlink(signame) except Exception, e: print "Problem fetching signature:",e os.unlink(signame) return addrs def fetch_into_file(url, fname, sigurl=None): print "Fetching %s -> %s" % (url, fname) tmpname=fname+".tmp" try: up=urllib2.urlopen(url) except Exception, e: up=None if up: fp=open(tmpname, "wb") fp.write(up.read()) up.close() fp.close() else: raise ScutterError('Could not open URL %s' % url) rc=0 if preprocessor!=None: cmd=preprocessor % (tmpname, fname) rc=os.system(cmd) s=os.stat(fname) if s.st_size==0: rc=999 else: os.rename(tmpname, fname) tmpname=fname if rc!=0: os.unlink(tmpname) os.unlink(fname) raise ScutterError('Error preprocessing RDF, code %d' % rc) newsig=pre_parse_and_check_for_signature(fname, url) if newsig!=None: sigurl=newsig emails=gpg_verify_url(url, tmpname, sigurl) if tmpname!=fname: os.unlink(tmpname) return emails def fetch_encrypted_into_file(url, fname, sigurl=None): print "Fetching %s -> %s" % (url, fname) tmpname=fname+".tmp" tmpname2=fname+".tmp2" up=urllib2.urlopen(url) if up: fp=open(tmpname, "wb") fp.write(up.read()) up.close() fp.close() else: raise ScutterError('Could not open URL %s' % url) # got encrypted file in the .tmp thing now. # need to decrypt into .tmp2 and capture sigs emails=gpg_decrypt_and_verify(tmpname, tmpname2) os.unlink(tmpname) # TODO -- dedeyplicate this code from pre_parse... rc=0 if preprocessor!=None: cmd=preprocessor % (tmpname2, fname) rc=os.system(cmd) s=os.stat(fname) if s.st_size==0: rc=999 os.unlink(tmpname2) else: os.rename(tmpname2, fname) tmpname2=fname if rc!=0: os.unlink(fname) raise ScutterError('Error preprocessing RDF, code %d' % rc) return emails def pre_parse_and_check_for_signature(fname, base_uri): """parses the RDF file into a test model, and looks for wot:assurance property about the file""" sigurl=None buri=RDF.Uri(string=base_uri) print "Parsing into test model, base URI",buri storage=RDF.Storage(storage_name="memory", name="test", options_string="") model=RDF.Model(storage) parser=RDF.Parser('raptor') furi=RDF.Uri(string="file:./%s" % fname) parser.parse_into_model(model, furi, buri) #dump_model(model) sigs=model.targets(RDF.Node(uri_string=str(buri)), FOAF.assuranceNode) if len(sigs): sigurl=str(sigs[0].uri) return sigurl def dump_model(model): stream=model.serialise() while not stream.end(): statement2=stream.current(); print statement2 stream.next(); print "--------------------------------------------" def owner_from_creator_mboxes(model, mboxes, mboxCnt, urinode): """ creates a suitable owner node for the mboxes concerned: the boxes come from a digital signature, so we add the nodes in attributed to the person themself. we assume that a merge will sort out the dupe nodes for each person.""" global mboxBase bnode=RDF.Node(uri_string=(mboxBase % (mboxCnt,))) pnode=RDF.Node(uri_string=(pgpBase % (mboxCnt,))) if len(mboxes)>0: # we've been able to find an owner for m in mboxes: s=RDF.Statement(subject=bnode, predicate=FOAF.mboxNode, object=m) # we attribute ownership of this fact to # a URI we invent that indicates the use of # the PGP key. TODO: tie this into the key # ID model.add_attributed_statement(s, pnode) else: # if ownership present in scutterplan, use that. # we know it's preset because the context of the statement # is the dynPlanNode qs=RDF.Statement(subject=urinode, predicate=planOwnerNode, object=None) stream=model.find_statements(qs) while not stream.end(): if stream.context() == dynPlanNode: return RDF.Node(node=stream.current().object) stream.next() # otherwise, we need to # create an unknown user to 'own' this node name_node=RDF.Node(literal="Anon%d" % mboxCnt) mbox_node=RDF.Node(uri_string="mailto:anon%d@no.where" % mboxCnt) model.add_attributed_statement( RDF.Statement(subject=bnode, predicate=FOAF.mboxNode, object=mbox_node), dynPlanNode) model.add_attributed_statement( RDF.Statement(subject=bnode, predicate=FOAF.nameNode, object=name_node), dynPlanNode) return bnode def _profiled_merge(): model.merge_attributed(FOAF.mboxNode) if __name__=="__main__": RDF.debug(0) storage=RDF.Storage(storage_name="hashes", name="foafbot", options_string="hash-type='bdb',contexts='yes',index-subjects='yes',index-objects='yes',index-predicates='yes',dir='.',new='yes'") model=AttributedModel.AttributedModel(storage) model.register_hook(FOAF.mboxNode, mbox_sha1_hook.hook) model.register_hook(FOAF.rdfTypeNode, plan_hook.hook) print "Loading..." s=Scutter(model, ["6C7F734E", "6C746DD1" ]) if 1: s.load_plan("file:./plan.rdf") s.scutter() print "Loading complete." print "Merging..." #profile.run("_profiled_merge()") model.dump("before.txt") model.merge_attributed(FOAF.mboxsha1Node) print "Merging complete." s.dump_plan() model.dump("after.txt") foafbot-0.5/AttributedModel.py0100775000016500001440000002210407671462513016016 0ustar edmunddusers# $Id: AttributedModel.py,v 1.16 2002/08/02 17:38:37 edmundd Exp $ # # Copyright (C) 2002 Edd Dumbill # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. import RDF import Redland _giNode=RDF.Node(uri_string="http://usefulinc.com/foafbot/tmp/genid"); class AttributedModel(RDF.Model): """A model which tracks the provenance of every statement""" def __init__(self, storage): RDF.Model.__init__(self, storage) self._hooks={} self._count=0 def _get_genid_counter(self): qs=RDF.Statement(subject=_giNode, predicate=_giNode, object=None) stream=self.find_statements(qs) if not stream.end(): return int(str(stream.current().object)) else: return 0 def _set_genid_counter(self, c): qs=RDF.Statement(subject=_giNode, predicate=_giNode, object=None) stream=self.find_statements(qs) while not stream.end(): self.remove_statement(stream.current()) stream.next() qs=RDF.Statement(subject=_giNode, predicate=_giNode, object=RDF.Node(literal="%d" % c)) self.add_statement(qs) def _replace_genids(self, statement, count): s=str(statement.subject) if s[0:6] == "(genid": statement.subject=RDF.Node(uri_string=("eddid:%d%s" % (count, s))) o=str(statement.object) if o[0:6] == "(genid": statement.object=RDF.Node(uri_string=("eddid:%d%s" % (count, o))) return statement def register_hook(self, pred, hook): """cause the function hook to be invoked when adding a statement with pred pred""" if self._hooks.has_key(pred): self._hooks[pred].append(hook) else: self._hooks[pred]=[hook] def attributed_contains_statement_in_context(self, st, c): stream=self.find_statements(st) while not stream.end(): if stream.context()==c: return 1 stream.next() return 0 def attributed_contains_statement(self, st): stream=self.find_statements(st) if not stream.end(): return 1 return 0 def attributed_sources(self, pred, obj): """return all nodes of ?s pred obj""" candidates=[] qs=RDF.Statement(subject=None, predicate=pred, object=obj) stream=self.find_statements(qs) while not stream.end(): candidates.append(RDF.Node(node=stream.current().subject)) stream.next() return candidates def attributed_sources_explain(self, pred, obj): candidates={} keylist=[] qs=RDF.Statement(subject=None, predicate=pred, object=obj) stream=self.find_statements(qs) while not stream.end(): print "found",stream.current(),"CTXT",stream.context() s=str(stream.current().subject) if candidates.has_key(s): candidates[s].append(RDF.Node(node=stream.context())) else: candidates[s]=[RDF.Node(node=stream.context())] keylist.append(RDF.Node(node=stream.current().subject)) stream.next() return [(snode, candidates[str(snode)]) for snode in keylist] def attributed_targets(self, subj, pred): """return all nodes of subj pred ?o""" candidates=[] qs=RDF.Statement(subject=subj, predicate=pred, object=None) stream=self.find_statements(qs) while not stream.end(): candidates.append(RDF.Node(node=stream.current().object)) stream.next() return candidates def attributed_targets_explain(self, subj, pred): candidates={} keylist=[] qs=RDF.Statement(subject=subj, predicate=pred, object=None) stream=self.find_statements(qs) while not stream.end(): print "found",stream.current(),"CTXT",stream.context() o=str(stream.current().object) if candidates.has_key(o): candidates[o].append(RDF.Node(node=stream.context())) else: candidates[o]=[RDF.Node(node=stream.context())] keylist.append(RDF.Node(node=stream.current().object)) stream.next() return [(onode, candidates[str(onode)]) for onode in keylist] def merge_attributed(self, pred): """merges an attributed self using the predicate as an unambiguous property""" h={} canonical={} mapme=[] transactions=[] qs=RDF.Statement(subject=None, predicate=pred, object=None) stream=self.find_statements(qs) while not stream.end(): s=stream.current() o=str(s.object) if not h.has_key(o): h[o]=s.subject elif h[o] != s.subject: ss=str(s.subject) if not canonical.has_key(ss): print "Adding mapping:",ss,"-->",h[o] canonical[ss]=h[o] mapme.append(RDF.Node(node=s.subject)) stream.next() stream=self.serialise() while not stream.end(): s=stream.current() ss=str(s.subject) os=str(s.object) new_s=None replace=0 if canonical.has_key(ss): if not replace: new_s=RDF.Statement(statement=s) replace=1 new_s.subject=canonical[ss] if canonical.has_key(os): if not replace: new_s=RDF.Statement(statement=s) replace=1 new_s.object=canonical[os] if replace: # print "REPLACING",s,"WITH",new_s transactions.append((RDF.Statement(statement=s), new_s, RDF.Node(node=stream.context()))) stream.next() print "Committing changes" for (victim, kid, context) in transactions: self.remove_statement(victim, context) self.add_statement(kid, context) def add_attributed_statement(self, in_statement, camefrom): to_add=[in_statement] if self._hooks.has_key(in_statement.predicate): for h in self._hooks[in_statement.predicate]: res=h(self, in_statement, camefrom) to_add=to_add+res for statement in to_add: # print "ADDING",statement,"CAMEFROM",camefrom self.add_statement(statement, camefrom) def regenerate_predicate_cache(self): """regenerates the predicate cache. useful if the model's storage pre-exists""" pass def parse_attributed(self, parser, camefrom, uri): print "parsing URI",uri stream=parser.parse_as_stream(uri) # I would use this, but it seems to be broken # model.add_statements(stream, camefrom) c=self._get_genid_counter() while not stream.end(): s=self._replace_genids(stream.current(), c) self.add_attributed_statement(s, camefrom) stream.next() c=c+1 self._set_genid_counter(c) def remove_attributed_statement(self, pred, sayer): """remove an attributed statement. requires the pred from the attributed statement and the sayer node""" # remove the attribution statement self.remove_statement(RDF.Statement(subject=pred, predicate=attrNode, object=sayer)) # remove the predicatemeaning statement victims=self.targets(pred, predNode) self.remove_statement(RDF.Statement(subject=pred, predicate=predNode, object=victims[0])) # remove pred from self._preds[victims[0]] : the pred # cache self._preds[victims[0]].remove(pred) # remove the statement itself: looks like a query # but will only match one statement st=self.find_statements(RDF.Statement(subject=None, predicate=pred, object=None)) while not st.end(): s=st.current() self.remove_statement(s) st.next() def delete_by_sayer(self, sayer): """delete every statement from a particular sayer""" self.context_remove_statements(sayer) def dump(self, fname="dump.txt"): stream=self.serialise() fh=open(fname, "wb") while not stream.end(): fh.write(str(stream.current())+" CTXT "+ str(stream.context())+"\n") stream.next() fh.close() foafbot-0.5/FOAF.py0100664000016500001440000000414707671462513013445 0ustar edmunddusers# $Id: FOAF.py,v 1.6 2002/08/02 17:38:37 edmundd Exp $ # # Copyright (C) 2002 Edd Dumbill # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. import RDF mboxNode=RDF.Node(uri_string="http://xmlns.com/foaf/0.1/mbox") mboxsha1Node=RDF.Node(uri_string="http://xmlns.com/foaf/0.1/mbox_sha1sum") nickNode=RDF.Node(uri_string="http://xmlns.com/foaf/0.1/nick") nameNode=RDF.Node(uri_string="http://xmlns.com/foaf/0.1/name") homepageNode=RDF.Node(uri_string="http://xmlns.com/foaf/0.1/homepage") imageNode=RDF.Node(uri_string="http://xmlns.com/foaf/0.1/image") depictionNode=RDF.Node(uri_string="http://xmlns.com/foaf/0.1/depiction") depictsNode=RDF.Node(uri_string="http://xmlns.com/foaf/0.1/depicts") phoneNode=RDF.Node(uri_string="http://xmlns.com/foaf/0.1/phone") workplaceHomepageNode=RDF.Node(uri_string="http://xmlns.com/foaf/0.1/workplaceHomepage") chatEventNode=RDF.Node(uri_string="http://xmlns.com/foaf/0.1/chatEvent") chatEventListNode=RDF.Node(uri_string="http://xmlns.com/foaf/0.1/chatEventList") rdfTypeNode=RDF.Node( uri_string="http://www.w3.org/1999/02/22-rdf-syntax-ns#type") rdfValueNode=RDF.Node( uri_string="http://www.w3.org/1999/02/22-rdf-syntax-ns#value") rdfsSeeAlsoNode=RDF.Node( uri_string="http://www.w3.org/2000/01/rdf-schema#seeAlso") assuranceNode=RDF.Node(uri_string="http://xmlns.com/wot/0.1/assurance") encryptedToNode=RDF.Node(uri_string="http://xmlns.com/wot/0.1/encryptedTo") hexidNode=RDF.Node(uri_string="http://xmlns.com/wot/0.1/hex_id") foafbot-0.5/DC.py0100664000016500001440000000213307671462513013211 0ustar edmunddusers# $Id: DC.py,v 1.3 2002/07/14 21:08:53 edmundd Exp $ # # Copyright (C) 2002 Edd Dumbill # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. import RDF titleNode=RDF.Node(uri_string="http://purl.org/dc/elements/1.1/title") dateNode=RDF.Node(uri_string="http://purl.org/dc/elements/1.1/date") descriptionNode=RDF.Node(uri_string="http://purl.org/dc/elements/1.1/description") creatorNode=RDF.Node(uri_string="http://purl.org/dc/elements/1.1/creator") foafbot-0.5/timeoutsocket.py0100664000016500001440000003067107671462513015632 0ustar edmunddusers #### # Copyright 2000,2001 by Timothy O'Malley # # All Rights Reserved # # Permission to use, copy, modify, and distribute this software # and its documentation for any purpose and without fee is hereby # granted, provided that the above copyright notice appear in all # copies and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Timothy O'Malley not be used in advertising or publicity # pertaining to distribution of the software without specific, written # prior permission. # # Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS # SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY # AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR # ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR # PERFORMANCE OF THIS SOFTWARE. # #### # http://www.timo-tasi.org/python/timeoutsocket.py """Timeout Socket This module enables a timeout mechanism on all TCP connections. It does this by inserting a shim into the socket module. After this module has been imported, all socket creation goes through this shim. As a result, every TCP connection will support a timeout. The beauty of this method is that it immediately and transparently enables the entire python library to support timeouts on TCP sockets. As an example, if you wanted to SMTP connections to have a 20 second timeout: import timeoutsocket import smtplib timeoutsocket.setDefaultSocketTimeout(20) The timeout applies to the socket functions that normally block on execution: read, write, connect, and accept. If any of these operations exceeds the specified timeout, the exception Timeout will be raised. The default timeout value is set to None. As a result, importing this module does not change the default behavior of a socket. The timeout mechanism only activates when the timeout has been set to a numeric value. (This behavior mimics the behavior of the select.select() function.) This module implements two classes: TimeoutSocket and TimeoutFile. The TimeoutSocket class defines a socket-like object that attempts to avoid the condition where a socket may block indefinitely. The TimeoutSocket class raises a Timeout exception whenever the current operation delays too long. The TimeoutFile class defines a file-like object that uses the TimeoutSocket class. When the makefile() method of TimeoutSocket is called, it returns an instance of a TimeoutFile. Each of these objects adds two methods to manage the timeout value: get_timeout() --> returns the timeout of the socket or file set_timeout() --> sets the timeout of the socket or file As an example, one might use the timeout feature to create httplib connections that will timeout after 30 seconds: import timeoutsocket import httplib H = httplib.HTTP("www.python.org") H.sock.set_timeout(30) Note: When used in this manner, the connect() routine may still block because it happens before the timeout is set. To avoid this, use the 'timeoutsocket.setDefaultSocketTimeout()' function. Good Luck! """ __version__ = "$Revision: 1.2 $" __author__ = "Timothy O'Malley " # # Imports # import select, string import socket if not hasattr(socket, "_no_timeoutsocket"): _socket = socket.socket else: _socket = socket._no_timeoutsocket # # Set up constants to test for Connected and Blocking operations. # We delete 'os' and 'errno' to keep our namespace clean(er). # Thanks to Alex Martelli and G. Li for the Windows error codes. # import os if os.name == "nt": _IsConnected = ( 10022, 10056 ) _ConnectBusy = ( 10035, ) _AcceptBusy = ( 10035, ) else: import errno _IsConnected = ( errno.EISCONN, ) _ConnectBusy = ( errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK ) _AcceptBusy = ( errno.EAGAIN, errno.EWOULDBLOCK ) del errno del os # # Default timeout value for ALL TimeoutSockets # _DefaultTimeout = None def setDefaultSocketTimeout(timeout): global _DefaultTimeout _DefaultTimeout = timeout def getDefaultSocketTimeout(): return _DefaultTimeout # # Exceptions for socket errors and timeouts # Error = socket.error class Timeout(Exception): pass # # Factory function # from socket import AF_INET, SOCK_STREAM def timeoutsocket(family=AF_INET, type=SOCK_STREAM, proto=None): if family != AF_INET or type != SOCK_STREAM: if proto: return _socket(family, type, proto) else: return _socket(family, type) return TimeoutSocket( _socket(family, type), _DefaultTimeout ) # end timeoutsocket # # The TimeoutSocket class definition # class TimeoutSocket: """TimeoutSocket object Implements a socket-like object that raises Timeout whenever an operation takes too long. The definition of 'too long' can be changed using the set_timeout() method. """ _copies = 0 _blocking = 1 def __init__(self, sock, timeout): self._sock = sock self._timeout = timeout # end __init__ def __getattr__(self, key): return getattr(self._sock, key) # end __getattr__ def get_timeout(self): return self._timeout # end set_timeout def set_timeout(self, timeout=None): self._timeout = timeout # end set_timeout def setblocking(self, blocking): self._blocking = blocking return self._sock.setblocking(blocking) # end set_timeout def connect_ex(self, addr): errcode = 0 try: self.connect(addr) except Error, why: errcode = why[0] return errcode # end connect_ex def connect(self, addr, port=None, dumbhack=None): # In case we were called as connect(host, port) if port != None: addr = (addr, port) # Shortcuts sock = self._sock timeout = self._timeout blocking = self._blocking # First, make a non-blocking call to connect try: sock.setblocking(0) sock.connect(addr) sock.setblocking(blocking) return except Error, why: # Set the socket's blocking mode back sock.setblocking(blocking) # If we are not blocking, re-raise if not blocking: raise # If we are already connected, then return success. # If we got a genuine error, re-raise it. errcode = why[0] if dumbhack and errcode in _IsConnected: return elif errcode not in _ConnectBusy: raise # Now, wait for the connect to happen # ONLY if dumbhack indicates this is pass number one. # If select raises an error, we pass it on. # Is this the right behavior? if not dumbhack: r,w,e = select.select([], [sock], [], timeout) if w: return self.connect(addr, dumbhack=1) # If we get here, then we should raise Timeout raise Timeout("Attempted connect to %s timed out." % str(addr) ) # end connect def accept(self, dumbhack=None): # Shortcuts sock = self._sock timeout = self._timeout blocking = self._blocking # First, make a non-blocking call to accept # If we get a valid result, then convert the # accept'ed socket into a TimeoutSocket. # Be carefult about the blocking mode of ourselves. try: sock.setblocking(0) newsock, addr = sock.accept() sock.setblocking(blocking) timeoutnewsock = self.__class__(newsock, timeout) timeoutnewsock.setblocking(blocking) return (timeoutnewsock, addr) except Error, why: # Set the socket's blocking mode back sock.setblocking(blocking) # If we are not supposed to block, then re-raise if not blocking: raise # If we got a genuine error, re-raise it. errcode = why[0] if errcode not in _AcceptBusy: raise # Now, wait for the accept to happen # ONLY if dumbhack indicates this is pass number one. # If select raises an error, we pass it on. # Is this the right behavior? if not dumbhack: r,w,e = select.select([sock], [], [], timeout) if r: return self.accept(dumbhack=1) # If we get here, then we should raise Timeout raise Timeout("Attempted accept timed out.") # end accept def send(self, data, flags=0): sock = self._sock if self._blocking: r,w,e = select.select([],[sock],[], self._timeout) if not w: raise Timeout("Send timed out") return sock.send(data, flags) # end send def recv(self, bufsize, flags=0): sock = self._sock if self._blocking: r,w,e = select.select([sock], [], [], self._timeout) if not r: raise Timeout("Recv timed out") return sock.recv(bufsize, flags) # end recv def makefile(self, flags="r", bufsize=-1): self._copies = self._copies +1 return TimeoutFile(self, flags, bufsize) # end makefile def close(self): if self._copies <= 0: self._sock.close() else: self._copies = self._copies -1 # end close # end TimeoutSocket class TimeoutFile: """TimeoutFile object Implements a file-like object on top of TimeoutSocket. """ def __init__(self, sock, mode="r", bufsize=4096): self._sock = sock self._bufsize = 4096 if bufsize > 0: self._bufsize = bufsize if not hasattr(sock, "_inqueue"): self._sock._inqueue = "" # end __init__ def __getattr__(self, key): return getattr(self._sock, key) # end __getattr__ def close(self): self._sock.close() self._sock = None # end close def write(self, data): self.send(data) # end write def read(self, size=-1): _sock = self._sock _bufsize = self._bufsize while 1: datalen = len(_sock._inqueue) if datalen >= size >= 0: break bufsize = _bufsize if size > 0: bufsize = min(bufsize, size - datalen ) buf = self.recv(bufsize) if not buf: break _sock._inqueue = _sock._inqueue + buf data = _sock._inqueue _sock._inqueue = "" if size > 0 and datalen > size: _sock._inqueue = data[size:] data = data[:size] return data # end read def readline(self, size=-1): _sock = self._sock _bufsize = self._bufsize while 1: idx = string.find(_sock._inqueue, "\n") if idx >= 0: break datalen = len(_sock._inqueue) if datalen >= size >= 0: break bufsize = _bufsize if size > 0: bufsize = min(bufsize, size - datalen ) buf = self.recv(bufsize) if not buf: break _sock._inqueue = _sock._inqueue + buf data = _sock._inqueue _sock._inqueue = "" if idx >= 0: idx = idx + 1 _sock._inqueue = data[idx:] data = data[:idx] elif size > 0 and datalen > size: _sock._inqueue = data[size:] data = data[:size] return data # end readline def readlines(self, sizehint=-1): result = [] data = self.read() while data: idx = string.find(data, "\n") if idx >= 0: idx = idx + 1 result.append( data[:idx] ) data = data[idx:] else: result.append( data ) data = "" return result # end readlines def flush(self): pass # end TimeoutFile # # Silently replace the socket() builtin function with # our timeoutsocket() definition. # if not hasattr(socket, "_no_timeoutsocket"): socket._no_timeoutsocket = socket.socket socket.socket = timeoutsocket del socket socket = timeoutsocket # Finis foafbot-0.5/mbox_sha1_hook.py0100664000016500001440000000274507671462513015635 0ustar edmunddusers#!/usr/bin/python2.2 # $Id: oracle.py,v 1.20 2002/07/26 06:47:07 edmundd Exp $ # # Copyright (C) 2002 Edd Dumbill # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # mbox_sha1_hook import RDF import FOAF import sha def hook(model, statement, camefrom): """hook called when mbox property encountered, will compute mbox sha1 sum and then return the new statement""" sha1val=sha.new(str(statement.object.uri)) s=RDF.Statement(subject=statement.subject, predicate=FOAF.mboxsha1Node, object=RDF.Node(literal=sha1val.hexdigest())) return [s] if __name__=="__main__": s=RDF.Statement( subject=RDF.Node(uri_string="http://foo.com/"), predicate=FOAF.mboxNode, object=RDF.Node(uri_string="mailto:edd@foo.com")) for r in hook(None, s, None): print r foafbot-0.5/plan_hook.py0100664000016500001440000000322307671462513014676 0ustar edmunddusers#!/usr/bin/python2.2 # $Id: oracle.py,v 1.20 2002/07/26 06:47:07 edmundd Exp $ # # Copyright (C) 2002 Edd Dumbill # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # mbox_sha1_hook import RDF import FOAF _seeAlsoNode=RDF.Node( uri_string="http://www.w3.org/2000/01/rdf-schema#seeAlso") _planNode=RDF.Node(uri_string="http://usefulinc.com/ns/scutter/0.1#Resource") def hook(model, statement, camefrom): """hook called when an object of type plan:Resource is found: we then insert a rdf:seeAlso into the store so it gets spidered.""" if statement.object == _planNode: s=RDF.Statement(subject=statement.subject, predicate=_seeAlsoNode, object=statement.subject) return [s] else: return [] if __name__=="__main__": s=RDF.Statement( subject=RDF.Node(uri_string="http://pants/heddley.com/index.rss"), predicate=FOAF.rdfTypeNode, object=_planNode) for r in hook(None, s, None): print r foafbot-0.5/getrdf.xsl0100644000016500001440000000073207671462514014356 0ustar edmunddusers foafbot-0.5/INSTALL0100664000016500001440000000123107671462514013401 0ustar edmunddusersTo get FOAFBot running, you need to do the following. 1. Install Python 2.2 or better. See http://www.python.org/ 2. Compile and install Redland, including the Python extensions http://www.redland.opensource.ac.uk/INSTALL.html. For best results try a recent nightly snapshot. 3. Install GPG, if not already installed. Amend scutter.py to point to your GPG installation (line 23) 4. Install xsltproc, from libxslt at http://xmlsoft.org/, or amend scutter.py (line 24) to point to your favorite XSLT processor. It's currently unlikely you'll get this to run on Windows platforms, but if you do please send me the changes you made to get it going. foafbot-0.5/README0100664000016500001440000000345707671462514013244 0ustar edmunddusersFOAFBot is Copyright (c) 2002-2003 Edd Dumbill It is licensed under the terms of the GNU General Public License, see the accompanying 'LICENSE' file for details. For instructions on how to install the prerequisite software for running FOAFBot, see the accompanying 'INSTALL' file. TO RUN FOAFBOT python ./foafbot.py [options] options: -h, --help show help -p, --plan filename of default scutterplan -s, --server specify IRC server to connect -n, --nick nickname to connect to IRC with -c, --channel name of IRC channel (omit leading #) (can have more than one channel) -f, --fresh respider, even if database exists (use this for the first run) -k, --keyid 8-digit hex ID of PGP key to decrypt with (can have more than one) example: python ./foafbot.py -s irc.example.com -c foaf -n foafy -f \ -k DEADB00F FOAFbot will create a large amount of junk in the directory you run it from. On starting FOAFBot, will use the plan you give it (one is distributed, named plan.rdf). It will retrieve the FOAF files linked, and then traverse all rdfs:seeAlso links it finds. For testing purposes you will probably want to point the bot at a simple plan.rdf, probably with just your own FOAF file and no seeAlso links. User-level usage information is available on the web at . QUESTIONS Please try hard to find answers for yourself before contacting the author. You may find help in the FOAF IRC channel. Alternatively, send email to foafbot@usefulinc.com. foafbot-0.5/TODO0100664000016500001440000000061007671462514013040 0ustar edmunddusers* bug: keyid recognition should be case insensitive * bug: when reloading from, ensure that seeAlso'd nodes are set to status NEW: vestigial ERROR statuses won't be overriden otherwise. * add some sort of remote query interface?? * generate web content from dbs * implement content negotiation * track failures; in general ensure better logging system * ensure IRC output is in UTF-8 foafbot-0.5/ChangeLog0100664000016500001440000000372107671462514014130 0ustar edmunddusers2003-06-11 Edd Dumbill * Revised entire codebase to work with Redland's new context features. AttributedModel.py is now a thin layer on top of these, by and large. 2002-08-02 Edd Dumbill * Added support for decrypting retrieved files. Use the -k option to specify a key ID (which must be on the keyring and have no passphrase). Notable new methods are in scutter.py: scutter.check_encrypted() and function fetch_encrypted_into_file(). * mbox_sha1_hook.py: added a hook file to add sha1sums for every incoming mbox property. Altered AttributedModel.py to accommodate this, see new method register_hook(). 2002-07-25 Edd Dumbill * AttributedModel.py (AttributedModel._temp_node): move temp_node method inside of the model class, part of various changes made to ensure that the temp uri counter is stored in the storage, so temp uris don't get overwritten next time the storage is used. * oracle.py (Oracle.sayers): removes duplicate sayers, and also prioritises known sayers to the front of the list. * AttributedModel.py: removed 'set' class. Made sayers() return a list instead. * foafbot.py (OracleBotQuitException): introduce exception that the bot throws when it wants to quit (the bot's main loop is a while 1, you see) (OracleBot.handle_instruction): remove 'reload' standalone facility, only 'reload from' left working. * oracle.py (Oracle.close): method to force a friendly closedown of the brain so that we can re-use the BDB files on next startup. Uncovers some work-needed in Redland's RDF.py. * foafbot.py (main): add -f option to force use of a fresh BDB, else try to load from previously existing BDBs * oracle.py (Oracle.__init__): support loading from existing cached BDBs * AttributedModel.py (AttributedModel.regenerate_predicate_cache): added this method to support loading from cached BDBs * Decided it was a good idea to start writing a changelog for this software.foafbot-0.5/plan.rdf0100664000016500001440000000232707671462514014006 0ustar edmunddusers RDFIG Scratchpad foafbot-0.5/LICENSE0100644000016500001440000004311007671462514013355 0ustar edmunddusers GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License.