sms-receiver/frontend/frontend.py
2019-07-29 11:50:35 +02:00

55 lines
1.9 KiB
Python

import sqlite3, time, uuid, json
from flask import Flask, request, render_template, jsonify
conn = sqlite3.connect('texts.db', check_same_thread=False)
conn.row_factory = sqlite3.Row
def load_config():
with open('config/api.json') as config:
api = json.load(config)
config = {
"api": api
}
return config
config = load_config()
app = Flask(__name__)
@app.route('/', methods=['GET'])
def index():
numbers = conn.execute('SELECT (SELECT body FROM public_messages WHERE `to` = msisdn ORDER BY timestamp), (SELECT `from` FROM public_messages WHERE `to` = msisdn ORDER BY timestamp), * FROM public_numbers;').fetchall()
return render_template('index.html', numbers=numbers)
@app.route('/public/<uid>', methods=['GET'])
def show_public(uid):
num = conn.execute("SELECT msisdn, country FROM public_numbers WHERE uid = ?;", [uid]).fetchone()
if num is None:
return 'Not found', 404
messages = conn.execute("SELECT * FROM public_messages WHERE `to` = ?;", [num['msisdn']]).fetchall()
return render_template('messages.html', num=num, messages=messages);
@app.route('/api/receive', methods=['PUT'])
def receive():
message = request.get_json()
if 'key' not in message or message['key'] != config["api"]["key"]:
return 'Forbidden', 403
numbers = list()
for n in conn.execute('SELECT msisdn FROM public_numbers;').fetchall():
numbers.append(n[0])
if message['msisdn'] not in numbers:
conn.execute('INSERT INTO public_numbers (uid, msisdn, country) VALUES (?, ?, ?);', (str(uuid.uuid4()), message['msisdn'], 'it'))
conn.commit()
try:
conn.execute('INSERT INTO public_messages (uid, `to`, `from`, body, `timestamp`) VALUES (?, ?, ?, ?, ?);', [str(uuid.uuid4()), message['msisdn'], message['from'], message['text'], int(time.time())])
conn.commit()
return jsonify('Ok'), 200
if __name__ == "__main__":
app.run()