tools.py
2.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import os
from email.utils import formatdate
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
import mimetypes
import json
from logging import getLogger
from time import localtime
from opensipkd.waktu import create_datetime
##########
# Daemon #
##########
def is_live(pid):
try:
os.kill(pid, 0)
except OSError:
return
return True
def read_pid_file(filename):
try:
with open(filename) as f:
s = f.read()
s = s.split()
s = s[0]
return int(s)
except IOError:
return
except ValueError:
return
except IndexError:
return
def write_pid_file(filename):
pid = os.getpid()
with open(filename, 'w') as f:
f.write(str(pid))
return pid
def make_pid_file(filename):
pid = read_pid_file(filename)
if pid and is_live(pid):
print(f'PID saya {pid} masih aktif.')
return
return write_pid_file(filename)
########
# Mail #
########
def nice_name(email, name):
if name:
return f'{name} <{email}>'
return email
def file_type(filename):
ctype, encoding = mimetypes.guess_type(filename)
if ctype is None or encoding is not None:
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
return maintype, subtype
def create_doc(
from_email, to_email, subject, body, from_name=None, to_name=None,
files=[]):
msg = doc = MIMEText(body)
if files:
doc = MIMEMultipart()
doc.attach(msg)
if subject:
doc['Subject'] = subject
doc['Date'] = formatdate(localtime=True)
if from_email:
doc['From'] = nice_name(from_email, from_name)
doc['To'] = nice_name(to_email, to_name)
for fname, data in files:
maintype, subtype = file_type(fname)
payload = MIMEBase(maintype, subtype)
payload.set_payload(data)
encoders.encode_base64(payload)
payload.add_header(
'Content-Disposition', 'attachment', filename=fname)
doc.attach(payload)
return doc
# Agar log tidak memuat isi attachment
def clean_log(p):
r = {}
keys = ['id', 'pengirim', 'from_name', 'penerima', 'pesan', 'jawaban',
'tgl_operator', 'subject', 'name', 'To', 'From', 'Subject', 'Body']
for key in keys:
if key in p:
r[key] = p[key]
if 'files' not in p:
return r
files = []
for fname, content in p['files']:
files.append(fname)
r['files'] = files
return r
def file2dict(filename):
log = getLogger('file2dict')
with open(filename) as f:
s = f.read()
try:
return json.loads(s)
except Exception as e:
log.error(f'eval({s}): {exception_message()}')
raise e
def file_time(filename):
t = os.stat(filename).st_mtime
t = localtime(t)
return create_datetime(
t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec)