1
0
Fork 0

Merge branch 'master' of cybre.tech:chr/matrix-appservice-minecraft

This commit is contained in:
khr 2020-03-30 01:58:01 +00:00
commit c9fc1a37e0
2 changed files with 46 additions and 31 deletions

View File

@ -19,6 +19,7 @@ import urllib
from urllib.parse import urlparse
from matrix_client.api import MatrixHttpApi
import PIL
import requests
from flask import Flask, jsonify, request
@ -29,7 +30,7 @@ global_config = {}
#
app = Flask(__name__)
minecraft = None
roomsync = {}
roomsync = set()
LOG = logging.getLogger(__name__)
@ -80,15 +81,15 @@ class socket_util(object):
self.write(integer_buf)
def write(self, data: bytes):
#socket.bind(address)
data_len = len(data)
offset = 0
while offset != data_len:
offset += self.soc.send(data[offset:])
def receive(self):
if self.soc.fileno() < 0:
self.socket_reset()
r,s,e = select.select([self.soc], [], [], 1)
#LOG.info("r" + str(r))
if r == []:
return ""
message_size = self.read_int()
@ -96,10 +97,11 @@ class socket_util(object):
self.close_socket()
return None
data = self.read(message_size)
LOG.debug("data: {!r}".format(data))
if data == None:
LOG.debug("data_none")
LOG.debug("data was none")
return None
message = json.loads(data)
message = json.loads(data.decode("utf-8"))
return message
@ -111,7 +113,7 @@ class socket_util(object):
return struct.unpack('>i', intbuf)[0]
def read(self, size):
data = ""
data = b""
while len(data) != size:
newdata = self.soc.recv(size - len(data))
if len(newdata) == 0:
@ -163,7 +165,7 @@ class MinecraftWrapper(socket_util):
raise subprocess.CalledProcessError(return_code, self.command)
def msg_process(self):
while(not self.exit):
while not self.exit:
try:
self.proc_monitor()
status = 1
@ -211,11 +213,12 @@ class MinecraftServerBridge(socket_util):
minecraft_bind_host: int,
minecraft_bind_port: int,
matrix_bind_port: int,
appservice_token: str
appservice_token: str,
server_name: str
):
#starting threads
LOG.info ("Starting Appservice Webserver")
flask_thread = threading.Thread(target=app.run,kwargs={ "port": minecraft_bind_port })
flask_thread = threading.Thread(target=app.run,kwargs={ "port": matrix_bind_port })
flask_thread.daemon = True
flask_thread.start()
@ -223,10 +226,10 @@ class MinecraftServerBridge(socket_util):
super().__init__(minecraft_bind_host, minecraft_bind_port)
LOG.info ("Calling Matrix Api")
self.api = MatrixHttpApi("http://localhost:8008", token=appservice_token)
self.user_re = re.compile("(?<=\@).*(?=\:)")
self.avatar_update_log = {}
LOG.info ("Finished Init")
self.server_name = server_name
def socket_reset(self):
super().socket_reset()
@ -239,8 +242,8 @@ class MinecraftServerBridge(socket_util):
except OSError as e:
if e.errno == 98:
LOG.warning(
"Unable to bind to port {}, trying again in {} seconds".format(
self.port, backoff
"Unable to bind to port {}: {}, trying again in {} seconds".format(
self.port, e.msg, backoff
)
)
time.sleep(backoff)
@ -253,7 +256,6 @@ class MinecraftServerBridge(socket_util):
self.soc, self.addr = self.soc.accept()
self.soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
LOG.info("Server accepted connection: " + str(self.addr))
def msg_process(self):
while(True):
@ -263,20 +265,23 @@ class MinecraftServerBridge(socket_util):
if status == 0: self.msglist.pop()
rcv = self.receive()
if rcv != "" and rcv != None:
LOG.debug(rcv)
self.msg_handle(rcv)
except Exception as e:
LOG.info(e)
LOG.exception(e)
self.socket_reset()
def msg_handle(self, msg):
#for msg, create user and post as user
#add minecraft user to minecraft channel, if this fails, no big deal
try:
LOG.info("trying to create id...")
new_user = "@mc_" + msg['user']
user_id = new_user + ":" + global_config['server_name']
self.api.register("m.login.application_service",username = "mc_" + msg['user'])
new_user = "mc_" + msg['user']
user_id = "@{}:{}".format(new_user, self.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
@ -294,13 +299,17 @@ class MinecraftServerBridge(socket_util):
#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
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.info("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"})
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")
@ -315,9 +324,10 @@ class MinecraftServerBridge(socket_util):
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.urlopen(mojang_url).read())
file = io.BytesIO(urllib.request.urlopen(mojang_url).read())
im = 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")
@ -328,7 +338,7 @@ class MinecraftServerBridge(socket_util):
upload = True
if 'avatar_url' in curr_url.keys():
LOG.info("Checking Avatar...")
file = io.BytesIO(urllib.urlopen(self.api.get_download_url(curr_url['avatar_url'])).read())
file = io.BytesIO(urllib.request.urlopen(self.api.get_download_url(curr_url['avatar_url'])).read())
im = Image.open(file)
image_buffer_curr = io.BytesIO()
im.save(image_buffer_curr, "PNG")
@ -344,6 +354,7 @@ class MinecraftServerBridge(socket_util):
else:
return None
USER_RE = re.compile("(?<=\@).*(?=\:)")
@app.route("/transactions/<transaction>", methods=["PUT"])
def on_receive_events(transaction):
@ -353,14 +364,14 @@ def on_receive_events(transaction):
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[event["room_id"]] = ""
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 = minecraft.user_re.search(event["user_id"]).group(0)
m_user = USER_RE.search(event["user_id"]).group(0)
m_cont = event['content']['body']
minecraft.msglist.insert(0, "/tellraw @a {\"text\":\"<" + m_user + "> " + m_cont + "\",\"insertion\":\"/tellraw @p %s\"}")
# minecraft.msglist.insert(0, "/tellraw @a {\"text\":\"<" + m_user + "> " + m_cont + "\",\"insertion\":\"/tellraw @p %s\"}")
return jsonify({})
@ -427,6 +438,7 @@ def main():
minecraft_bind_port=global_config['bridge_mcdata_port'],
matrix_bind_port=global_config["bridge_matrixapi_port"],
appservice_token=global_config["as_token"],
server_name=global_config["server_name"],
)
LOG.info("All Threads Running")
while (not minecraft.exit):
@ -437,3 +449,5 @@ def main():
if __name__ == "__main__":
main()
# vim: set expandtab sw=4 ts=4 softtabstop=4:

View File

@ -1,3 +1,4 @@
flask
requests
matrix_client
pillow