vmm
author Pascal Volk <neverseen@users.sourceforge.net>
Sat, 16 Aug 2008 02:19:32 +0000
changeset 45 9e66138aad0b
parent 44 c9ab6900ede9
child 47 191d5a5adc4a
permissions -rwxr-xr-x
* 'VirtualMailManager/VirtualMailManager.py' - Implemented: + VirtualMailManager.domain_alias_add() + VirtualMailManager.domain_alias_delete() * 'VirtualMailManager/Domain.py' - Implemented: + Domain._aliasExists() + Domain.saveAlias() + deleteAlias() - Fixed Domain._exists(); returns only True when the domain exists AND it's the primary domain - Fixed table order in Domain.delete() * 'vmm' - _printList() added ace2idna support for alias domains - Implemented: + domain_alias_add() + domain_alias_delete()

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright 2007-2008 VEB IT
# See COPYING for distribution information.
# $Id$

"""This is the vmm main script."""

from VirtualMailManager.constants.VERSION import VERSION

__author__ = 'Pascal Volk <p.volk@veb-it.de>'
__version__ = VERSION
__revision__ = 'rev '+'$Rev$'.split()[1]
__date__ = '$Date$'.split()[1]

import os
import sys
import gettext

from VirtualMailManager.VirtualMailManager import VirtualMailManager
from VirtualMailManager.Config import VMMConfig
import VirtualMailManager.Exceptions as VMME
import VirtualMailManager.constants.EXIT as EXIT
import VirtualMailManager.constants.ERROR as ERR

__prog__ = os.path.basename(sys.argv[0])

gettext.bindtextdomain(__prog__, '/usr/local/share/locale')
gettext.textdomain(__prog__)
_ = gettext.gettext

def usage(excode=0, errMsg=None):
    sys.stderr.write(_("""\
Usage: %s SUBCOMMAND OBJECT ARGS*
  short long
  subcommand               object            args (* = optional)\n\n""")%
  __prog__)
    sys.stderr.write("""\
  da    domainadd          domain.tld        transport*
  di    domaininfo         domain.tld        detailed*
  dt    domaintransport    domain.tld        transport force*
  dd    domaindelete       domain.tld        delalias*|deluser*|delall*
  daa   domainaliasadd     aliasdomain.tld   domain.tld
  dad   domainaliasdelete  aliasdomain.tld
  ua    useradd            user@domain.tld   password*
  ui    userinfo           user@domain.tld   du*
  un    username           user@domain.tld   'Users Name'
  up    userpassword       user@domain.tld   password*
  ut    usertransport      user@domain.tld   transport
  u0    userdisable        user@domain.tld   smtp*|pop3*|imap*|managesieve*|all*
  u1    userenable         user@domain.tld   smtp*|pop3*|imap*|managesieve*|all*
  ud    userdelete         user@domain.tld
  aa    aliasadd           alias@domain.tld  user@domain.tld
  ai    aliasinfo          alias@domain.tld
  ad    aliasdelete        alias@domain.tld  user@domain.tld*
  gu    getuser            userid
  ld    listdomains                          pattern*
  cf    configure                            section*
  h     help
  v     version

""")
    if not errMsg is None:
        sys.stderr.write('%s: %s\n' % (_('Error'), errMsg))
    sys.exit(excode)

def getVMM():
    try:
        vmm = VirtualMailManager()
        return vmm
    except (VMME.VMMException, VMME.VMMNotRootException, VMME.VMMPermException,
            VMME.VMMConfigException), e:
        sys.stderr.write("%s: %s\n" % (_('Error'),e[0][0]))
        sys.exit(e[0][1])

def configure():
    try:
        if len(sys.argv) < 3:
            vmm.configure()
        else:
            vmm.configure(sys.argv[2])
    except (EOFError, KeyboardInterrupt):
        sys.stderr.write('\n%s!\n' % _('Ouch'))
        sys.exit(EXIT.USER_INTERRUPT)
    except VMME.VMMConfigException, e:
        sys.stderr.write(str(e))
        sys.exit(ERR.CONF_ERROR)
    sys.exit(0)

def _getOrder():
    order = ()
    if sys.argv[1] in ['di', 'domaininfo']:
        order = (('domainname', 0), ('gid', 1), ('transport', 0),
                ('domaindir', 0), ('aliasdomains', 0), ('accounts', 0),
                ('aliases', 0))
    elif sys.argv[1] in ['ui', 'userinfo']:
        if argc == 4 or vmm.cfgGetBoolean('maildir', 'diskusage'):
            order = (('address', 0), ('name', 0), ('uid', 1), ('gid', 1),
                    ('transport', 0), ('maildir', 0), ('disk usage', 0),
                    ('smtp', 1), ('pop3', 1), ('imap', 1), ('managesieve', 1))
        else:
            order = (('address', 0), ('name', 0), ('uid', 1), ('gid', 1),
                    ('transport', 0), ('maildir', 0), ('smtp', 1), ('pop3', 1),
                    ('imap', 1), ('managesieve', 1))
    elif sys.argv[1] in ['gu', 'getuser']:
        order = (('uid', 1), ('gid', 1), ('address', 0))
    return order

def _printInfo(info, title):
    msg = '%s %s' % (title, _('information'))
    print '%s\n%s' % (msg, '-'*len(msg))
    for k,u in _getOrder():
        if u:
            print '\t%s: %s' % (k.upper().ljust(15, '.'), info[k])
        else:
            print '\t%s: %s' % (k.title().ljust(15, '.'), info[k])
    print

def _printList(alist, title):
    msg = '%s %s' % (_('Available'), title)
    print '%s\n%s' % (msg, '-'*len(msg))
    if len(alist) > 0:
        if title != _('alias domains'):
            for val in alist:
                print '\t%s' % val
        else:
            for dom in alist:
                if not dom.startswith('xn--'):
                    print '\t%s' % dom
                else:
                    print '\t%s (%s)' % (dom, vmm.ace2idna(dom))
    else:
        print _('\tNone')
    print

def _printAliases(alias, targets):
    msg = _('Alias information')
    print '%s\n%s' % (msg, '-'*len(msg))
    print _('\tMail for %s goes to:') % alias
    if len(targets) > 0:
        for target in targets:
            print '\t     -> %s' % target
    else:
        print _('\tNone')
    print

def _formatDom(domain, main=True):
    if domain.startswith('xn--'):
        domain = '%s (%s)' % (domain, vmm.ace2idna(domain))
    if main:
        return '\t[+] %s' %  domain
    else:
        return '\t[-]     %s' % domain

def _printDomList(dids, domains):
    if argc < 3:
        msg = _('Available domains')
    else:
        msg = _('Matching domains')
    print '%s\n%s' % (msg, '-'*len(msg))
    if not len(domains):
        print _('\tNone')
    else:
        for id in dids:
            if domains[id][0] is not None:
                print _formatDom(domains[id][0])
            if len(domains[id]) > 1:
                for alias in domains[id][1:]:
                    print _formatDom(alias, main=False)
    print

def domain_add():
    if argc < 3:
        usage(EXIT.MISSING_ARGS, _('Missing domain name.'))
    elif argc < 4:
        vmm.domain_add(sys.argv[2].lower())
    else:
        vmm.domain_add(sys.argv[2].lower(), sys.argv[3])

def domain_delete():
    if argc < 3:
        usage(EXIT.MISSING_ARGS, _('Missing domain name.'))
    elif argc < 4:
        vmm.domain_delete(sys.argv[2].lower())
    else:
        vmm.domain_delete(sys.argv[2].lower(), sys.argv[3])

def domain_info():
    if argc < 3:
        usage(EXIT.MISSING_ARGS, _('Missing domain name.'))
    elif argc < 4:
        _printInfo(vmm.domain_info(sys.argv[2].lower()), _('Domain'))
    else:
        infos = vmm.domain_info(sys.argv[2].lower(), sys.argv[3])
        _printInfo(infos[0], _('Domain'))
        _printList(infos[1], _('alias domains'))
        _printList(infos[2], _('accounts'))
        _printList(infos[3], _('aliases'))

def domain_transport():
    if argc < 3:
        usage(EXIT.MISSING_ARGS, _('Missing domain name and new transport.'))
    if argc < 4:
        usage(EXIT.MISSING_ARGS, _('Missing new transport.'))
    elif argc < 5:
        vmm.domain_transport(sys.argv[2].lower(), sys.argv[3])
    else:
        vmm.domain_transport(sys.argv[2].lower(), sys.argv[3], sys.argv[4])

def domain_alias_add():
    if argc < 3:
        usage(EXIT.MISSING_ARGS,
                _('Missing alias domain name and target domain name.'))
    elif argc < 4:
        usage(EXIT.MISSING_ARGS, _('Missing target domain name.'))
    else:
        vmm.domain_alias_add(sys.argv[2].lower(), sys.argv[3].lower())

def domain_alias_delete():
    if argc < 3:
        usage(EXIT.MISSING_ARGS, _('Missing alias domain name.'))
    else:
        vmm.domain_alias_delete(sys.argv[2].lower())

def user_add():
    if argc < 3:
        usage(EXIT.MISSING_ARGS, _('Missing e-mail address.'))
    elif argc < 4:
        password = None
    else:
        password = sys.argv[3]
    vmm.user_add(sys.argv[2].lower(), password)

def user_delete():
    if argc < 3:
        usage(EXIT.MISSING_ARGS, _('Missing e-mail address.'))
    else:
        vmm.user_delete(sys.argv[2].lower())

def user_info():
    if argc < 3:
        usage(EXIT.MISSING_ARGS, _('Missing e-mail address.'))
    elif argc < 4:
        _printInfo(vmm.user_info(sys.argv[2].lower()), 'Account')
    else:
        _printInfo(vmm.user_info(sys.argv[2].lower(), True), 'Account')

def user_name():
    if argc < 3:
        usage(EXIT.MISSING_ARGS, _('Missing e-mail address and users name.'))
    if argc < 4:
        usage(EXIT.MISSING_ARGS, _('Missing users name.'))
    else:
        vmm.user_name(sys.argv[2].lower(), sys.argv[3])

def user_transport():
    if argc < 3:
        usage(EXIT.MISSING_ARGS, _('Missing e-mail address and transport.'))
    if argc <4:
        usage(EXIT.MISSING_ARGS, _('Missing transport.'))
    else:
        vmm.user_transport(sys.argv[2].lower(), sys.argv[3])

def user_enable():
    if argc < 3:
        usage(EXIT.MISSING_ARGS, _('Missing e-mail address.'))
    elif argc < 4:
        vmm.user_enable(sys.argv[2].lower())
    else:
        vmm.user_enable(sys.argv[2].lower(), sys.argv[3].lower())

def user_disable():
    if argc < 3:
        usage(EXIT.MISSING_ARGS, _('Missing e-mail address.'))
    elif argc < 4:
        vmm.user_disable(sys.argv[2].lower())
    else:
        vmm.user_disable(sys.argv[2].lower(), sys.argv[3].lower())

def user_password():
    if argc < 3:
        usage(EXIT.MISSING_ARGS, _('Missing e-mail address.'))
    elif argc < 4:
        password = None
    else:
        password = sys.argv[3]
    vmm.user_password(sys.argv[2].lower(), password)

def alias_add():
    if argc < 4:
        usage(EXIT.MISSING_ARGS, _('Missing alias address and destination.'))
    else:
        vmm.alias_add(sys.argv[2].lower(), sys.argv[3])

def alias_info():
    if argc < 3:
        usage(EXIT.MISSING_ARGS, _('Missing alias address'))
    else:
        _printAliases(sys.argv[2], vmm.alias_info(sys.argv[2].lower()))

def alias_delete():
    if argc < 3:
        usage(EXIT.MISSING_ARGS, _('Missing alias address'))
    elif argc < 4:
        vmm.alias_delete(sys.argv[2].lower())
    else:
        vmm.alias_delete(sys.argv[2].lower(), sys.argv[3].lower())

def user_byID():
    if argc < 3:
        usage(EXIT.MISSING_ARGS, _('Missing userid'))
    else:
        _printInfo(vmm.user_byID(sys.argv[2]), 'Account')

def domain_list():
    if argc < 3:
        order, doms = vmm.domain_list()
    else:
        order, doms = vmm.domain_list(sys.argv[2].lower())
    _printDomList(order, doms)

def showWarnings():
    if vmm.hasWarnings():
        print _('\nWarnings:')
        for w in vmm.getWarnings():
            print " * ",w

#def main():
if __name__ == '__main__':
    argc = len(sys.argv)
    if argc < 2:
        usage(EXIT.MISSING_ARGS)
    vmm = getVMM()
    try:
        if sys.argv[1] in ['cf',  'configure'] or not vmm.setupIsDone():
            configure()
    except VMME.VMMConfigException, e:
        sys.stderr.write(str(e))
        sys.exit(ERR.CONF_ERROR)
    except VMME.VMMException, e:
        sys.stderr.write("%s: %s\n" % (_('Error'), e[0][0]))
        sys.exit(e[0][1])
    try:
        if sys.argv[1] in ['da', 'domainadd']:
            domain_add()
        elif sys.argv[1] in ['di', 'domaininfo']:
            domain_info()
        elif sys.argv[1] in ['dt', 'domaintransport']:
            domain_transport()
        elif sys.argv[1] in ['dd', 'domaindelete']:
            domain_delete()
        elif sys.argv[1] in ['daa', 'domainaliasadd']:
            domain_alias_add()
        elif sys.argv[1] in ['dad', 'domainaliasdelete']:
            domain_alias_delete()
        elif sys.argv[1] in ['ua', 'useradd']:
            user_add()
        elif sys.argv[1] in ['ui', 'userinfo']:
            user_info()
        elif sys.argv[1] in ['un', 'username']:
            user_name()
        elif sys.argv[1] in ['up', 'userpassword']:
            user_password()
        elif sys.argv[1] in ['ut', 'usertransport']:
            user_transport()
        elif sys.argv[1] in ['u0', 'userdisable']:
            user_disable()
        elif sys.argv[1] in ['u1', 'userenable']:
            user_enable()
        elif sys.argv[1] in ['ud', 'userdelete']:
            user_delete()
        elif sys.argv[1] in ['aa', 'aliasadd']:
            alias_add()
        elif sys.argv[1] in ['ai', 'aliasinfo']:
            alias_info()
        elif sys.argv[1] in ['ad', 'aliasdelete']:
            alias_delete()
        elif sys.argv[1] in ['gu', 'getuser']:
            user_byID()
        elif sys.argv[1] in ['ld', 'listdomains']:
            domain_list()
        elif sys.argv[1] in ['h', 'help']:
            usage()
        elif sys.argv[1] in ['v', 'version']:
            print "%s, version %s (%s from %s)\n" % (__prog__, __version__,
                    __revision__, __date__)
        else:
            usage(EXIT.UNKNOWN_COMMAND,
                    "%s: '%s'" % (_('Unknown subcommand'), sys.argv[1]))
        showWarnings()
    except (EOFError, KeyboardInterrupt):
        sys.stderr.write('\n%s!\n' % _('Ouch'))
        sys.exit(EXIT.USER_INTERRUPT)
    except VMME.VMMException, e:
        sys.stderr.write("%s: %s\n" % (_('Error'), e[0][0]))
        sys.exit(e[0][1])