cammiechat/chat.py

158 lines
4.4 KiB
Python
Raw Normal View History

2018-12-04 20:07:17 +01:00
#!/bin/false
# Don't run directly, use gunicorn
from flask import Flask, request, escape, render_template
2019-10-08 02:21:36 +02:00
from flask_socketio import SocketIO, emit, send
2018-12-04 20:07:17 +01:00
import subprocess
import json
from datetime import datetime
from collections import defaultdict
import mpd
2019-08-02 20:34:45 +02:00
from urllib.parse import urlencode
2019-08-02 20:45:33 +02:00
import urllib.request
2019-08-02 20:38:56 +02:00
import base64
2022-02-28 19:55:51 +01:00
import requests
from dataclasses import dataclass
2018-12-04 20:07:17 +01:00
mpc = mpd.MPDClient()
mpc.timeout = 0.2
app = Flask(__name__, static_url_path='/static')
2019-10-08 03:46:04 +02:00
# This is fine
socketio = SocketIO(app, cors_allowed_origins='*')
2018-12-04 20:07:17 +01:00
messages = []
last_sent = defaultdict(lambda: datetime(1970,1,1))
timeout = 1
@dataclass
2018-12-04 20:07:17 +01:00
class Message:
time: datetime
sender: str
sendertype: str
msg: str
2018-12-04 20:07:17 +01:00
@app.route("/messages/")
def messages_get():
try:
mpc.connect("localhost", 6600)
song = mpc.currentsong()
status = mpc.status()
except:
status = {"state": "not connected"}
song = {}
try:
mpc.disconnect()
except:
pass
return render_template("message_os.html", messages=messages, mpd_song=song, mpd_status=status)
2018-12-04 20:07:17 +01:00
2019-10-08 02:21:36 +02:00
@app.route("/reply/", methods = ["POST"])
def reply_post():
if request.data:
if "X-Username" in request.headers:
sender = request.headers["X-Username"]
sendertype = "name"
elif "X-Real-IP" in request.headers:
sender = request.headers["X-Real-IP"]
sendertype = "ip"
else:
sender = "somebody"
sendertype = "unknown"
if sender[:6] == "abefor":
sender = "abeforkelder"
time = datetime.now()
last_sent_from_ip = last_sent[sendertype + sender]
last_sent[sendertype + sender] = time
if (time-last_sent_from_ip).total_seconds() < timeout:
return "OK Felix"
message = request.data.decode()
if len(message) > 200:
return "Message too long, maximum 200"
if not message:
return "No message found"
socketio.emit('replymessage', {'message': message}, broadcast=True)
2021-09-27 15:17:31 +02:00
return "Message sent\n"
return "Failed\n"
2018-12-04 20:07:17 +01:00
@app.route("/messages/", methods = ["POST"])
def messages_post():
if request.data:
if "X-Username" in request.headers:
sender = request.headers["X-Username"]
sendertype = "name"
elif "X-Real-IP" in request.headers:
sender = request.headers["X-Real-IP"]
sendertype = "ip"
else:
sender = "somebody"
sendertype = "unknown"
if sender[:6] == "abefor":
sender = "abeforkelder"
time = datetime.now()
last_sent_from_ip = last_sent[sendertype + sender]
last_sent[sendertype + sender] = time
if (time-last_sent_from_ip).total_seconds() < timeout:
return "OK Felix"
2019-09-03 01:05:40 +02:00
message = request.data.decode()
2018-12-04 20:07:17 +01:00
if len(message) > 200:
return "Message too long, maximum 200"
2019-09-03 00:36:39 +02:00
if not message:
2018-12-04 20:07:17 +01:00
return "No message found"
2019-09-03 01:05:40 +02:00
if "spam" in message.lower():
2018-12-04 20:07:17 +01:00
messages.append(Message(time, "1.3.3.7", "ip", "Nee"))
2018-12-04 21:01:57 +01:00
return "OK"
2019-09-03 00:27:49 +02:00
2019-09-03 01:05:40 +02:00
# Save message to serve it in this application
messages.append(Message(time, sender, sendertype, message))
# Send message to MessageOS
msg_with_sendr: str = "<{}> {}".format(sender, message) if sender != "somebody" else message
msg_b64 = base64.b64encode(msg_with_sendr.encode())
2019-08-02 20:34:45 +02:00
2019-09-03 01:05:40 +02:00
url = "http://10.0.5.42:8000/" # Set destination URL here
post_fields = {"X-Messages": msg_b64}
2019-08-02 20:46:53 +02:00
assembly_request = urllib.request.Request(url, urlencode(post_fields).encode())
2019-09-03 01:05:40 +02:00
assembly_request.add_header("X-Messages", msg_b64)
2019-08-02 20:46:53 +02:00
urllib.request.urlopen(assembly_request).read().decode()
2022-02-28 19:55:51 +01:00
try:
requests.put("http://10.0.0.10/api/mailbox.json", json={"topic": "morsemessage", "message": msg_with_sendr})
except:
pass
2018-12-04 20:07:17 +01:00
return "OK"
2022-02-28 19:58:51 +01:00
# make sure only messages from the last hour are sent
# this command also only sends messages the user doesn't have yet.
@app.route('/<last_index>/api.json')
def api(last_index):
curr_time = datetime.now()
ci = len(messages)-1
while curr_time - messages[ci].time < datetime.timedelta(hours = 1) and ci > last_index:
ci -= 1
return jsonify({"newest_msg_index": len(messages) , "messages": messages[ci:]})
2018-12-04 20:07:17 +01:00
if __name__ == "__main__":
2019-10-08 02:21:36 +02:00
socketio.run(app)