1
0
Fork 0

Workinggit add requirements.txt

This commit is contained in:
khr 2020-03-29 09:00:58 +02:00
parent dd0ff125a7
commit c2ed0fda5a
2 changed files with 39 additions and 24 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__)
@ -86,8 +87,9 @@ class socket_util(object):
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.debug("r: {!r}".format(r))
if r == []:
return ""
message_size = self.read_int()
@ -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)
@ -262,6 +265,7 @@ 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.exception(e)
@ -271,10 +275,13 @@ class MinecraftServerBridge(socket_util):
#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
@ -292,6 +299,7 @@ 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
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()
@ -299,6 +307,9 @@ class MinecraftServerBridge(socket_util):
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")
@ -313,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")
@ -326,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")
@ -342,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):
@ -351,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({})
@ -425,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):
@ -436,4 +450,4 @@ def main():
if __name__ == "__main__":
main()
# vi: set expandtab sw=4 ts=4 softtabstop=4
# vim: set expandtab sw=4 ts=4 softtabstop=4:

View File

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