You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Comrad/komrade/backend/switchboard.py

85 lines
2.5 KiB
Python

4 years ago
# internal imports
import os,sys; sys.path.append(os.path.abspath(os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__),'..')),'..')))
from komrade import *
4 years ago
from komrade.backend import *
4 years ago
# external imports
from flask import Flask, request, jsonify
from flask_classful import FlaskView
OPERATOR = None
4 years ago
TELEPHONE = None
4 years ago
from flask_classful import FlaskView, route
4 years ago
class TheSwitchboard(FlaskView, Logger):
4 years ago
default_methods = ['GET']
excluded_methods = ['phone','op']
@property
def phone(self):
global TELEPHONE
4 years ago
from komrade.backend.the_telephone import TheTelephone
4 years ago
if not TELEPHONE: TELEPHONE=TheTelephone()
return TELEPHONE
@property
def op(self):
global OPERATOR
4 years ago
from komrade.backend.the_operator import TheOperator
4 years ago
if not OPERATOR: OPERATOR=TheOperator()
return OPERATOR
4 years ago
4 years ago
def get(self,msg):
4 years ago
self.log('Incoming call!:',msg)
4 years ago
if not msg:
self.log('empty request!')
return OPERATOR_INTERCEPT_MESSAGE
4 years ago
4 years ago
# unenescape
msg = msg.replace('_','/')
4 years ago
if not isBase64(msg):
self.log('not valid input!')
return OPERATOR_INTERCEPT_MESSAGE
4 years ago
encr_b64_str = msg
4 years ago
4 years ago
# first try to get from string to bytes
self.log('incoming <--',encr_b64_str)
try:
4 years ago
encr_b64_b = encr_b64_str.encode('utf-8')
4 years ago
self.log('encr_b64_b',encr_b64_b)
4 years ago
except UnicodeEncodeError:
self.log('not valid unicode?')
4 years ago
return OPERATOR_INTERCEPT_MESSAGE
4 years ago
# then try to get from b64 bytes to raw bytes
4 years ago
try:
data = b64decode(encr_b64_b)
self.log('data',data)
self.log(f'successfully understood input')
except binascii.Error as e:
self.log('not valid b64?')
return OPERATOR_INTERCEPT_MESSAGE
4 years ago
4 years ago
# # step 3: give to The Operator
4 years ago
try:
4 years ago
# return 'Success! your message was: '+str(data)
4 years ago
res = self.op.receive(data)
4 years ago
return res
4 years ago
except AssertionError as e:
4 years ago
self.log('got exception!!',e)
return OPERATOR_INTERCEPT_MESSAGE
4 years ago
# return response to caller
4 years ago
return OPERATOR_INTERCEPT_MESSAGE
4 years ago
def run_forever(port='8080'):
4 years ago
global OPERATOR,TELEPHONE
TELEPHONE = TheTelephone(allow_builtin=False)
4 years ago
OPERATOR = TheOperator(allow_builtin=False)
4 years ago
app = Flask(__name__)
4 years ago
TheSwitchboard.register(app, route_base='/op/', route_prefix=None)
4 years ago
app.run(debug=True, port=port, host='0.0.0.0')