2020-10-28 15:20:03 -05:00
|
|
|
import flask
|
2020-10-29 16:24:53 -05:00
|
|
|
import sys
|
2021-04-13 19:10:03 -05:00
|
|
|
from flask import request, jsonify, g, make_response
|
2020-10-28 15:20:03 -05:00
|
|
|
from flask_apscheduler import APScheduler
|
|
|
|
|
from datetime import datetime,timedelta,timezone
|
|
|
|
|
import sqlite3
|
2020-10-29 16:24:53 -05:00
|
|
|
import smtplib
|
2022-01-11 19:33:18 -06:00
|
|
|
from telethon.sync import TelegramClient
|
2022-01-12 19:46:05 -06:00
|
|
|
import asyncio
|
2020-10-28 15:20:03 -05:00
|
|
|
|
2020-10-29 16:24:53 -05:00
|
|
|
# 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"
|
2020-10-28 15:20:03 -05:00
|
|
|
DATABASE='deadswitch.sqlite3'
|
|
|
|
|
|
|
|
|
|
class Config(object):
|
|
|
|
|
JOBS = [
|
|
|
|
|
{
|
|
|
|
|
'id': 'job1',
|
|
|
|
|
'func': 'api1:expiryCheck',
|
|
|
|
|
'trigger': 'interval',
|
|
|
|
|
'seconds': 10
|
|
|
|
|
}
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
SCHEDULER_API_ENABLED = True
|
|
|
|
|
|
2022-06-17 16:45:19 -05:00
|
|
|
def sendSelfTelegram(message,toId):
|
2022-01-11 19:33:18 -06:00
|
|
|
print(f"sending telegram message to myself")
|
|
|
|
|
# get your api_id, api_hash, token
|
|
|
|
|
# from telegram as described above
|
|
|
|
|
api_id = '2452309'
|
|
|
|
|
api_hash = '4cc6a58946508e59547d15d530a421ae'
|
|
|
|
|
|
|
|
|
|
# your phone number
|
|
|
|
|
phone = '+13616553044'
|
|
|
|
|
|
|
|
|
|
# creating a telegram session and assigning
|
|
|
|
|
# it to a variable client
|
|
|
|
|
client = TelegramClient('session', api_id, api_hash)
|
|
|
|
|
|
|
|
|
|
# connecting and building the session
|
|
|
|
|
client.connect()
|
|
|
|
|
|
|
|
|
|
# in case of script ran first time it will
|
|
|
|
|
# ask either to input token or otp sent to
|
|
|
|
|
# number or sent or your telegram id
|
|
|
|
|
if not client.is_user_authorized():
|
|
|
|
|
client.send_code_request(phone)
|
|
|
|
|
|
|
|
|
|
# signing in the client
|
|
|
|
|
client.sign_in(phone, input('Enter the code: '))
|
|
|
|
|
try:
|
2022-06-17 16:45:19 -05:00
|
|
|
client.send_message(toId, message, parse_mode='html')
|
2022-01-11 19:33:18 -06:00
|
|
|
except Exception as e:
|
|
|
|
|
# there may be many error coming in while like peer
|
|
|
|
|
# error, wwrong access_hash, flood_error, etc
|
|
|
|
|
print(e);
|
|
|
|
|
|
|
|
|
|
# disconnecting the telegram session
|
|
|
|
|
client.disconnect()
|
|
|
|
|
|
|
|
|
|
|
2022-06-17 16:45:19 -05:00
|
|
|
def sendNotification(topic,toAddr):
|
2020-10-29 16:24:53 -05:00
|
|
|
print(f"sending mail to {toAddr} for topic {topic}")
|
|
|
|
|
port = 25
|
|
|
|
|
server=smtplib.SMTP("localhost", port)
|
|
|
|
|
sender_email = "deadswitch@kawomi.com"
|
2020-11-02 12:03:28 -06:00
|
|
|
receiver_email = toAddr
|
2021-01-07 18:51:33 -06:00
|
|
|
message = f"""Subject: deadSwitch not pushed on topic {topic}\n\nNotification of deadSwitch not pushed on topic {topic}.
|
|
|
|
|
|
|
|
|
|
https://deadswitch.kawomi.com/api/v1?topic={topic}
|
|
|
|
|
|
|
|
|
|
"""
|
2022-06-17 16:45:19 -05:00
|
|
|
sendSelfTelegram(message, 5070349790)
|
|
|
|
|
|
|
|
|
|
if not "@" in toAddr:
|
|
|
|
|
print(f"not sending mail - {toAddr} not an email-address.")
|
|
|
|
|
return False
|
2020-10-29 16:24:53 -05:00
|
|
|
server.sendmail(sender_email, receiver_email, message)
|
|
|
|
|
|
2020-10-28 15:20:03 -05:00
|
|
|
def expiryCheck():
|
2022-01-12 19:46:05 -06:00
|
|
|
asyncio.set_event_loop(asyncio.SelectorEventLoop())
|
2020-10-29 16:24:53 -05:00
|
|
|
print('.',end='')
|
2020-10-28 15:20:03 -05:00
|
|
|
db=sqlite3.connect(DATABASE,detect_types=sqlite3.PARSE_DECLTYPES)
|
|
|
|
|
cursor = db.cursor()
|
2020-10-29 16:24:53 -05:00
|
|
|
for theRow in cursor.execute("select expiry,topic,email from entries where active=True and isNotified=False and expiry < datetime()"):
|
2020-10-28 15:20:03 -05:00
|
|
|
print(theRow)
|
2020-12-17 08:20:59 -06:00
|
|
|
for theEmailAddr in theRow[2].split(','):
|
2022-06-17 16:45:19 -05:00
|
|
|
sendNotification(theRow[1],theEmailAddr)
|
2020-10-29 16:24:53 -05:00
|
|
|
db.execute("update entries set isNotified=True where topic=?",[theRow[1]])
|
|
|
|
|
db.commit()
|
2020-10-28 15:20:03 -05:00
|
|
|
db.close()
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
|
app = flask.Flask(__name__)
|
2020-10-29 16:24:53 -05:00
|
|
|
app.config["DEBUG"] = False
|
2020-10-28 15:20:03 -05:00
|
|
|
|
|
|
|
|
app.config.from_object(Config())
|
|
|
|
|
scheduler = APScheduler()
|
|
|
|
|
# it is also possible to enable the API directly
|
|
|
|
|
# scheduler.api_enabled = True
|
|
|
|
|
scheduler.init_app(app)
|
|
|
|
|
scheduler.start()
|
|
|
|
|
|
|
|
|
|
def get_db():
|
|
|
|
|
db = getattr(g, '_database', None)
|
|
|
|
|
if db is None:
|
|
|
|
|
db = g._database = sqlite3.connect(DATABASE,detect_types=sqlite3.PARSE_DECLTYPES)
|
|
|
|
|
return db
|
|
|
|
|
|
|
|
|
|
@app.teardown_appcontext
|
|
|
|
|
def close_connection(exception):
|
|
|
|
|
db = getattr(g, '_database', None)
|
|
|
|
|
if db is not None:
|
|
|
|
|
db.commit()
|
|
|
|
|
db.close()
|
|
|
|
|
|
|
|
|
|
@app.route('/', methods=['GET'])
|
|
|
|
|
def home():
|
2020-10-29 16:24:53 -05:00
|
|
|
return """<h1>Dead-Switch web service</h1>
|
|
|
|
|
<hr>
|
2022-01-17 17:40:35 -06:00
|
|
|
<h2>2020-10-29 - joe@kawomi.com</h2>
|
2020-10-29 16:24:53 -05:00
|
|
|
<hr>
|
|
|
|
|
Examples:
|
|
|
|
|
<ul>
|
|
|
|
|
<li>curl "https://deadswitch.kawomi.com/api/v1?topic=sys.demo"</li>
|
2022-01-17 17:40:35 -06:00
|
|
|
<li>curl -d "" -X POST "https://deadswitch.kawomi.com/api/v1?topic=sys.demo&secs=60&email=joe@kawomi.com"</li>
|
2020-10-29 16:24:53 -05:00
|
|
|
</ul>"""
|
2020-10-28 15:20:03 -05:00
|
|
|
|
|
|
|
|
|
2021-04-13 19:10:03 -05:00
|
|
|
@app.route('/api/v1', methods=['OPTIONS'])
|
|
|
|
|
def api_returnOptions():
|
|
|
|
|
response = make_response()
|
|
|
|
|
response.headers.add("Access-Control-Allow-Origin", "*")
|
|
|
|
|
response.headers.add('Access-Control-Allow-Headers', "*")
|
|
|
|
|
response.headers.add('Access-Control-Allow-Methods', "*")
|
|
|
|
|
return response
|
|
|
|
|
|
2020-10-28 15:20:03 -05:00
|
|
|
@app.route('/api/v1', methods=['GET'])
|
|
|
|
|
def api_getByTopic():
|
|
|
|
|
if 'topic' in request.args:
|
|
|
|
|
topic=request.args['topic']
|
|
|
|
|
else:
|
2020-10-29 16:24:53 -05:00
|
|
|
return jsonify({'success':False, 'error':"No topic given"})
|
2020-10-28 15:20:03 -05:00
|
|
|
|
|
|
|
|
cursor = get_db().cursor()
|
2020-10-29 16:24:53 -05:00
|
|
|
cursor.execute("select active,expiry,email,isNotified,expiry<datetime('now') \"isExpired\",lastSeen from entries where topic=?",[topic])
|
|
|
|
|
theRow=cursor.fetchone()
|
|
|
|
|
if theRow is None:
|
|
|
|
|
return jsonify({'success':False, 'error':f"No entry found for topic _{topic}_"})
|
2020-10-28 15:20:03 -05:00
|
|
|
|
2021-04-13 19:10:03 -05:00
|
|
|
return _corsify_actual_response(jsonify({'success':True, 'topic':topic, 'active':bool(theRow[0]), 'expiry':theRow[1].strftime("%Y-%m-%d %H:%M:%S"), 'lastSeen':theRow[5].strftime("%Y-%m-%d %H:%M:%S"),'isExpired':bool(theRow[4]),'email':theRow[2], 'isNotified':bool(theRow[3])}))
|
2020-10-28 15:20:03 -05:00
|
|
|
|
|
|
|
|
@app.route('/api/v1', methods=['PUT','POST'])
|
|
|
|
|
def api_setRecord():
|
|
|
|
|
if 'topic' in request.args:
|
|
|
|
|
topic = request.args['topic']
|
|
|
|
|
else:
|
2020-10-29 16:24:53 -05:00
|
|
|
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"})
|
|
|
|
|
|
2020-10-28 15:20:03 -05:00
|
|
|
if 'secs' in request.args:
|
|
|
|
|
secs = int(request.args['secs'])
|
|
|
|
|
else:
|
2020-10-29 16:24:53 -05:00
|
|
|
return jsonify({'success':False, 'error':"No secs given"})
|
2020-10-28 15:20:03 -05:00
|
|
|
|
|
|
|
|
expiryDateTime=datetime.now(tz=timezone.utc) + timedelta(seconds=secs)
|
|
|
|
|
|
2020-10-29 16:24:53 -05:00
|
|
|
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)})
|
2020-10-28 15:20:03 -05:00
|
|
|
|
2020-10-29 16:24:53 -05:00
|
|
|
return jsonify({'success':True, 'expiry':expiryDateTime.strftime("%Y-%m-%d %H:%M:%S"), 'email':email})
|
2020-10-28 15:20:03 -05:00
|
|
|
|
2021-04-13 19:10:03 -05:00
|
|
|
def _corsify_actual_response(response):
|
|
|
|
|
response.headers.add("Access-Control-Allow-Origin", "*")
|
|
|
|
|
return response
|
|
|
|
|
|
2020-10-29 18:24:01 -05:00
|
|
|
app.run(use_reloader=False,port=5123)
|