Пример #1
0
 def __init__(self, server, ssl, secret):
     try:
         from sievelib.managesieve import Client
     except ImportError:
         log.error("Cannot use managesieve backend. Install sievelib python library "
                   "or use file backend instead")
         raise Exception('Cannot contact server')
     self.client = Client(server)
     self.ssl = ssl
     self.passwd = secret
Пример #2
0
def connect_to_server(
        host: str = typer.Option(...),
        username: str = typer.Option(...),
        tls: bool = True,
        password: str = typer.Option(..., prompt=True, hide_input=True),
):
    global client
    client = Client(host)
    if not client.connect(username, password, starttls=tls):
        msg.fail("Couldn't connect to server. Wrong password?")
        raise typer.Exit(code=1)
Пример #3
0
 def login(self, user, password):
     self.msc = Client(parameters.get_admin("SERVER"),
                       int(parameters.get_admin("PORT")),
                       debug=False)
     use_starttls = True if parameters.get_admin("STARTTLS") == "yes" \
         else False
     authmech = parameters.get_admin("AUTHENTICATION_MECH")
     if authmech == "AUTO":
         authmech = None
     try:
         ret = self.msc.connect(user, password, use_starttls, authmech)
     except Error:
         ret = False
     if not ret:
         return False, _(
             "Connection to MANAGESIEVE server failed, check your "
             "configuration")
     return True, None
Пример #4
0
 def login(self, user, password):
     conf = dict(param_tools.get_global_parameters("modoboa_sievefilters"))
     self.msc = Client(conf["server"], conf["port"], debug=False)
     authmech = conf["authentication_mech"]
     if authmech == "AUTO":
         authmech = None
     try:
         ret = self.msc.connect(user,
                                password,
                                starttls=conf["starttls"],
                                authmech=authmech)
     except Error:
         ret = False
     if not ret:
         return False, _(
             "Connection to MANAGESIEVE server failed, check your "
             "configuration")
     return True, None
Пример #5
0
 def __init__(self, server, ssl, secret):
     try:
         from sievelib.managesieve import Client
     except ImportError:
         log.error("Cannot use managesieve backend. Install sievelib python library "
                   "or use file backend instead")
         raise Exception('Cannot contact server')
     self.client = Client(server)
     self.ssl = ssl
     self.passwd = secret
Пример #6
0
 def login(self, user, password):
     self.msc = Client(parameters.get_admin("SERVER"),
                       int(parameters.get_admin("PORT")),
                       debug=False)
     use_starttls = True if parameters.get_admin("STARTTLS") == "yes" \
         else False
     authmech = parameters.get_admin("AUTHENTICATION_MECH")
     if authmech == "AUTO":
         authmech = None
     try:
         ret = self.msc.connect(user, password, use_starttls, authmech)
     except Error:
         ret = False
     if not ret:
         return False, _(
             "Connection to MANAGESIEVE server failed, check your "
             "configuration"
         )
     return True, None
Пример #7
0
class OofManagesieveBackend(object):
    """Store the sieve script using ManageSieve protocol"""

    def __init__(self, server, ssl, secret):
        try:
            from sievelib.managesieve import Client
        except ImportError:
            log.error("Cannot use managesieve backend. Install sievelib python library "
                      "or use file backend instead")
            raise Exception('Cannot contact server')
        self.client = Client(server)
        self.ssl = ssl
        self.passwd = secret

    def user_script(self, mailbox):
        """Return the user active sieve script if it is different from out of
        office.

        :param str mailbox: the mailbox user
        """
        self.client.connect(mailbox, self.passwd, starttls=self.ssl)
        (active_script, scripts) = self.client.listscripts()
        user_script = None
        if active_script is not None and active_script != SIEVE_SCRIPT_NAME:
            user_script = active_script
        self.client.logout()
        return user_script

    def store(self, mailbox, script):
        """Store the OOF sieve script.

        :param str mailbox: the mailbox user
        :param str script: the sieve script
        """
        self.client.connect(mailbox, self.passwd, starttls=self.ssl)
        self.client.putscript(SIEVE_SCRIPT_NAME, script)
        self.client.setactive(SIEVE_SCRIPT_NAME)
        self.client.logout()

    def load(self, mailbox):
        """Load the OOF sieve script.

        :param str mailbox: the mailbox user
        """
        self.client.connect(mailbox, self.passwd, starttls=self.ssl)
        script = self.client.getscript(SIEVE_SCRIPT_NAME)
        self.client.logout()
        return script
Пример #8
0
class SieveClient(object):
    __metaclass__ = ConnectionsManager

    def __init__(self, user=None, password=None):
        try:
            ret, msg = self.login(user, password)
        except Error as e:
            raise ConnectionError(str(e))
        if not ret:
            raise ConnectionError(msg)

    def login(self, user, password):
        self.msc = Client(parameters.get_admin("SERVER"),
                          int(parameters.get_admin("PORT")),
                          debug=False)
        use_starttls = True if parameters.get_admin("STARTTLS") == "yes" \
            else False
        authmech = parameters.get_admin("AUTHENTICATION_MECH")
        if authmech == "AUTO":
            authmech = None
        try:
            ret = self.msc.connect(user, password, use_starttls, authmech)
        except Error:
            ret = False
        if not ret:
            return False, _(
                "Connection to MANAGESIEVE server failed, check your "
                "configuration")
        return True, None

    def logout(self):
        self.msc.logout()
        self.msc = None

    def refresh(self, user, password):
        import ssl

        if self.msc is not None:
            try:
                self.msc.capability()
            except Error as e:
                pass
            else:
                return
        try:
            ret, msg = self.login(user, password)
        except (Error, ssl.SSLError) as e:
            raise ConnectionError(e)
        if not ret:
            raise ConnectionError(msg)

    def listscripts(self):
        return self.msc.listscripts()

    def getscript(self, name, format="raw"):
        content = self.msc.getscript(name)
        if content is None:
            raise SieveClientError(self.msc.errmsg)
        if format == "raw":
            return content
        p = Parser()
        if not p.parse(content):
            print "Parse error????"
            return None
        fs = FiltersSet(name)
        fs.from_parser_result(p)
        return fs

    def pushscript(self, name, content, active=False):
        if isinstance(content, unicode):
            content = content.encode("utf-8")
        if not self.msc.havespace(name, len(content)):
            error = "%s (%s)" % (_("Not enough space on server"),
                                 self.msc.errmsg)
            raise SieveClientError(error)
        if not self.msc.putscript(name, content):
            raise SieveClientError(self.msc.errmsg)
        if active and not self.msc.setactive(name):
            raise SieveClientError(self.msc.errmsg)

    def deletescript(self, name):
        if not self.msc.deletescript(name):
            raise SieveClientError(self.msc.errmsg)

    def activatescript(self, name):
        if not self.msc.setactive(name):
            raise SieveClientError(self.msc.errmsg)
Пример #9
0
def create_sieve_script():

    main_user = session.get('main_user', None)

    if not main_user:
        raise False

    username = main_user['email']
    password = main_user['password']

    user = User.query.filter(User.username == username).first()

    # Get user vacation Settings
    vacation_settings = (Settings.query.filter(
        Settings.user_id == user.id).filter(Settings.enabled == True).filter(
            Settings.section == "email").filter(
                Settings.setting_type == "email-vacation").first()) or False

    # Get user filter settings
    filter_settings = (Settings.query.filter(
        Settings.user_id == user.id).filter(
            Settings.section == "email").filter(
                Settings.setting_type == "email-filters").first()) or False

    # Get user forwarding settings
    forward_settings = (Settings.query.filter(
        Settings.user_id == user.id).filter(Settings.enabled == True).filter(
            Settings.section == "email").filter(
                Settings.setting_type == "email-forward").first()) or False

    sieve_payload = {}
    sieve_reqs = []

    if vacation_settings:
        vs = get_vacation_vars(vacation_settings)
        sieve_payload["vacation_settings"] = vs[0]
        sieve_reqs = sieve_reqs + vs[1]
    else:
        sieve_payload["vacation_settings"] = False

    if filter_settings:
        fs = get_filter_vars(filter_settings)
        sieve_payload["filter_settings"] = fs[0]
        sieve_reqs = sieve_reqs + fs[1]
    else:
        sieve_payload["filter_settings"] = False

    if forward_settings:
        fs = get_forward_vars(forward_settings)
        sieve_payload["forward_settings"] = fs[0]
        sieve_reqs = sieve_reqs + fs[1]
    else:
        sieve_payload["forward_settings"] = False

    sieve_payload["requirements"] = ', '.join('"{0}"'.format(req)
                                              for req in sieve_reqs)
    # connect to the managesieve host
    client = Client(app.config['IMAP_HOST'])
    client.connect(username, password, starttls=True, authmech="PLAIN")
    script = Template("cowui.sieve", sieve_payload).render()

    client.setactive("")
    client.deletescript("cowui")
    client.putscript("cowui", script)
    client.setactive("cowui")
    client.logout()
Пример #10
0
def main():

    (config, nSec) = loadImapConfig()

    (SERVER, USER, PASSWORD, RULES, INBOX, FOLDER) = readImapConfig(config)

    # Make connections to server
    # Sieve client connection
    c = Client(SERVER)
    if not c.connect(USER, PASSWORD, starttls=True, authmech="PLAIN"):
        print("Connection failed")
        return 0
    else:
        print(c.listscripts())
    M = makeConnection(SERVER, USER, PASSWORD)
    PASSWORD = "******"
    M.select()

    end = ""
    while (not end):
        # Could we move this parsing part out of the while?
        script = c.getscript('sieve-script')
        p = Parser()
        p.parse(script)

        (rules, more) = extractActions(p)

        # We are going to filter based on one message
        msg = selectMessage(M)
        (keyword, filterCond) = selectHeaderAuto(M, msg)

        actions = selectAction(p, M)
        # actions[0][1] contains the rule selector
        # print("actions ", actions[0][1])
        # print(rules[actions[0][1].strip('"')])

        # For a manual selection option?
        # header= selectHeader()
        # keyword = selectKeyword(header)

        # Eliminate
        # conditions = []
        # conditions.append((keyword, ":contains", filterCond))

        #print("filtercond", filterCond)
        newActions = addRule(rules, more, keyword, filterCond, actions)

        #print("nA",newActions)
        #print("nA 0",newActions[0][0][2][0].tosieve())
        #print("nA 0")

        fs = constructFilterSet(newActions)

        sieveContent = io.StringIO()
        # fs.tosieve(open(FILE_SIEVE, 'w'))
        # fs.tosieve()
        # sys.exit()
        fs.tosieve(sieveContent)

        #import time
        #time.sleep(5)
        # Let's do a backup of the old sieve script
        name = time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime())
        res = c.putscript(name + 'sogo', script)
        print("res", res)

        # Now we can put the new sieve filters in place
        # fSieve = open(FILE_SIEVE, 'r')
        # if not c.putscript('sogo', fSieve.read()):
        #print(sieveContent.getvalue())

        if not c.putscript('sogo', sieveContent.getvalue()):
            print("fail!")

        # Let's start the git backup

        repo = Repo(repoDir)
        index = repo.index

        print("listscripts", c.listscripts())
        listScripts = c.listscripts()
        print("listscripts", listScripts)
        if (listScripts != None):
            listScripts = listScripts[1]
            listScripts.sort()
            print("listscripts", c.listscripts())
            print(listScripts[0])

            # script = listScripts[-1] # The last one
            sieveFile = c.getscript('sogo')
            file = open(repoDir + repoFile, 'w')
            file.write(sieveFile)
            file.close()
            index.add(['*'])
            index.commit(name + 'sogo')

            if len(listScripts) > 6:
                # We will keep the last five ones (plus the active one)
                numScripts = len(listScripts) - 6
                i = 0
                while numScripts > 0:
                    script = listScripts[i]
                    c.deletescript(script)
                    i = i + 1
                    numScripts = numScripts - 1

        end = input("More rules? (empty to continue) ")
Пример #11
0
def addToSieve(msg=""):
    config = loadImapConfig()[0]

    (SERVER, USER, PASSWORD, RULES, INBOX, FOLDER) = readImapConfig(config)

    # Make connections to server
    # Sieve client connection
    c = Client(SERVER)
    if not c.connect(USER, PASSWORD, starttls=True, authmech="PLAIN"):
        print("Connection failed")
        return 0
    M = makeConnection(SERVER, USER, PASSWORD)
    PASSWORD = "******"
    M.select()

    #end = ""
    #while (not end):
    # Could we move this parsing part out of the while?
    script = c.getscript('sieve-script')
    p = Parser()
    p.parse(script)
    #print("p.result",p.result)

    (rules, more) = extractActions(p)

    # We are going to filter based on one message
    if not msg:
        msg = selectMessage(M)
    (keyword, filterCond) = selectHeaderAuto(M, msg)

    actions = selectAction(p, M)
    # actions[0][1] contains the rule selector
    # print("actions ", actions[0][1])
    # print(rules[actions[0][1].strip('"')])

    # For a manual selection option?
    # header= selectHeader()
    # keyword = selectKeyword(header)

    # Eliminate
    # conditions = []
    # conditions.append((keyword, ":contains", filterCond))

    #print("filtercond", filterCond)
    newActions = addRule(rules, more, keyword, filterCond, actions)

    #print("nA",newActions)
    #print("nA 0",newActions[0][0][2][0].tosieve())
    #print("nA 0")

    (fs, moreSieve) = constructFilterSet(newActions)

    sieveContent = io.StringIO()
    # We need to add the require in order to use the body section
    sieveContent.write('require ["body"];\n')
    # fs.tosieve(open(FILE_SIEVE, 'w'))
    #fs.tosieve()
    #print(moreSieve)
    #sys.exit()
    print(USER)
    fs.tosieve(sieveContent)
    sieveContent.write(moreSieve)
    with open(os.path.expanduser('~' + USER) + '/sieve/body.sieve') as f:
        sieveContent.write(f.read())
    print(sieveContent.getvalue())
    #"""#Filter:
    #if anyof (body :raw :contains "puntoclick.info") {
    #    fileinto "Spam";
    #    stop;
    #}""")

    #import time
    #time.sleep(5)
    # Let's do a backup of the old sieve script
    name = time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime())
    res = c.putscript(name + 'sogo', script)
    print("res", res)

    # Now we can put the new sieve filters in place
    # fSieve = open(FILE_SIEVE, 'r')
    # if not c.putscript('sogo', fSieve.read()):
    #print(sieveContent.getvalue())

    if not c.putscript('sieve-script', sieveContent.getvalue()):
        print("fail!")

    # Let's start the git backup

    repo = Repo(repoDir)
    index = repo.index

    print("listscripts", c.listscripts())
    listScripts = c.listscripts()
    print("listscripts", listScripts)
    if (listScripts != None):
        listScripts = listScripts[1]
        listScripts.sort()
        print("listscripts", c.listscripts())
        print(listScripts[0])

        # script = listScripts[-1] # The last one
        sieveFile = c.getscript('sieve-script')
        file = open(repoDir + repoFile, 'w')
        file.write(sieveFile)
        file.close()
        index.add(['*'])
        index.commit(name + 'sogo')

        if len(listScripts) > 6:
            # We will keep the last five ones (plus the active one)
            numScripts = len(listScripts) - 6
            i = 0
            while numScripts > 0:
                script = listScripts[i]
                c.deletescript(script)
                i = i + 1
                numScripts = numScripts - 1
Пример #12
0
def getCli(usr, pwd):
    client = Client("imap.mailbox.org")
    conn = client.connect(usr, pwd, starttls=True, authmech="LOGIN")
    check(conn, "connection")
    return client
Пример #13
0
class SieveClient(object, metaclass=ConnectionsManager):
    def __init__(self, user=None, password=None):
        try:
            ret, msg = self.login(user, password)
        except Error as e:
            raise ConnectionError(str(e))
        if not ret:
            raise ConnectionError(msg)

    def login(self, user, password):
        conf = dict(param_tools.get_global_parameters("modoboa_sievefilters"))
        self.msc = Client(conf["server"], conf["port"], debug=False)
        authmech = conf["authentication_mech"]
        if authmech == "AUTO":
            authmech = None
        try:
            ret = self.msc.connect(user,
                                   password,
                                   starttls=conf["starttls"],
                                   authmech=authmech)
        except Error:
            ret = False
        if not ret:
            return False, _(
                "Connection to MANAGESIEVE server failed, check your "
                "configuration")
        return True, None

    def logout(self):
        self.msc.logout()
        self.msc = None

    def refresh(self, user, password):
        import ssl

        if self.msc is not None:
            try:
                self.msc.capability()
            except Error as e:
                pass
            else:
                return
        try:
            ret, msg = self.login(user, password)
        except (Error, ssl.SSLError) as e:
            raise ConnectionError(e)
        if not ret:
            raise ConnectionError(msg)

    def listscripts(self):
        return self.msc.listscripts()

    def getscript(self, name, format="raw"):
        content = self.msc.getscript(name)
        if content is None:
            raise SieveClientError(self.msc.errmsg)
        if format == "raw":
            return content
        p = Parser()
        if not p.parse(content):
            print("Parse error????")
            return None
        fs = FiltersSet(name)
        fs.from_parser_result(p)
        return fs

    def pushscript(self, name, content, active=False):
        if isinstance(content, str):
            content = content.encode("utf-8")
        if not self.msc.havespace(name, len(content)):
            error = "%s (%s)" % (_("Not enough space on server"),
                                 self.msc.errmsg)
            raise SieveClientError(error)
        if not self.msc.putscript(name, content):
            raise SieveClientError(self.msc.errmsg)
        if active and not self.msc.setactive(name):
            raise SieveClientError(self.msc.errmsg)

    def deletescript(self, name):
        if not self.msc.deletescript(name):
            raise SieveClientError(self.msc.errmsg)

    def activatescript(self, name):
        if not self.msc.setactive(name):
            raise SieveClientError(self.msc.errmsg)
Пример #14
0
def addToSieve(msg=""):
    config = loadImapConfig()[0]

    (SERVER, USER, PASSWORD, RULES, INBOX, FOLDER) = readImapConfig(config)

    # Make connections to server
    # Sieve client connection
    c = Client(SERVER)
    if not c.connect(USER, PASSWORD, starttls=True, authmech="PLAIN"):
        print("Connection failed")
        return 0
    M = makeConnection(SERVER, USER, PASSWORD)
    PASSWORD = "******"
    M.select()

    #end = ""
    #while (not end):
    # Could we move this parsing part out of the while?
    script = c.getscript('sieve-script')
    p = Parser()
    p.parse(script)
    #print("p.result",p.result)

    (rules, more) = extractActions(p)

    # We are going to filter based on one message
    if not msg:
        msg = selectMessage(M)
    (keyword, filterCond) = selectHeaderAuto(M, msg)

    actions = selectAction(p, M)
    # actions[0][1] contains the rule selector
    # print("actions ", actions[0][1])
    # print(rules[actions[0][1].strip('"')])

    # For a manual selection option?
    # header= selectHeader()
    # keyword = selectKeyword(header)

    # Eliminate
    # conditions = []
    # conditions.append((keyword, ":contains", filterCond))

    #print("filtercond", filterCond)
    newActions = addRule(rules, more, keyword, filterCond, actions)

    #print("nA",newActions)
    #print("nA 0",newActions[0][0][2][0].tosieve())
    #print("nA 0")

    (fs, moreSieve) = constructFilterSet(newActions)

    sieveContent = io.StringIO()
    # We need to add the require in order to use the body section
    sieveContent.write('require ["body"];\n')
    # fs.tosieve(open(FILE_SIEVE, 'w'))
    #fs.tosieve()
    #print(moreSieve)
    #sys.exit()
    print(USER)
    fs.tosieve(sieveContent)
    sieveContent.write(moreSieve)
    with open(os.path.expanduser('~'+USER)+'/sieve/body.sieve') as f:
        sieveContent.write(f.read())
    print(sieveContent.getvalue())
#"""#Filter:
#if anyof (body :raw :contains "puntoclick.info") {
#    fileinto "Spam";
#    stop;
#}""")

    #import time
    #time.sleep(5)
    # Let's do a backup of the old sieve script
    name = time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime())
    res  = c.putscript(name+'sogo', script)
    print("res",res)

    # Now we can put the new sieve filters in place
    # fSieve = open(FILE_SIEVE, 'r')
    # if not c.putscript('sogo', fSieve.read()):
    #print(sieveContent.getvalue())

    if not c.putscript('sieve-script', sieveContent.getvalue()):
        print("fail!")

    # Let's start the git backup

    repo = Repo(repoDir)
    index = repo.index

    print("listscripts",c.listscripts())
    listScripts=c.listscripts()
    print("listscripts",listScripts)
    if (listScripts != None):
        listScripts=listScripts[1]
        listScripts.sort() 
        print("listscripts",c.listscripts())
        print(listScripts[0])

        # script = listScripts[-1] # The last one
        sieveFile=c.getscript('sieve-script')
        file=open(repoDir+repoFile,'w')
        file.write(sieveFile)
        file.close()
        index.add(['*'])
        index.commit(name+'sogo')

        if len(listScripts)>6:
            # We will keep the last five ones (plus the active one)
            numScripts = len(listScripts) - 6
            i = 0
            while numScripts > 0:
                script = listScripts[i]
                c.deletescript(script)
                i = i + 1
                numScripts = numScripts - 1
Пример #15
0
class OofManagesieveBackend(object):
    """Store the sieve script using ManageSieve protocol"""
    def __init__(self, server, ssl, secret):
        try:
            from sievelib.managesieve import Client
        except ImportError:
            log.error(
                "Cannot use managesieve backend. Install sievelib python library "
                "or use file backend instead")
            raise Exception('Cannot contact server')
        self.client = Client(server)
        self.ssl = ssl
        self.passwd = secret

    def user_script(self, mailbox):
        """Return the user active sieve script if it is different from out of
        office.

        :param str mailbox: the mailbox user
        """
        self.client.connect(mailbox, self.passwd, starttls=self.ssl)
        (active_script, scripts) = self.client.listscripts()
        user_script = None
        if active_script is not None and active_script != SIEVE_SCRIPT_NAME:
            user_script = active_script
        self.client.logout()
        return user_script

    def store(self, mailbox, script):
        """Store the OOF sieve script.

        :param str mailbox: the mailbox user
        :param str script: the sieve script
        """
        self.client.connect(mailbox, self.passwd, starttls=self.ssl)
        self.client.putscript(SIEVE_SCRIPT_NAME, script)
        self.client.setactive(SIEVE_SCRIPT_NAME)
        self.client.logout()

    def load(self, mailbox):
        """Load the OOF sieve script.

        :param str mailbox: the mailbox user
        """
        self.client.connect(mailbox, self.passwd, starttls=self.ssl)
        script = self.client.getscript(SIEVE_SCRIPT_NAME)
        self.client.logout()
        return script
Пример #16
0
def main():

    (config, nSec) = loadImapConfig()

    (SERVER, USER, PASSWORD, RULES, INBOX, FOLDER) = readImapConfig(config)

    # Make connections to server
    # Sieve client connection
    c = Client(SERVER)
    if not c.connect(USER, PASSWORD, starttls=True, authmech="PLAIN"):
        print("Connection failed")
        return 0
    else:
        print(c.listscripts())
    M = makeConnection(SERVER, USER, PASSWORD)
    PASSWORD = "******"
    M.select()

    end = ""
    while (not end):
        # Could we move this parsing part out of the while?
        script = c.getscript('sieve-script')
        p = Parser()
        p.parse(script)

        (rules, more) = extractActions(p)

        # We are going to filter based on one message
        msg = selectMessage(M)
        (keyword, filterCond) = selectHeaderAuto(M, msg)

        actions = selectAction(p, M)
        # actions[0][1] contains the rule selector
        # print("actions ", actions[0][1])
        # print(rules[actions[0][1].strip('"')])

        # For a manual selection option?
        # header= selectHeader()
        # keyword = selectKeyword(header)

        # Eliminate
        # conditions = []
        # conditions.append((keyword, ":contains", filterCond))

        #print("filtercond", filterCond)
        newActions = addRule(rules, more, keyword, filterCond, actions)

        #print("nA",newActions)
        #print("nA 0",newActions[0][0][2][0].tosieve())
        #print("nA 0")

        fs = constructFilterSet(newActions)

        sieveContent = io.StringIO()
        # fs.tosieve(open(FILE_SIEVE, 'w'))
        # fs.tosieve()
        # sys.exit()
        fs.tosieve(sieveContent)

        #import time
        #time.sleep(5)
        # Let's do a backup of the old sieve script
        name = time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime())
        res  = c.putscript(name+'sogo', script)
        print("res",res)

        # Now we can put the new sieve filters in place
        # fSieve = open(FILE_SIEVE, 'r')
        # if not c.putscript('sogo', fSieve.read()):
        #print(sieveContent.getvalue())

        if not c.putscript('sogo', sieveContent.getvalue()):
            print("fail!")

        # Let's start the git backup

        repo = Repo(repoDir)
        index = repo.index

        print("listscripts",c.listscripts())
        listScripts=c.listscripts()
        print("listscripts",listScripts)
        if (listScripts != None):
            listScripts=listScripts[1]
            listScripts.sort() 
            print("listscripts",c.listscripts())
            print(listScripts[0])

            # script = listScripts[-1] # The last one
            sieveFile=c.getscript('sogo')
            file=open(repoDir+repoFile,'w')
            file.write(sieveFile)
            file.close()
            index.add(['*'])
            index.commit(name+'sogo')

            if len(listScripts)>6:
       	        # We will keep the last five ones (plus the active one)
                numScripts = len(listScripts) - 6
                i = 0
                while numScripts > 0:
                    script = listScripts[i]
                    c.deletescript(script)
                    i = i + 1
                    numScripts = numScripts - 1

        end = input("More rules? (empty to continue) ")
Пример #17
0
class SieveClient(object):
    __metaclass__ = ConnectionsManager

    def __init__(self, user=None, password=None):
        try:
            ret, msg = self.login(user, password)
        except Error as e:
            raise ConnectionError(str(e))
        if not ret:
            raise ConnectionError(msg)

    def login(self, user, password):
        self.msc = Client(parameters.get_admin("SERVER"),
                          int(parameters.get_admin("PORT")),
                          debug=False)
        use_starttls = True if parameters.get_admin("STARTTLS") == "yes" \
            else False
        authmech = parameters.get_admin("AUTHENTICATION_MECH")
        if authmech == "AUTO":
            authmech = None
        try:
            ret = self.msc.connect(user, password, use_starttls, authmech)
        except Error:
            ret = False
        if not ret:
            return False, _(
                "Connection to MANAGESIEVE server failed, check your "
                "configuration"
            )
        return True, None

    def logout(self):
        self.msc.logout()
        self.msc = None

    def refresh(self, user, password):
        import ssl

        if self.msc is not None:
            try:
                self.msc.capability()
            except Error as e:
                pass
            else:
                return
        try:
            ret, msg = self.login(user, password)
        except (Error, ssl.SSLError) as e:
            raise ConnectionError(e)
        if not ret:
            raise ConnectionError(msg)

    def listscripts(self):
        return self.msc.listscripts()

    def getscript(self, name, format="raw"):
        content = self.msc.getscript(name)
        if content is None:
            raise SieveClientError(self.msc.errmsg)
        if format == "raw":
            return content
        p = Parser()
        if not p.parse(content):
            print "Parse error????"
            return None
        fs = FiltersSet(name)
        fs.from_parser_result(p)
        return fs

    def pushscript(self, name, content, active=False):
        if isinstance(content, unicode):
            content = content.encode("utf-8")
        if not self.msc.havespace(name, len(content)):
            error = "%s (%s)" % (
                _("Not enough space on server"), self.msc.errmsg)
            raise SieveClientError(error)
        if not self.msc.putscript(name, content):
            raise SieveClientError(self.msc.errmsg)
        if active and not self.msc.setactive(name):
            raise SieveClientError(self.msc.errmsg)

    def deletescript(self, name):
        if not self.msc.deletescript(name):
            raise SieveClientError(self.msc.errmsg)

    def activatescript(self, name):
        if not self.msc.setactive(name):
            raise SieveClientError(self.msc.errmsg)