Skip to content

Commit

Permalink
Reformat with black
Browse files Browse the repository at this point in the history
  • Loading branch information
ThiefMaster committed Sep 9, 2020
1 parent deca97e commit f9ca6d6
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 45 deletions.
58 changes: 38 additions & 20 deletions maildump/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ def disconnect():

def create_tables():
log.debug('Creating tables')
_conn.execute("""
_conn.execute(
"""
CREATE TABLE IF NOT EXISTS message (
id INTEGER PRIMARY KEY ASC,
sender TEXT,
Expand All @@ -41,9 +42,11 @@ def create_tables():
type TEXT,
created_at TIMESTAMP
)
""")
"""
)

_conn.execute("""
_conn.execute(
"""
CREATE TABLE IF NOT EXISTS message_part (
id INTEGER PRIMARY KEY ASC,
message_id INTEGER NOT NULL,
Expand All @@ -56,7 +59,8 @@ def create_tables():
size INTEGER,
created_at TIMESTAMP
)
""")
"""
)


def iter_message_parts(message):
Expand All @@ -81,12 +85,17 @@ def add_message(sender, recipients, body, message):
bcc_list = split_addresses(decode_header(message['BCC'])) if 'BCC' in message else []
all_recipients = {'to': to_list, 'cc': cc_list, 'bcc': bcc_list}
cur = _conn.cursor()
cur.execute(sql, (decode_header(sender),
json.dumps(all_recipients),
decode_header(message['Subject']),
body,
message.get_content_type(),
len(body)))
cur.execute(
sql,
(
decode_header(sender),
json.dumps(all_recipients),
decode_header(message['Subject']),
body,
message.get_content_type(),
len(body),
),
)
message_id = cur.lastrowid
# Store parts (why do we do this for non-multipart at all?!)
parts = 0
Expand All @@ -113,14 +122,19 @@ def _add_message_part(message_id, cid, part):

body = part.get_payload(decode=True)
body_len = len(body) if body else 0
_conn.execute(sql, (message_id,
cid,
part.get_content_type(),
part.get_filename() is not None,
part.get_filename(),
part.get_content_charset(),
body,
body_len))
_conn.execute(
sql,
(
message_id,
cid,
part.get_content_type(),
part.get_filename() is not None,
part.get_filename(),
part.get_content_charset(),
body,
body_len,
),
)


def _get_message_cols(lightweight):
Expand Down Expand Up @@ -174,7 +188,9 @@ def _get_message_part_types(message_id, types):
is_attachment = 0
LIMIT
1
""".format(','.join('?' * len(types)))
""".format(
','.join('?' * len(types))
)
return _conn.execute(sql, (message_id,) + types).fetchone()


Expand Down Expand Up @@ -202,7 +218,9 @@ def _message_has_types(message_id, types):
type IN ({0})
LIMIT
1
""".format(','.join('?' * len(types)))
""".format(
','.join('?' * len(types))
)
res = _conn.execute(sql, (message_id,) + types).fetchone()
return res is not None

Expand Down
3 changes: 1 addition & 2 deletions maildump/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ def decode_header(value):


def split_addresses(value):
return [('{0} <{1}>'.format(name, addr) if name else addr)
for name, addr in getaddresses([value])]
return [('{0} <{1}>'.format(name, addr) if name else addr) for name, addr in getaddresses([value])]


def rest(f):
Expand Down
16 changes: 8 additions & 8 deletions maildump/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ def check_auth():
if auth and htpasswd.check_password(auth.username, auth.password):
log.debug('Request authenticated ({0})'.format(auth.username))
return
return app.response_class('This MailDump instance is password-protected.', 401, {
'WWW-Authenticate': 'Basic realm="MailDump"'
})
return app.response_class(
'This MailDump instance is password-protected.', 401, {'WWW-Authenticate': 'Basic realm="MailDump"'}
)


@app.route('/')
Expand All @@ -58,9 +58,7 @@ def delete_messages():
@rest
def get_messages():
lightweight = not bool_arg(request.args.get('full'))
return {
'messages': db.get_messages(lightweight)
}
return {'messages': db.get_messages(lightweight)}


@app.route('/messages/<int:message_id>', methods=('DELETE',))
Expand Down Expand Up @@ -117,8 +115,10 @@ def get_message_plain(message_id):

def _fix_cid_links(soup, message_id):
def _url_from_cid_match(m):
return m.group().replace(m.group('replace'),
url_for('get_message_part', message_id=message_id, cid=m.group('cid')))
return m.group().replace(
m.group('replace'), url_for('get_message_part', message_id=message_id, cid=m.group('cid'))
)

# Iterate over all attributes that do not contain CSS and replace cid references
for tag in (x for x in soup.descendants if isinstance(x, bs4.Tag)):
for name, value in tag.attrs.items():
Expand Down
6 changes: 5 additions & 1 deletion maildump_runner/geventdaemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@


class GeventDaemonContext(daemon.DaemonContext):
""" DaemonContext for gevent.
"""DaemonContext for gevent.
Receive same options as a DaemonContext (python-daemon), Except:
Expand Down Expand Up @@ -42,6 +42,7 @@ def open(self):
# always reinit even when not forked when registering signals
self._apply_monkey_patch()
import gevent

if self.gevent_hub is not None:
# gevent 1.0 only
gevent.get_hub(self.gevent_hub)
Expand All @@ -51,13 +52,15 @@ def open(self):
def _apply_monkey_patch(self):
import gevent
import gevent.monkey

if isinstance(self.monkey, dict):
gevent.monkey.patch_all(**self.monkey)
elif self.monkey:
gevent.monkey.patch_all()

if self.monkey_greenlet_report:
import logging

original_report = gevent.hub.Hub.print_exception

def print_exception(self, context, type, value, tb):
Expand All @@ -70,6 +73,7 @@ def print_exception(self, context, type, value, tb):

def _setup_gevent_signals(self):
from gevent.signal import signal as gevent_signal

if self.gevent_signal_map is None:
gevent_signal(signal.SIGTERM, self.terminate)
return
Expand Down
27 changes: 13 additions & 14 deletions maildump_runner/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,17 +40,20 @@ def main():
parser.add_argument('--db', metavar='PATH', help='SQLite database - in-memory if missing')
parser.add_argument('--htpasswd', metavar='HTPASSWD', help='Apache-style htpasswd file')
parser.add_argument('-v', '--version', help='Display the version and exit', action='store_true')
parser.add_argument('-f', '--foreground', help='Run in the foreground (default if no pid file is specified)',
action='store_true')
parser.add_argument(
'-f', '--foreground', help='Run in the foreground (default if no pid file is specified)', action='store_true'
)
parser.add_argument('-d', '--debug', help='Run the web app in debug mode', action='store_true')
parser.add_argument('-n', '--no-quit', help='Do not allow clients to terminate the application',
action='store_true')
parser.add_argument(
'-n', '--no-quit', help='Do not allow clients to terminate the application', action='store_true'
)
parser.add_argument('-p', '--pidfile', help='Use a PID file')
parser.add_argument('--stop', help='Sends SIGTERM to the running daemon (needs --pidfile)', action='store_true')
args = parser.parse_args()

if args.version:
from maildump.util import get_version

print('MailDump {0}'.format(get_version()))
sys.exit(0)

Expand Down Expand Up @@ -89,16 +92,14 @@ def main():
print('Htpasswd file does not exist')
sys.exit(1)

daemon_kw = {'monkey_greenlet_report': False,
'signal_map': {signal.SIGTERM: terminate_server,
signal.SIGINT: terminate_server}}
daemon_kw = {
'monkey_greenlet_report': False,
'signal_map': {signal.SIGTERM: terminate_server, signal.SIGINT: terminate_server},
}

if args.foreground:
# Do not detach and keep std streams open
daemon_kw.update({'detach_process': False,
'stdin': sys.stdin,
'stdout': sys.stdout,
'stderr': sys.stderr})
daemon_kw.update({'detach_process': False, 'stdin': sys.stdin, 'stdout': sys.stdout, 'stderr': sys.stderr})

pidfile = None
if args.pidfile:
Expand Down Expand Up @@ -144,9 +145,7 @@ def main():
app.config['MAILDUMP_NO_QUIT'] = args.no_quit

level = logbook.DEBUG if args.debug else logbook.INFO
format_string = (
u'[{record.time:%Y-%m-%d %H:%M:%S}] {record.level_name:<8} {record.channel}: {record.message}'
)
format_string = u'[{record.time:%Y-%m-%d %H:%M:%S}] {record.level_name:<8} {record.channel}: {record.message}'
stderr_handler = ColorizedStderrHandler(level=level, format_string=format_string)
with NullHandler().applicationbound():
with stderr_handler.applicationbound():
Expand Down

0 comments on commit f9ca6d6

Please sign in to comment.