anonkun/events.py

119 lines
2.3 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
"""
SocketIO events.
"""
import time
import random
import bleach
2018-06-21 20:44:43 -04:00
from flask import session
from flask_socketio import SocketIO, emit, join_room
2018-06-25 15:52:10 -04:00
import tools
import database as db
socketio = SocketIO()
@socketio.on('joined')
def joined(data):
"""
Sent by clients when they enter a room.
"""
room = data["room"]
join_room(room)
@socketio.on('message')
def message(data):
"""
Sent by a client when the user entered a new message.
"""
room = data["room"]
message = data["message"]
date = int(time.time())
data["date"] = date
message = message.strip()
if not message:
return
tags = ["b", "code", "i", "s"]
message = bleach.clean(message, tags=tags)
lines = []
for line in message.splitlines():
if line.startswith(">"):
line = '<span class="greenText">' + line + '</span>'
lines.append(line)
message = "<br />".join(lines)
2018-06-25 15:52:10 -04:00
message = tools.handle_img(message)
data["message"] = message
2018-06-17 21:10:41 -04:00
db.log_chat_message(data)
emit("message", data, room=room)
@socketio.on("new_post")
def new_post(data):
"""
Called when the QM makes a new post.
"""
room = data["room"]
2018-06-21 20:44:43 -04:00
res = db.get_quest_meta(quest_id=room)
if not res:
return
if session.get("user_id") != res[3]:
return
2018-06-21 20:44:43 -04:00
post = data["post"]
post = bleach.clean(post.strip())
post = post.replace("\n", "<br />")
post = tools.handle_img(post)
data["post"] = [post]
data["date"] = int(time.time())
post_id = db.insert_quest_post(room, post, data["date"])
data["post_id"] = post_id
emit("new_post", data, room=room)
2018-06-21 20:44:43 -04:00
@socketio.on("update_post")
def update_post(data):
"""
Called when the QM edits and saves a post.
"""
room = data["room"]
res = db.get_quest_meta(quest_id=room)
if not res:
return
if session.get("user_id") != res[3]:
return
post = data["post"]
2018-06-21 22:49:25 -04:00
post = post.strip().replace("<br>", "<br />")
post = tools.handle_img(post)
2018-06-21 22:49:25 -04:00
data["post"] = post
2018-06-21 20:44:43 -04:00
post_id = data["post_id"]
db.update_quest_post(post_id, post)
emit("update_post", data, room=room)
@socketio.on("dice_post")
def dice_(data):
"""
Called when the QM posts a new dice call.
"""
print(data)
room = data["room"]
res = db.get_quest_meta(quest_id=room)
if not res:
return
if session.get("user_id") != res[3]:
return
date = int(time.time())
data["date"] = date
data["post_id"] = 0
emit("dice_post", data, room=room)