MailComponent refactoring

- MailComponent constructor received all parameters red in the configuration file
- MailComponent get a new attribut lang. get_lang* methods have been put in Lang.

darcs-hash:20060206133123-86b55-377d908cb7164dc8a04c53cae6ce0444f9cc347b.gz
This commit is contained in:
David Rousselie
2006-02-06 14:31:23 +01:00
parent a063a69773
commit 8dc5a2aaa5
5 changed files with 87 additions and 51 deletions

View File

@@ -50,31 +50,37 @@ class ComponentFatalError(RuntimeError):
pass pass
class MailComponent(Component): class MailComponent(Component):
def __init__(self, config): def __init__(self,
jid,
secret,
server,
port,
default_lang,
check_interval,
spool_dir,
storage):
Component.__init__(self, \ Component.__init__(self, \
JID(config.get_content("config/jabber/service")), \ JID(jid), \
config.get_content("config/jabber/secret"), \ secret, \
config.get_content("config/jabber/server"), \ server, \
int(config.get_content("config/jabber/port")), \ port, \
disco_category = "gateway", \ disco_category = "gateway", \
disco_type = "headline") disco_type = "headline")
self.__logger = logging.getLogger("jabber.Component") self.__logger = logging.getLogger("jabber.Component")
self.__shutdown = 0 self.__shutdown = 0
self.__default_lang = config.get_content("config/jabber/language") self.__lang = Lang(default_lang)
signal.signal(signal.SIGINT, self.signal_handler) signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler) signal.signal(signal.SIGTERM, self.signal_handler)
self.__interval = int(config.get_content("config/check_interval")) self.__interval = check_interval
self.__config = config spool_dir += "/" + jid
spool_dir = config.get_content("config/spooldir") + "/" + \
config.get_content("config/jabber/service")
try: try:
self.__storage = globals()[config.get_content("config/storage") \ self.__storage = globals()[storage \
+ "Storage"](2, spool_dir = spool_dir) + "Storage"](2, spool_dir = spool_dir)
except: except:
print >>sys.stderr, "Cannot find " \ print >>sys.stderr, "Cannot find " \
+ config.get_content("config/storage") + "Storage class" + storage + "Storage class"
sys.exit(1) sys.exit(1)
# dump registered accounts (save) every hour # dump registered accounts (save) every hour
self.__count = 60 self.__count = 60
@@ -83,16 +89,6 @@ class MailComponent(Component):
def __del__(self): def __del__(self):
logging.shutdown() logging.shutdown()
def get_lang(self, node):
lang = node.getLang()
if lang is None:
self.__logger.debug("Using default lang " + self.__default_lang)
lang = self.__default_lang
return lang
def get_lang_class(self, lang):
return getattr(Lang, lang)
""" Register Form creator """ """ Register Form creator """
def get_reg_form(self, lang_class): def get_reg_form(self, lang_class):
reg_form = X() reg_form = X()
@@ -484,7 +480,7 @@ class MailComponent(Component):
""" Discovery get nested nodes handler """ """ Discovery get nested nodes handler """
def disco_get_items(self, node, iq): def disco_get_items(self, node, iq):
self.__logger.debug("DISCO_GET_ITEMS") self.__logger.debug("DISCO_GET_ITEMS")
lang_class = self.get_lang_class(self.get_lang(iq.get_node())) lang_class = self.__lang.get_lang_class_from_node(iq.get_node())
base_from_jid = unicode(iq.get_from().bare()) base_from_jid = unicode(iq.get_from().bare())
di = DiscoItems() di = DiscoItems()
if not node: if not node:
@@ -510,7 +506,7 @@ class MailComponent(Component):
""" Send back register form to user """ """ Send back register form to user """
def get_register(self, iq): def get_register(self, iq):
self.__logger.debug("GET_REGISTER") self.__logger.debug("GET_REGISTER")
lang_class = self.get_lang_class(self.get_lang(iq.get_node())) lang_class = self.__lang.get_lang_class_from_node(iq.get_node())
base_from_jid = unicode(iq.get_from().bare()) base_from_jid = unicode(iq.get_from().bare())
to = iq.get_to() to = iq.get_to()
iq = iq.make_result_response() iq = iq.make_result_response()
@@ -527,7 +523,7 @@ class MailComponent(Component):
""" Handle user registration response """ """ Handle user registration response """
def set_register(self, iq): def set_register(self, iq):
self.__logger.debug("SET_REGISTER") self.__logger.debug("SET_REGISTER")
lang_class = self.get_lang_class(self.get_lang(iq.get_node())) lang_class = self.__lang.get_lang_class_from_node(iq.get_node())
to = iq.get_to() to = iq.get_to()
from_jid = iq.get_from() from_jid = iq.get_from()
base_from_jid = unicode(from_jid.bare()) base_from_jid = unicode(from_jid.bare())
@@ -699,7 +695,7 @@ class MailComponent(Component):
self.__logger.debug("PRESENCE_AVAILABLE") self.__logger.debug("PRESENCE_AVAILABLE")
from_jid = stanza.get_from() from_jid = stanza.get_from()
base_from_jid = unicode(from_jid.bare()) base_from_jid = unicode(from_jid.bare())
lang_class = self.get_lang_class(self.get_lang(stanza.get_node())) lang_class = self.__lang.get_lang_class_from_node(stanza.get_node())
name = stanza.get_to().node name = stanza.get_to().node
show = stanza.get_show() show = stanza.get_show()
self.__logger.debug("SHOW : " + str(show)) self.__logger.debug("SHOW : " + str(show))
@@ -819,7 +815,7 @@ class MailComponent(Component):
""" Handle new message """ """ Handle new message """
def message(self, message): def message(self, message):
self.__logger.debug("MESSAGE: " + message.get_body()) self.__logger.debug("MESSAGE: " + message.get_body())
lang_class = self.get_lang_class(self.get_lang(message.get_node())) lang_class = self.__lang.get_lang_class_from_node(message.get_node())
name = message.get_to().node name = message.get_to().node
base_from_jid = unicode(message.get_from().bare()) base_from_jid = unicode(message.get_from().bare())
if re.compile("\[PASSWORD\]").search(message.get_subject()) is not None \ if re.compile("\[PASSWORD\]").search(message.get_subject()) is not None \
@@ -905,7 +901,6 @@ class MailComponent(Component):
account = self.__storage[(jid, name)] account = self.__storage[(jid, name)]
if account.first_check and account.live_email_only: if account.first_check and account.live_email_only:
account.first_check = False account.first_check = False
print "HERE"
if account.password is None: if account.password is None:
self.__ask_password(name, jid, account.default_lang_class, account) self.__ask_password(name, jid, account.default_lang_class, account)
return return

View File

@@ -23,6 +23,22 @@
class Lang: class Lang:
def __init__(self, default_lang = "en"):
self.default_lang = default_lang
def get_lang_from_node(self, node):
lang = node.getLang()
if lang is None:
print "Using default lang " + self.default_lang
lang = self.default_lang
return lang
def get_lang_class(self, lang):
return getattr(Lang, lang)
def get_lang_class_from_node(self, node):
return self.get_lang_class(self.get_lang_from_node(node))
class en: class en:
register_title = u"Jabber Mail connection registration" register_title = u"Jabber Mail connection registration"
register_instructions = u"Enter connection parameters" register_instructions = u"Enter connection parameters"
@@ -32,7 +48,7 @@ class Lang:
account_password_store = u"Store password on jabber server ?" account_password_store = u"Store password on jabber server ?"
account_host = u"Host" account_host = u"Host"
account_port = u"Port" account_port = u"Port"
account_type = u"Mail serveur type" account_type = u"Mail server type"
account_mailbox = u"Mailbox path (IMAP)" account_mailbox = u"Mailbox path (IMAP)"
account_ffc_action = u"Action when state is 'Free For Chat'" account_ffc_action = u"Action when state is 'Free For Chat'"
account_online_action = u"Action when state is 'Online'" account_online_action = u"Action when state is 'Online'"

View File

@@ -22,8 +22,10 @@
import sys import sys
import logging
import email import email
import email.Header import email.Header
import traceback
import poplib import poplib
import imaplib import imaplib
@@ -129,6 +131,8 @@ class MailConnection(object):
""" Wrapper to mail connection and action. """ Wrapper to mail connection and action.
Abstract class, do not represent real mail connection type""" Abstract class, do not represent real mail connection type"""
_logger = logging.getLogger("jabber.MailConnection")
def __init__(self, login = "", password = "", host = "", \ def __init__(self, login = "", password = "", host = "", \
port = 110, ssl = False): port = 110, ssl = False):
""" Initialize MailConnection object for common parameters of all """ Initialize MailConnection object for common parameters of all
@@ -192,7 +196,8 @@ class MailConnection(object):
(self.store_password and self.password or "/\\") + "#" \ (self.store_password and self.password or "/\\") + "#" \
+ self.host + "#" + str(self.port) + "#" + str(self.chat_action) + "#" \ + self.host + "#" + str(self.port) + "#" + str(self.chat_action) + "#" \
+ str(self.online_action) + "#" + str(self.away_action) + "#" + \ + str(self.online_action) + "#" + str(self.away_action) + "#" + \
str(self.xa_action) + "#" + str(self.dnd_action) + "#" + str(self.offline_action) + "#" + str(self.interval) + "#" + str(self.live_email_only) str(self.xa_action) + "#" + str(self.dnd_action) + "#" + \
str(self.offline_action) + "#" + str(self.interval) + "#" + str(self.live_email_only)
def get_decoded_part(self, part, charset_hint): def get_decoded_part(self, part, charset_hint):
content_charset = part.get_content_charset() content_charset = part.get_content_charset()
@@ -213,7 +218,9 @@ class MailConnection(object):
try: try:
result = unicode(part.get_payload(decode=True).decode(charset_hint)) result = unicode(part.get_payload(decode=True).decode(charset_hint))
except Exception, e: except Exception, e:
print e type, value, stack = sys.exc_info()
print >>sys.stderr, "".join(traceback.format_exception
(type, value, stack, 5))
return result return result
def format_message(self, email_msg, include_body = True): def format_message(self, email_msg, include_body = True):
@@ -257,7 +264,9 @@ class MailConnection(object):
try: try:
result += unicode(subject_decoded[i][0].decode(charset_hint)) result += unicode(subject_decoded[i][0].decode(charset_hint))
except Exception, e: except Exception, e:
print e type, value, stack = sys.exc_info()
print >>sys.stderr, "".join(traceback.format_exception
(type, value, stack, 5))
result += u"\n\n" result += u"\n\n"
@@ -308,6 +317,8 @@ class MailConnection(object):
action = property(get_action) action = property(get_action)
class IMAPConnection(MailConnection): class IMAPConnection(MailConnection):
_logger = logging.getLogger("jabber.IMAPConnection")
def __init__(self, login = "", password = "", host = "", \ def __init__(self, login = "", password = "", host = "", \
port = None, ssl = False, mailbox = "INBOX"): port = None, ssl = False, mailbox = "INBOX"):
if not port: if not port:
@@ -334,10 +345,10 @@ class IMAPConnection(MailConnection):
return MailConnection.get_status(self) + "/" + self.mailbox return MailConnection.get_status(self) + "/" + self.mailbox
def connect(self): def connect(self):
print >>sys.stderr, "Connecting to IMAP server " \ IMAPConnection._logger.debug("Connecting to IMAP server " \
+ self.login + "@" + self.host + ":" + str(self.port) \ + self.login + "@" + self.host + ":" + str(self.port) \
+ " (" + self.mailbox + "). SSL=" \ + " (" + self.mailbox + "). SSL=" \
+ str(self.ssl) + str(self.ssl))
if self.ssl: if self.ssl:
self.connection = MYIMAP4_SSL(self.host, self.port) self.connection = MYIMAP4_SSL(self.host, self.port)
else: else:
@@ -345,12 +356,12 @@ class IMAPConnection(MailConnection):
self.connection.login(self.login, self.password) self.connection.login(self.login, self.password)
def disconnect(self): def disconnect(self):
print >>sys.stderr, "Disconnecting from IMAP server " \ IMAPConnection._logger.debug("Disconnecting from IMAP server " \
+ self.host + self.host)
self.connection.logout() self.connection.logout()
def get_mail_list(self): def get_mail_list(self):
print >>sys.stderr, "Getting mail list" IMAPConnection._logger.debug("Getting mail list")
typ, data = self.connection.select(self.mailbox) typ, data = self.connection.select(self.mailbox)
typ, data = self.connection.search(None, 'UNSEEN') typ, data = self.connection.search(None, 'UNSEEN')
if typ == 'OK': if typ == 'OK':
@@ -358,7 +369,7 @@ class IMAPConnection(MailConnection):
return None return None
def get_mail(self, index): def get_mail(self, index):
print >>sys.stderr, "Getting mail " + str(index) IMAPConnection._logger.debug("Getting mail " + str(index))
typ, data = self.connection.select(self.mailbox) typ, data = self.connection.select(self.mailbox)
typ, data = self.connection.fetch(index, '(RFC822)') typ, data = self.connection.fetch(index, '(RFC822)')
self.connection.store(index, "FLAGS", "UNSEEN") self.connection.store(index, "FLAGS", "UNSEEN")
@@ -367,7 +378,7 @@ class IMAPConnection(MailConnection):
return u"Error while fetching mail " + str(index) return u"Error while fetching mail " + str(index)
def get_mail_summary(self, index): def get_mail_summary(self, index):
print >>sys.stderr, "Getting mail summary " + str(index) IMAPConnection._logger.debug("Getting mail summary " + str(index))
typ, data = self.connection.select(self.mailbox) typ, data = self.connection.select(self.mailbox)
typ, data = self.connection.fetch(index, '(RFC822)') typ, data = self.connection.fetch(index, '(RFC822)')
self.connection.store(index, "FLAGS", "UNSEEN") self.connection.store(index, "FLAGS", "UNSEEN")
@@ -378,6 +389,8 @@ class IMAPConnection(MailConnection):
type = property(get_type) type = property(get_type)
class POP3Connection(MailConnection): class POP3Connection(MailConnection):
_logger = logging.getLogger("jabber.POP3Connection")
def __init__(self, login = "", password = "", host = "", \ def __init__(self, login = "", password = "", host = "", \
port = None, ssl = False): port = None, ssl = False):
if not port: if not port:
@@ -393,9 +406,9 @@ class POP3Connection(MailConnection):
return "pop3" return "pop3"
def connect(self): def connect(self):
print >>sys.stderr, "Connecting to POP3 server " \ POP3Connection._logger.debug("Connecting to POP3 server " \
+ self.login + "@" + self.host + ":" + str(self.port)\ + self.login + "@" + self.host + ":" + str(self.port)\
+ ". SSL=" + str(self.ssl) + ". SSL=" + str(self.ssl))
if self.ssl: if self.ssl:
self.connection = MYPOP3_SSL(self.host, self.port) self.connection = MYPOP3_SSL(self.host, self.port)
else: else:
@@ -408,24 +421,24 @@ class POP3Connection(MailConnection):
def disconnect(self): def disconnect(self):
print >>sys.stderr, "Disconnecting from POP3 server " \ POP3Connection._logger.debug("Disconnecting from POP3 server " \
+ self.host + self.host)
self.connection.quit() self.connection.quit()
def get_mail_list(self): def get_mail_list(self):
print >>sys.stderr, "Getting mail list" POP3Connection._logger.debug("Getting mail list")
count, size = self.connection.stat() count, size = self.connection.stat()
return [str(i) for i in range(1, count + 1)] return [str(i) for i in range(1, count + 1)]
def get_mail(self, index): def get_mail(self, index):
print >>sys.stderr, "Getting mail " + str(index) POP3Connection._logger.debug("Getting mail " + str(index))
ret, data, size = self.connection.retr(index) ret, data, size = self.connection.retr(index)
if ret[0:3] == '+OK': if ret[0:3] == '+OK':
return self.format_message(email.message_from_string('\n'.join(data))) return self.format_message(email.message_from_string('\n'.join(data)))
return u"Error while fetching mail " + str(index) return u"Error while fetching mail " + str(index)
def get_mail_summary(self, index): def get_mail_summary(self, index):
print >>sys.stderr, "Getting mail summary " + str(index) POP3Connection._logger.debug("Getting mail summary " + str(index))
ret, data, size = self.connection.retr(index) ret, data, size = self.connection.retr(index)
if ret[0:3] == '+OK': if ret[0:3] == '+OK':
return self.format_message_summary(email.message_from_string('\n'.join(data))) return self.format_message_summary(email.message_from_string('\n'.join(data)))

View File

@@ -26,6 +26,7 @@ import os.path
import sys import sys
import anydbm import anydbm
import mailconnection_factory import mailconnection_factory
import logging
from UserDict import UserDict from UserDict import UserDict
from pysqlite2 import dbapi2 as sqlite from pysqlite2 import dbapi2 as sqlite
@@ -105,6 +106,8 @@ class Storage(UserDict):
pass pass
class DBMStorage(Storage): class DBMStorage(Storage):
_logger = logging.getLogger("jabber.DBMStorage")
def __init__(self, nb_pk_fields = 1, spool_dir = ".", db_file = None): def __init__(self, nb_pk_fields = 1, spool_dir = ".", db_file = None):
# print "DBM INIT" # print "DBM INIT"
Storage.__init__(self, nb_pk_fields, spool_dir, db_file) Storage.__init__(self, nb_pk_fields, spool_dir, db_file)
@@ -165,12 +168,14 @@ class DBMStorage(Storage):
class SQLiteStorage(Storage): class SQLiteStorage(Storage):
_logger = logging.getLogger("jabber.SQLiteStorage")
def __init__(self, nb_pk_fields = 1, spool_dir = ".", db_file = None): def __init__(self, nb_pk_fields = 1, spool_dir = ".", db_file = None):
self.__connection = None self.__connection = None
Storage.__init__(self, nb_pk_fields, spool_dir, db_file) Storage.__init__(self, nb_pk_fields, spool_dir, db_file)
def create(self): def create(self):
# print "creating new Table" SQLiteStorage._logger.debug("creating new Table")
cursor = self.__connection.cursor() cursor = self.__connection.cursor()
cursor.execute(""" cursor.execute("""
create table account( create table account(

9
jmc.py
View File

@@ -49,7 +49,14 @@ def main(config_file = "jmc.xml", isDebug = 0):
mailconnection.default_encoding = config.get_content("config/mail_default_encoding") mailconnection.default_encoding = config.get_content("config/mail_default_encoding")
print "creating component..." print "creating component..."
mailcomp = MailComponent(config) mailcomp = MailComponent(config.get_content("config/jabber/service"), \
config.get_content("config/jabber/secret"), \
config.get_content("config/jabber/server"), \
int(config.get_content("config/jabber/port")), \
config.get_content("config/jabber/language"), \
int(config.get_content("config/check_interval")), \
config.get_content("config/spooldir"), \
config.get_content("config/storage"))
print "starting..." print "starting..."
mailcomp.run(1) mailcomp.run(1)