123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178 |
- #!/usr/bin/env python3
- #
- # lcmail-wizard - Script for mail (and log) auto deletion
- #
- # Actions:
- # * Create new mail dir structure if new entries are added
- # inside lcmail-wizard.yml, but not delete mail dir
- # if entries are removed from lcmail-wizard.yml
- # * Read lcmail-wizard.yml file parsing auto del rules,
- # and procede with deletion (mail and log)
- #
- # See README for more information
- #
- import argparse
- import datetime
- import logging
- import os
- import yaml
- # Default envs
- BASE = os.path.abspath(os.path.dirname(__file__))
- CONF = os.path.join(BASE, "lcmail-wizard.yml")
- HOME = os.environ["HOME"]
- LOGDIR = os.path.join(BASE, "log/")
- MAILDIR = os.path.join(HOME, ".maildir")
- PROCMAIL = os.path.join(HOME, ".procmail")
- TRASH = os.path.join(MAILDIR, ".Trash/cur")
- # Log configuration
- logging.basicConfig(
- filename=LOGDIR + "lcmail-wizard.log." + datetime.date.today().strftime("%y-%m-%d"),
- filemode="a",
- level=logging.DEBUG,
- format="%(asctime)s - %(levelname)s: %(message)s",
- )
- # Argparse configuration
- parser = argparse.ArgumentParser(
- description="lcmail-wizard.py - Script for mail (and log) auto deletion",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- )
- parser.add_argument(
- "-c",
- "--create",
- help="update maildir structure (creation only)",
- action="store_true",
- default=False,
- )
- parser.add_argument(
- "-d", "--debug", help="no action, only logging", action="store_true", default=False
- )
- args = parser.parse_args()
- def pconf():
- """ Parse yaml configuration file """
- try:
- with open(CONF, "r") as fsi:
- try:
- conf = yaml.load(fsi)
- return conf
- except BaseException:
- logging.exception("%s not loaded", CONF)
- except FileNotFoundError:
- logging.exception("%s not found", CONF)
- def cdate(filename):
- """ Return creation datetime """
- time = os.path.getctime(filename)
- return datetime.datetime.fromtimestamp(time)
- def ddate(filename):
- """ Return difference between creation date and nowdate in days """
- return abs((datetime.datetime.now() - cdate(filename)).days)
- def mkdir_maildir(debug):
- """ Update mail directories (only creation update for safe) """
- types = pconf()
- for type in types:
- if type == "mail":
- dirs = types[type]
- for dir in dirs:
- if debug:
- if os.path.exists(os.path.join(MAILDIR, dir)):
- pass
- else:
- logging.debug(
- "%s folder structure created", os.path.join(MAILDIR, dir)
- )
- else:
- if os.path.exists(os.path.join(MAILDIR, dir)):
- pass
- else:
- os.makedirs(os.path.join(MAILDIR, dir), mode=0o700)
- os.makedirs(os.path.join(MAILDIR, dir, "cur"), mode=0o700)
- os.makedirs(os.path.join(MAILDIR, dir, "new"), mode=0o700)
- os.makedirs(os.path.join(MAILDIR, dir, "tmp"), mode=0o700)
- logging.info(
- "%s folder structure created", os.path.join(MAILDIR, dir)
- )
- def empty_mail_log(debug):
- """ Empty logs and mails """
- types = pconf()
- for type in types:
- if type == "mail":
- dirs = types[type]
- for dir in dirs:
- if dirs[dir] != 0:
- os.chdir(os.path.join(MAILDIR, dir, "cur"))
- for mail in os.listdir("."):
- if ddate(mail) >= dirs[dir]:
- if debug:
- logging.debug(
- "%s in %s with ddate %s conf %s to delete",
- mail,
- dir,
- ddate(mail),
- dirs[dir],
- )
- else:
- os.rename(mail, os.path.join(TRASH, mail))
- logging.info("%s in %s deleted", mail, dir)
- elif type == "log":
- dirs = types[type]
- for dir in dirs:
- if dir == "procmail":
- if dirs[dir] != 0:
- os.chdir(os.path.join(PROCMAIL, "log"))
- for log in os.listdir("."):
- if ddate(log) >= dirs[dir]:
- if debug:
- logging.debug(
- "%s in %s/log with ddate %s conf %s to delete",
- log,
- dir,
- ddate(log),
- dirs[dir],
- )
- else:
- os.remove(log)
- logging.info("%s in %s/log deleted", log, dir)
- elif dir == "lcmail":
- if dirs[dir] != 0:
- os.chdir(os.path.join(LOGDIR))
- for log in os.listdir("."):
- if ddate(log) >= dirs[dir]:
- if debug:
- logging.debug(
- "%s in %s/log with ddate %s conf %s to delete",
- log,
- dir,
- ddate(log),
- dirs[dir],
- )
- else:
- os.remove(log)
- logging.info("%s in %s/log deleted", log, dir)
- else:
- pass
- else:
- pass
- if __name__ == "__main__":
- try:
- if args.create:
- mkdir_maildir(args.debug)
- else:
- empty_mail_log(args.debug)
- except BaseException:
- logging.exception("General exception occured")
|