rate limit survive script restart

This commit is contained in:
jb-alvarado 2019-11-25 22:59:34 +01:00
parent a4c15d9aff
commit 08ac2fac83

View File

@ -31,6 +31,7 @@ import smtplib
import socket import socket
import ssl import ssl
import sys import sys
import tempfile
import time import time
from argparse import ArgumentParser from argparse import ArgumentParser
from datetime import date, datetime, timedelta from datetime import date, datetime, timedelta
@ -366,14 +367,18 @@ class Mailer:
self.level = _mail.level self.level = _mail.level
self.time = None self.time = None
self.timestamp = get_time('stamp') self.timestamp = get_time('stamp')
self.last_error = None
self.rate_limit = 600 self.rate_limit = 600
self.temp_msg = os.path.join(tempfile.gettempdir(), 'ffplayout.txt')
def current_time(self): def current_time(self):
self.time = get_time(None) self.time = get_time(None)
def send_mail(self, msg): def send_mail(self, msg):
if _mail.recip: if _mail.recip:
# write message to temp file for rate limit
with open(self.temp_msg, 'w+') as f:
f.write(msg)
self.current_time() self.current_time()
message = MIMEMultipart() message = MIMEMultipart()
@ -402,25 +407,31 @@ class Mailer:
server.sendmail(_mail.s_addr, _mail.recip, text) server.sendmail(_mail.s_addr, _mail.recip, text)
server.quit() server.quit()
def send_if_new(self, msg): def check_if_new(self, msg):
# send messege only when is new or the rate_limit is pass # send messege only when is new or the rate_limit is pass
if msg != self.last_error \ if os.path.isfile(self.temp_msg):
or get_time('stamp') - self.timestamp > self.rate_limit: mod_time = os.path.getmtime(self.temp_msg)
with open(self.temp_msg, 'r', encoding='utf-8') as f:
last_msg = f.read()
if msg != last_msg \
or get_time('stamp') - mod_time > self.rate_limit:
self.send_mail(msg)
else:
self.send_mail(msg) self.send_mail(msg)
self.timestamp = get_time('stamp')
self.last_error = msg
def info(self, msg): def info(self, msg):
if self.level in ['INFO']: if self.level in ['INFO']:
self.send_if_new(msg) self.check_if_new(msg)
def warning(self, msg): def warning(self, msg):
if self.level in ['INFO', 'WARNING']: if self.level in ['INFO', 'WARNING']:
self.send_if_new(msg) self.check_if_new(msg)
def error(self, msg): def error(self, msg):
if self.level in ['INFO', 'WARNING', 'ERROR']: if self.level in ['INFO', 'WARNING', 'ERROR']:
self.send_if_new(msg) self.check_if_new(msg)
class Messenger: class Messenger: