gajim-plural/core/core.py

472 lines
15 KiB
Python
Raw Normal View History

2003-10-22 22:23:45 +02:00
#!/usr/bin/env python
## core/core.py
##
## Gajim Team:
## - Yann Le Boulanger <asterix@crans.org>
## - Vincent Hanquez <tab@tuxfamily.org>
##
## Copyright (C) 2003 Gajim Team
##
## 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; version 2 only.
##
## 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.
##
2004-02-25 01:33:06 +01:00
import sys, os
2003-11-30 16:50:23 +01:00
sys.path.append("..")
2003-10-22 22:23:45 +02:00
import time
2003-11-15 13:38:43 +01:00
import string
2003-10-22 22:23:45 +02:00
import logging
import common.hub
import common.jabber
import common.optparser
log = logging.getLogger('core.core')
log.setLevel(logging.DEBUG)
2003-11-30 16:50:23 +01:00
2004-01-18 23:56:28 +01:00
CONFPATH = "~/.gajim/config"
LOGPATH = os.path.expanduser("~/.gajim/logs/")
2003-10-22 22:23:45 +02:00
class GajimCore:
2004-01-17 16:38:29 +01:00
"""Core"""
2003-10-22 22:23:45 +02:00
def __init__(self):
2004-02-25 01:33:06 +01:00
self.init_cfg_file()
2003-10-22 22:23:45 +02:00
self.cfgParser = common.optparser.OptionsParser(CONFPATH)
self.hub = common.hub.GajimHub()
self.parse()
2004-03-16 16:39:36 +01:00
self.connected = {}
#connexions {con: name, ...}
self.connexions = {}
for a in self.accounts:
self.connected[a] = 0
2003-10-22 22:23:45 +02:00
# END __init__
2004-02-25 01:33:06 +01:00
def init_cfg_file(self):
fname = os.path.expanduser(CONFPATH)
reps = string.split(fname, '/')
del reps[0]
path = ''
while len(reps) > 1:
path = path + '/' + reps[0]
del reps[0]
try:
os.stat(os.path.expanduser(path))
except OSError:
try:
os.mkdir(os.path.expanduser(path))
except:
print "Can't create %s" % path
sys.exit
try:
os.stat(fname)
except:
print "creating %s" % fname
fic = open(fname, "w")
fic.write("[Profile]\naccounts = \n\n[Core]\ndelauth = 1\nalwaysauth = 0\nmodules = logger gtkgui\ndelroster = 1\n")
fic.close()
# END init_cfg_file
def parse(self):
self.cfgParser.parseCfgFile()
self.accounts = {}
2004-02-25 01:33:06 +01:00
accts = string.split(self.cfgParser.tab['Profile']['accounts'], ' ')
if accts == ['']:
accts = []
for a in accts:
self.accounts[a] = self.cfgParser.tab[a]
2004-02-18 22:03:45 +01:00
def vCardCB(self, con, vc):
"""Called when we recieve a vCard"""
vcard = {'jid': vc.getFrom().getBasic()}
if vc._getTag('vCard') == common.jabber.NS_VCARD:
2004-02-18 22:03:45 +01:00
card = vc.getChildren()[0]
for info in card.getChildren():
if info.getChildren() == []:
vcard[info.getName()] = info.getData()
else:
vcard[info.getName()] = {}
for c in info.getChildren():
vcard[info.getName()][c.getName()] = c.getData()
2004-03-16 16:39:36 +01:00
self.hub.sendPlugin('VCARD', self.connexions[con], vcard)
2004-02-18 22:03:45 +01:00
2003-10-22 22:23:45 +02:00
def messageCB(self, con, msg):
2004-01-17 16:38:29 +01:00
"""Called when we recieve a message"""
2004-03-16 16:39:36 +01:00
self.hub.sendPlugin('MSG', self.connexions[con], \
(msg.getFrom().getBasic(), msg.getBody()))
2003-10-22 22:23:45 +02:00
# END messageCB
def presenceCB(self, con, prs):
2004-01-17 16:38:29 +01:00
"""Called when we recieve a presence"""
2003-10-22 22:23:45 +02:00
who = str(prs.getFrom())
type = prs.getType()
if type == None: type = 'available'
2003-10-27 17:30:37 +01:00
log.debug("PresenceCB : %s" % type)
2003-10-22 22:23:45 +02:00
if type == 'available':
if prs.getShow():
show = prs.getShow()
else:
show = 'online'
2004-03-16 16:39:36 +01:00
self.hub.sendPlugin('NOTIFY', self.connexions[con], \
(prs.getFrom().getBasic(), show, prs.getStatus(), \
prs.getFrom().getResource()))
2003-10-27 17:30:37 +01:00
elif type == 'unavailable':
2004-03-16 16:39:36 +01:00
self.hub.sendPlugin('NOTIFY', self.connexions[con], \
(prs.getFrom().getBasic(), 'offline', prs.getStatus(), \
prs.getFrom().getResource()))
2003-10-27 17:30:37 +01:00
elif type == 'subscribe':
log.debug("subscribe request from %s" % who)
if self.cfgParser.Core['alwaysauth'] == 1 or \
string.find(who, "@") <= 0:
2004-03-16 16:39:36 +01:00
con.send(common.jabber.Presence(who, 'subscribed'))
2003-12-20 14:22:37 +01:00
if string.find(who, "@") <= 0:
2004-03-16 16:39:36 +01:00
self.hub.sendPlugin('NOTIFY', self.connexions[con], \
(who, 'offline', 'offline', prs.getFrom().getResource()))
else:
2004-02-25 01:33:06 +01:00
txt = prs.getStatus()
if not txt:
txt = "I would like to add you to my roster."
2004-03-16 16:39:36 +01:00
self.hub.sendPlugin('SUBSCRIBE', self.connexions[con], (who, 'txt'))
2003-10-27 17:30:37 +01:00
elif type == 'subscribed':
jid = prs.getFrom()
2004-03-16 16:39:36 +01:00
self.hub.sendPlugin('SUBSCRIBED', self.connexions[con],\
(jid.getBasic(), jid.getNode(), jid.getResource()))
self.hub.queueIn.put(('UPDUSER', self.connexions[con], \
(jid.getBasic(), jid.getNode(), ['general'])))
#BE CAREFUL : no con.updateRosterItem() in a callback
2003-10-27 17:30:37 +01:00
log.debug("we are now subscribed to %s" % who)
elif type == 'unsubscribe':
log.debug("unsubscribe request from %s" % who)
elif type == 'unsubscribed':
log.debug("we are now unsubscribed to %s" % who)
2004-03-16 16:39:36 +01:00
self.hub.sendPlugin('UNSUBSCRIBED', self.connexions[con], \
prs.getFrom().getBasic())
elif type == 'error':
errmsg = prs._node.kids[0].getData()
self.hub.sendPlugin('NOTIFY', self.connexions[con], \
(prs.getFrom().getBasic(), 'error', errmsg, \
prs.getFrom().getResource()))
2003-10-22 22:23:45 +02:00
# END presenceCB
def disconnectedCB(self, con):
2004-01-17 16:38:29 +01:00
"""Called when we are disconnected"""
2003-10-22 22:23:45 +02:00
log.debug("disconnectedCB")
2004-03-16 16:39:36 +01:00
if self.connected[self.connexions[con]] == 1:
self.connected[self.connexions[con]] = 0
con.disconnect()
self.hub.sendPlugin('STATUS', self.connexions[con], 'offline')
2004-04-02 03:26:48 +02:00
if self.connexions.has_key(con):
del self.connexions[con]
2003-10-22 22:23:45 +02:00
# END disconenctedCB
2003-11-30 23:40:24 +01:00
def connect(self, account):
2004-01-17 16:38:29 +01:00
"""Connect and authentificate to the Jabber server"""
hostname = self.cfgParser.tab[account]["hostname"]
name = self.cfgParser.tab[account]["name"]
password = self.cfgParser.tab[account]["password"]
ressource = self.cfgParser.tab[account]["ressource"]
2004-03-16 16:39:36 +01:00
con = common.jabber.Client(host = hostname, \
2004-03-18 17:38:14 +01:00
debug = [], log = sys.stderr, \
# debug = [common.jabber.DBG_ALWAYS], log = sys.stderr, \
connection=common.xmlstream.TCP, port=5222)
#debug = [common.jabber.DBG_ALWAYS], log = sys.stderr, \
#connection=common.xmlstream.TCP_SSL, port=5223)
2003-10-22 22:23:45 +02:00
try:
2004-03-16 16:39:36 +01:00
con.connect()
2003-10-22 22:23:45 +02:00
except IOError, e:
log.debug("Couldn't connect to %s %s" % (hostname, e))
2004-03-16 16:39:36 +01:00
self.hub.sendPlugin('STATUS', account, 'offline')
self.hub.sendPlugin('WARNING', None, "Couldn't connect to %s" \
% hostname)
return 0
2004-02-17 19:06:18 +01:00
except common.xmlstream.socket.error, e:
2004-01-17 16:38:29 +01:00
log.debug("Couldn't connect to %s %s" % (hostname, e))
2004-03-16 16:39:36 +01:00
self.hub.sendPlugin('STATUS', account, 'offline')
self.hub.sendPlugin('WARNING', None, "Couldn't connect to %s : %s" \
% (hostname, e))
2004-01-17 16:38:29 +01:00
return 0
2003-10-22 22:23:45 +02:00
else:
log.debug("Connected to server")
2004-03-16 16:39:36 +01:00
con.registerHandler('message', self.messageCB)
con.registerHandler('presence', self.presenceCB)
con.registerHandler('iq',self.vCardCB,'result')#common.jabber.NS_VCARD)
con.setDisconnectHandler(self.disconnectedCB)
#BUG in jabberpy library : if hostname is wrong : "boucle"
2004-03-16 16:39:36 +01:00
if con.auth(name, password, ressource):
con.requestRoster()
roster = con.getRoster().getRaw()
2003-11-02 22:39:40 +01:00
if not roster :
roster = {}
2004-03-16 16:39:36 +01:00
self.hub.sendPlugin('ROSTER', account, roster)
con.sendInitPresence()
self.hub.sendPlugin('STATUS', account, 'online')
self.connexions[con] = account
2004-03-16 16:39:36 +01:00
self.connected[account] = 1
2004-03-16 19:53:49 +01:00
return con
2003-10-22 22:23:45 +02:00
else:
log.debug("Couldn't authentificate to %s" % hostname)
2004-03-16 16:39:36 +01:00
self.hub.sendPlugin('STATUS', account, 'offline')
self.hub.sendPlugin('WARNING', None, \
'Authentification failed with %s, check your login and password'\
% hostname)
return 0
2003-10-22 22:23:45 +02:00
# END connect
def mainLoop(self):
"""Main Loop : Read the incomming queue to execute commands comming from
plugins and process Jabber"""
2003-10-22 22:23:45 +02:00
while 1:
if not self.hub.queueIn.empty():
ev = self.hub.queueIn.get()
2004-03-22 14:09:59 +01:00
if ev[1] and (ev[1] in self.connexions.values()):
for con in self.connexions.keys():
if ev[1] == self.connexions[con]:
break
else:
con = None
2004-03-16 16:39:36 +01:00
#('QUIT', account, ())
2003-10-22 22:23:45 +02:00
if ev[0] == 'QUIT':
2004-03-16 19:53:49 +01:00
# for con in self.connexions.keys():
2004-03-16 16:39:36 +01:00
# if self.connected[a] == 1:
# self.connected[a] = 0
2004-03-16 19:53:49 +01:00
# con.disconnect()
2004-03-16 16:39:36 +01:00
self.hub.sendPlugin('QUIT', None, ())
2003-10-22 22:23:45 +02:00
return
2004-03-16 16:39:36 +01:00
#('ASK_CONFIG', account, (who_ask, section, default_config))
elif ev[0] == 'ASK_CONFIG':
2004-03-16 16:39:36 +01:00
if ev[2][1] == 'accounts':
self.hub.sendPlugin('CONFIG', None, (ev[2][0], self.accounts))
else:
2004-03-16 16:39:36 +01:00
if self.cfgParser.tab.has_key(ev[2][1]):
self.hub.sendPlugin('CONFIG', None, (ev[2][0], \
self.cfgParser.__getattr__(ev[2][1])))
2004-02-25 01:33:06 +01:00
else:
2004-03-16 16:39:36 +01:00
self.cfgParser.tab[ev[2][1]] = ev[2][2]
2004-02-25 01:33:06 +01:00
self.cfgParser.writeCfgFile()
2004-03-16 16:39:36 +01:00
self.hub.sendPlugin('CONFIG', None, (ev[2][0], ev[2][2]))
#('CONFIG', account, (section, config))
elif ev[0] == 'CONFIG':
2004-03-16 16:39:36 +01:00
if ev[2][0] == 'accounts':
#Remove all old accounts
accts = string.split(self.cfgParser.tab\
['Profile']['accounts'], ' ')
2004-02-25 01:33:06 +01:00
if accts == ['']:
accts = []
for a in accts:
del self.cfgParser.tab[a]
#Write all new accounts
2004-03-16 16:39:36 +01:00
accts = ev[2][1].keys()
self.cfgParser.tab['Profile']['accounts'] = \
string.join(accts)
for a in accts:
2004-03-16 16:39:36 +01:00
self.cfgParser.tab[a] = ev[2][1][a]
if not a in self.connected.keys():
self.connected[a]= 0
else:
2004-03-16 16:39:36 +01:00
self.cfgParser.tab[ev[2][0]] = ev[2][1]
self.cfgParser.writeCfgFile()
#TODO: tell the changes to other plugins
2004-03-16 16:39:36 +01:00
#('STATUS', account, (status, msg))
2003-10-22 22:23:45 +02:00
elif ev[0] == 'STATUS':
2004-03-16 16:39:36 +01:00
if (ev[2][0] != 'offline') and (self.connected[ev[1]] == 0):
2004-03-16 19:53:49 +01:00
con = self.connect(ev[1])
2004-03-16 16:39:36 +01:00
elif (ev[2][0] == 'offline') and (self.connected[ev[1]] == 1):
self.connected[ev[1]] = 0
con.disconnect()
self.hub.sendPlugin('STATUS', ev[1], 'offline')
if ev[2][0] != 'offline' and self.connected[ev[1]] == 1:
2003-11-09 23:29:41 +01:00
p = common.jabber.Presence()
2004-03-16 16:39:36 +01:00
p.setShow(ev[2][0])
p.setStatus(ev[2][1])
con.send(p)
self.hub.sendPlugin('STATUS', ev[1], ev[2][0])
#('MSG', account, (jid, msg))
2003-10-22 22:23:45 +02:00
elif ev[0] == 'MSG':
2004-03-16 16:39:36 +01:00
msg = common.jabber.Message(ev[2][0], ev[2][1])
2003-10-22 22:23:45 +02:00
msg.setType('chat')
2004-03-16 16:39:36 +01:00
con.send(msg)
self.hub.sendPlugin('MSGSENT', ev[1], ev[2])
#('SUB', account, (jid, txt))
2003-10-27 17:30:37 +01:00
elif ev[0] == 'SUB':
2004-03-16 16:39:36 +01:00
log.debug('subscription request for %s' % ev[2][0])
pres = common.jabber.Presence(ev[2][0], 'subscribe')
if ev[2][1]:
pres.setStatus(ev[2][1])
2004-02-25 01:33:06 +01:00
else:
pres.setStatus("I would like to add you to my roster.")
2004-03-16 16:39:36 +01:00
con.send(pres)
#('REQ', account, jid)
2003-11-02 22:39:40 +01:00
elif ev[0] == 'AUTH':
2004-03-16 16:39:36 +01:00
con.send(common.jabber.Presence(ev[2], 'subscribed'))
#('DENY', account, jid)
elif ev[0] == 'DENY':
2004-03-16 16:39:36 +01:00
con.send(common.jabber.Presence(ev[2], 'unsubscribed'))
#('UNSUB', accountjid)
2003-10-27 17:30:37 +01:00
elif ev[0] == 'UNSUB':
if self.cfgParser.Core.has_key('delauth'):
delauth = self.cfgParser.Core['delauth']
else:
delauth = 1
if self.cfgParser.Core.has_key('delroster'):
delroster = self.cfgParser.Core['delroster']
else:
delroster = 1
if delauth:
2004-03-16 16:39:36 +01:00
con.send(common.jabber.Presence(ev[2], 'unsubscribe'))
if delroster:
2004-03-16 16:39:36 +01:00
con.removeRosterItem(ev[2])
#('UPDUSER', account, (jid, name, groups))
2003-11-03 00:35:38 +01:00
elif ev[0] == 'UPDUSER':
2004-03-16 16:39:36 +01:00
con.updateRosterItem(jid=ev[2][0], name=ev[2][1], \
groups=ev[2][2])
#('REQ_AGENTS', account, ())
2003-11-12 22:51:38 +01:00
elif ev[0] == 'REQ_AGENTS':
2004-03-16 16:39:36 +01:00
agents = con.requestAgents()
self.hub.sendPlugin('AGENTS', ev[1], agents)
#('REQ_AGENT_INFO', account, agent)
2003-11-15 13:38:43 +01:00
elif ev[0] == 'REQ_AGENT_INFO':
2004-03-16 16:39:36 +01:00
con.requestRegInfo(ev[2])
agent_info = con.getRegInfo()
self.hub.sendPlugin('AGENT_INFO', ev[1], (ev[2], agent_info))
#('REG_AGENT', account, infos)
2003-11-15 13:38:43 +01:00
elif ev[0] == 'REG_AGENT':
2004-03-16 16:39:36 +01:00
con.sendRegInfo(ev[2])
#('NEW_ACC', (hostname, login, password, name, ressource))
elif ev[0] == 'NEW_ACC':
c = common.jabber.Client(host = \
2004-03-16 16:39:36 +01:00
ev[2][0], debug = False, log = sys.stderr)
try:
c.connect()
except IOError, e:
log.debug("Couldn't connect to %s %s" % (hostname, e))
return 0
else:
log.debug("Connected to server")
c.requestRegInfo()
req = c.getRegInfo()
2004-03-16 16:39:36 +01:00
c.setRegInfo( 'username', ev[2][1])
c.setRegInfo( 'password', ev[2][2])
#FIXME: if users already exist, no error message :(
if not c.sendRegInfo():
print "error " + c.lastErr
else:
2004-03-16 16:39:36 +01:00
self.hub.sendPlugin('ACC_OK', ev[1], ev[2])
2004-03-22 14:09:59 +01:00
#('ACC_CHG', old_account, new_account)
elif ev[0] == 'ACC_CHG':
self.connected[ev[2]] = self.connected[ev[1]]
del self.connected[ev[1]]
if con:
self.connexions[con] = self.connected[ev[2]]
2004-03-16 16:39:36 +01:00
#('ASK_VCARD', account, jid)
elif ev[0] == 'ASK_VCARD':
2004-03-16 16:39:36 +01:00
iq = common.jabber.Iq(to=ev[2], type="get")
iq._setTag('vCard', common.jabber.NS_VCARD)
2004-03-16 16:39:36 +01:00
iq.setID(con.getAnID())
con.send(iq)
2004-03-04 21:56:39 +01:00
#('VCARD', {entry1: data, entry2: {entry21: data, ...}, ...})
elif ev[0] == 'VCARD':
iq = common.jabber.Iq(type="set")
2004-03-16 16:39:36 +01:00
iq.setID(con.getAnID())
iq2 = iq._setTag('vCard', common.jabber.NS_VCARD)
2004-03-16 16:39:36 +01:00
for i in ev[2].keys():
if i != 'jid':
2004-03-16 16:39:36 +01:00
if type(ev[2][i]) == type({}):
iq3 = iq2.insertTag(i)
2004-03-16 16:39:36 +01:00
for j in ev[2][i].keys():
iq3.insertTag(j).putData(ev[2][i][j])
else:
2004-03-16 16:39:36 +01:00
iq2.insertTag(i).putData(ev[2][i])
con.send(iq)
#('AGENT_LOGGING', account, (agent, type))
2004-03-04 21:56:39 +01:00
elif ev[0] == 'AGENT_LOGGING':
2004-03-16 16:39:36 +01:00
t = ev[2][1];
2004-03-04 21:56:39 +01:00
if not t:
t='available';
2004-03-16 16:39:36 +01:00
p = common.jabber.Presence(to=ev[2][0], type=t)
con.send(p)
#('LOG_NB_LINE', account, jid)
elif ev[0] == 'LOG_NB_LINE':
fic = open(LOGPATH + ev[2], "r")
nb = 0
while (fic.readline()):
nb = nb+1
fic.close()
self.hub.sendPlugin('LOG_NB_LINE', ev[1], (ev[2], nb))
#('LOG_GET_RANGE', account, (jid, line_begin, line_end))
elif ev[0] == 'LOG_GET_RANGE':
fic = open(LOGPATH + ev[2][0], "r")
nb = 0
while (nb < ev[2][1] and fic.readline()):
nb = nb+1
while nb < ev[2][2]:
line = fic.readline()
nb = nb+1
if line:
lineSplited = string.split(line, ':')
if len(lineSplited) > 2:
self.hub.sendPlugin('LOG_LINE', ev[1], (ev[2][0], nb, \
lineSplited[0], lineSplited[1], lineSplited[2:]))
fic.close()
2003-10-27 17:30:37 +01:00
else:
log.debug("Unknown Command %s" % ev[0])
2004-03-16 16:39:36 +01:00
else:
for con in self.connexions:
if self.connected[self.connexions[con]] == 1:
con.process(1)
2003-10-22 22:23:45 +02:00
time.sleep(0.1)
# END main
# END GajimCore
2003-11-30 16:50:23 +01:00
def loadPlugins(gc):
"""Load defaults plugins : plugins in 'modules' option of Core section
in ConfFile and register them to the hub"""
modStr = gc.cfgParser.Core['modules']
2004-01-17 16:38:29 +01:00
if modStr:
2003-12-20 14:22:37 +01:00
mods = string.split (modStr, ' ')
2003-11-30 16:50:23 +01:00
2003-12-20 14:22:37 +01:00
for mod in mods:
modObj = gc.hub.newPlugin(mod)
gc.hub.register(mod, 'ROSTER')
2004-01-08 00:49:23 +01:00
gc.hub.register(mod, 'WARNING')
gc.hub.register(mod, 'STATUS')
2003-12-20 14:22:37 +01:00
gc.hub.register(mod, 'NOTIFY')
gc.hub.register(mod, 'MSG')
2003-12-20 23:42:10 +01:00
gc.hub.register(mod, 'MSGSENT')
2003-12-20 14:22:37 +01:00
gc.hub.register(mod, 'SUBSCRIBED')
gc.hub.register(mod, 'SUBSCRIBE')
gc.hub.register(mod, 'AGENTS')
gc.hub.register(mod, 'AGENT_INFO')
gc.hub.register(mod, 'QUIT')
gc.hub.register(mod, 'ACC_OK')
gc.hub.register(mod, 'CONFIG')
gc.hub.register(mod, 'VCARD')
gc.hub.register(mod, 'LOG_NB_LINE')
gc.hub.register(mod, 'LOG_LINE')
2003-12-20 14:22:37 +01:00
modObj.load()
2003-11-30 16:50:23 +01:00
# END loadPLugins
2003-10-22 22:23:45 +02:00
def start():
2004-01-17 16:38:29 +01:00
"""Start the Core"""
2003-10-22 22:23:45 +02:00
gc = GajimCore()
2003-11-30 16:50:23 +01:00
loadPlugins(gc)
2004-01-17 16:38:29 +01:00
try:
gc.mainLoop()
except KeyboardInterrupt:
print "Keyboard Interrupt : Bye!"
2004-03-16 19:53:49 +01:00
for con in gc.connexions.keys():
2004-03-16 16:39:36 +01:00
if gc.connected[gc.connexions[con]]:
con.disconnect()
gc.hub.sendPlugin('QUIT', None, ())
2004-01-17 16:38:29 +01:00
return 0
2004-02-17 19:06:18 +01:00
# except:
# print "Erreur survenue"
# gc.hub.sendPlugin('QUIT', ())
2003-11-30 16:50:23 +01:00
# END start