Permalink
Browse files

1) Some PEP8 fixes.

2) Now platform has a pointer to the XMPP server to be able to show some
information in the web ui. New roster view added for this reason.
3) Debug function now shows also xmpp debug info.
4) requestRoster is no longer a blocking method.
5) New deleteContact method.
6) Some fixes in the socialnetwork module, specially Group management.
7) db_fake DB is now concurrent-safe.
8) db_fake: group removes are fixed.
  • Loading branch information...
javipalanca committed May 7, 2013
1 parent fdb61fa commit 26c08b4edeef3577a2b10656ec202e6e38ebbffc
View
@@ -133,9 +133,9 @@ def main():
raise SystemExit
if dbg==['always']:
platform = spade_backend.SpadeBackend(configfilename, debug=True)
platform = spade_backend.SpadeBackend(s, configfilename, debug=True)
else:
platform = spade_backend.SpadeBackend(configfilename)
platform = spade_backend.SpadeBackend(s, configfilename)
sys.stdout.write(".")
sys.stdout.flush()
platform.start()
View
@@ -492,13 +492,13 @@ def DEBUG(self, dmsg, typ="info", component="spade"):
if self._debug:
# Print on screen
if typ == "info":
print colors.color_none + "DEBUG:[" + component + "] " + dmsg + " , info" + colors.color_none
print colors.color_none + self.getName() +":[" + component + "] " + dmsg + " , info" + colors.color_none
elif typ == "err":
print colors.color_none + "DEBUG:[" + component + "] " + color_red + dmsg + " , error" + colors.color_none
print colors.color_none + self.getName() + ":[" + component + "] " + color_red + dmsg + " , error" + colors.color_none
elif typ == "ok":
print colors.color_none + "DEBUG:[" + component + "] " + colors.color_green + dmsg + " , ok" + colors.color_none
print colors.color_none + self.getName() + ":[" + component + "] " + colors.color_green + dmsg + " , ok" + colors.color_none
elif typ == "warn":
print colors.color_none + "DEBUG:[" + component + "] " + colors.color_yellow + dmsg + " , warn" + colors.color_none
print colors.color_none + self.getName() + ":[" + component + "] " + colors.color_yellow + dmsg + " , warn" + colors.color_none
# Log to file
if self._debug_file:
@@ -518,6 +518,10 @@ def setDebug(self, activate=True):
def setDebugToScreen(self, activate=True):
self._debug = activate
if activate:
self.jabber._DEBUG.active_set(['always'])
else:
self.jabber._DEBUG.active_set()
def setDebugToFile(self, activate=True, fname=""):
if not fname:
View
@@ -1,48 +1,30 @@
# -*- coding: utf-8 -*-
from AMS import AmsAgentDescription
from DF import DfAgentDescription, ServiceDescription, Service
from Agent import PlatformAgent, require_login
import xmpp
import threading
#import Agent
import Envelope
import FIPAMessage
import AID
import Behaviour
import os.path
import sys
import traceback
import SocketServer
import SimpleHTTPServer
import BaseHTTPServer
import time
import thread
import copy
import ACLMessage
import types
import ACLParser
import BasicFipaDateTime
#from swi import SWIHandler
from wui import *
from os.path import *
from spade.AMS import AmsAgentDescription
from spade.DF import DfAgentDescription, Service
from spade.Agent import PlatformAgent, require_login
import spade.Envelope
import spade.AID
import spade.Behaviour
import spade.ACLMessage
import spade.BasicFipaDateTime
class PlatformRestart(Exception):
def __init__(self):
pass
#from spade.wui import require_login
from os.path import abspath
class PlatformRestart(Exception):
def __str__(self):
return
class SpadePlatform(PlatformAgent):
class RouteBehaviour(Behaviour.Behaviour):
class RouteBehaviour(spade.Behaviour.Behaviour):
#This behavior routes messages between agents.
#Also uses MTPs when different protocols are required (HTTP, ...)
def __init__(self):
Behaviour.Behaviour.__init__(self)
spade.Behaviour.Behaviour.__init__(self)
def _process(self):
msg = self._receive(True)
@@ -74,19 +56,16 @@ def _process(self):
#switch(protocol)
if protocol in self.myAgent.mtps.keys():
self.myAgent.DEBUG("Message through protocol " + str(protocol))
#ap = ACLParser.ACLxmlParser()
#payload = ap.encodeXML(newmsg)
#payload = str(newmsg)
payload = newmsg
envelope = Envelope.Envelope()
envelope = spade.Envelope.Envelope()
envelope.setFrom(newmsg.getSender())
for i in newmsg.getReceivers():
envelope.addTo(i)
envelope.setAclRepresentation(newmsg.getAclRepresentation())
envelope.setPayloadLength(len(str(payload)))
envelope.setPayloadEncoding("US-ASCII")
envelope.setDate(BasicFipaDateTime.BasicFipaDateTime())
envelope.setDate(spade.BasicFipaDateTime.BasicFipaDateTime())
self.myAgent.mtps[protocol].send(envelope, payload)
else:
# Default case: it's an XMPP message
@@ -127,18 +106,19 @@ def _setup(self):
self.wui.registerController("index", self.index)
self.wui.registerController("agents", self.agents)
self.wui.registerController("services", self.services)
self.wui.registerController("roster", self.get_roster)
self.wui.setPort(8008)
self.wui.start()
import mtp
import spade.mtp
# Load MTPs
for name, _mtp in self.config.acc.mtp.items():
try:
mod = "mtp."+name
mod = __import__(mod, globals(), locals(),[name])
mod = "spade.mtp." + name
mod = __import__(mod, globals(), locals(), [name])
self.mtps[_mtp['protocol']] = mod.INSTANCE(name, self.config, self)
except Exception, e:
self.DEBUG("EXCEPTION IMPORTING MTPS: "+ str(e), 'err','acc')
self.DEBUG("EXCEPTION IMPORTING MTPS: " + str(e), 'err', 'acc')
def takeDown(self):
for k, _mtp in self.mtps.items():
@@ -148,6 +128,9 @@ def takeDown(self):
except:
pass
def setXMPPServer(self, server):
self.server = server
#Controllers
def index(self):
import sys
@@ -163,7 +146,7 @@ def index(self):
def agents(self):
import sys
import time
so = self.session
#so = self.session
servername = self.getDomain()
platform = self.getName()
version = str(sys.version)
@@ -212,23 +195,43 @@ def services(self):
self.DEBUG("Services: " + str(servs))
return "services.pyra", dict(name=platform, servername=servername, platform=platform, version=version, time=the_time, services=servs)
@require_login
def get_roster(self):
import sys
import time
import copy
servername = self.getDomain()
platform = self.getName()
version = str(sys.version)
the_time = str(time.ctime())
roster = copy.copy(self.server.DB.db)
for server, v in roster.items():
try:
del v["__ir__"]
except: pass
for r in v.values():
try:
del r["roster"]["__ir__"]
except: pass
return "roster.pyra", dict(name=platform, servername=servername, platform=platform, version=version, time=the_time, roster=roster)
def getMembers(self, aname):
msg = ACLMessage.ACLMessage()
msg = spade.ACLMessage.ACLMessage()
msg.setOntology("spade:x:organization")
template = Behaviour.ACLTemplate()
template = spade.Behaviour.ACLTemplate()
template.setConversationId(msg.getConversationId())
t = Behaviour.MessageTemplate(template)
t = spade.Behaviour.MessageTemplate(template)
b = self.GetMembersBehav()
b.msg = msg
b.aname = aname
self.addBehaviour(b, t)
b.join()
return b.result
class GetMembersBehav(Behaviour.OneShotBehaviour):
class GetMembersBehav(spade.Behaviour.OneShotBehaviour):
def _process(self):
self.result = []
self.msg.addReceiver(AID.aid(self.aname, addresses=["xmpp://" + self.aname]))
self.msg.addReceiver(spade.AID.aid(self.aname, addresses=["xmpp://" + self.aname]))
self.msg.setContent("MEMBERS")
self.myAgent.send(self.msg)
rep = None
View
@@ -1,9 +1,11 @@
# -*- coding: utf-8 -*-
import Behaviour
import AID
from xmpp import *
from xmpp.protocol import Presence
import time
class ContactNotInGroup(Exception): pass
class ContactInGroup(Exception): pass
class PresenceBehaviour(Behaviour.EventBehaviour):
def _process(self):
@@ -45,23 +47,24 @@ def _process(self):
elif typ in ["available", ""]:
self.msg.setType("")
self.myAgent.roster.roster.PresenceHandler(dis=None, pres=self.msg)
self.DEBUG(str(self.msg.getFrom()) + " is now available.", 'ok','presence')
self.DEBUG(str(self.msg.getFrom()) + " is now available.", 'ok', 'presence')
elif typ == "unavailable":
self.myAgent.roster.roster.PresenceHandler(dis=None, pres=self.msg)
self.DEBUG(str(self.msg.getFrom()) + " is now unavailable.", 'ok','presence')
self.DEBUG(str(self.msg.getFrom()) + " is now unavailable.", 'ok', 'presence')
else:
self.myAgent.roster.roster.PresenceHandler(dis=None, pres=self.msg)
#Send and ACLMessage with the presence information to be aware
msg = self.myAgent.newMessage()
msg.setPerformative('inform')
msg.setSender(AID.aid(to, ["xmpp://"+str(to)]))
msg.setSender(AID.aid(to, ["xmpp://" + str(to)]))
msg.setOntology("Presence")
msg.setProtocol(typ)
msg.setContent(str(self.msg))
self.myAgent.postMessage(msg)
class Roster:
"""
This class manages the social aspect of the agents.
@@ -70,7 +73,7 @@ class Roster:
"""
def __init__(self, agent):
self.myAgent = agent
self.roster = self.myAgent.jabber.getRoster() #self.myAgent.jabber.Roster
self.roster = self.myAgent.jabber.getRoster() # self.myAgent.jabber.Roster
self._acceptAllSubscriptions = False
self._declineAllSubscriptions = False
self._followbackAllSubscriptions = False
@@ -105,7 +108,7 @@ def subscribe(self, jid):
'''
self.roster.Subscribe(jid)
def unsubscribe(self,jid):
def unsubscribe(self, jid):
'''
Unsubscribe from an agent
There is no need of confirmation by the forementioned agent
@@ -122,7 +125,7 @@ def checkSubscription(self, jid):
'''
item = self.getContact(jid)
if item and 'subscription' in item.keys():
return item['subscription']
return item['subscription']
return 'none'
def acceptSubscription(self, jid):
@@ -169,9 +172,11 @@ def followbackAllSubscriptions(self, accept=True):
self.myAgent.DEBUG("Followback all subscription requests.", 'info')
def requestRoster(self, force=False):
if force:
self.roster.set = 0
return self.roster.getRoster()
self.roster.Request(force)
#self.myAgent.DEBUG("Received roster: " + str(self.roster._data), 'ok')
def getRoster(self):
return self.roster
def waitingRoster(self):
return not self.roster.set
@@ -194,6 +199,9 @@ def getContact(self, jid):
'''
return self.roster.getItem(jid)
def deleteContact(self, jid):
self.roster.delItem(jid)
def getContacts(self):
'''
returns a list of your contacts with their presence information
@@ -205,7 +213,9 @@ def getAsk(self, jid):
def getGroups(self, jid):
if self.getContact(jid):
return self.roster.getGroups(jid)
return self.roster.getGroups(jid)
else:
return []
def getName(self, jid):
return self.roster.getName(jid)
@@ -232,30 +242,44 @@ def addContactToGroup(self, jid, group):
if group not in groups:
groups.append(group)
self.roster.setItem(jid=jid, groups=groups)
counter = 20
while group not in self.getGroups(jid) and counter > 0:
time.sleep(0.5)
counter -= 1
if group not in self.getGroups(jid):
raise ContactNotInGroup
def delContactFromGroup(self, jid, group):
groups = self.getGroups(jid)
if group in groups:
groups.remove(group)
self.roster.setItem(jid=jid, groups=groups)
self.roster.setItem(jid=jid, groups=groups)
counter = 20
while group in self.getGroups(jid) and counter > 0:
time.sleep(0.5)
counter -= 1
if group in self.getGroups(jid):
raise ContactInGroup
def isContactInGroup(self, jid, group):
return group in self.getGroups(jid)
def getContactsInGroup(self, group):
result = list()
for jid in self.getContacts():
contact = self.getContact(jid)
if contact != None and contact['groups'] != None and group in contact['groups']:
groups = self.getGroups(jid)
if groups and group in groups:
result.append(jid)
return result
def sendToGroup(self, msg, group):
if isinstance(msg, ACLMessage.ACLMessage):
for jid in self.getContactsInGroup(group):
msg.addReceiver(AID.aid(jid,['xmpp://'+str(jid)]))
msg.addReceiver(AID.aid(jid, ['xmpp://' + str(jid)]))
self.myAgent.send(msg)
else:
for jid in self.getContactsInGroup(group):
msg.setTo(jid)
self.myAgent.send(msg)
msg.setTo(jid)
self.myAgent.send(msg)
Oops, something went wrong.

0 comments on commit 26c08b4

Please sign in to comment.