a better code for roster_Window class

This commit is contained in:
Yann Leboulanger 2004-03-16 15:39:36 +00:00
parent 8e0bd6c409
commit 9954becd9c
3 changed files with 254 additions and 245 deletions

View File

@ -54,7 +54,7 @@ class GajimHub:
self.events[event] = [qu] self.events[event] = [qu]
# END register # END register
def sendPlugin(self, event, data): def sendPlugin(self, event, con, data):
""" Sends an event to registered plugins """ Sends an event to registered plugins
NOTIFY : ('NOTIFY', (user, status, message)) NOTIFY : ('NOTIFY', (user, status, message))
MSG : ('MSG', (user, msg)) MSG : ('MSG', (user, msg))
@ -63,6 +63,6 @@ class GajimHub:
if self.events.has_key(event): if self.events.has_key(event):
for i in self.events[event]: for i in self.events[event]:
i.put((event, data)) i.put((event, con, data))
# END sendPlugin # END sendPlugin
# END GajimHub # END GajimHub

View File

@ -36,11 +36,15 @@ CONFPATH = "~/.gajim/config"
class GajimCore: class GajimCore:
"""Core""" """Core"""
def __init__(self): def __init__(self):
self.connected = 0
self.init_cfg_file() self.init_cfg_file()
self.cfgParser = common.optparser.OptionsParser(CONFPATH) self.cfgParser = common.optparser.OptionsParser(CONFPATH)
self.hub = common.hub.GajimHub() self.hub = common.hub.GajimHub()
self.parse() self.parse()
self.connected = {}
#connexions {con: name, ...}
self.connexions = {}
for a in self.accounts:
self.connected[a] = 0
# END __init__ # END __init__
def init_cfg_file(self): def init_cfg_file(self):
@ -89,12 +93,12 @@ class GajimCore:
vcard[info.getName()] = {} vcard[info.getName()] = {}
for c in info.getChildren(): for c in info.getChildren():
vcard[info.getName()][c.getName()] = c.getData() vcard[info.getName()][c.getName()] = c.getData()
self.hub.sendPlugin('VCARD', vcard) self.hub.sendPlugin('VCARD', self.connexions[con], vcard)
def messageCB(self, con, msg): def messageCB(self, con, msg):
"""Called when we recieve a message""" """Called when we recieve a message"""
self.hub.sendPlugin('MSG', (msg.getFrom().getBasic(), \ self.hub.sendPlugin('MSG', self.connexions[con], \
msg.getBody())) (msg.getFrom().getBasic(), msg.getBody()))
# END messageCB # END messageCB
def presenceCB(self, con, prs): def presenceCB(self, con, prs):
@ -108,38 +112,40 @@ class GajimCore:
show = prs.getShow() show = prs.getShow()
else: else:
show = 'online' show = 'online'
self.hub.sendPlugin('NOTIFY', (prs.getFrom().getBasic(), \ self.hub.sendPlugin('NOTIFY', self.connexions[con], \
show, prs.getStatus(), prs.getFrom().getResource())) (prs.getFrom().getBasic(), show, prs.getStatus(), \
prs.getFrom().getResource()))
elif type == 'unavailable': elif type == 'unavailable':
self.hub.sendPlugin('NOTIFY', \ self.hub.sendPlugin('NOTIFY', self.connexions[con], \
(prs.getFrom().getBasic(), 'offline', prs.getStatus(), \ (prs.getFrom().getBasic(), 'offline', prs.getStatus(), \
prs.getFrom().getResource())) prs.getFrom().getResource()))
elif type == 'subscribe': elif type == 'subscribe':
log.debug("subscribe request from %s" % who) log.debug("subscribe request from %s" % who)
if self.cfgParser.Core['alwaysauth'] == 1 or \ if self.cfgParser.Core['alwaysauth'] == 1 or \
string.find(who, "@") <= 0: string.find(who, "@") <= 0:
self.con.send(common.jabber.Presence(who, 'subscribed')) con.send(common.jabber.Presence(who, 'subscribed'))
if string.find(who, "@") <= 0: if string.find(who, "@") <= 0:
self.hub.sendPlugin('NOTIFY', (who, 'offline', 'offline', \ self.hub.sendPlugin('NOTIFY', self.connexions[con], \
prs.getFrom().getResource())) (who, 'offline', 'offline', prs.getFrom().getResource()))
else: else:
txt = prs.getStatus() txt = prs.getStatus()
if not txt: if not txt:
txt = "I would like to add you to my roster." txt = "I would like to add you to my roster."
self.hub.sendPlugin('SUBSCRIBE', (who, 'txt')) self.hub.sendPlugin('SUBSCRIBE', self.connexions[con], (who, 'txt'))
elif type == 'subscribed': elif type == 'subscribed':
jid = prs.getFrom() jid = prs.getFrom()
self.hub.sendPlugin('SUBSCRIBED', {'jid':jid.getBasic(), \ self.hub.sendPlugin('SUBSCRIBED', self.connexions[con],\
'nom':jid.getNode(), 'ressource':jid.getResource()}) (jid.getBasic(), jid.getNode(), jid.getResource()))
self.hub.queueIn.put(('UPDUSER', (jid.getBasic(), \ self.hub.queueIn.put(('UPDUSER', self.connexions[con], \
jid.getNode(), ['general']))) (jid.getBasic(), jid.getNode(), ['general'])))
#BE CAREFUL : no self.con.updateRosterItem() in a callback #BE CAREFUL : no con.updateRosterItem() in a callback
log.debug("we are now subscribed to %s" % who) log.debug("we are now subscribed to %s" % who)
elif type == 'unsubscribe': elif type == 'unsubscribe':
log.debug("unsubscribe request from %s" % who) log.debug("unsubscribe request from %s" % who)
elif type == 'unsubscribed': elif type == 'unsubscribed':
log.debug("we are now unsubscribed to %s" % who) log.debug("we are now unsubscribed to %s" % who)
self.hub.sendPlugin('UNSUBSCRIBED', prs.getFrom().getBasic()) self.hub.sendPlugin('UNSUBSCRIBED', self.connexions[con], \
prs.getFrom().getBasic())
elif type == 'error': elif type == 'error':
print "\n\n******** ERROR *******" print "\n\n******** ERROR *******"
#print "From : %s" % prs.getFrom() #print "From : %s" % prs.getFrom()
@ -158,10 +164,10 @@ class GajimCore:
def disconnectedCB(self, con): def disconnectedCB(self, con):
"""Called when we are disconnected""" """Called when we are disconnected"""
log.debug("disconnectedCB") log.debug("disconnectedCB")
if self.connected == 1: if self.connected[self.connexions[con]] == 1:
self.connected = 0 self.connected[self.connexions[con]] = 0
self.con.disconnect() con.disconnect()
self.hub.sendPlugin('STATUS', 'offline') self.hub.sendPlugin('STATUS', self.connexions[con], 'offline')
# END disconenctedCB # END disconenctedCB
def connect(self, account): def connect(self, account):
@ -170,45 +176,49 @@ class GajimCore:
name = self.cfgParser.tab[account]["name"] name = self.cfgParser.tab[account]["name"]
password = self.cfgParser.tab[account]["password"] password = self.cfgParser.tab[account]["password"]
ressource = self.cfgParser.tab[account]["ressource"] ressource = self.cfgParser.tab[account]["ressource"]
self.con = common.jabber.Client(host = hostname, \ con = common.jabber.Client(host = hostname, \
debug = [common.jabber.DBG_ALWAYS], log = sys.stderr, \ debug = [common.jabber.DBG_ALWAYS], log = sys.stderr, \
connection=common.xmlstream.TCP, port=5222) connection=common.xmlstream.TCP, port=5222)
#debug = [common.jabber.DBG_ALWAYS], log = sys.stderr, \ #debug = [common.jabber.DBG_ALWAYS], log = sys.stderr, \
#connection=common.xmlstream.TCP_SSL, port=5223) #connection=common.xmlstream.TCP_SSL, port=5223)
self.connexions[con] = account
try: try:
self.con.connect() con.connect()
except IOError, e: except IOError, e:
log.debug("Couldn't connect to %s %s" % (hostname, e)) log.debug("Couldn't connect to %s %s" % (hostname, e))
self.hub.sendPlugin('STATUS', 'offline') self.hub.sendPlugin('STATUS', account, 'offline')
self.hub.sendPlugin('WARNING', "Couldn't connect to %s" % hostname) self.hub.sendPlugin('WARNING', None, "Couldn't connect to %s" \
% hostname)
return 0 return 0
except common.xmlstream.socket.error, e: except common.xmlstream.socket.error, e:
log.debug("Couldn't connect to %s %s" % (hostname, e)) log.debug("Couldn't connect to %s %s" % (hostname, e))
self.hub.sendPlugin('STATUS', 'offline') self.hub.sendPlugin('STATUS', account, 'offline')
self.hub.sendPlugin('WARNING', "Couldn't connect to %s : %s" % (hostname, e)) self.hub.sendPlugin('WARNING', None, "Couldn't connect to %s : %s" \
% (hostname, e))
return 0 return 0
else: else:
log.debug("Connected to server") log.debug("Connected to server")
self.con.registerHandler('message', self.messageCB) con.registerHandler('message', self.messageCB)
self.con.registerHandler('presence', self.presenceCB) con.registerHandler('presence', self.presenceCB)
self.con.registerHandler('iq',self.vCardCB,'result')#common.jabber.NS_VCARD) con.registerHandler('iq',self.vCardCB,'result')#common.jabber.NS_VCARD)
self.con.setDisconnectHandler(self.disconnectedCB) con.setDisconnectHandler(self.disconnectedCB)
#BUG in jabberpy library : if hostname is wrong : "boucle" #BUG in jabberpy library : if hostname is wrong : "boucle"
if self.con.auth(name, password, ressource): if con.auth(name, password, ressource):
self.con.requestRoster() con.requestRoster()
roster = self.con.getRoster().getRaw() roster = con.getRoster().getRaw()
if not roster : if not roster :
roster = {} roster = {}
self.hub.sendPlugin('ROSTER', roster) self.hub.sendPlugin('ROSTER', account, roster)
self.con.sendInitPresence() con.sendInitPresence()
self.hub.sendPlugin('STATUS', 'online') self.hub.sendPlugin('STATUS', account, 'online')
self.connected = 1 self.connected[account] = 1
else: else:
log.debug("Couldn't authentificate to %s" % hostname) log.debug("Couldn't authentificate to %s" % hostname)
self.hub.sendPlugin('STATUS', 'offline') self.hub.sendPlugin('STATUS', account, 'offline')
self.hub.sendPlugin('WARNING', \ self.hub.sendPlugin('WARNING', None, \
'Authentification failed, check your login and password') 'Authentification failed with %s, check your login and password'\
% hostname)
return 0 return 0
# END connect # END connect
@ -218,27 +228,32 @@ class GajimCore:
while 1: while 1:
if not self.hub.queueIn.empty(): if not self.hub.queueIn.empty():
ev = self.hub.queueIn.get() ev = self.hub.queueIn.get()
for con in self.connexions.keys():
if ev[1] == self.connexions[con]:
break
#('QUIT', account, ())
if ev[0] == 'QUIT': if ev[0] == 'QUIT':
if self.connected == 1: for con in self.connexions.keys():
self.connected = 0 # if self.connected[a] == 1:
self.con.disconnect() # self.connected[a] = 0
self.hub.sendPlugin('QUIT', ()) con.disconnect()
self.hub.sendPlugin('QUIT', None, ())
return return
#('ASK_CONFIG', (who_ask, section, default_config)) #('ASK_CONFIG', account, (who_ask, section, default_config))
elif ev[0] == 'ASK_CONFIG': elif ev[0] == 'ASK_CONFIG':
if ev[1][1] == 'accounts': if ev[2][1] == 'accounts':
self.hub.sendPlugin('CONFIG', (ev[1][0], self.accounts)) self.hub.sendPlugin('CONFIG', None, (ev[2][0], self.accounts))
else: else:
if self.cfgParser.tab.has_key(ev[1][1]): if self.cfgParser.tab.has_key(ev[2][1]):
self.hub.sendPlugin('CONFIG', (ev[1][0], \ self.hub.sendPlugin('CONFIG', None, (ev[2][0], \
self.cfgParser.__getattr__(ev[1][1]))) self.cfgParser.__getattr__(ev[2][1])))
else: else:
self.cfgParser.tab[ev[1][1]] = ev[1][2] self.cfgParser.tab[ev[2][1]] = ev[2][2]
self.cfgParser.writeCfgFile() self.cfgParser.writeCfgFile()
self.hub.sendPlugin('CONFIG', (ev[1][0], ev[1][2])) self.hub.sendPlugin('CONFIG', None, (ev[2][0], ev[2][2]))
#('CONFIG', (section, config)) #('CONFIG', account, (section, config))
elif ev[0] == 'CONFIG': elif ev[0] == 'CONFIG':
if ev[1][0] == 'accounts': if ev[2][0] == 'accounts':
#Remove all old accounts #Remove all old accounts
accts = string.split(self.cfgParser.tab\ accts = string.split(self.cfgParser.tab\
['Profile']['accounts'], ' ') ['Profile']['accounts'], ' ')
@ -247,51 +262,51 @@ class GajimCore:
for a in accts: for a in accts:
del self.cfgParser.tab[a] del self.cfgParser.tab[a]
#Write all new accounts #Write all new accounts
accts = ev[1][1].keys() accts = ev[2][1].keys()
self.cfgParser.tab['Profile']['accounts'] = \ self.cfgParser.tab['Profile']['accounts'] = \
string.join(accts) string.join(accts)
for a in accts: for a in accts:
self.cfgParser.tab[a] = ev[1][1][a] self.cfgParser.tab[a] = ev[2][1][a]
else: else:
self.cfgParser.tab[ev[1][0]] = ev[1][1] self.cfgParser.tab[ev[2][0]] = ev[2][1]
self.cfgParser.writeCfgFile() self.cfgParser.writeCfgFile()
#TODO: tell the changes to other plugins #TODO: tell the changes to other plugins
#('STATUS', (status, msg, account)) #('STATUS', account, (status, msg))
elif ev[0] == 'STATUS': elif ev[0] == 'STATUS':
if (ev[1][0] != 'offline') and (self.connected == 0): if (ev[2][0] != 'offline') and (self.connected[ev[1]] == 0):
self.connect(ev[1][2]) self.connect(ev[1])
elif (ev[1][0] == 'offline') and (self.connected == 1): elif (ev[2][0] == 'offline') and (self.connected[ev[1]] == 1):
self.connected = 0 self.connected[ev[1]] = 0
self.con.disconnect() con.disconnect()
self.hub.sendPlugin('STATUS', 'offline') self.hub.sendPlugin('STATUS', ev[1], 'offline')
if ev[1][0] != 'offline' and self.connected == 1: if ev[2][0] != 'offline' and self.connected[ev[1]] == 1:
p = common.jabber.Presence() p = common.jabber.Presence()
p.setShow(ev[1][0]) p.setShow(ev[2][0])
p.setStatus(ev[1][1]) p.setStatus(ev[2][1])
self.con.send(p) con.send(p)
self.hub.sendPlugin('STATUS', ev[1][0]) self.hub.sendPlugin('STATUS', ev[1], ev[2][0])
#('MSG', (jid, msg)) #('MSG', account, (jid, msg))
elif ev[0] == 'MSG': elif ev[0] == 'MSG':
msg = common.jabber.Message(ev[1][0], ev[1][1]) msg = common.jabber.Message(ev[2][0], ev[2][1])
msg.setType('chat') msg.setType('chat')
self.con.send(msg) con.send(msg)
self.hub.sendPlugin('MSGSENT', ev[1]) self.hub.sendPlugin('MSGSENT', ev[1], ev[2])
#('SUB', (jid, txt)) #('SUB', account, (jid, txt))
elif ev[0] == 'SUB': elif ev[0] == 'SUB':
log.debug('subscription request for %s' % ev[1][0]) log.debug('subscription request for %s' % ev[2][0])
pres = common.jabber.Presence(ev[1][0], 'subscribe') pres = common.jabber.Presence(ev[2][0], 'subscribe')
if ev[1][1]: if ev[2][1]:
pres.setStatus(ev[1][1]) pres.setStatus(ev[2][1])
else: else:
pres.setStatus("I would like to add you to my roster.") pres.setStatus("I would like to add you to my roster.")
self.con.send(pres) con.send(pres)
#('REQ', jid) #('REQ', account, jid)
elif ev[0] == 'AUTH': elif ev[0] == 'AUTH':
self.con.send(common.jabber.Presence(ev[1], 'subscribed')) con.send(common.jabber.Presence(ev[2], 'subscribed'))
#('DENY', jid) #('DENY', account, jid)
elif ev[0] == 'DENY': elif ev[0] == 'DENY':
self.con.send(common.jabber.Presence(ev[1], 'unsubscribed')) con.send(common.jabber.Presence(ev[2], 'unsubscribed'))
#('UNSUB', jid) #('UNSUB', accountjid)
elif ev[0] == 'UNSUB': elif ev[0] == 'UNSUB':
if self.cfgParser.Core.has_key('delauth'): if self.cfgParser.Core.has_key('delauth'):
delauth = self.cfgParser.Core['delauth'] delauth = self.cfgParser.Core['delauth']
@ -302,26 +317,29 @@ class GajimCore:
else: else:
delroster = 1 delroster = 1
if delauth: if delauth:
self.con.send(common.jabber.Presence(ev[1], 'unsubscribe')) con.send(common.jabber.Presence(ev[2], 'unsubscribe'))
if delroster: if delroster:
self.con.removeRosterItem(ev[1]) con.removeRosterItem(ev[2])
#('UPDUSER', (jid, name, groups)) #('UPDUSER', account, (jid, name, groups))
elif ev[0] == 'UPDUSER': elif ev[0] == 'UPDUSER':
self.con.updateRosterItem(jid=ev[1][0], name=ev[1][1], \ con.updateRosterItem(jid=ev[2][0], name=ev[2][1], \
groups=ev[1][2]) groups=ev[2][2])
#('REQ_AGENTS', account, ())
elif ev[0] == 'REQ_AGENTS': elif ev[0] == 'REQ_AGENTS':
agents = self.con.requestAgents() agents = con.requestAgents()
self.hub.sendPlugin('AGENTS', agents) self.hub.sendPlugin('AGENTS', ev[1], agents)
#('REQ_AGENT_INFO', account, agent)
elif ev[0] == 'REQ_AGENT_INFO': elif ev[0] == 'REQ_AGENT_INFO':
self.con.requestRegInfo(ev[1]) con.requestRegInfo(ev[2])
agent_info = self.con.getRegInfo() agent_info = con.getRegInfo()
self.hub.sendPlugin('AGENT_INFO', (ev[1], agent_info)) self.hub.sendPlugin('AGENT_INFO', ev[1], (ev[2], agent_info))
#('REG_AGENT', account, infos)
elif ev[0] == 'REG_AGENT': elif ev[0] == 'REG_AGENT':
self.con.sendRegInfo(ev[1]) con.sendRegInfo(ev[2])
#('NEW_ACC', (hostname, login, password, name, ressource)) #('NEW_ACC', (hostname, login, password, name, ressource))
elif ev[0] == 'NEW_ACC': elif ev[0] == 'NEW_ACC':
c = common.jabber.Client(host = \ c = common.jabber.Client(host = \
ev[1][0], debug = False, log = sys.stderr) ev[2][0], debug = False, log = sys.stderr)
try: try:
c.connect() c.connect()
except IOError, e: except IOError, e:
@ -331,44 +349,46 @@ class GajimCore:
log.debug("Connected to server") log.debug("Connected to server")
c.requestRegInfo() c.requestRegInfo()
req = c.getRegInfo() req = c.getRegInfo()
c.setRegInfo( 'username', ev[1][1]) c.setRegInfo( 'username', ev[2][1])
c.setRegInfo( 'password', ev[1][2]) c.setRegInfo( 'password', ev[2][2])
#FIXME: if users already exist, no error message :( #FIXME: if users already exist, no error message :(
if not c.sendRegInfo(): if not c.sendRegInfo():
print "error " + c.lastErr print "error " + c.lastErr
else: else:
self.hub.sendPlugin('ACC_OK', ev[1]) self.hub.sendPlugin('ACC_OK', ev[1], ev[2])
#('ASK_VCARD', jid) #('ASK_VCARD', account, jid)
elif ev[0] == 'ASK_VCARD': elif ev[0] == 'ASK_VCARD':
iq = common.jabber.Iq(to=ev[1], type="get") iq = common.jabber.Iq(to=ev[2], type="get")
iq._setTag('vCard', common.jabber.NS_VCARD) iq._setTag('vCard', common.jabber.NS_VCARD)
iq.setID(self.con.getAnID()) iq.setID(con.getAnID())
self.con.send(iq) con.send(iq)
#('VCARD', {entry1: data, entry2: {entry21: data, ...}, ...}) #('VCARD', {entry1: data, entry2: {entry21: data, ...}, ...})
elif ev[0] == 'VCARD': elif ev[0] == 'VCARD':
iq = common.jabber.Iq(type="set") iq = common.jabber.Iq(type="set")
iq.setID(self.con.getAnID()) iq.setID(con.getAnID())
iq2 = iq._setTag('vCard', common.jabber.NS_VCARD) iq2 = iq._setTag('vCard', common.jabber.NS_VCARD)
for i in ev[1].keys(): for i in ev[2].keys():
if i != 'jid': if i != 'jid':
if type(ev[1][i]) == type({}): if type(ev[2][i]) == type({}):
iq3 = iq2.insertTag(i) iq3 = iq2.insertTag(i)
for j in ev[1][i].keys(): for j in ev[2][i].keys():
iq3.insertTag(j).putData(ev[1][i][j]) iq3.insertTag(j).putData(ev[2][i][j])
else: else:
iq2.insertTag(i).putData(ev[1][i]) iq2.insertTag(i).putData(ev[2][i])
self.con.send(iq) con.send(iq)
#('AGENT_LOGGING', (agent, type)) #('AGENT_LOGGING', account, (agent, type))
elif ev[0] == 'AGENT_LOGGING': elif ev[0] == 'AGENT_LOGGING':
t = ev[1][1]; t = ev[2][1];
if not t: if not t:
t='available'; t='available';
p = common.jabber.Presence(to=ev[1][0], type=t) p = common.jabber.Presence(to=ev[2][0], type=t)
self.con.send(p) con.send(p)
else: else:
log.debug("Unknown Command %s" % ev[0]) log.debug("Unknown Command %s" % ev[0])
elif self.connected == 1: else:
self.con.process(1) for con in self.connexions:
if self.connected[self.connexions[con]] == 1:
con.process(1)
time.sleep(0.1) time.sleep(0.1)
# END main # END main
# END GajimCore # END GajimCore
@ -403,21 +423,16 @@ def start():
"""Start the Core""" """Start the Core"""
gc = GajimCore() gc = GajimCore()
loadPlugins(gc) loadPlugins(gc)
################ pr des tests ###########
# gc.hub.sendPlugin('NOTIFY', ('aste@lagaule.org', 'online', 'online', 'oleron'))
# gc.hub.sendPlugin('MSG', ('ate@lagaule.org', 'msg'))
#########################################
try: try:
gc.mainLoop() gc.mainLoop()
except KeyboardInterrupt: except KeyboardInterrupt:
print "Keyboard Interrupt : Bye!" print "Keyboard Interrupt : Bye!"
if gc.connected: for con in gc.connexions:
gc.con.disconnect() if gc.connected[gc.connexions[con]]:
gc.hub.sendPlugin('QUIT', ()) con.disconnect()
gc.hub.sendPlugin('QUIT', None, ())
return 0 return 0
# except: # except:
# print "Erreur survenue" # print "Erreur survenue"
# if gc.connected:
# gc.con.disconnect()
# gc.hub.sendPlugin('QUIT', ()) # gc.hub.sendPlugin('QUIT', ())
# END start # END start

View File

@ -1058,13 +1058,14 @@ class roster_Window:
def add_user_to_roster(self, user, account): def add_user_to_roster(self, user, account):
"""Add a user to the roster and add groups if they aren't in roster""" """Add a user to the roster and add groups if they aren't in roster"""
newgrp = 0 newgrp = 0
showOffline = self.plugin.config['showoffline']
self.contacts[account][user.jid] = user self.contacts[account][user.jid] = user
if user.groups == []: if user.groups == []:
if string.find(user.jid, "@") <= 0: if string.find(user.jid, "@") <= 0:
user.groups.append('Agents') user.groups.append('Agents')
else: else:
user.groups.append('general') user.groups.append('general')
if user.show != 'offline' or self.showOffline or 'Agents' in user.groups: if user.show != 'offline' or showOffline or 'Agents' in user.groups:
model = self.tree.get_model() model = self.tree.get_model()
for g in user.groups: for g in user.groups:
if not self.groups[account].has_key(g): if not self.groups[account].has_key(g):
@ -1096,7 +1097,7 @@ class roster_Window:
def draw_roster(self): def draw_roster(self):
"""Clear and draw roster""" """Clear and draw roster"""
self.tree.get_model().clear() self.tree.get_model().clear()
for acct in self.contacts.keys() for acct in self.contacts.keys():
self.add_account_to_roster(acct) self.add_account_to_roster(acct)
for user in self.contacts[acct]: for user in self.contacts[acct]:
self.add_user_to_roster(user, acct) self.add_user_to_roster(user, acct)
@ -1138,40 +1139,39 @@ class roster_Window:
def chg_user_status(self, user, show, status, account): def chg_user_status(self, user, show, status, account):
"""When a user change his status""" """When a user change his status"""
if self.l_contact[user.jid]['iter'] == []: iters = self.get_user_iter(user.jid, account)
showOffline = self.plugin.config['showoffline']
if not iters:
self.add_user(user) self.add_user(user)
else: else:
model = self.tree.get_model() model = self.tree.get_model()
if show == 'offline' and not self.showOffline: if show == 'offline' and not showOffline:
self.remove_user(user) self.remove_user(user)
else: else:
for i in self.l_contact[user.jid]['iter']: for i in iters:
if self.pixbufs.has_key(show): if self.pixbufs.has_key(show):
model.set_value(i, 0, self.pixbufs[show]) model.set_value(i, 0, self.pixbufs[show])
#update icon in chat window user.show = show
if self.tab_messages.has_key(user.jid): user.status = status
self.tab_messages[user.jid].img.set_from_pixbuf(self.pixbufs[show])
u.show = show
u.status = status
#Print status in chat window #Print status in chat window
if self.plugin.windows.has_key("%s_%s" % (user.jid, account)): if self.plugin.windows[account].has_key(user.jid):
self.windows["%s_%s" % (user.jid, account)].print_conversation(\ self.plugin.windows[account][user.jid].img.set_from_pixbuf(self.pixbufs[show])
self.plugin.windows[account][user.jid].print_conversation(\
"%s is now %s (%s)" % (user.name, show, status), 'status') "%s is now %s (%s)" % (user.name, show, status), 'status')
def on_info(self, widget, jid): def on_info(self, widget, user, account):
"""Call infoUser_Window class to display user's information""" """Call infoUser_Window class to display user's information"""
jid = self.l_contact[jid]['user'].jid if not self.plugin.windows[account].has_key('infos'+user.jid):
if not self.tab_vcard.has_key(jid): self.plugin.windows[account]['infos'+user.jid] = infoUser_Window(user, self.plugin)
self.tab_vcard[jid] = infoUser_Window(self.l_contact[jid]['user'], self)
def on_agent_logging(self, widget, jid, type): def on_agent_logging(self, widget, jid, state, account):
"""When an agent is requested to log in or off""" """When an agent is requested to log in or off"""
self.queueOUT.put(('AGENT_LOGGING', (jid, type))) self.plugin.send('AGENT_LOGGING', account, (jid, state))
def mk_menu_c(self, event, iter): def mk_menu_user(self, event, iter):
"""Make user's popup menu""" """Make user's popup menu"""
model = self.tree.get_model() model = self.tree.get_model()
jid = model.get_value(iter, 2) jid = model.get_value(iter, 3)
path = model.get_path(iter) path = model.get_path(iter)
menu = gtk.Menu() menu = gtk.Menu()
item = gtk.MenuItem("Start chat") item = gtk.MenuItem("Start chat")
@ -1225,16 +1225,16 @@ class roster_Window:
def mk_menu_agent(self, event, iter): def mk_menu_agent(self, event, iter):
"""Make agent's popup menu""" """Make agent's popup menu"""
model = self.tree.get_model() model = self.tree.get_model()
jid = model.get_value(iter, 1) jid = model.get_value(iter, 3)
menu = gtk.Menu() menu = gtk.Menu()
item = gtk.MenuItem("Log on") item = gtk.MenuItem("Log on")
if self.l_contact[jid]['user'].show != 'offline': if self.contacts[jid].show != 'offline':
item.set_sensitive(FALSE) item.set_sensitive(FALSE)
menu.append(item) menu.append(item)
item.connect("activate", self.on_agent_logging, jid, 'available') item.connect("activate", self.on_agent_logging, jid, 'available')
item = gtk.MenuItem("Log off") item = gtk.MenuItem("Log off")
if self.l_contact[jid]['user'].show == 'offline': if self.contacts[jid].show == 'offline':
item.set_sensitive(FALSE) item.set_sensitive(FALSE)
menu.append(item) menu.append(item)
item.connect("activate", self.on_agent_logging, jid, 'unavailable') item.connect("activate", self.on_agent_logging, jid, 'unavailable')
@ -1242,26 +1242,18 @@ class roster_Window:
menu.popup(None, None, None, event.button, event.time) menu.popup(None, None, None, event.button, event.time)
menu.show_all() menu.show_all()
def authorize(self, widget, jid): def authorize(self, widget, jid, account):
"""Authorize a user""" """Authorize a user"""
self.queueOUT.put(('AUTH', jid)) self.plugin.send('AUTH', account, jid)
def req_sub(self, widget, jid, txt): def req_sub(self, widget, jid, txt, account):
"""Request subscription to a user""" """Request subscription to a user"""
self.queueOUT.put(('SUB', (jid, txt))) self.plugin.send('SUB', account, (jid, txt))
if not self.l_contact.has_key(jid): if not self.contacts[account].has_key(jid):
user1 = user(jid, jid, ['general'], 'requested', \ user1 = user(jid, jid, ['general'], 'requested', \
'requested', 'sub', '') 'requested', 'sub', '')
self.add_user(user1) self.add_user(user1)
def init_tree(self):
"""initialize treeview, l_contact and l_group"""
self.tree.get_model().clear()
#l_contact = {jid:{'user':_, 'iter':[iter1, ...]]
self.l_contact = {}
#l_group = {name:{'iter':_, 'hide':Bool}
self.l_group = {}
def on_treeview_event(self, widget, event): def on_treeview_event(self, widget, event):
"""popup user's group's or agent menu""" """popup user's group's or agent menu"""
if (event.button == 3) & (event.type == gtk.gdk.BUTTON_PRESS): if (event.button == 3) & (event.type == gtk.gdk.BUTTON_PRESS):
@ -1272,13 +1264,13 @@ class roster_Window:
return return
model = self.tree.get_model() model = self.tree.get_model()
iter = model.get_iter(path) iter = model.get_iter(path)
data = model.get_value(iter, 2) type = model.get_value(iter, 2)
if data == 'group': if data == 'group':
self.mk_menu_g(event) self.mk_menu_g(event)
elif data == 'agent': elif data == 'agent':
self.mk_menu_agent(event, iter) self.mk_menu_agent(event, iter)
else: elif data == 'user':
self.mk_menu_c(event, iter) self.mk_menu_user(event, iter)
return gtk.TRUE return gtk.TRUE
return gtk.FALSE return gtk.FALSE
@ -1296,12 +1288,15 @@ class roster_Window:
txt = w.run() txt = w.run()
else: else:
txt = status txt = status
if len(self.plugin.accounts) > 0: accounts = self.plugin.accts.get_accounts()
self.queueOUT.put(('STATUS', None, (status, txt))) if len(accounts) == 0:
else:
warning_Window("You must setup an account before connecting to jabber network.") warning_Window("You must setup an account before connecting to jabber network.")
return
for acct in accounts:
self.plugin.send('STATUS', acct, (status, txt))
def on_status_changed(self, account, status): def on_status_changed(self, account, status):
"""the core tells us that our status has changed"""
optionmenu = self.xml.get_widget('optionmenu') optionmenu = self.xml.get_widget('optionmenu')
for i in range(7): for i in range(7):
if optionmenu.get_menu().get_children()[i].name == status: if optionmenu.get_menu().get_children()[i].name == status:
@ -1310,64 +1305,63 @@ class roster_Window:
if status == 'offline': if status == 'offline':
self.plugin.connected[account] = 0 self.plugin.connected[account] = 0
self.plugin.sleeper = None self.plugin.sleeper = None
for jid in self.l_contact.keys(): for jid in self.contacts.keys():
user = self.l_contact[jid]['user'] user = self.contacts[jid]
#TODO: give account to chg_status self.chg_user_status(user, 'offline', 'Disconnected', account)
self.chg_status(user, 'offline', 'Disconnected', 'account') elif self.plugin.connected[account] == 0:
elif self.plugin.connected[ev[1]] == 0: self.plugin.connected[account] = 1
self.plugin.connected[ev[1]] = 1
self.plugin.sleeper = None#common.sleepy.Sleepy(\ self.plugin.sleeper = None#common.sleepy.Sleepy(\
#self.autoawaytime*60, self.autoxatime*60) #self.autoawaytime*60, self.autoxatime*60)
def on_message(self, jid, msg, account): def on_message(self, jid, msg, account):
"""when we receive a message""" """when we receive a message"""
if not self.l_contact.has_key(jid): if not self.contacts.has_key(jid):
user1 = user(jid, jid, ['not in list'], \ user1 = user(jid, jid, ['not in list'], \
'not in list', 'not in list', 'none', '') 'not in list', 'not in list', 'none', '')
self.add_user(user1) self.add_user(user1)
autopopup = self.plugin.config['autopopup'] autopopup = self.plugin.config['autopopup']
if autopopup == 0 and not self.tab_messages.has_key(jid): if autopopup == 0 and not self.plugin.windows[account].has_key(jid):
#We save it in a queue #We save it in a queue
if not self.tab_queues.has_key(jid): if not self.plugin.queues[account].has_key(jid):
model = self.tree.get_model() model = self.tree.get_model()
self.tab_queues[jid] = Queue.Queue(50) self.plugin.queues[account][jid] = Queue.Queue(50)
for i in self.l_contact[jid]['iter']: for i in self.get_user_iter(jid, account):
model.set_value(i, 0, self.pixbufs['message']) model.set_value(i, 0, self.pixbufs['message'])
tim = time.strftime("[%H:%M:%S]") tim = time.strftime("[%H:%M:%S]")
self.tab_queues[jid].put((msg, tim)) self.plugin.queues[account][jid].put((msg, tim))
else: else:
if not self.tab_messages.has_key(jid): if not self.plugin.windows[account].has_key(jid):
if self.l_contact.has_key(jid): self.plugin.windows[account][jid] = \
self.tab_messages[jid] = \ message_Window(self.contacts[account][jid], self)
message_Window(self.l_contact[jid]['user'], self) self.plugin.windows[account][jid].print_conversation(msg)
self.tab_messages[jid].print_conversation(msg)
def on_prefs(self, widget): def on_prefs(self, widget):
"""When preferences is selected : """When preferences is selected :
call the preference_Window class""" call the preference_Window class"""
window = preference_Window(self) if not self.plugin.windows.has_key('preferences'):
self.plugin.windows['preferences'] = preference_Window(self)
def on_add(self, widget): def on_add(self, widget):
"""When add user is selected : """When add user is selected :
call the add class""" call the add class"""
window_add = addContact_Window(self) addContact_Window(self)
def on_about(self, widget): def on_about(self, widget):
"""When about is selected : """When about is selected :
call the about class""" call the about class"""
window_about = about_Window() if not self.plugin.windows.has_key('about'):
self.plugin.windows['about'] = about_Window()
def on_accounts(self, widget): def on_accounts(self, widget):
"""When accounts is seleted : """When accounts is seleted :
call the accounts class to modify accounts""" call the accounts class to modify accounts"""
global accountsWindow if not self.plugin.windows.has_key('accounts'):
if not accountsWindow: self.plugin.windows['accounts'] = accounts_Window(self)
accountsWindow = accounts_Window(self)
def on_quit(self, widget): def on_quit(self, widget):
"""When we quit the gtk plugin : """When we quit the gtk plugin :
tell that to the core and exit gtk""" tell that to the core and exit gtk"""
self.queueOUT.put(('QUIT','')) self.plugin.send('QUIT', None, '')
print "plugin gtkgui stopped" print "plugin gtkgui stopped"
gtk.mainquit() gtk.mainquit()
@ -1375,20 +1369,25 @@ class roster_Window:
"""When an iter is dubble clicked : """When an iter is dubble clicked :
open the chat window""" open the chat window"""
model = self.tree.get_model() model = self.tree.get_model()
acct_iter = model.get_iter((path[0]))
account = model.get_value(acct_iter, 3)
iter = model.get_iter(path) iter = model.get_iter(path)
jid = model.get_value(iter, 2) type = model.get_value(iter, 2)
if (jid == 'group'): jid = model.get_value(iter, 3)
if (type == 'group'):
if (self.tree.row_expanded(path)): if (self.tree.row_expanded(path)):
self.tree.collapse_row(path) self.tree.collapse_row(path)
else: else:
self.tree.expand_row(path, FALSE) self.tree.expand_row(path, FALSE)
else: else:
if self.tab_messages.has_key(jid): if self.plugin.windows[account].has_key(jid):
self.tab_messages[jid].window.present() self.plugin.windows[account][jid].window.present()
elif self.l_contact.has_key(jid): elif self.contacts[account].has_key(jid):
self.tab_messages[jid] = message_Window(self.l_contact[jid]['user'], self) self.plugin.windows[account][jid] = \
if self.tab_queues.has_key(jid): message_Window(self.contacts[account][jid], self)
self.tab_messages[jid].read_queue(self.tab_queues[jid]) if self.plugin.queues[account].has_key(jid):
self.plugin.windows[account][jid].read_queue(\
self.plugin.queues[account][jid])
def on_row_expanded(self, widget, iter, path): def on_row_expanded(self, widget, iter, path):
"""When a row is expanded : """When a row is expanded :
@ -1425,13 +1424,15 @@ class roster_Window:
def on_browse(self, widget): def on_browse(self, widget):
"""When browse agent is selected : """When browse agent is selected :
Call browse class""" Call browse class"""
global browserWindow if not self.plugin.windows.has_key('browser'):
if not browserWindow: self.plugin.windows['browser'] = browseAgent_Window(self)
browserWindow = browseAgent_Window(self)
def mkpixbufs(self): def mkpixbufs(self):
"""initialise pixbufs array""" """initialise pixbufs array"""
self.path = 'plugins/gtkgui/icons/' + self.iconstyle + '/' iconstyle = self.plugin.config['iconstyle']
if not iconstyle:
iconstyle = 'sun'
self.path = 'plugins/gtkgui/icons/' + iconstyle + '/'
self.pixbufs = {} self.pixbufs = {}
for state in ('online', 'away', 'xa', 'dnd', 'offline', \ for state in ('online', 'away', 'xa', 'dnd', 'offline', \
'requested', 'message', 'opened', 'closed', 'not in list'): 'requested', 'message', 'opened', 'closed', 'not in list'):
@ -1454,24 +1455,23 @@ class roster_Window:
def on_show_off(self, widget): def on_show_off(self, widget):
"""when show offline option is changed : """when show offline option is changed :
redraw the treeview""" redraw the treeview"""
self.showOffline = 1 - self.showOffline self.plugin.config['showoffline'] = 1 - self.plugin.config['showoffline']
self.redraw_roster() self.redraw_roster()
def __init__(self, plugin): def __init__(self, plugin):
# FIXME : handle no file ... # FIXME : handle no file ...
self.xml = gtk.glade.XML(GTKGUI_GLADE, 'Gajim') self.xml = gtk.glade.XML(GTKGUI_GLADE, 'Gajim')
self.window = self.xml.get_widget('Gajim')
self.tree = self.xml.get_widget('treeview') self.tree = self.xml.get_widget('treeview')
self.plugin = plugin self.plugin = plugin
self.connected = 0 self.connected = {}
self.contacts = {}
for a in self.plugin.accounts.keys():
self.contacts[a] = {}
self.connected[a] = 0
#(icon, name, type, jid, editable) #(icon, name, type, jid, editable)
model = gtk.TreeStore(gtk.gdk.Pixbuf, str, str, str, \ model = gtk.TreeStore(gtk.gdk.Pixbuf, str, str, str, \
gobject.TYPE_BOOLEAN) gobject.TYPE_BOOLEAN)
self.tree.set_model(model) self.tree.set_model(model)
self.init_tree()
self.iconstyle = self.plugin.config['iconstyle']
if not self.iconstyle:
self.iconstyle = 'sun'
self.mkpixbufs() self.mkpixbufs()
# map = self.tree.get_colormap() # map = self.tree.get_colormap()
# colour = map.alloc_color("red") # light red # colour = map.alloc_color("red") # light red
@ -1491,19 +1491,9 @@ class roster_Window:
# print self.tree.get_property('expander-column') # print self.tree.get_property('expander-column')
# self.tree.set_style(st) # self.tree.set_style(st)
self.xml.get_widget('optionmenu').set_history(6) self.xml.get_widget('optionmenu').set_history(6)
self.tab_messages = {}
self.tab_queues = {}
self.tab_vcard = {}
if self.plugin.config.has_key('showoffline'): showOffline = self.plugin.config['showoffline']
self.showOffline = self.plugin.config['showoffline'] self.xml.get_widget('show_offline').set_active(showOffline)
else:
self.showOffline = 0
xml.get_widget('show_offline').set_active(self.showOffline)
self.grpbgcolor = 'gray50'
self.userbgcolor = 'white'
#columns #columns
col = gtk.TreeViewColumn() col = gtk.TreeViewColumn()
@ -1524,20 +1514,20 @@ class roster_Window:
self.tree.set_expander_column(col) self.tree.set_expander_column(col)
#signals #signals
xml.signal_connect('gtk_main_quit', self.on_quit) self.xml.signal_connect('gtk_main_quit', self.on_quit)
xml.signal_connect('on_preferences_activate', self.on_prefs) self.xml.signal_connect('on_preferences_activate', self.on_prefs)
xml.signal_connect('on_accounts_activate', self.on_accounts) self.xml.signal_connect('on_accounts_activate', self.on_accounts)
xml.signal_connect('on_browse_agents_activate', self.on_browse) self.xml.signal_connect('on_browse_agents_activate', self.on_browse)
xml.signal_connect('on_add_activate', self.on_add) self.xml.signal_connect('on_add_activate', self.on_add)
xml.signal_connect('on_show_offline_activate', self.on_show_off) self.xml.signal_connect('on_show_offline_activate', self.on_show_off)
xml.signal_connect('on_about_activate', self.on_about) self.xml.signal_connect('on_about_activate', self.on_about)
xml.signal_connect('on_quit_activate', self.on_quit) self.xml.signal_connect('on_quit_activate', self.on_quit)
xml.signal_connect('on_treeview_event', self.on_treeview_event) self.xml.signal_connect('on_treeview_event', self.on_treeview_event)
xml.signal_connect('on_status_changed', self.on_status_changed) self.xml.signal_connect('on_status_changed', self.on_status_changed)
xml.signal_connect('on_optionmenu_changed', self.on_optionmenu_changed) self.xml.signal_connect('on_optionmenu_changed', self.on_optionmenu_changed)
xml.signal_connect('on_row_activated', self.on_row_activated) self.xml.signal_connect('on_row_activated', self.on_row_activated)
xml.signal_connect('on_row_expanded', self.on_row_expanded) self.xml.signal_connect('on_row_expanded', self.on_row_expanded)
xml.signal_connect('on_row_collapsed', self.on_row_collapsed) self.xml.signal_connect('on_row_collapsed', self.on_row_collapsed)
class plugin: class plugin:
"""Class called by the core in a new thread""" """Class called by the core in a new thread"""
@ -1667,8 +1657,8 @@ class plugin:
#TODO: change icon #TODO: change icon
#('AGENTS', account, agents) #('AGENTS', account, agents)
elif ev[0] == 'AGENTS': elif ev[0] == 'AGENTS':
if self.windows.has_key('browser'): if self.windows[ev[1]].has_key('browser'):
self.windows['browser'].agents(ev[2]) self.windows[ev[1]]['browser'].agents(ev[2])
#('AGENTS_INFO', account, (agent, infos)) #('AGENTS_INFO', account, (agent, infos))
elif ev[0] == 'AGENT_INFO': elif ev[0] == 'AGENT_INFO':
if not ev[2][1].has_key('instructions'): if not ev[2][1].has_key('instructions'):
@ -1679,8 +1669,8 @@ class plugin:
elif ev[0] == 'ACC_OK': elif ev[0] == 'ACC_OK':
self.accounts[ev[2][3]] = {'ressource': ev[2][4], \ self.accounts[ev[2][3]] = {'ressource': ev[2][4], \
'password': ev[2][2], 'hostname': ev[2][0], 'name': ev[2][1]} 'password': ev[2][2], 'hostname': ev[2][0], 'name': ev[2][1]}
self.send('CONFIG', None, ('accounts', self.accounts))) self.send('CONFIG', None, ('accounts', self.accounts))
if self.windiws.has_key('accounts'): if self.windows.has_key('accounts'):
self.windows['accounts'].init_accounts() self.windows['accounts'].init_accounts()
elif ev[0] == 'QUIT': elif ev[0] == 'QUIT':
self.roster.on_quit(self) self.roster.on_quit(self)
@ -1717,7 +1707,6 @@ class plugin:
gtk.threads_enter() gtk.threads_enter()
self.queueIN = quIN self.queueIN = quIN
self.queueOUT = quOUT self.queueOUT = quOUT
self.windows = {}
self.send('ASK_CONFIG', None, ('GtkGui', 'GtkGui', {'autopopup':1,\ self.send('ASK_CONFIG', None, ('GtkGui', 'GtkGui', {'autopopup':1,\
'showoffline':0,\ 'showoffline':0,\
'autoaway':0,\ 'autoaway':0,\
@ -1731,6 +1720,11 @@ class plugin:
self.config = self.wait('CONFIG') self.config = self.wait('CONFIG')
self.send('ASK_CONFIG', None, ('GtkGui', 'accounts')) self.send('ASK_CONFIG', None, ('GtkGui', 'accounts'))
self.accounts = self.wait('CONFIG') self.accounts = self.wait('CONFIG')
self.windows = {}
self.queues = {}
for a in self.accounts.keys():
self.windows[a] = {}
self.queues[a] = {}
self.roster = roster_Window(self) self.roster = roster_Window(self)
# if self.config.has_key('autoaway'): # if self.config.has_key('autoaway'):
# self.autoaway = self.config['autoaway'] # self.autoaway = self.config['autoaway']