From 28749be207b4788a9911734349f1c4b5a26c8173 Mon Sep 17 00:00:00 2001 From: Joe Tretter Date: Thu, 29 Oct 2020 16:24:53 -0500 Subject: [PATCH] first version? --- api1.py | 73 ++++++++++++++++++++++++++++++++++----------- createDB.sql | 1 + deadswitch.sqlite3 | Bin 8192 -> 0 bytes mail.py | 1 - 4 files changed, 57 insertions(+), 18 deletions(-) create mode 100644 createDB.sql delete mode 100644 deadswitch.sqlite3 diff --git a/api1.py b/api1.py index 5bd784c..8ec6b9b 100644 --- a/api1.py +++ b/api1.py @@ -1,12 +1,18 @@ import flask +import sys from flask import request, jsonify, g from flask_apscheduler import APScheduler from datetime import datetime,timedelta,timezone import sqlite3 +import smtplib +# testing: +# start dummy web server for dev with root: python3 -m smtpd -c DebuggingServer -n localhost:25 + +# Request: +# curl -X POST "http://localhost:5000/api/v1?topic=abc.def&secs=60&email=j.tretter@gmail.com" DATABASE='deadswitch.sqlite3' - class Config(object): JOBS = [ { @@ -19,18 +25,33 @@ class Config(object): SCHEDULER_API_ENABLED = True +def sendMail(topic,toAddr): + print(f"sending mail to {toAddr} for topic {topic}") + port = 25 + server=smtplib.SMTP("localhost", port) + sender_email = "deadswitch@kawomi.com" + receiver_email = "joerg.tretter@gmail.com" + message = f"""\ + Subject: deadSwitch not pushed on topic {topic} + + Notification of deadSwitch not pushed on topic {topic}.""" + server.sendmail(sender_email, receiver_email, message) + def expiryCheck(): - print('LA ') + print('.',end='') db=sqlite3.connect(DATABASE,detect_types=sqlite3.PARSE_DECLTYPES) cursor = db.cursor() - for theRow in cursor.execute("select expiry,topic from entries where expiry < datetime()"): + for theRow in cursor.execute("select expiry,topic,email from entries where active=True and isNotified=False and expiry < datetime()"): print(theRow) + sendMail(theRow[1],theRow[2]) + db.execute("update entries set isNotified=True where topic=?",[theRow[1]]) + db.commit() db.close() if __name__ == '__main__': app = flask.Flask(__name__) - app.config["DEBUG"] = True + app.config["DEBUG"] = False app.config.from_object(Config()) scheduler = APScheduler() @@ -54,7 +75,15 @@ if __name__ == '__main__': @app.route('/', methods=['GET']) def home(): - return "

Hello

" + return """

Dead-Switch web service

+
+

2020-10-29 - j.tretter@gmail.com

+
+ Examples: + """ @app.route('/api/v1', methods=['GET']) @@ -62,33 +91,43 @@ if __name__ == '__main__': if 'topic' in request.args: topic=request.args['topic'] else: - return "Error: need topic" + return jsonify({'success':False, 'error':"No topic given"}) cursor = get_db().cursor() - cursor.execute("select expiry from entries where topic=?",[topic]) - expdatetime=cursor.fetchone()[0] + cursor.execute("select active,expiry,email,isNotified,expiryGET" + topic + ": " + expdatetime.strftime("%Y-%m-%d %H:%M:%S") + return jsonify({'success':True, 'topic':topic, 'active':theRow[0], 'expiry':theRow[1].strftime("%Y-%m-%d %H:%M:%S"), 'lastSeen':theRow[5].strftime("%Y-%m-%d %H:%M:%S"),'isExpired':theRow[4],'email':theRow[2], 'isNotified':theRow[3]}) @app.route('/api/v1', methods=['PUT','POST']) def api_setRecord(): if 'topic' in request.args: topic = request.args['topic'] else: - return "Error: need topic" - + return jsonify({'success':False, 'error':"No topic given"}) + + if 'email' in request.args: + email = request.args['email'] + else: + return jsonify({'success':False, 'error':"No email given"}) + if 'secs' in request.args: secs = int(request.args['secs']) else: - return "Errof: need secs" + return jsonify({'success':False, 'error':"No secs given"}) expiryDateTime=datetime.now(tz=timezone.utc) + timedelta(seconds=secs) - cursor = get_db().cursor() - cursor.execute("update entries set expiry=? where topic=?",[expiryDateTime,topic]) - if cursor.rowcount == 0: - cursor.execute("Insert into entries (topic,expiry) values (?,?)",[topic,expiryDateTime]) + try: + cursor = get_db().cursor() + cursor.execute("update entries set active=True,isNotified=False,email=?,expiry=?,lastSeen=datetime('now') where topic=?",[email,expiryDateTime,topic]) + if cursor.rowcount == 0: + cursor.execute("Insert into entries (active,topic,expiry,email,isNotified,lastSeen) values (True,?,?,?,False,datetime('now'))",[topic,expiryDateTime,email]) + except Exception as e: + return jsonify({'success':False, 'error':str(e)}) - return "

SET

" + expiryDateTime.strftime("%Y-%m-%d %H:%M:%S") + return jsonify({'success':True, 'expiry':expiryDateTime.strftime("%Y-%m-%d %H:%M:%S"), 'email':email}) app.run(use_reloader=False) \ No newline at end of file diff --git a/createDB.sql b/createDB.sql new file mode 100644 index 0000000..1896fa2 --- /dev/null +++ b/createDB.sql @@ -0,0 +1 @@ +CREATE TABLE entries (active boolean,topic string,email string, expiry timestamp, isNotified boolean, lastSeen timestamp); \ No newline at end of file diff --git a/deadswitch.sqlite3 b/deadswitch.sqlite3 deleted file mode 100644 index d9838bc41c905dd84591a76f4a2e5812b0d6432f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8192 zcmeI#!D<3A5C-6h7H^_A4||zowYp@pB6crU%ifey^#xXqCD7GnH=sUMU&c${rV(A} zrFiY(9}?zI7zli~EZ(QaYToYiG_f2~lZ2obW+E4fDsGomb>X2rxGsL>zhaa8(Rcka z-1s85P!NCs1Rwwb2tWV=5P$##AOHaf+!uHgwU+0JgH2YSTJLObba88y*Lgf%#=IO) zrZL|x`O)q(v*yB0?moJ#kD19&Y)z^Qo1|I$`ZqsQ<9z>dOh5nv5P$##AOHafKmY;| tfB*y_@P7n4qUz0()!N_at&&Ri0@+hT4xXd1AIZ>HLC_zlCn+N-e*o2qFLM9@ diff --git a/mail.py b/mail.py index 385919f..dd35776 100644 --- a/mail.py +++ b/mail.py @@ -1,7 +1,6 @@ import smtplib port = 25 - server=smtplib.SMTP("localhost", port) sender_email = "deadswitch@kawomi.com" receiver_email = "joerg.tretter@gmail.com"