123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- #!/usr/bin/env python
- # -*- coding: UTF-8 -*-
- import config
- import fstools
- import json
- import logging
- import mail
- import os
- import psutil
- import report
- import time
-
- LOCK_FILE = os.path.join(config.TARGET_FOLDER, "lock")
- PID = os.getpid()
-
- logger = logging.getLogger('root')
- report.stdoutLoggingConfigure(log_name_lvl=[('root', config.LOG_LEVEL), ])
-
-
- def has_handle(fpath):
- for proc in psutil.process_iter():
- try:
- for item in proc.open_files():
- if fpath == item.path:
- return True
- except Exception:
- pass
-
- return False
-
-
- if __name__ == "__main__":
- while True:
- # Check if LOCK_FILE EXISTS
- if not os.path.exists(LOCK_FILE):
- # Create LOCK_FILE
- with open(LOCK_FILE, 'w') as fh:
- fh.write(str(PID))
- logger.debug("Creating lock-file %s with PID %d", LOCK_FILE, PID)
- # Read LOCK_FILE content
- with open(LOCK_FILE, 'r') as fh:
- lf_pid = json.loads(fh.read())
- # Check if LOCK_FILE has my PID
- if lf_pid == PID:
- # Scan for files to send
- for filename in fstools.filelist(config.TARGET_FOLDER):
- # Exclude LOCK_FILE
- if filename != LOCK_FILE and not has_handle(filename):
- logger.info("Found %s to send via E-Mail to %s.", filename, config.SEND_TO)
- # Send File as E-Mail
- try:
- mail.send_mail(
- config.SEND_FROM,
- config.SEND_TO,
- "Gesanntes Dokument - %s" % os.path.basename(filename),
- "Hier ist das gescannte Dokument vom Scanner in Buchen:",
- files=[filename],
- server=config.SMTP_SERVER,
- username=config.SMTP_USER,
- password=config.SMTP_PASSWORD
- )
- except Exception:
- logger.exception("Exception while sending an E-Mail")
- else:
- # Remove file
- logger.debug("Removing file %s", filename)
- os.remove(filename)
- # Remove LOCK_FILE
- logger.debug("Removing lock-file %s", LOCK_FILE)
- os.remove(LOCK_FILE)
- else:
- logger.warning("LOCK_FILE has PID %d and this proces %d. No action!", lf_pid, PID)
- else:
- logger.warning("LOCK_FILE %s already exists. No action!", LOCK_FILE)
- time.sleep(60)
|