|
7 | 7 | import os |
8 | 8 | import socket |
9 | 9 | import sys |
| 10 | +import threading |
10 | 11 | import traceback |
11 | 12 | from email.mime.text import MIMEText |
12 | 13 | from io import StringIO |
|
27 | 28 | # http://bugs.python.org/issue7980 |
28 | 29 | datetime.datetime.strptime("2013", "%Y") |
29 | 30 | EMAIL_TIMESTAMPS = [] |
| 31 | +EMAIL_TIMESTAMPS_LOCK = threading.Lock() |
30 | 32 |
|
31 | 33 |
|
32 | 34 | class CustomFormatter(logging.Formatter): |
@@ -126,23 +128,28 @@ def load_settings(): |
126 | 128 | cursor.close() |
127 | 129 |
|
128 | 130 |
|
129 | | -def should_email(): |
| 131 | +def should_email() -> bool: |
130 | 132 | """Prevent email bombs |
131 | 133 |
|
132 | 134 | Use the setting `pywwa_email_limit` to threshold the number of emails |
133 | 135 | permitted within the past hour |
134 | 136 |
|
135 | | - @return boolean if we should email or not |
| 137 | + Returns: |
| 138 | + bool: True if an email should be sent, False if not |
136 | 139 | """ |
137 | | - EMAIL_TIMESTAMPS.insert(0, utc()) |
138 | | - delta = EMAIL_TIMESTAMPS[0] - EMAIL_TIMESTAMPS[-1] |
139 | | - email_limit = int(SETTINGS.get("pywwa_email_limit", 10)) |
140 | | - if len(EMAIL_TIMESTAMPS) < email_limit: |
141 | | - return True |
142 | | - while len(EMAIL_TIMESTAMPS) > email_limit: |
143 | | - EMAIL_TIMESTAMPS.pop() |
144 | | - |
145 | | - return delta > datetime.timedelta(hours=1) |
| 140 | + with EMAIL_TIMESTAMPS_LOCK: |
| 141 | + # Insert current timestamp into the beginning of the list |
| 142 | + EMAIL_TIMESTAMPS.insert(0, utc()) |
| 143 | + # Figure out the amount of time from now to the end of the list |
| 144 | + delta = EMAIL_TIMESTAMPS[0] - EMAIL_TIMESTAMPS[-1] |
| 145 | + # Figure out the allowed limit over the hour interval |
| 146 | + email_limit = int(SETTINGS.get("pywwa_email_limit", 10)) |
| 147 | + if len(EMAIL_TIMESTAMPS) < email_limit: |
| 148 | + return True |
| 149 | + while len(EMAIL_TIMESTAMPS) > email_limit: |
| 150 | + EMAIL_TIMESTAMPS.pop() |
| 151 | + |
| 152 | + return delta > datetime.timedelta(hours=1) |
146 | 153 |
|
147 | 154 |
|
148 | 155 | def email_error(exp, message="", trimstr=100): |
|
0 commit comments