Преглед изворни кода

Initial application creation

test_without_lockfile
Dirk Alders пре 1 година
родитељ
комит
d288a8fb11
9 измењених фајлова са 178 додато и 0 уклоњено
  1. 1
    0
      .gitignore
  2. 6
    0
      .gitmodules
  3. 41
    0
      __install__.py
  4. 14
    0
      config_example/config.py
  5. 62
    0
      file2mail.py
  6. 4
    0
      file2mail.sh
  7. 1
    0
      fstools
  8. 48
    0
      mail.py
  9. 1
    0
      report

+ 1
- 0
.gitignore Прегледај датотеку

@@ -1,3 +1,4 @@
1
+config.py
1 2
 # ---> Linux
2 3
 *~
3 4
 

+ 6
- 0
.gitmodules Прегледај датотеку

@@ -0,0 +1,6 @@
1
+[submodule "fstools"]
2
+	path = fstools
3
+	url = https://git.mount-mockery.de/pylib/fstools.git
4
+[submodule "report"]
5
+	path = report
6
+	url = https://git.mount-mockery.de/pylib/report.git

+ 41
- 0
__install__.py Прегледај датотеку

@@ -0,0 +1,41 @@
1
+#!/bin/python
2
+#
3
+import os
4
+import sys
5
+
6
+SERVICE_FILE = """
7
+[Unit]
8
+Description=File2Mail Service
9
+After=network-online.target
10
+Wants=network-online.target
11
+[Service]
12
+User=%(UID)d
13
+Group=%(GID)d
14
+ExecStart=%(MY_PATH)s/file2mail.sh
15
+Type=simple
16
+[Install]
17
+WantedBy=default.target
18
+"""
19
+
20
+
21
+def help():
22
+    print("Usage: prog <UID> <GID> <TARGET_PATH>")
23
+
24
+if __name__ == "__main__":
25
+    if len(sys.argv) == 4:
26
+        try:
27
+            uid = int(sys.argv[1])
28
+            gid = int(sys.argv[2])
29
+        except ValueError:
30
+            help()
31
+        else:
32
+            if os.path.isdir(sys.argv[3]):
33
+                with open(os.path.join(sys.argv[3], 'file2mail.service'), "w") as fh:
34
+                    fh.write(SERVICE_FILE % {
35
+                        "MY_PATH": os.path.dirname(os.path.abspath(__file__)),
36
+                        "UID": uid,
37
+                        "GID": gid})
38
+            else:
39
+                help()
40
+    else:
41
+        help()

+ 14
- 0
config_example/config.py Прегледај датотеку

@@ -0,0 +1,14 @@
1
+# Folder to be monitored for new files
2
+TARGET_FOLDER = "/home/scan"
3
+
4
+# Recipiant for the files found in TARGET_PATH
5
+SEND_TO = "scan@mount-mockery.de"
6
+
7
+# Sender
8
+SEND_FROM = "Scanner-Buchen <scan@mount-mockery.de>"
9
+SMTP_SERVER = "mount-mockery.de"
10
+SMTP_USER = "smtp-sendmail"
11
+SMTP_PASSWORD = "----XXX----"
12
+
13
+# Possible log-levels: DEBUG, INFO, WARNING, ERROR
14
+LOG_LEVEL = "INFO"

+ 62
- 0
file2mail.py Прегледај датотеку

@@ -0,0 +1,62 @@
1
+#!/usr/bin/env python
2
+# -*- coding: UTF-8 -*-
3
+import config
4
+import fstools
5
+import json
6
+import logging
7
+import mail
8
+import os
9
+import report
10
+import time
11
+
12
+LOCK_FILE = os.path.join(config.TARGET_FOLDER, "lock")
13
+PID = os.getpid()
14
+
15
+logger = logging.getLogger('root')
16
+report.stdoutLoggingConfigure(log_name_lvl=[('root', config.LOG_LEVEL), ])
17
+
18
+
19
+if __name__ == "__main__":
20
+    while True:
21
+        # Check if LOCK_FILE EXISTS
22
+        if not os.path.exists(LOCK_FILE):
23
+            # Create LOCK_FILE
24
+            with open(LOCK_FILE, 'w') as fh:
25
+                fh.write(str(PID))
26
+            logger.debug("Creating lock-file %s with PID %d", LOCK_FILE, PID)
27
+            # Read LOCK_FILE content
28
+            with open(LOCK_FILE, 'r') as fh:
29
+                lf_pid = json.loads(fh.read())
30
+            # Check if LOCK_FILE has my PID
31
+            if lf_pid == PID:
32
+                # Scan for files to send
33
+                for filename in fstools.filelist(config.TARGET_FOLDER):
34
+                    # Exclude LOCK_FILE
35
+                    if filename != LOCK_FILE:
36
+                        logger.info("Found %s to send via E-Mail to %s.", filename, config.SEND_TO)
37
+                        # Send File as E-Mail
38
+                        try:
39
+                            mail.send_mail(
40
+                                config.SEND_FROM,
41
+                                config.SEND_TO,
42
+                                "Gesanntes Dokument - %s" % os.path.basename(filename),
43
+                                "Hier ist das gescannte Dokument vom Scanner in Buchen:", 
44
+                                files=[filename],
45
+                                server=config.SMTP_SERVER,
46
+                                username=config.SMTP_USER,
47
+                                password=config.SMTP_PASSWORD
48
+                            )
49
+                        except Exception:
50
+                            logger.exception("Exception while sending an E-Mail")
51
+                        else:
52
+                            # Remove file
53
+                            logger.debug("Removing file %s", filename)
54
+                            os.remove(filename                        )
55
+                # Remove LOCK_FILE
56
+                logger.debug("Removing lock-file %s", LOCK_FILE)
57
+                os.remove(LOCK_FILE)
58
+            else:
59
+                logger.warning("LOCK_FILE has PID %d and this proces %d. No action!", lf_pid, PID)
60
+        else:
61
+            logger.warning("LOCK_FILE %s already exists. No action!", LOCK_FILE)
62
+        time.sleep(60)

+ 4
- 0
file2mail.sh Прегледај датотеку

@@ -0,0 +1,4 @@
1
+#!/bin/sh
2
+#
3
+BASEPATH=`dirname $0`
4
+python $BASEPATH/file2mail.py

+ 1
- 0
fstools

@@ -0,0 +1 @@
1
+Subproject commit c10e8792abb05671dab6de51cdadda3bf8ead50f

+ 48
- 0
mail.py Прегледај датотеку

@@ -0,0 +1,48 @@
1
+import smtplib
2
+from pathlib import Path
3
+from email.mime.multipart import MIMEMultipart
4
+from email.mime.base import MIMEBase
5
+from email.mime.text import MIMEText
6
+from email.utils import COMMASPACE, formatdate
7
+from email import encoders
8
+
9
+
10
+def send_mail(send_from, send_to, subject, message, files=[],
11
+              server="localhost", username='', password='',
12
+              use_tls=True):
13
+    """Compose and send email with provided info and attachments.
14
+
15
+    Args:
16
+        send_from (str): from name
17
+        send_to (list[str]): to name(s)
18
+        subject (str): message title
19
+        message (str): message body
20
+        files (list[str]): list of file paths to be attached to email
21
+        server (str): mail server host name
22
+        username (str): server auth username
23
+        password (str): server auth password
24
+        use_tls (bool): use TLS mode
25
+    """
26
+    msg = MIMEMultipart()
27
+    msg['From'] = send_from
28
+    msg['To'] = send_to
29
+    msg['Date'] = formatdate(localtime=True)
30
+    msg['Subject'] = subject
31
+
32
+    msg.attach(MIMEText(message))
33
+
34
+    for path in files:
35
+        part = MIMEBase('application', "octet-stream")
36
+        with open(path, 'rb') as file:
37
+            part.set_payload(file.read())
38
+        encoders.encode_base64(part)
39
+        part.add_header('Content-Disposition',
40
+                        'attachment; filename={}'.format(Path(path).name))
41
+        msg.attach(part)
42
+
43
+    smtp = smtplib.SMTP(server)
44
+    if use_tls:
45
+        smtp.starttls()
46
+    smtp.login(username, password)
47
+    smtp.sendmail(send_from, send_to.split(', '), msg.as_string())
48
+    smtp.quit()

+ 1
- 0
report

@@ -0,0 +1 @@
1
+Subproject commit b53dd30eae1d679b7eec4999bec50aed55bc105b

Loading…
Откажи
Сачувај