예제 #1
0
def main():
    options, args = opt_args()

    if not  options.user and not options.public:
        print('Please use\n' \
            '%s --user <username>  or\n' \
            '%s --public' % (sys.argv[0], sys.argv[0]))
        sys.exit(1)
    if options.user:
        user = kopano.server(options).user(options.user)
        store = user.store
        name = user.name
    if options.public:
        name = 'Public'
        store = kopano.server(options).public_store
    if not options.delete:
        print('Store:', name.encode('utf-8').decode())
        print('{:50} {:50} {:50}'.format('Folder name', 'Parent folder', 'Entryid'))

        for folder in store.root.folders():
            print('{:50} {:50} {:50}'.format(folder.name.encode('utf8').decode(), folder.parent.name.encode('utf8').decode(), folder.entryid))
            if options.extend:
                props = printmapiprops(folder)
                f = open('%s-%s.prop' % (folder.name, folder.entryid), 'w')
                for prop in props:
                    f.write('{0:5}  {1:37}  {2:8}  {3:10}  {4:1}\n'.format(prop[0], prop[1], prop[2], prop[3], prop[4]))
                f.close()

    else:
        print('Not in yet')
예제 #2
0
    def index(self):
        html ='<html>'

        for company in kopano.server().companies():
            html = html + '<table>'
            html = html + "<tr><th>company.name</th><th>user.name </th><th> user.store.guid</th><th>user.server.name</th><tr>\n"
            for user in kopano.server().company(company.name).users():
                html = html + "<tr><td>" + company.name + "</td><td><a href=/viewuser/"+ company.name + "/" + user.name + ">" + user.name + "</a><td><a href=/listfolders/"+ company.name + "/" + user.name + ">Folders</a></td></td><td>" + user.store.guid + "</td><td>" + user.server.name + "</td><tr>\n"
            html = html + '</table>\n'

            html =  html + '</html>\n'

        return html
예제 #3
0
def main():
    options, args = opt_args()
    if options.top:
        try:
            curses.wrapper(top, kopano.server(options=options, parse_args=True))
        except KeyboardInterrupt:
            sys.exit(-1)
    else:
        for option, (table, sort) in TABLES.items():
            if getattr(options, option):
                table = kopano.server(options=options, parse_args=True).table(table)
                table.sort(sort)
                print(table.csv(delimiter=';') if options.dump else table.text())
예제 #4
0
def main():
    global server
    global options
    global LDAP
    options, args = opt_args()
    if options.configFile:
        if not os.path.isfile(options.configFile):
            print('Config file not found')
            sys.exit(1)
        import importlib

        LDAP = importlib.import_module(options.configFile.split('.')[0], package=None)
        if 'ldap3' not in sys.modules:
            print('please install ldap3 (pip3 install ldap3)')
            sys.exit(1)

    if not options.user and not options.importFile:
        print('please use: {} --user <username> or \n{} --import-exchange-rules <json file>'.format(sys.argv[0],sys.argv[0]))
        sys.exit(1)

    server = kopano.server(options=options)
    if options.user:
        kopano_rule(server=server, user=options.user, listrules=options.listrules, rule=options.rule,
                    state=options.state, emptyRules=options.emptyRules, rulename=options.createrule,
                    conditions=options.conditions, actions=options.actions, exceptions=options.exceptions,
                    StopProcessingRules=options.StopProcessingRules, CreateFolder=options.CreateFolder)

    if options.importFile:
        exchange_rules()
예제 #5
0
def main(jsonfile, limit, socket, ssl_keyfile, ssl_pass):
    try:
        server = kopano.server(server_socket=socket,
                               sslkey_file=ssl_keyfile,
                               sslkey_pass=ssl_pass,
                               parse_args=False)
    except Exception as excinfo:
        print("Unable to connect to '{}', '{}'".format(socket, excinfo))
        sys.exit(-1)

    requests = []
    limit += 1

    for index, user in enumerate(server.users()):
        index += 1  # graph's index starts at 1

        if index == limit:
            break

        request = {
            'id': index,
            'method': 'GET',
            'url': '/api/gc/v1/users/{}'.format(user.userid)
        }

        requests.append(request)

    data = {}
    data['requests'] = requests
    with open(jsonfile, 'w') as fp:
        fp.write(json.dumps(data, indent=2))
예제 #6
0
def main():
    try:
        parser, options, args = parser_opt_args()
        if args:
            raise Exception("extra argument '%s' specified" % args[0])

        server = kopano.server(options, parse_args=True)
        check_options(parser, options, server)

        global_options(options, server)
        for c in options.companies:
            company_options(c, options, server)
        for g in options.groups:
            group_options(g, options, server)
        for u in options.users:
            user_options(u, options, server)
        for s in options.stores:
            store_options(s, options, server)

    except (SystemError, KeyboardInterrupt): # TODO SystemError?
        print()
        sys.exit(130)
    except Exception as e:
        if 'options' in locals() and options.debug:
            print(traceback.format_exc(), file=sys.stderr)
        else:
            print(str(e), file=sys.stderr)
        sys.exit(1)
예제 #7
0
def main():
    username, config_file, entryid = sys.argv[1:]

    config = kopano.Config(filename=config_file)
    server = kopano.server(config=config)

    user = server.user(username)
    item = user.item(entryid)
    mr = item.meetingrequest

    if mr.is_request:
        server.log.debug("Accepting meeting request tentative from %s",
                         get_sender(item))
        mr.accept(tentative=True, response=False)
    elif mr.is_response:
        server.log.debug("Processing meeting request response from %s",
                         get_sender(item))
        mr.process_response()
    elif mr.is_cancellation:
        server.log.debug("Processing meeting request cancellation from %s",
                         get_sender(item))
        mr.process_cancellation()

    now = datetime.now()

    try:
        server.log.debug("Updating freebusy")
        user.freebusy.publish(now - timedelta(7), now + timedelta(180))
    except kopano.errors.NotFoundError as e:
        server.log.error("Unable to publish freebusy information: %s", str(e))
예제 #8
0
def user():
    server = kopano.server(parse_args=False, auth_user=USERNAME1, auth_pass=PASSWORD1)
    user = server.user(USERNAME1)
    user.auth_header = create_auth_header(USERNAME1, PASSWORD1)
    yield user

    [f.empty() for f in user.folders(recurse=False)]
예제 #9
0
    def __init__(self, *args, **kw):
        fuse.Fuse.__init__(self, *args, **kw)

        self.server = kopano.server()

        self.path_object = {
        }  # XXX caching everything, so don't use this on a large account..
예제 #10
0
def main():
    options, _ = parser('ksplu').parse_args()
    log = logger(options)
    server = server(options=options,
                    auth_user='******',
                    auth_pass='',
                    parse_args=True)
    restriction = Restriction(
        mapiobj=SNotRestriction(SExistRestriction(PR_EC_IMAP_EMAIL_SIZE)))

    for user in server.users():  # XXX multi-company..
        # Skip users without IMAP enabled
        if not 'imap' in user.features:
            log.info('Skipping user %s, IMAP disabled', user.name)
            continue

        log.debug('Processing user %s', user.name)
        for folder in user.store.folders():
            # Inbox folder's container class is None..
            if folder.container_class != 'IPF.Note' and folder.container_class != None:
                continue

            log.info('Processing folder %s', folder.name)
            for item in folder.items(restriction=restriction):
                log.debug('Processing item %s', item.subject)
                generate_imap_message(item)
예제 #11
0
    def listitem(self, company=None,user=None,folder=None,item=None):
        user = dict(user=user)
        company = dict(company=company)
        itemname= dict(item=item)
        foldername= dict(folder=folder)
        html=''
        print(itemname['item'] + "\n")
        html = '<html><h1>Company: %s <br>User: %s</h1>' % (company['company'],user['user'])
        #html = html + "<table><tr><th>prop.name</th><th>prop.value</th><tr>\n"
        if itemname['item']:
            #html = html + "<table><tr><th>item.subject</th><th>item.entryid</th><tr>\n"
            for folder in kopano.server().company(company['company']).user(user['user']).store.folders():
                if folder.entryid == foldername['folder']:
                    for item in folder.items():
                        print("curr %s" , item.entryid.encode('hex'))
                        print("look %s", itemname['item'])
                        if item.entryid.encode('hex')==itemname['item']:
                            print("match")
                            for prop in item.props():
                                if (prop.idname == 'PR_HTML') or (prop.idname=='PR_BODY'):
                                    try:
                                        html = html + "<table><tr><td>%s</td><td>%s</td><tr>\n" % ( prop.name , str(prop.value))
                                    except:
                                        pass

        html = html + '</table></html>\n'

        return html
예제 #12
0
def main():
    username, config_file, entryid = sys.argv[1:]

    config = kopano.Config(filename=config_file)
    server = kopano.server(config=config)

    process(username, server, entryid)
예제 #13
0
def main():
    args = sys.argv[1:]
    username, config_file = args[:2]

    entryid = args[2] if len(args) > 2 else None
    config = kopano.Config(filename=config_file)
    server = kopano.server(config=config)

    accept(username, server, entryid)
예제 #14
0
    def listfolders(self, company=None,user=None,folder=None):
        user = dict(user=user)
        company = dict(company=company)
        foldername= dict(folder=folder)
        html = '<html><h1>Company: %s <br>User: %s</h1>' % (company['company'],user['user'])
        if foldername['folder']:
            html = html + "<table><tr><th>item.subject</th><th>item.entryid</th><tr>\n"
            for folder in kopano.server().company(company['company']).user(user['user']).store.folders():
                if folder.entryid == foldername['folder']:
                    for item in folder.items():
                        html = html + "<tr><td><a href=/listitem/%s/%s/%s/%s>%s</a></td><td>%s</td><tr>\n" %( company['company'],user['user'],folder.entryid,item.entryid.encode('hex'),item.subject.encode("utf-8"),item.entryid.encode('hex'))
        else:
            html = html + "<table><tr><th>item.subject</th><th>item.entryid</th><tr>\n"
            for folder in kopano.server().company(company['company']).user(user['user']).store.folders():
                html = html + "<tr><td><a href=/listfolders/%s/%s/%s>%s</a></td><td>%s</td><tr>\n" %( company['company'],user['user'],folder.entryid,folder.name,folder.entryid)

        html = html + '</table></html>\n'

        return html
예제 #15
0
def main():
    parser = kopano.parser(
        "CSKQ",
        usage="Usage: %prog [options] from to subject username msgfile")
    options, args = parser.parse_args()

    if len(args) != 5:
        print(
            "Invalid arguments, you have to supply the arguments: from, to, subject, username, and msgfile",
            file=sys.stderr)
        sys.exit(1)

    config_dict = kopano.CONFIG
    config_dict.update(CONFIG)
    config = kopano.Config(config_dict, options=options, service="autorespond")
    log = logger("autorespond", options=options, config=config)
    server = kopano.server(options=options, config=config)

    (from_, to, subject, username, msg_file) = args
    (to_me, bcc_me, cc_me) = (
        os.getenv("MESSAGE_TO_ME"),
        os.getenv("MESSAGE_BCC_ME"),
        os.getenv("MESSAGE_CC_ME"),
    )

    try:
        fh = open(msg_file, "rb")
        msg = fh.read()
        fh.close()
    except:
        log.info("Could not open msg file: %s", msg_file)
        sys.exit(1)

    if not (config["autorespond_norecip"] or
            (config["autorespond_bcc"] and bcc_me) or
            (config["autorespond_cc"] and cc_me) or to_me):
        log.debug("Response not send due to configuration")
    elif not (from_ and to and username and msg and msg_file):
        log.info(
            "One of the input arguments was empty (from: %s, to: %s, username: %s, msg: %s)",
            from_, to, username, msg)
    elif from_ == to:
        log.info("Loop detected, from == to (%s)", from_)
    elif in_blacklist(log, from_, to):
        log.info("From or to is in blacklist (from: %s, to: %s)", from_, to)
    elif check_time(config["senddb"], config["timelimit"], username, to):
        log.info(
            "Ignoring since we already sent OOO message within timelimit (username: %s, to: %s, timelimit: %d)",
            username, to, config["timelimit"])
    else:
        add_time(config["senddb"], username, to)
        send_ooo(server, username, msg, config["copy_to_sentmail"])
        log.info("Sent OOO to %s (username %s)", to, username)
예제 #16
0
def main():
    parser = kopano.parser('SPQuf')
    options, args = parser.parse_args()
    server = kopano.server(options=options, parse_args=True)

    for user in kopano.users():
        if server.options.folders:
            folders = [user.folder(path) for path in server.options.folders]
        else:
            folders = [user.subtree]

        for base in folders:
            for folder in [base] + list(base.folders()):
                dump_folder(folder)
예제 #17
0
def main():
    options, _ = kopano.parser('Suf').parse_args()
    server = kopano.server(options=options, parse_args=True)
    if not server.options.users:
        print('No user specified')
        sys.exit(1)
    user = server.user(server.options.users[0])

    if not server.options.folders:
        folders = list(user.store.folders())
    else:
        folders = [next(user.store.folders())]

    sync_folders(folders)
예제 #18
0
def main():
    server = kopano.server(parse_args=True)
    user = kopano.user(server.options.auth_user)
    header = urwid.Text('inbox')
    footer = urwid.Text(FOOT1)
    mail = Mail(user.store.outbox)
    mailbox = MailBox(user.store.inbox, mail)
    columns = urwid.Columns([('fixed', 32, mailbox), mail], 1)
    frame = urwid.Frame(urwid.AttrWrap(columns, 'body'),
                        header=urwid.AttrMap(header, 'headfoot'),
                        footer=urwid.AttrMap(footer, 'headfoot'))
    mailbox.cols = mail.cols = columns
    mailbox.footer = mail.footer = footer
    urwid.MainLoop(frame, PALETTE).run()
예제 #19
0
    def viewuser(self, company=None,user=None):
        user = dict(user=user)
        company = dict(company=company)

        html = '<html><h1>Company: %s <br>User: %s</h1>' % (company['company'],user['user'])
        html = html + "<table><tr><th>prop.idname</th><th>prop.proptype</th><th>prop.value</th><tr>\n"

        for props in kopano.server().company(company['company']).user(user['user']).props():
            if props.typename == 'PT_BINARY':
                html = html + "<tr><td>" + str(props.idname) + "</td><td>" +  "</td><td>" + str(props.value.encode('hex').upper()) + "</td><tr>\n"
            else:
                html = html + "<tr><td>" + str(props.idname) + "</td><td>" + "</td><td>" + str(props.value) + "</td><tr>\n"

        html = html + '</table></html>\n'
        return html
예제 #20
0
def main():
    args = sys.argv[1:]
    username, config_file = args[:2]

    config = kopano.Config(filename=config_file)
    server = kopano.server(config=config)

    user = server.user(username)
    autoaccept = user.autoaccept

    if len(args) > 2:
        items = [user.item(args[2])]
    else:
        items = []
        for item in user.inbox:
            mr = item.meetingrequest
            if((mr.is_request and mr.response_requested and not mr.processed) or \
               (mr.is_cancellation and not mr.processed)):
                items.append(item)

    for item in items:
        mr = item.meetingrequest

        if mr.is_request:
            decline_message = None

            if not autoaccept.recurring and item.recurring:
                decline_message = "Recurring meetings are not allowed"

            elif not autoaccept.conflicts:
                conflicts = conflict_occurrences(user, item)
                if conflicts:
                    decline_message = conflict_message(conflicts)

            if decline_message:
                mr.decline(message=decline_message)
            else:
                mr.accept(add_bcc=True)

        elif mr.is_cancellation:
            mr.process_cancellation(delete=True)

    now = datetime.now()
    try:
        user.freebusy.publish(now - timedelta(7), now + timedelta(180))
    except kopano.errors.NotFoundError as e:
        print("Unable to publish freebusy information: " + str(e),
              file=sys.stderr)
예제 #21
0
def main():
    global delcounter
    learncounter = 0
    (users, allusers, remoteusers, autolearn, autodelete, deleteafter,
     spamcommand) = getconfig()
    z = kopano.server(parse_args=True)
    if allusers and not users:
        users = []
        for user in z.users(remote=remoteusers):
            users.append(user.name)
    for username in users:
        try:
            user = z.user(username)
            for item in user.store.junk.items():
                if autolearn:
                    if (not item.header('x-spam-flag')) or (
                            item.header('x-spam-flag') == 'NO'):
                        print("%s : untagged spam [Subject: %s]" %
                              (user.name, item.subject))
                        try:
                            p = subprocess.Popen(spamcommand,
                                                 shell=True,
                                                 stdin=subprocess.PIPE,
                                                 stdout=subprocess.PIPE)
                            learn, output_err = p.communicate(item.eml())
                        except:
                            print('failed to run [%s] [%s]' %
                                  (spamcommand, output_err))
                        if learn:
                            print("%s : learned [%s]" %
                                  (user.name, learn.rstrip('\n')))
                            delmsg = 'delete after learn'
                            deletejunk(user, item, delmsg)
                            learncounter += 1
                        continue
                if autodelete:
                    if item.received.date() < (
                            datetime.date.today() -
                            datetime.timedelta(days=deleteafter)):
                        delmsg = 'autodelete'
                        deletejunk(user, item, delmsg)
        except Exception as error:
            print("%s : Unable to open store/item : [%s] [%s]" %
                  (username, username, error))
            continue
    print("Summary learned %d items, deleted %d items" %
          (learncounter, delcounter))
예제 #22
0
def write_worker():
    server = None

    while True:
        try:
            if o.restart_session == True or server == None or (
                    o.random_restart_session and random.randint(0, 1) == 1):
                server = kopano.server(o)

            item = server.user(
                o.user).store.inbox.create_item(eml=eml_file_data)

        except KeyboardInterrupt:
            return

        except Exception as e:
            print(e)
예제 #23
0
 def cmd_add(self, options):
     username = options.users[0]
     for name in (username, options.target):
         if name and not self.server.get_user(name):
             print("no such user: %s" % name, file=sys.stderr)
             sys.exit(1)
     if options.server:
         try:
             ts = kopano.server(
                 server_socket=options.server,
                 sslkey_file = self.server.sslkey_file,
                 sslkey_pass = self.server.sslkey_pass
             )
         except Exception as e:
             print("could not connect to server: %s (%s)" % (options.server, e), file=sys.stderr)
             sys.exit(1)
     self.do_cmd('ADD %s %s %s\r\n' % (username, options.target or '_', options.server or '_'))
예제 #24
0
    def subscribe_user(self, server, username, target_user, target_server, storeb_eid):
        self.log.info('subscribing: %s -> %s', username, target_server)

        usera = server.user(username)
        storea = usera.store

        # TODO report errors back directly to command-line process
        if storeb_eid:
            storeb = server.store(entryid=storeb_eid)
        elif target_server != '_':
            try:
                server2 = kopano.server(
                    server_socket=target_server,
                    sslkey_file = server.sslkey_file,
                    sslkey_pass = server.sslkey_pass
                )
            except Exception as e:
                self.log.error("could not connect to server: %s (%s)" % (target_server, e), file=sys.stderr)
            try:
                userb = server2.user(username) # TODO assuming the user is there?
                storeb = server2.create_store(userb, _msr=True)
                storeb.subtree.empty() # remove default english special folders
            except kopano.DuplicateError:
                self.log.error('user already has hooked store on server %s, try to unhook first' % target_server)
                return
        else:
            storeb = server.user(target_user).store

        state_path = os.path.join(self.state_path, usera.name)

        sink = NotificationSink(state_path, usera, usera.store, self.iqueue, self.log)

        storea.subscribe(sink, object_types=['item', 'folder'])

        STORE_STORE[storea.entryid] = storeb.entryid
        USER_SINK[username] = sink
        update_user_info(state_path, usera, 'items', 'store', 0)
        update_user_info(state_path, usera, 'init_done', 'store', 'no')
        update_user_info(state_path, usera, 'queue_empty', 'store', 'no')
        update_user_info(state_path, usera, 'target', 'store', target_user)
        update_user_info(state_path, usera, 'server', 'store', target_server)
        update_user_info(state_path, usera, 'store', 'store', storeb.entryid)

        db_put(state_path, 'folder_map_'+storea.subtree.sourcekey, storeb.subtree.entryid)

        _queue_or_store(state_path, usera, storea.entryid, None, self.iqueue)
예제 #25
0
def _server(auth_user, auth_pass, oidc=False, reconnect=False):
    # return global connection, using credentials from first user to
    # authenticate, and use it for all notifications
    global SERVER

    try:  # TODO thread lock?
        SERVER
    except NameError:
        reconnect = True

    if reconnect:
        SERVER = kopano.server(auth_user=auth_user,
                               auth_pass=auth_pass,
                               notifications=True,
                               oidc=oidc)

    return SERVER
예제 #26
0
def main():
    username, config_file, entryid = sys.argv[1:]

    config = kopano.Config(filename=config_file)
    server = kopano.server(config=config)

    user = server.user(username)
    item = user.item(entryid)
    mr = item.meetingrequest

    if mr.is_request:
        mr.accept(tentative=True, response=False)
    elif mr.is_response:
        mr.process_response()
    elif mr.is_cancellation:
        mr.process_cancellation()

    now = datetime.now()
    user.freebusy.publish(now - timedelta(7), now + timedelta(180))
예제 #27
0
def main():
    try:
        options, args = opt_args()
        if len(options.users) != 1:
            raise Exception('please specify one user')
        log = logger(options)
        server = kopano.server(options=options, parse_args=True)
        if options.restore:
            if len(args) != 1:
                raise Exception('please specify one directory')
            if not options.users:
                user = server.user(args[0])
            else:
                user = server.user(options.users[0])
            restore(args[0], user, log)
        else:
            user = server.user(options.users[0])
            backup(user, log)
    except Exception as e:
        print(e.message or e.strerror)
        sys.exit(1)
예제 #28
0
def _server(auth_user, auth_pass, oidc=False):
    """Connect to a Kopano server.

    Args:
        auth_user (str): authentication username.
        auth_pass (str): authentication password.
        oidc (bool): is it OIDC or not. Defaults to False.

    Returns:
        kopano.Server: a instance of the Kopano Server.
    """
    server = kopano.server(auth_user=auth_user,
                           auth_pass=auth_pass,
                           notifications=True,
                           parse_args=False,
                           store_cache=False,
                           oidc=oidc,
                           config={})
    logging.info("server connection established, server:%s, auth_user:%s",
                 server, server.auth_user)
    return server
예제 #29
0
def read_worker():
    server = None

    while True:
        try:
            if o.restart_session == True or server == None or (
                    o.random_restart_session and random.randint(0, 1) == 1):
                server = kopano.server(o)

            u = server.user(o.user)
            for folder in u.store.folders():
                for item in folder:
                    if random.randint(0, 1) == 1:
                        dummy = [(att.filename, att.mimetype, len(att.data))
                                 for att in item.attachments()]

        except KeyboardInterrupt:
            return

        except Exception as e:
            print(e)
예제 #30
0
def main():
    options, args = opt_args()
    if not options.user or not options.days:
        print('Please use:\n {} --user <username> --days <days> ',
              format(sys.argv[0]))
        sys.exit(1)

    user = kopano.server(options).user(options.user)
    print('Running script for \'{}\''.format(_encode(user.name)))

    if options.wastebasket:
        folder = user.store.wastebasket
        deleteitems(options, user, folder)

    if options.junk:
        folder = user.store.junk
        deleteitems(options, user, folder)
    '''
    Loop over all the folders that are passed with the -f parameter
    '''
    if options.folders:
        for folder in user.store.folders(options.folders):
            deleteitems(options, user, folder)