1
0
Fork 0
matrix-appservice-minecraft/service.py

251 lines
9.0 KiB
Python

import argparse
import base64
import io
import json
import logging
import re
import threading
import time
from typing import Dict
import urllib
from matrix_client.api import MatrixHttpApi
import PIL
import requests
import flask
import message_queue
LOG = logging.getLogger(__name__)
USER_RE = re.compile(r"(?<=\@).*(?=\:)")
global_msg_queue = None
app = flask.Flask(__name__)
roomsync = set()
@app.route("/transactions/<transaction>", methods=["PUT"])
def on_receive_events(transaction):
global global_msg_queue
LOG.info("got event")
events = flask.request.get_json()["events"]
for event in events:
LOG.info("User: %s Room: %s" % (event["user_id"], event["room_id"]))
LOG.info("Event Type: %s" % event["type"])
LOG.info("Content: %s" % event["content"])
roomsync.add(event["room_id"])
if (
event["type"] == "m.room.message"
and event["content"]["msgtype"] == "m.text"
and event["user_id"].find("@mc_") == -1
):
m_user = USER_RE.search(event["user_id"]).group(0)
m_cont = event["content"]["body"]
m_user, m_cont
if global_msg_queue is not None:
global_msg_queue.add({
"command":
'/tellraw @a {"text":"<' + m_user + '> ' + m_cont + '","insertion":"/tellraw @p %s"}',
})
else:
LOG.warning("No message queue available")
return flask.jsonify({})
@app.route("/rooms/<room>", methods=["GET"])
def on_room(room):
LOG.info("returning: " + str(room))
return flask.jsonify({})
class Appservice:
def __init__(self, appservice_token: str, matrix_server_name: str):
self.api = MatrixHttpApi(
"http://localhost:8008", token=appservice_token
)
self.avatar_update_log: Dict[str, float] = {}
self.matrix_server_name = matrix_server_name
def process_message(self, msg):
# for msg, create user and post as user
# add minecraft user to minecraft channel, if this fails, no big deal
try:
new_user = "mc_" + msg["user"]
user_id = "@{}:{}".format(new_user, self.matrix_server_name)
LOG.info("trying to create user {}...".format(new_user))
self.api.register(
{"type": "m.login.application_service", "username": new_user}
)
except Exception as e:
LOG.exception(e)
# for each room we're aware of, post server chat inside. Eventually 1 room should equal 1 server
for room in roomsync:
# generate a unique transaction id based on the current time
txn_id = str(int(time.time() * 1000))
# attempt to join room
LOG.info("trying to join room as user and as bridge manager")
self.api._send(
"POST",
"/rooms/" + room + "/join",
query_params={"user_id": user_id},
headers={"Content-Type": "application/json"},
)
self.api._send(
"POST",
"/rooms/" + room + "/join",
headers={"Content-Type": "application/json"},
)
# set our display name to something nice
LOG.info("trying to set display name...")
self.api._send(
"PUT",
"/profile/" + user_id + "/displayname/",
content={"displayname": msg["user"]},
query_params={"user_id": user_id},
headers={"Content-Type": "application/json"},
)
# get our mc skin!!
# backup: #avatar_url = "https://www.minecraftskinstealer.com/face.php?u="+msg['user']
# only get this if the user hasn't updated in a long time
try:
LOG.info("Checking if we need to update avatar...")
if (
msg["user"] not in self.avatar_update_log.keys()
or abs(self.avatar_update_log[msg["user"]] - time.time())
> 180
):
self.avatar_update_log[msg["user"]] = time.time()
avatar_url = self.get_mc_skin(msg["user"], user_id)
if avatar_url:
LOG.debug("avatar_url is " + avatar_url)
self.api._send(
"PUT",
"/profile/" + user_id + "/avatar_url/",
content={"avatar_url": avatar_url},
query_params={"user_id": user_id},
headers={"Content-Type": "application/json"},
)
except Exception as e:
LOG.exception(e)
# Not the end of the world if it fails, send the message now.
# attempt to post in room
LOG.info("Attempting to post in Room")
self.api._send(
"PUT",
"/rooms/" + room + "/send/m.room.message/" + txn_id,
content={"msgtype": "m.text", "body": msg["msg"]},
query_params={"user_id": user_id},
headers={"Content-Type": "application/json"},
)
def get_mc_skin(self, user, user_id):
LOG.info("Getting Minecraft Avatar")
mojang_info = requests.get(
"https://api.mojang.com/users/profiles/minecraft/" + user
).json() # get uuid
mojang_info = requests.get(
"https://sessionserver.mojang.com/session/minecraft/profile/"
+ mojang_info["id"]
).json() # get more info from uuid
mojang_info = json.loads(
base64.b64decode(mojang_info["properties"][0]["value"])
)
mojang_url = mojang_info["textures"]["SKIN"]["url"]
# r = requests.get(mojang_url, stream=True)
# r.raw.decode_content = True # handle spurious Content-Encoding
file = io.BytesIO(urllib.request.urlopen(mojang_url).read())
im = PIL.Image.open(file)
img_head = im.crop((8, 8, 16, 16))
img_head = img_head.resize(
(im.width * 8, im.height * 8), resample=PIL.Image.NEAREST
) # Resize with nearest neighbor to get pixels
image_buffer_head = io.BytesIO()
img_head.save(image_buffer_head, "PNG")
# compare to user's current id so we're not uploading the same pic twice
# GET /_matrix/client/r0/profile/{userId}/avatar_url
LOG.info("Getting Current Avatar URL")
curr_url = self.api._send(
"GET",
"/profile/" + user_id + "/avatar_url/",
query_params={"user_id": user_id},
headers={"Content-Type": "application/json"},
)
upload = True
if "avatar_url" in curr_url.keys():
LOG.info("Checking Avatar...")
file = io.BytesIO(
urllib.request.urlopen(
self.api.get_download_url(curr_url["avatar_url"])
).read()
)
im = PIL.Image.open(file)
image_buffer_curr = io.BytesIO()
im.save(image_buffer_curr, "PNG")
if (image_buffer_head.getvalue()) == (image_buffer_curr.getvalue()):
LOG.debug("Image Same")
upload = False
if upload:
# upload img
# POST /_matrix/media/r0/upload
LOG.debug("Returning updated avatar")
LOG.debug(image_buffer_head)
return self.api.media_upload(
image_buffer_head.getvalue(), "image/png"
)["content_uri"]
else:
return None
def receive_messages(
appservice: Appservice, msg_queue: message_queue.MessageQueue
):
for message in msg_queue:
appservice.process_message(message)
def main():
global global_msg_queue
logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument("--matrix_server_name", required=True)
parser.add_argument("--appservice_token", required=True)
parser.add_argument("--matrix_api_port", type=int, default=5000)
parser.add_argument("--minecraft_wrapper_port", type=int, default=5001)
args = parser.parse_args()
LOG.info("Running Minecraft Matrix Bridge")
appservice = Appservice(
appservice_token=args.appservice_token,
matrix_server_name=args.matrix_server_name,
)
global_msg_queue = message_queue.MessageQueue(
host="0.0.0.0",
port=args.minecraft_wrapper_port,
side=message_queue.Side.SERVER,
)
flask_thread = threading.Thread(
target=app.run, kwargs={"port": args.matrix_api_port}, daemon=True,
)
receive_worker = threading.Thread(
target=receive_messages, args=(appservice, global_msg_queue), daemon=True,
)
flask_thread.start()
receive_worker.start()
LOG.info("All threads created")
receive_worker.join()
flask_thread.join()
global_msg_queue.close()
LOG.info("All threads terminated")
if __name__ == "__main__":
main()