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 urllib.parse import urlparse
from matrix_client.api import MatrixHttpApi from matrix_client.api import MatrixHttpApi
import PIL
import requests import requests
from flask import Flask, jsonify, request from flask import Flask, jsonify, request
@ -29,7 +30,7 @@ global_config = {}
# #
app = Flask(__name__) app = Flask(__name__)
minecraft = None minecraft = None
roomsync = {} roomsync = set()
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@ -86,8 +87,9 @@ class socket_util(object):
offset += self.soc.send(data[offset:]) offset += self.soc.send(data[offset:])
def receive(self): def receive(self):
if self.soc.fileno() < 0:
self.socket_reset()
r,s,e = select.select([self.soc], [], [], 1) r,s,e = select.select([self.soc], [], [], 1)
LOG.debug("r: {!r}".format(r))
if r == []: if r == []:
return "" return ""
message_size = self.read_int() message_size = self.read_int()
@ -211,11 +213,12 @@ class MinecraftServerBridge(socket_util):
minecraft_bind_host: int, minecraft_bind_host: int,
minecraft_bind_port: int, minecraft_bind_port: int,
matrix_bind_port: int, matrix_bind_port: int,
appservice_token: str appservice_token: str,
server_name: str
): ):
#starting threads #starting threads
LOG.info ("Starting Appservice Webserver") 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.daemon = True
flask_thread.start() flask_thread.start()
@ -223,10 +226,10 @@ class MinecraftServerBridge(socket_util):
super().__init__(minecraft_bind_host, minecraft_bind_port) super().__init__(minecraft_bind_host, minecraft_bind_port)
LOG.info ("Calling Matrix Api") LOG.info ("Calling Matrix Api")
self.api = MatrixHttpApi("http://localhost:8008", token=appservice_token) self.api = MatrixHttpApi("http://localhost:8008", token=appservice_token)
self.user_re = re.compile("(?<=\@).*(?=\:)")
self.avatar_update_log = {} self.avatar_update_log = {}
LOG.info ("Finished Init") LOG.info ("Finished Init")
self.server_name = server_name
def socket_reset(self): def socket_reset(self):
super().socket_reset() super().socket_reset()
@ -239,8 +242,8 @@ class MinecraftServerBridge(socket_util):
except OSError as e: except OSError as e:
if e.errno == 98: if e.errno == 98:
LOG.warning( LOG.warning(
"Unable to bind to port {}, trying again in {} seconds".format( "Unable to bind to port {}: {}, trying again in {} seconds".format(
self.port, backoff self.port, e.msg, backoff
) )
) )
time.sleep(backoff) time.sleep(backoff)
@ -262,6 +265,7 @@ class MinecraftServerBridge(socket_util):
if status == 0: self.msglist.pop() if status == 0: self.msglist.pop()
rcv = self.receive() rcv = self.receive()
if rcv != "" and rcv != None: if rcv != "" and rcv != None:
LOG.debug(rcv)
self.msg_handle(rcv) self.msg_handle(rcv)
except Exception as e: except Exception as e:
LOG.exception(e) LOG.exception(e)
@ -271,10 +275,13 @@ class MinecraftServerBridge(socket_util):
#for msg, create user and post as user #for msg, create user and post as user
#add minecraft user to minecraft channel, if this fails, no big deal #add minecraft user to minecraft channel, if this fails, no big deal
try: try:
LOG.info("trying to create id...") new_user = "mc_" + msg['user']
new_user = "@mc_" + msg['user'] user_id = "@{}:{}".format(new_user, self.server_name)
user_id = new_user + ":" + global_config['server_name'] LOG.info("trying to create user {}...".format(new_user))
self.api.register("m.login.application_service",username = "mc_" + msg['user']) self.api.register({
"type": "m.login.application_service",
"username": new_user,
})
except Exception as e: except Exception as e:
LOG.exception(e) LOG.exception(e)
#for each room we're aware of, post server chat inside. Eventually 1 room should equal 1 server #for each room we're aware of, post server chat inside. Eventually 1 room should equal 1 server
@ -292,13 +299,17 @@ class MinecraftServerBridge(socket_util):
#get our mc skin!! #get our mc skin!!
#backup: #avatar_url = "https://www.minecraftskinstealer.com/face.php?u="+msg['user'] #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 #only get this if the user hasn't updated in a long time
LOG.info("Checking if we need to update avatar...") try:
if msg['user'] not in self.avatar_update_log.keys() or abs(self.avatar_update_log[msg['user']] - time.time()) > 180: LOG.info("Checking if we need to update avatar...")
self.avatar_update_log[msg['user']] = time.time() if msg['user'] not in self.avatar_update_log.keys() or abs(self.avatar_update_log[msg['user']] - time.time()) > 180:
avatar_url = self.get_mc_skin(msg['user'], user_id) self.avatar_update_log[msg['user']] = time.time()
if avatar_url: avatar_url = self.get_mc_skin(msg['user'], user_id)
LOG.debug("avatar_url is " + avatar_url) if 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"}) 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 #attempt to post in room
LOG.info("Attempting 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'] mojang_url = mojang_info['textures']['SKIN']['url']
#r = requests.get(mojang_url, stream=True) #r = requests.get(mojang_url, stream=True)
#r.raw.decode_content = True # handle spurious Content-Encoding #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) im = Image.open(file)
img_head = im.crop((8,8,16,16)) 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() image_buffer_head = io.BytesIO()
img_head.save(image_buffer_head, "PNG") img_head.save(image_buffer_head, "PNG")
@ -326,7 +338,7 @@ class MinecraftServerBridge(socket_util):
upload = True upload = True
if 'avatar_url' in curr_url.keys(): if 'avatar_url' in curr_url.keys():
LOG.info("Checking Avatar...") 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) im = Image.open(file)
image_buffer_curr = io.BytesIO() image_buffer_curr = io.BytesIO()
im.save(image_buffer_curr, "PNG") im.save(image_buffer_curr, "PNG")
@ -342,6 +354,7 @@ class MinecraftServerBridge(socket_util):
else: else:
return None return None
USER_RE = re.compile("(?<=\@).*(?=\:)")
@app.route("/transactions/<transaction>", methods=["PUT"]) @app.route("/transactions/<transaction>", methods=["PUT"])
def on_receive_events(transaction): 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("User: %s Room: %s" % (event["user_id"], event["room_id"]))
LOG.info("Event Type: %s" % event["type"]) LOG.info("Event Type: %s" % event["type"])
LOG.info("Content: %s" % event["content"]) LOG.info("Content: %s" % event["content"])
roomsync[event["room_id"]] = "" roomsync.add(event["room_id"])
if event['type'] == 'm.room.message' and \ if event['type'] == 'm.room.message' and \
event['content']['msgtype'] == 'm.text' and \ event['content']['msgtype'] == 'm.text' and \
event["user_id"].find("@mc_") == -1: 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'] 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({}) return jsonify({})
@ -425,6 +438,7 @@ def main():
minecraft_bind_port=global_config['bridge_mcdata_port'], minecraft_bind_port=global_config['bridge_mcdata_port'],
matrix_bind_port=global_config["bridge_matrixapi_port"], matrix_bind_port=global_config["bridge_matrixapi_port"],
appservice_token=global_config["as_token"], appservice_token=global_config["as_token"],
server_name=global_config["server_name"],
) )
LOG.info("All Threads Running") LOG.info("All Threads Running")
while (not minecraft.exit): while (not minecraft.exit):
@ -436,4 +450,4 @@ def main():
if __name__ == "__main__": if __name__ == "__main__":
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 flask
requests requests
matrix_client matrix_client
pillow