Remove trailing whitespaces.

This commit is contained in:
Emmanuel Gil Peyrot 2013-01-18 17:55:34 +01:00
commit 27b3592e16
2 changed files with 899 additions and 899 deletions

View file

@ -65,7 +65,7 @@ def sat_next_id():
return "sat_id_"+str(sat_id)
class SAT(service.Service):
def get_next_id(self):
return sat_next_id()
@ -87,26 +87,26 @@ class SAT(service.Service):
"""Save a constant"""
if CONST.has_key(name):
error(_('Trying to redefine a constant'))
raise Exception
raise Exception
CONST[name] = value
def __init__(self):
#TODO: standardize callback system
self.__general_cb_map = {} #callback called for general reasons (key = name)
self.__general_cb_map = {} #callback called for general reasons (key = name)
self.__private_data = {} #used for internal callbacks (key = id)
self.profiles = {}
self.plugins = {}
self.menus = {} #used to know which new menus are wanted by plugins
self.memory=Memory(self)
local_dir = self.memory.getConfig('', 'local_dir')
if not os.path.exists(local_dir):
os.makedirs(local_dir)
self.trigger = TriggerManager() #trigger are used to change SàT behaviour
self.trigger = TriggerManager() #trigger are used to change SàT behaviour
self.bridge=DBusBridge()
self.bridge.register("getVersion", lambda: self.get_const('client_version'))
self.bridge.register("getProfileName", self.memory.getProfileName)
@ -147,8 +147,8 @@ class SAT(service.Service):
self.bridge.register("getMenus", self.getMenus)
self.bridge.register("getMenuHelp", self.getMenuHelp)
self.bridge.register("callMenu", self.callMenu)
self.memory.initialized.addCallback(self._postMemoryInit)
self.memory.initialized.addCallback(self._postMemoryInit)
def _postMemoryInit(self, ignore):
"""Method called after memory initialization is done"""
@ -159,7 +159,7 @@ class SAT(service.Service):
def _import_plugins(self):
"""Import all plugins found in plugins directory"""
import sat.plugins
plugins_path = os.path.dirname(sat.plugins.__file__)
plugins_path = os.path.dirname(sat.plugins.__file__)
plug_lst = [os.path.splitext(plugin)[0] for plugin in map(os.path.basename,glob(os.path.join(plugins_path,"plugin*.py")))]
__plugins_to_import = {} #plugins we still have to import
for plug in plug_lst:
@ -198,11 +198,11 @@ class SAT(service.Service):
self.plugins[import_name].is_handler = False
#TODO: test xmppclient presence and register handler parent
def connect(self, profile_key = '@DEFAULT@'):
"""Connect to jabber server"""
self.asyncConnect(profile_key)
def asyncConnect(self, profile_key = '@DEFAULT@'):
"""Connect to jabber server with asynchronous reply
@param profile_key: %(doc_profile)s
@ -212,7 +212,7 @@ class SAT(service.Service):
if not profile:
error (_('Trying to connect a non-exsitant profile'))
raise ProfileUnknownError(profile_key)
if (self.isConnected(profile)):
info(_("already connected !"))
return defer.succeed("None")
@ -227,12 +227,12 @@ class SAT(service.Service):
current = self.profiles[profile] = xmpp.SatXMPPClient(self, profile,
jid.JID(self.memory.getParamA("JabberID", "Connection", profile_key = profile), profile),
self.memory.getParamA("Password", "Connection", profile_key = profile),
self.memory.getParamA("Server", "Connection", profile_key = profile),
self.memory.getParamA("Server", "Connection", profile_key = profile),
port)
current.messageProt = xmpp.SatMessageProtocol(self)
current.messageProt.setHandlerParent(current)
current.roster = xmpp.SatRosterProtocol(self)
current.roster.setHandlerParent(current)
@ -247,7 +247,7 @@ class SAT(service.Service):
current.versionHandler.setHandlerParent(current)
debug (_("setting plugins parents"))
for plugin in self.plugins.iteritems():
if plugin[1].is_handler:
plugin[1].getHandler(profile).setHandlerParent(current)
@ -307,7 +307,7 @@ class SAT(service.Service):
info("Salut à toi ô mon frère !")
#TODO: manage autoconnect
#self.connect()
def stopService(self):
self.memory.save()
info("Salut aussi à Rantanplan")
@ -315,13 +315,13 @@ class SAT(service.Service):
def run(self):
debug(_("running app"))
reactor.run()
def stop(self):
debug(_("stopping app"))
reactor.stop()
## Misc methods ##
def getJidNStream(self, profile_key):
"""Convenient method to get jid and stream from profile key
@return: tuple (jid, xmlstream) from profile, can be None"""
@ -347,8 +347,8 @@ class SAT(service.Service):
serverRegistrer = xmlstream.XmlStreamFactory(xmpp.RegisteringAuthenticator(self, server, login, password, email, next_id, profile))
connector = reactor.connectTCP(server, port, serverRegistrer)
serverRegistrer.clientConnectionLost = lambda conn, reason: connector.disconnect()
return next_id
return next_id
def registerNewAccountCB(self, id, data, profile):
user = jid.parse(self.memory.getParamA("JabberID", "Connection", profile_key=profile))[0]
@ -363,7 +363,7 @@ class SAT(service.Service):
confirm_id = sat_next_id()
self.__private_data[confirm_id]=(id,profile)
self.askConfirmation(confirm_id, "YES/NO",
{"message":_("Are you sure to register new account [%(user)s] to server %(server)s ?") % {'user':user, 'server':server, 'profile':profile}},
self.regisConfirmCB, profile)
@ -393,7 +393,7 @@ class SAT(service.Service):
profile = self.memory.getProfileName(profile_key)
assert(profile)
to_jid = jid.JID(target)
iq = compat.IQ(self.profiles[profile].xmlstream, 'set')
iq["to"] = target
iq["from"] = self.profiles[profile].jid.full()
@ -456,7 +456,7 @@ class SAT(service.Service):
## jabber methods ##
def getWaitingConf(self, profile_key=None):
assert(profile_key)
client = self.getClient(profile_key)
@ -467,22 +467,22 @@ class SAT(service.Service):
conf_type, data = client._waiting_conf[conf_id][:2]
ret.append((conf_id, conf_type, data))
return ret
def sendMessage(self, to, msg, subject=None, mess_type='auto', profile_key='@DEFAULT@'):
#FIXME: check validity of recipient
profile = self.memory.getProfileName(profile_key)
assert(profile)
client = self.profiles[profile]
current_jid = client.jid
mess_data = { #we put data in a dict, so trigger methods can change them
mess_data = { #we put data in a dict, so trigger methods can change them
"to": jid.JID(to),
"message": msg,
"subject": subject,
"type": mess_type
}
if mess_data["type"] == "auto":
# we try to guess the type
# we try to guess the type
if mess_data["subject"]:
mess_data["type"] = 'normal'
elif not mess_data["to"].resource: #if to JID has a resource, the type is not 'groupchat'
@ -492,7 +492,7 @@ class SAT(service.Service):
#FIXME: should entity_type manage ressources ?
except (UnknownEntityError, KeyError):
entity_type = "contact"
if entity_type == "chatroom":
mess_data["type"] = 'groupchat'
else:
@ -500,10 +500,10 @@ class SAT(service.Service):
else:
mess_data["type"] == 'chat'
mess_data["type"] == "chat" if mess_data["subject"] else "normal"
if not self.trigger.point("sendMessage", mess_data, profile):
return
debug(_("Sending jabber message of type [%(type)s] to %(to)s...") % {"type": mess_data["type"], "to": to})
message = domish.Element((None,'message'))
message["to"] = mess_data["to"].full()
@ -531,8 +531,8 @@ class SAT(service.Service):
del statuses['']
self.bridge.presenceUpdate(self.profiles[profile].jid.full(), show,
int(priority), statuses, profile)
def subscription(self, subs_type, raw_jid, profile_key):
"""Called to manage subscription
@param subs_type: subsciption type (cf RFC 3921)
@ -592,31 +592,31 @@ class SAT(service.Service):
def serverDiscoItems(self, disco_result, disco_client, profile, initialized):
"""xep-0030 Discovery Protocol.
@param disco_result: result of the disco item querry
@param disco_client: SatDiscoProtocol instance
@param profile: profile of the user
@param disco_client: SatDiscoProtocol instance
@param profile: profile of the user
@param initialized: deferred which must be chained when everything is done"""
def _check_entity_cb(result, entity, profile):
for category, type in result.identities:
debug (_('Identity added: (%(category)s,%(type)s) ==> %(entity)s [%(profile)s]') % {
'category':category, 'type':type, 'entity':entity, 'profile':profile})
self.memory.addServerIdentity(category, type, entity, profile)
self.memory.addServerIdentity(category, type, entity, profile)
def _errback(result, entity, profile):
warning(_("Can't get information on identity [%(entity)s] for profile [%(profile)s]") % {'entity':entity, 'profile': profile})
defer_list = []
for item in disco_result._items:
if item.entity.full().count('.') == 1: #XXX: workaround for a bug on jabberfr, tmp
warning(_('Using jabberfr workaround, be sure your domain has at least two levels (e.g. "example.tld", not "example" alone)'))
continue
args = [item.entity, profile]
args = [item.entity, profile]
defer_list.append(disco_client.requestInfo(item.entity).addCallbacks(_check_entity_cb, _errback, args, None, args))
defer.DeferredList(defer_list).chainDeferred(initialized)
## Generic HMI ##
## Generic HMI ##
def actionResult(self, action_id, action_type, data, profile):
"""Send the result of an action
@param action_id: same action_id used with action

View file

@ -28,7 +28,7 @@ from calendar import timegm
class SatXMPPClient(client.XMPPClient):
def __init__(self, host_app, profile, user_jid, password, host=None, port=5222):
client.XMPPClient.__init__(self, user_jid, password, host, port)
self.factory.clientConnectionLost = self.connectionLost
@ -39,7 +39,7 @@ class SatXMPPClient(client.XMPPClient):
self.conn_deferred = defer.Deferred()
self._waiting_conf = {} #callback called when a confirmation is received
self._progress_cb_map = {} #callback called when a progress is requested (key = progress id)
def getConnectionDeferred(self):
"""Return a deferred which fire when the client is connected"""
@ -53,28 +53,28 @@ class SatXMPPClient(client.XMPPClient):
info (_("********** [%s] CONNECTED **********") % self.profile)
self.streamInitialized()
self.host_app.bridge.connected(self.profile) #we send the signal to the clients
def streamInitialized(self):
"""Called after _authd"""
debug (_("XML stream is initialized"))
self.keep_alife = task.LoopingCall(self.xmlstream.send, " ") #Needed to avoid disconnection (specially with openfire)
self.keep_alife.start(180)
self.disco = SatDiscoProtocol(self)
self.disco.setHandlerParent(self)
self.discoHandler = disco.DiscoHandler()
self.discoHandler.setHandlerParent(self)
if not self.host_app.trigger.point("Disco Handled", self.profile):
return
self.roster.requestRoster()
self.presence.available()
self.disco.requestInfo(jid.JID(self.jid.host)).addCallback(self.host_app.serverDisco, self.profile) #FIXME: use these informations
self.disco.requestItems(jid.JID(self.jid.host)).addCallback(self.host_app.serverDiscoItems, self.disco, self.profile, self.client_initialized)
self.conn_deferred.callback(None)
@ -90,7 +90,7 @@ class SatXMPPClient(client.XMPPClient):
def isConnected(self):
return self.__connected
def connectionLost(self, connector, unused_reason):
self.__connected=False
info (_("********** [%s] DISCONNECTED **********") % self.profile)
@ -103,7 +103,7 @@ class SatXMPPClient(client.XMPPClient):
class SatMessageProtocol(xmppim.MessageProtocol):
def __init__(self, host):
xmppim.MessageProtocol.__init__(self)
self.host = host
@ -128,7 +128,7 @@ class SatMessageProtocol(xmppim.MessageProtocol):
self.host.memory.addToHistory(jid.JID(message["from"]), jid.JID(message["to"]), mess_body, mess_type, profile=self.parent.profile)
self.host.bridge.newMessage(message["from"], mess_body, mess_type, message['to'], extra, profile=self.parent.profile)
break
class SatRosterProtocol(xmppim.RosterClientProtocol):
def __init__(self, host):
@ -138,7 +138,7 @@ class SatRosterProtocol(xmppim.RosterClientProtocol):
#XXX: the two following dicts keep a local copy of the roster
self._groups = {} #map from groups to bare jids: key=group value=set of bare jids
self._jids = {} #map from bare jids to RosterItem: key=jid value=RosterItem
def rosterCb(self, roster):
for raw_jid, item in roster.iteritems():
self.onRosterSet(item)
@ -153,7 +153,7 @@ class SatRosterProtocol(xmppim.RosterClientProtocol):
"""Remove a contact from roster list"""
xmppim.RosterClientProtocol.removeItem(self, to)
#TODO: check IQ result
#XXX: disabled (cf http://wokkel.ik.nu/ticket/56))
#def addItem(self, to):
#"""Add a contact to roster list"""
@ -187,7 +187,7 @@ class SatRosterProtocol(xmppim.RosterClientProtocol):
if item.name:
item_attr['name'] = item.name
return item_attr
def onRosterSet(self, item):
"""Called when a new/update roster item is received"""
#TODO: send a signal to frontends
@ -199,13 +199,13 @@ class SatRosterProtocol(xmppim.RosterClientProtocol):
return
info (_("new contact in roster list: %s"), item.jid.full())
#self.host.memory.addContact(item.jid, item_attr, item.groups, self.parent.profile)
bare_jid = item.jid.userhost()
self._jids[bare_jid] = item
for group in item.groups:
self._groups.setdefault(group,set()).add(bare_jid)
self.host.bridge.newContact(item.jid.full(), self.getAttributes(item), item.groups, self.parent.profile)
def onRosterRemove(self, entity):
"""Called when a roster removal event is received"""
print _("removing %s from roster list") % entity.full()
@ -226,7 +226,7 @@ class SatRosterProtocol(xmppim.RosterClientProtocol):
except KeyError:
log.warning("there is not cache for the group [%(groups)s] of the removed roster item [%(jid)s]" %
{"group": group, "jid": bare_jid})
#then we send the bridge signal
self.host.bridge.contactDeleted(entity.userhost(), self.parent.profile)
@ -247,7 +247,7 @@ class SatRosterProtocol(xmppim.RosterClientProtocol):
def isJidInRoster(self, entity_jid):
"""Return True if jid is in roster"""
return entity_jid.userhost() in self._jids
def getItems(self):
"""Return all items of the roster"""
return self._jids.values()
@ -257,20 +257,20 @@ class SatRosterProtocol(xmppim.RosterClientProtocol):
return self._groups[group]
except KeyError:
return exceptions.UnknownGroupError
class SatPresenceProtocol(xmppim.PresenceClientProtocol):
def __init__(self, host):
xmppim.PresenceClientProtocol.__init__(self)
self.host = host
def availableReceived(self, entity, show=None, statuses=None, priority=0):
debug (_("presence update for [%(entity)s] (available, show=%(show)s statuses=%(statuses)s priority=%(priority)d)") % {'entity':entity, 'show':show, 'statuses':statuses, 'priority':priority})
if not statuses:
statuses = {}
if statuses.has_key(None): #we only want string keys
statuses["default"] = statuses[None]
del statuses[None]
@ -281,13 +281,13 @@ class SatPresenceProtocol(xmppim.PresenceClientProtocol):
#now it's time to notify frontends
self.host.bridge.presenceUpdate(entity.full(), show or "",
int(priority), statuses, self.parent.profile)
def unavailableReceived(self, entity, statuses=None):
debug (_("presence update for [%(entity)s] (unavailable, statuses=%(statuses)s)") % {'entity':entity, 'statuses':statuses})
if not statuses:
statuses = {}
if statuses.has_key(None): #we only want string keys
statuses["default"] = statuses[None]
del statuses[None]
@ -295,13 +295,13 @@ class SatPresenceProtocol(xmppim.PresenceClientProtocol):
#now it's time to notify frontends
self.host.bridge.presenceUpdate(entity.full(), "unavailable", 0, statuses, self.parent.profile)
def available(self, entity=None, show=None, statuses=None, priority=0):
if not statuses:
statuses = {}
# default for us is None for wokkel
# so we must temporarily switch to wokkel's convention...
# so we must temporarily switch to wokkel's convention...
if 'default' in statuses:
statuses[None] = statuses['default']
@ -380,10 +380,10 @@ class RegisteringAuthenticator(xmlstream.ConnectAuthenticator):
self.answer_id = answer_id
self.profile = profile
print _("Registration asked for"),user_login, user_pass, jabber_host
def connectionMade(self):
print "connectionMade"
self.xmlstream.namespace = "jabber:client"
self.xmlstream.sendHeader()
@ -405,7 +405,7 @@ class RegisteringAuthenticator(xmlstream.ConnectAuthenticator):
answer_data={"message":_("Registration successfull")}
self.host.bridge.actionResult(answer_type, self.answer_id, answer_data, self.profile)
self.xmlstream.sendFooter()
def registrationFailure(self, failure):
info (_("Registration failure: %s") % str(failure.value))
answer_type = "ERROR"