Branch 'pykolab-0.4' - 11 commits - pykolab/cli

Jeroen van Meeuwen vanmeeuwen at kolabsys.com
Wed May 30 14:53:01 CEST 2012


 pykolab/cli/cmd_add_domain.py             |   88 ++++++++++++++++++++++++++++++
 pykolab/cli/cmd_create_mailbox.py         |   29 +++++++++
 pykolab/cli/cmd_delete_mailbox.py         |    5 +
 pykolab/cli/cmd_list_deleted_mailboxes.py |    2 
 pykolab/cli/cmd_list_domains.py           |   19 +++---
 pykolab/cli/cmd_list_mailboxes.py         |   31 ++++++++--
 pykolab/cli/cmd_remove_mailaddress.py     |   71 ++++++++++++++++++------
 pykolab/cli/commands.py                   |   19 ++++--
 8 files changed, 225 insertions(+), 39 deletions(-)

New commits:
commit bacec56dd67501c58aa002f784dbfffa0567691e
Author: Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen at kolabsys.com>
Date:   Tue May 15 09:09:29 2012 +0100

    Add command add-domain

diff --git a/pykolab/cli/cmd_add_domain.py b/pykolab/cli/cmd_add_domain.py
new file mode 100644
index 0000000..f3d5d97
--- /dev/null
+++ b/pykolab/cli/cmd_add_domain.py
@@ -0,0 +1,88 @@
+# -*- coding: utf-8 -*-
+# Copyright 2010-2012 Kolab Systems AG (http://www.kolabsys.com)
+#
+# Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen a kolabsys.com>
+#
+# 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 3 or, at your option, any later version
+#
+# 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 Library General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+
+import sys
+
+import commands
+
+import pykolab
+
+from pykolab import utils
+from pykolab.translate import _
+
+log = pykolab.getLogger('pykolab.cli')
+conf = pykolab.getConf()
+
+def __init__():
+    commands.register('add_domain', execute, description=description())
+
+def cli_options():
+    my_option_group = conf.add_cli_parser_option_group(_("CLI Options"))
+    my_option_group.add_option(
+            '--alias-for',
+            dest    = "parent_domain",
+            action  = "store",
+            default = None,
+            help    = _("Add domain as alias for DOMAIN"),
+            metavar = "DOMAIN",
+        )
+
+def description():
+    return _("Add a new domain or domain alias.")
+
+def execute(*args, **kw):
+    from pykolab import wap_client
+
+    # Use uber-administrative privileges
+    username = conf.get('ldap', 'bind_dn')
+    if username == None:
+        log.error(_("Could not find credentials with sufficient permissions" + \
+                "to add a domain name space."))
+
+        sys.exit(1)
+
+    wap_client.authenticate(username=username)
+    domains = wap_client.domains_list()
+
+    dna = conf.get('ldap', 'domain_name_attribute')
+
+    if not conf.parent_domain == None:
+        parent_found = False
+        if isinstance(domains['list'], dict):
+            for _domain in domains['list'].keys():
+                if parent_found:
+                    continue
+
+                if isinstance(domains['list'][_domain][dna], basestring):
+                    if conf.parent_domain == domains['list'][_domain][dna]:
+                        parent_found = True
+                elif isinstance(domains['list'][_domain], list):
+                    if conf.parent_domain in domains['list'][_domain][dna]:
+                        parent_found = True
+
+        if not parent_found:
+            log.error(_("Invalid parent domain"))
+            sys.exit(1)
+
+    try:
+        domain = conf.cli_args.pop(0)
+    except IndexError, errmsg:
+        domain = utils.ask_question(_("Domain name"))
+
+    wap_client.domain_add(domain, conf.parent_domain)


commit b7befebb9e143be244ee52e94f14e0167dbd2712
Author: Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen at kolabsys.com>
Date:   Mon May 14 11:56:40 2012 +0100

    Unset add_domain from not being implemented yet

diff --git a/pykolab/cli/commands.py b/pykolab/cli/commands.py
index 8b96d12..6dedc6c 100644
--- a/pykolab/cli/commands.py
+++ b/pykolab/cli/commands.py
@@ -63,7 +63,6 @@ def __init__():
     register('add_group', not_yet_implemented, description="Not yet implemented")
     register('delete_group', not_yet_implemented, description="Not yet implemented")
 
-    register('add_domain', not_yet_implemented, description="Not yet implemented")
     register('delete_domain', not_yet_implemented, description="Not yet implemented")
 
 def list_commands(*args, **kw):


commit b32fad15d1bb4ba76fcb1abe7120e5eceded0e5c
Author: Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen at kolabsys.com>
Date:   Mon May 14 11:55:12 2012 +0100

    Correct cmd_list_domains to use the configured domain_name_attribute

diff --git a/pykolab/cli/cmd_list_domains.py b/pykolab/cli/cmd_list_domains.py
index cf12ee4..fd2c7da 100644
--- a/pykolab/cli/cmd_list_domains.py
+++ b/pykolab/cli/cmd_list_domains.py
@@ -22,7 +22,6 @@ import commands
 import pykolab
 
 from pykolab.translate import _
-from pykolab import wap_client
 
 log = pykolab.getLogger('pykolab.cli')
 conf = pykolab.getConf()
@@ -31,21 +30,23 @@ def __init__():
     commands.register('list_domains', execute, description="List Kolab domains.")
 
 def execute(*args, **kw):
+    from pykolab import wap_client
     # Create the authentication object.
     # TODO: Binds with superuser credentials!
     wap_client.authenticate()
     domains = wap_client.domains_list()
 
-    #print "domains:", domains['list']
+    dna = conf.get('ldap', 'domain_name_attribute')
 
     print "%-39s %-40s" % ("Primary Domain Name Space","Secondary Domain Name Space(s)")
 
     # TODO: Take a hint in --quiet, and otherwise print out a nice table
     # with headers and such.
-    for domain_dn in domains['list'].keys():
-        if isinstance(domains['list'][domain_dn]['associateddomain'], list):
-            print domains['list'][domain_dn]['associateddomain'][0]
-            for domain_alias in domains['list'][domain_dn]['associateddomain'][1:]:
-                print "%-39s %-40s" % ('', domain_alias)
-        else:
-            print domains['list'][domain_dn]['associateddomain']
+    if isinstance(domains['list'], dict):
+        for domain_dn in domains['list'].keys():
+            if isinstance(domains['list'][domain_dn][dna], list):
+                print domains['list'][domain_dn][dna][0]
+                for domain_alias in domains['list'][domain_dn][dna][1:]:
+                    print "%-39s %-40s" % ('', domain_alias)
+            else:
+                print domains['list'][domain_dn][dna]


commit 065556118aaa11bfd287413d12fd775f79618ff1
Author: Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen at kolabsys.com>
Date:   Mon May 14 11:52:06 2012 +0100

    Correct cmd_list_deleted_mailboxes

diff --git a/pykolab/cli/cmd_list_deleted_mailboxes.py b/pykolab/cli/cmd_list_deleted_mailboxes.py
index b29e977..90bcddd 100644
--- a/pykolab/cli/cmd_list_deleted_mailboxes.py
+++ b/pykolab/cli/cmd_list_deleted_mailboxes.py
@@ -21,6 +21,7 @@ import commands
 
 import pykolab
 
+from pykolab.imap import IMAP
 from pykolab.translate import _
 
 log = pykolab.getLogger('pykolab.cli')
@@ -33,6 +34,7 @@ def execute(*args, **kw):
     """
         List deleted mailboxes
     """
+    imap = IMAP()
     imap.connect()
     folders = imap.lm("DELETED/*")
     print "Deleted folders:"


commit fb6003ce967d0205909c6ae04dba99a1cd82d628
Author: Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen at kolabsys.com>
Date:   Sun May 13 17:30:48 2012 +0100

    Update cmd_remove_mailaddress

diff --git a/pykolab/cli/cmd_remove_mailaddress.py b/pykolab/cli/cmd_remove_mailaddress.py
index d6eb43b..19c4756 100644
--- a/pykolab/cli/cmd_remove_mailaddress.py
+++ b/pykolab/cli/cmd_remove_mailaddress.py
@@ -17,10 +17,14 @@
 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 #
 
+import sys
+
 import commands
 
 import pykolab
 
+from pykolab.auth import Auth
+from pykolab import utils
 from pykolab.translate import _
 
 log = pykolab.getLogger('pykolab.cli')
@@ -30,27 +34,60 @@ def __init__():
     commands.register('remove_mail', execute, description=description())
 
 def description():
-    return """Remove a user's mail address."""
+    return """Remove a recipient's mail address."""
 
 def execute(*args, **kw):
-    uid = conf.cli_args.pop(0)
-    email_address = conf.cli_args.pop(0)
+    try:
+        email_address = conf.cli_args.pop(0)
+    except IndexError, errmsg:
+        email_address = utils.ask_question("Email address to remove")
+
+    # Get the domain from the email address
+    if len(email_address.split('@')) > 1:
+        domain = email_address.split('@')[1]
+    else:
+        log.error(_("Invalid or unqualified email address."))
+        sys.exit(1)
+
+    auth = Auth()
+    auth.connect(domain=domain)
+    recipients = auth.find_recipient(email_address)
+
+    if len(recipients) == 0:
+        log.error(_("No recipient found for email address %r") % (email_address))
+        sys.exit(1)
+
+    log.debug(_("Found the following recipient(s): %r") % (recipients), level=8)
+
+    mail_attributes = conf.get_list(domain, 'mail_attributes')
+    if mail_attributes == None or len(mail_attributes) < 1:
+        mail_attributes = conf.get_list(conf.get('kolab', 'auth_mechanism'), 'mail_attributes')
+
+    log.debug(_("Using the following mail attributes: %r") % (mail_attributes), level=8)
+
+    if isinstance(recipients, basestring):
+        recipient = recipients
 
-    user = auth.find_user('uid', uid)
-    user = {
-            'dn': user
-        }
+        # Only a single recipient found, remove the address
+        attributes = auth.get_entry_attributes(domain, recipient, mail_attributes)
 
-    user['mail'] = auth.get_user_attribute('klab.cc', user, 'mail')
-    user['mailalternateaddress'] = auth.get_user_attribute('klab.cc', user, 'mailalternateaddress')
+        # See which attribute holds the value we're trying to remove
+        for attribute in attributes.keys():
+            if isinstance(attributes[attribute], list):
+                if email_address in attributes[attribute]:
+                    attributes[attribute].pop(attributes[attribute].index(email_address))
+                    replace_attributes = {
+                            attribute: attributes[attribute]
+                        }
 
-    if user['mail'] == email_address:
-        auth.set_user_attribute('klab.cc', user, 'mail', '')
+                    auth.set_entry_attributes(domain, recipient, replace_attributes)
+            else:
+                if email_address == attributes[attribute]:
+                    auth.set_entry_attributes(domain, recipient, {attribute: None})
+        pass
 
-    if email_address in user['mailalternateaddress']:
-        _user_addresses = []
-        for address in user['mailalternateaddress']:
-            if not address == email_address:
-                _user_addresses.append(address)
+    else:
+        print >> sys.stderr, _("Found the following recipients:")
 
-        auth.set_user_attribute('klab.cc', user, 'mailAlternateAddress', _user_addresses)
+        for recipient in recipients:
+            print recipient


commit 803459c61a2c854e712cd54a5c20a3f213d3f3df
Author: Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen at kolabsys.com>
Date:   Sun May 13 17:07:29 2012 +0100

    Correct commands referring to cmd_name

diff --git a/pykolab/cli/commands.py b/pykolab/cli/commands.py
index 86f0a33..8b96d12 100644
--- a/pykolab/cli/commands.py
+++ b/pykolab/cli/commands.py
@@ -169,11 +169,13 @@ def register(cmd_name, func, group=None, description=None, aliases=[]):
     if callable(func):
         if group == None:
             commands[cmd_name] = {
+                    'cmd_name': cmd_name,
                     'function': func,
                     'description': description
                 }
         else:
             commands[group][cmd_name] = {
+                    'cmd_name': cmd_name,
                     'function': func,
                     'description': description
                 }


commit a91eae7fb743a09d52abe607f5e5b7b23cf762ef
Author: Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen at kolabsys.com>
Date:   Sun May 13 17:05:29 2012 +0100

    Correct cmd_list_mailboxes

diff --git a/pykolab/cli/cmd_list_mailboxes.py b/pykolab/cli/cmd_list_mailboxes.py
index 35e7a7b..185dea2 100644
--- a/pykolab/cli/cmd_list_mailboxes.py
+++ b/pykolab/cli/cmd_list_mailboxes.py
@@ -21,15 +21,19 @@ import commands
 
 import pykolab
 
+from pykolab.imap import IMAP
 from pykolab.translate import _
 
 log = pykolab.getLogger('pykolab.cli')
 conf = pykolab.getConf()
 
 def __init__():
-    commands.register('list_mailboxes', execute, description="List mailboxes.\n" + \
+    commands.register('list_mailboxes', execute, description=description(), aliases='lm')
+
+def description():
+    return "List mailboxes.\n" + \
         "%-28s" % ('') + \
-        "Use wildcards '*' and '%' for more control.\n")
+        "Use wildcards '*' and '%' for more control.\n"
 
 def cli_options():
     my_option_group = conf.add_cli_parser_option_group(_("CLI Options"))
@@ -43,17 +47,32 @@ def execute(*args, **kw):
     """
         List mailboxes
     """
-    try:
-        searches = [ conf.cli_args.pop(1) ]
-    except IndexError, e:
-        #searches = [ 'DELETED/*', 'shared/*', 'user/*' ]
+
+    searches = []
+
+    # See if conf.cli_args components make sense.
+    for arg in conf.cli_args:
+        if arg == '*':
+            searches.append(arg)
+        if arg.startswith('user'):
+            searches.append(arg)
+        if arg.startswith('shared'):
+            searches.append(arg)
+        if arg.startswith('DELETED'):
+            searches.append(arg)
+        if arg.startswith('news'):
+            searches.append(arg)
+
+    if len(searches) == 0:
         searches = [ '' ]
 
+    imap = IMAP()
     imap.connect()
 
     folders = []
 
     for search in searches:
+        log.debug(_("Appending folder search for %r") % (search), level=8)
         folders.extend(imap.lm(search))
 
     for folder in folders:


commit 51a22f50389e429fe8eef84f423e7cdbe1fa6499
Author: Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen at kolabsys.com>
Date:   Sun May 13 17:05:07 2012 +0100

    Correct cmd_delete_mailbox.py

diff --git a/pykolab/cli/cmd_delete_mailbox.py b/pykolab/cli/cmd_delete_mailbox.py
index 973cd8b..0978b7e 100644
--- a/pykolab/cli/cmd_delete_mailbox.py
+++ b/pykolab/cli/cmd_delete_mailbox.py
@@ -17,10 +17,13 @@
 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 #
 
+import sys
+
 import commands
 
 import pykolab
 
+from pykolab.imap import IMAP
 from pykolab.translate import _
 
 log = pykolab.getLogger('pykolab.cli')
@@ -43,6 +46,8 @@ def execute(*args, **kw):
         print >> sys.stderr, _("No mailbox specified")
         sys.exit(1)
 
+    imap = IMAP()
+
     imap.connect()
     delete_folders = imap.lm(delete_folder)
     for delete_folder in delete_folders:


commit aad5fa666715d8e68ea3a110a0e5d6a44a11beb1
Author: Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen at kolabsys.com>
Date:   Sun May 13 17:04:38 2012 +0100

    Enable use of alias commands with cli options

diff --git a/pykolab/cli/commands.py b/pykolab/cli/commands.py
index 155a110..86f0a33 100644
--- a/pykolab/cli/commands.py
+++ b/pykolab/cli/commands.py
@@ -125,10 +125,11 @@ def execute(cmd_name, *args, **kw):
             pass
 
     else:
+        command_name = commands[cmd_name]['cmd_name']
         try:
-            exec("from cmd_%s import cli_options as %s_cli_options" % (cmd_name,cmd_name))
-            exec("%s_cli_options()" % (cmd_name))
-        except ImportError, e:
+            exec("from cmd_%s import cli_options as %s_cli_options" % (command_name,command_name))
+            exec("%s_cli_options()" % (command_name))
+        except ImportError, errmsg:
             pass
 
     conf.finalize_conf()
@@ -183,6 +184,7 @@ def register(cmd_name, func, group=None, description=None, aliases=[]):
 
         for alias in aliases:
             commands[alias] = {
+                    'cmd_name': cmd_name,
                     'function': func,
                     'description': _("Alias for %s") % (cmd_name)
                 }


commit aa3695ace4ad5953c644017461c5b65b9d7d7dde
Author: Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen at kolabsys.com>
Date:   Sun May 13 17:03:29 2012 +0100

    Correct cmd_create_mailbox.py

diff --git a/pykolab/cli/cmd_create_mailbox.py b/pykolab/cli/cmd_create_mailbox.py
index 20d9d6d..4ecc788 100644
--- a/pykolab/cli/cmd_create_mailbox.py
+++ b/pykolab/cli/cmd_create_mailbox.py
@@ -17,10 +17,13 @@
 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 #
 
+import sys
+
 import commands
 
 import pykolab
 
+from pykolab.imap import IMAP
 from pykolab.translate import _
 
 log = pykolab.getLogger('pykolab.cli')
@@ -29,12 +32,36 @@ conf = pykolab.getConf()
 def __init__():
     commands.register('create_mailbox', execute, description=description(), aliases='cm')
 
+def cli_options():
+    my_option_group = conf.add_cli_parser_option_group(_("CLI Options"))
+    my_option_group.add_option( '--metadata',
+                                dest    = "metadata",
+                                action  = "store",
+                                default = None,
+                                help    = _("Set metadata for folder to ANNOTATION=VALUE"))
+
 def description():
     return """Create a mailbox or sub-folder of an existing mailbox."""
 
 def execute(*args, **kw):
-    mailbox = conf.cli_args.pop(0)
+    try:
+        mailbox = conf.cli_args.pop(0)
+    except IndexError, errmsg:
+        log.error(_("Invalid argument"))
+        sys.exit(1)
 
+    if not conf.metadata == None:
+        if len(conf.metadata.split('=')) == 2:
+            annotation = conf.metadata.split('=')[0]
+            annotation_value = conf.metadata.split('=')[1]
+        else:
+            log.error(_("Invalid argument for metadata"))
+            sys.exit(1)
+
+    imap = IMAP()
     imap.connect()
     imap.cm(mailbox)
 
+    if not conf.metadata == None:
+        imap.setannotation(mailbox, conf.metadata.split('=')[0], conf.metadata.split('=')[1])
+


commit 588fd44c3aab2e8e22e801b4a0e763d3d7b5d00c
Author: Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen at kolabsys.com>
Date:   Wed May 30 14:41:38 2012 +0200

    Do not load commands that fail loading (#811)

diff --git a/pykolab/cli/commands.py b/pykolab/cli/commands.py
index 7236b0b..155a110 100644
--- a/pykolab/cli/commands.py
+++ b/pykolab/cli/commands.py
@@ -43,7 +43,11 @@ def __init__():
                 module_name = filename.replace('.py','')
                 cmd_name = module_name.replace('cmd_', '')
                 #print "exec(\"from %s import __init__ as %s_register\"" % (module_name,cmd_name)
-                exec("from %s import __init__ as %s_register" % (module_name,cmd_name))
+                try:
+                    exec("from %s import __init__ as %s_register" % (module_name,cmd_name))
+                except ImportError, errmsg:
+                    pass
+
                 exec("%s_register()" % (cmd_name))
 
         for dirname in dirnames:
@@ -189,4 +193,4 @@ def register(cmd_name, func, group=None, description=None, aliases=[]):
 
 def not_yet_implemented(*args, **kw):
     print _("Not yet implemented")
-    sys.exit(1)
\ No newline at end of file
+    sys.exit(1)





More information about the commits mailing list