Ejemplo n.º 1
0
    def __init__(self):
        self.sio = Server(logger=False)
        self.sio.on('connect', self.connect)
        self.sio.on('disconnect', self.disconnect)
        self.sio.on('list_room', self.list_room)
        self.sio.on('join_room', self.join_room)
        self.sio.on('leave_room', self.leave_room)
        self.sio.on('ready', self.ready)
        self.sio.on('command', self.command)

        self.connections: List[PlayerConnection] = []
Ejemplo n.º 2
0
class FlaskRunner(SimpleFlaskRunner):
    def __init__(self,
                 m2m_app,
                 host="127.0.0.1",
                 port=None,
                 listen_on="0.0.0.0",
                 *args,
                 **kw):
        super(FlaskRunner, self).__init__(m2m_app=m2m_app,
                                          host=host,
                                          port=port,
                                          listen_on=listen_on,
                                          *args,
                                          **kw)

        @self.flask_app.route("/")
        def home():
            return redirect(url_for('static', filename='motor.html'))

        self.sio_app = SioServer(async_mode='gevent')

        @self.sio_app.on('connect')
        def connect(sid, environ):
            self.logger.debug('client connected: %s' % sid)

    def _get_server(self):
        return WSGIServer((self.listen_on, self.port),
                          SioMiddleware(self.sio_app, self.flask_app),
                          handler_class=WebSocketHandler)

    def emit(self, event, message=None, sid=None):
        self.sio_app.emit(event, message, room=sid)

    def get_handler_decorator(self, name):
        return self.sio_app.on(name)

    def add_message_handler(self, name, handler, client=False, response=False):
        def wrapper(*args, **kw):
            if not client:
                args = args[1:]
            if response:
                return handler(*args, **kw)
            else:
                handler(*args, **kw)

        self.sio_app.on(name, wrapper)
Ejemplo n.º 3
0
    def __init__(self, m2m_app, port=None, listen_on="0.0.0.0", *args, **kw):
        super(FlaskRunner, self).__init__(m2m_app=m2m_app, port=port,
                                          listen_on=listen_on, *args, **kw)

        @self.flask_app.route("/")
        def home():
            return redirect(url_for('static', filename='index.html'))

        self.sio_app = SioServer(async_mode='gevent')

        @self.sio_app.on('connect')
        def connect(sid, environ):
            self.logger.debug('client connected: %s' % sid)
Ejemplo n.º 4
0
    if endpoint == 'static':
        filename = values.get('filename', None)
        if filename:
            file_path = os.path.join(app.static_folder, filename)
            values['q'] = int(os.stat(file_path).st_mtime)
    return url_for(endpoint, **values)


@app.context_processor
def override_url_for():
    return dict(url_for=dated_url_for)


@app.route('/', methods=["GET", "POST"])
def index():
    return render_template("index.html")


# Create SocketIO Server
sio = Server(async_mode="threading",
             logger=app.logger,
             engineio_logger=app.logger)
sio.register_namespace(ChatNamespace(sio, '/chat'))

# Set SocketIO WSGI Application
app.wsgi_app = WSGIApp(sio, app.wsgi_app)

if __name__ == "__main__":
    dotenv.load_dotenv(dotenv_path=".env")

    app.run(host="localhost", port=3000, threaded=True)
Ejemplo n.º 5
0
import os
import socketio
from socketio import AsyncServer, Server
import logging
import eventlet.wsgi

from werkzeug.middleware.proxy_fix import ProxyFix

sio = Server(async_mode="eventlet", logger=True)


# So now we have an action list for the server at least - forget multiple sessions for now?
@sio.event
def connect(sid, environ):
    print("connection attempted")


app = app = ProxyFix(socketio.WSGIApp(sio), x_for=1, x_proto=1)

# default to 0.0.0.0
eventlet.wsgi.server(eventlet.listen(('', 8000)), app)
Ejemplo n.º 6
0
from socketio import RedisManager, Server

from django.conf import settings


mgr = RedisManager(settings.REDIS_URL)  # , write_only=True)

sio = Server(client_manager=mgr, cors_allowed_origins='*')


def _emit(event_name, sid, data):
    return sio.emit(event_name, data, to=sid)


def emit_error(sid, data):
    return _emit('error', sid, data)


def emit_my_event(sid, data):
    return _emit('my_event', sid, data)
Ejemplo n.º 7
0
    def is_authenticated(self):
        return self.authenticated

def num(a):
    b = format(Decimal(str(a)).normalize(), 'f')
    print (a,"->",b)

def format(a):
    a =  '{0:.10f}'.format(a)
    return a




app = Flask(__name__)
sio =  Server(app)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RTXXS'
cors = CORS(app)
app.config['SESSION_TYPE'] = 'filesystem'
sess = Session(app)
login_manager = LoginManager()
login_manager.init_app(app)



BITTREX = ccxt.bittrex()
print(BITTREX.balance)
BTC = BITTREX.fetch_ticker("BTC/USDT")['last']
ETH = BITTREX.fetch_ticker("ETH/USDT")['last']
LTC = BITTREX.fetch_ticker("LTC/USDT")['last']
XRP = BITTREX.fetch_ticker("XRP/USDT")['last']
Ejemplo n.º 8
0
class ParcheesiServer:

    MAX_CAPACITY = 100

    def __init__(self):
        self.sio = Server(logger=False)
        self.sio.on('connect', self.connect)
        self.sio.on('disconnect', self.disconnect)
        self.sio.on('list_room', self.list_room)
        self.sio.on('join_room', self.join_room)
        self.sio.on('leave_room', self.leave_room)
        self.sio.on('ready', self.ready)
        self.sio.on('command', self.command)

        self.connections: List[PlayerConnection] = []

    def connect(self, sid, env, auth):
        print('connect', sid, auth)
        if auth is None:
            return False

        if 'username' not in auth.keys():
            return False

        if len(self.connections) < self.MAX_CAPACITY:
            connection = PlayerConnection(self.sio, sid, auth['username'])
            self.connections.append(connection)
            self.sio.save_session(sid, {
                'connection': connection,
                'room_name': None,
            })
            return True

        return False

    def disconnect(self, sid):
        print('disconnect ', sid)
        session = self.sio.get_session(sid)
        connection = session['connection']
        room_name = session['room_name']
        self.connections.remove(connection)
        if room_name is not None:
            GameRoomDB.leave(connection, room_name)

    def list_room(self, sid):
        data = list(GameRoomDB.rooms.keys())
        return data

    def join_room(self, sid, room_name):
        session = self.sio.get_session(sid)
        if session['room_name'] is not None:
            return _ack(IsInRoomError(session['room_name']))

        connection = session['connection']
        status = GameRoomDB.join(connection, room_name)
        if status.ok():
            session['room_name'] = room_name
        return _ack(status)

    def leave_room(self, sid):
        session = self.sio.get_session(sid)
        connection = session['connection']
        room_name = session['room_name']
        if room_name is None:
            return _ack(Status(-1, 'Not in a room'))

        GameRoomDB.leave(connection, room_name)
        session['room_name'] = None
        return _ack(NoError())

    def ready(self, sid):
        session = self.sio.get_session(sid)
        room_name = session['room_name']
        if room_name is None:
            return _ack(Status(-1, 'Not in a room'))

        room = GameRoomDB.rooms[room_name]
        if room.is_playing:
            return _ack(IsPlayingError())

        room.ready(session['connection'])

        if room.is_able_to_start():
            self.sio.start_background_task(room.start)

        return _ack(NoError())

    def command(self, sid, command_str):
        session = self.sio.get_session(sid)
        connection = session['connection']
        game = GameRoomDB.rooms.get(session['room_name'], None)
        if game is None:
            return _ack(Status(-1, 'Game is None'))

        status = game.receive_command(connection, command_str)
        return _ack(status)

    def listen(self, host='localhost', port=5050):
        app = WSGIApp(self.sio)
        eventlet.wsgi.server(eventlet.listen((host, port)), app)
Ejemplo n.º 9
0
from config import HOST, PORT, DEBUG
from db_helper.models import MESSAGE_STATUS
from db_helper.dao import set_user_info, get_user_info, update_user_online_info, active_user_list, \
    get_user_message, save_send_message, update_message_ack
from helpers import get_dict, set_json, get_session_key, get_server_socket
from response_helper import failed_response, success_response, user_list_response, buyer_receive_ack_response, \
    new_message_response, sent_ack_response, receive_ack_response, register_response, send_info_response
from trace import trace_info, trace_debug
"""
TODO:: Auto Scale System Notification Implement.
Possible Solution Can be pass Server IP and make a internal emit to trigger.
"""

basicConfig(level=CRITICAL)

sio = Server()

if DEBUG:
    app = WSGIApp(
        sio,
        static_files={
            '/': 'Client.html',
            '/socket.io.js': 'socket.io.js',
            # '/static/style.css': 'static/style.css',
        })
else:
    app = WSGIApp(sio)

SCOPE_WHITE_LIST = {"telemesh"}

USER_SESSION = dict()
Ejemplo n.º 10
0
def create_sio():
  sio = Server(async_mode="threading")
  sio.register_namespace(UpbitNamespace(sio, '/upbit'))
  
  return sio
  
Ejemplo n.º 11
0
def run(config=None,
        plugin_providers=None,
        product_name='ajenti',
        dev_mode=False,
        debug_mode=False,
        autologin=False):
    """
    A global entry point for Ajenti.

    :param config: config file implementation instance to use
    :type  config: :class:`aj.config.BaseConfig`
    :param plugin_providers: list of plugin providers to load plugins from
    :type  plugin_providers: list(:class:`aj.plugins.PluginProvider`)
    :param str product_name: a product name to use
    :param bool dev_mode: enables dev mode (automatic resource recompilation)
    :param bool debug_mode: enables debug mode (verbose and extra logging)
    :param bool autologin: disables authentication and logs everyone in as the user running the panel. This is EXTREMELY INSECURE.
    """
    if config is None:
        raise TypeError('`config` can\'t be None')

    reload(sys)
    if hasattr(sys, 'setdefaultencoding'):
        sys.setdefaultencoding('utf8')

    aj.product = product_name
    aj.debug = debug_mode
    aj.dev = dev_mode
    aj.dev_autologin = autologin

    aj.init()
    aj.log.set_log_params(tag='master', master_pid=os.getpid())
    aj.context = Context()
    aj.config = config
    aj.plugin_providers = plugin_providers or []
    logging.info(f'Loading config from {aj.config}')
    aj.config.load()
    aj.config.ensure_structure()

    logging.info('Loading users from /etc/ajenti/users.yml')
    aj.users = AjentiUsers(aj.config.data['auth']['users_file'])
    aj.users.load()

    logging.info('Loading smtp config from /etc/ajenti/smtp.yml')
    aj.smtp_config = SmtpConfig()
    aj.smtp_config.load()
    aj.smtp_config.ensure_structure()

    if aj.debug:
        logging.warning('Debug mode')
    if aj.dev:
        logging.warning('Dev mode')

    try:
        locale.setlocale(locale.LC_ALL, '')
    except locale.Error:
        logging.warning('Couldn\'t set default locale')

    # install a passthrough gettext replacement since all localization is handled in frontend
    # and _() is here only for string extraction
    __builtins__['_'] = lambda x: x

    logging.info(f'Ajenti Core {aj.version}')
    logging.info(f'Master PID - {os.getpid()}')
    logging.info(f'Detected platform: {aj.platform} / {aj.platform_string}')
    logging.info(f'Python version: {aj.python_version}')

    # Load plugins
    PluginManager.get(aj.context).load_all_from(aj.plugin_providers)
    if len(PluginManager.get(aj.context)) == 0:
        logging.warning('No plugins were loaded!')

    if aj.config.data['bind']['mode'] == 'unix':
        path = aj.config.data['bind']['socket']
        if os.path.exists(path):
            os.unlink(path)
        listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        try:
            listener.bind(path)
        except OSError:
            logging.error(f'Could not bind to {path}')
            sys.exit(1)

    if aj.config.data['bind']['mode'] == 'tcp':
        host = aj.config.data['bind']['host']
        port = aj.config.data['bind']['port']
        listener = socket.socket(
            socket.AF_INET6 if ':' in host else socket.AF_INET,
            socket.SOCK_STREAM)
        if aj.platform not in ['freebsd', 'osx']:
            try:
                listener.setsockopt(socket.IPPROTO_TCP, socket.TCP_CORK, 1)
            except socket.error:
                logging.warning('Could not set TCP_CORK')
        listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        logging.info(f'Binding to [{host}]:{port}')
        try:
            listener.bind((host, port))
        except socket.error as e:
            logging.error(f'Could not bind: {str(e)}')
            sys.exit(1)

    listener.listen(10)

    gateway = GateMiddleware.get(aj.context)
    middleware_stack = HttpMasterMiddleware.all(aj.context) + [gateway]

    sio = Server(async_mode='gevent',
                 cors_allowed_origins=aj.config.data['trusted_domains'])
    application = WSGIApp(
        sio,
        HttpRoot(HttpMiddlewareAggregator(middleware_stack)).dispatch)
    sio.register_namespace(SocketIONamespace(context=aj.context))

    if aj.config.data['ssl']['enable'] and aj.config.data['bind'][
            'mode'] == 'tcp':
        aj.server = pywsgi.WSGIServer(
            listener,
            log=open(os.devnull, 'w'),
            application=application,
            handler_class=RequestHandler,
            policy_server=False,
        )
        aj.server.ssl_args = {'server_side': True}
        cert_path = aj.config.data['ssl']['certificate']
        if aj.config.data['ssl']['fqdn_certificate']:
            fqdn_cert_path = aj.config.data['ssl']['fqdn_certificate']
        else:
            fqdn_cert_path = cert_path

        context = gevent.ssl.SSLContext(ssl.PROTOCOL_TLS)
        context.load_cert_chain(certfile=fqdn_cert_path,
                                keyfile=fqdn_cert_path)
        context.options |= ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1
        context.set_ciphers(
            'ALL:!ADH:!EXP:!LOW:!RC2:!3DES:!SEED:!RC4:+HIGH:+MEDIUM')

        if aj.config.data['ssl']['client_auth']['enable']:

            logging.info('Enabling SSL client authentication')
            context.load_verify_locations(cafile=cert_path)
            if aj.config.data['ssl']['client_auth']['force']:
                context.verify_mode = ssl.CERT_REQUIRED
            else:
                context.verify_mode = ssl.CERT_OPTIONAL

            ## Test callback : client_certificate_callback must return None to get forward
            # context.set_servername_callback(AuthenticationService.get(aj.context).client_certificate_callback)

        aj.server.wrap_socket = lambda socket, **args: context.wrap_socket(
            sock=socket, server_side=True)
        logging.info('SSL enabled')

        if aj.config.data['ssl']['force']:
            from aj.https_redirect import http_to_https
            target_url = f'https://{aj.config.data["name"]}:{port}'
            gevent.spawn(http_to_https, target_url)
            logging.info(
                f'HTTP to HTTPS redirection activated to {target_url}')
    else:
        # No policy_server argument for http
        aj.server = pywsgi.WSGIServer(
            listener,
            log=open(os.devnull, 'w'),
            application=application,
            handler_class=RequestHandler,
        )

    # auth.log
    try:
        syslog.openlog(
            ident=str(aj.product),
            facility=syslog.LOG_AUTH,
        )
    except Exception as e:
        syslog.openlog(aj.product)

    def cleanup():
        if hasattr(cleanup, 'started'):
            return
        cleanup.started = True
        logging.info(f'Process {os.getpid()} exiting normally')
        gevent.signal_handler(signal.SIGINT, lambda: None)
        gevent.signal_handler(signal.SIGTERM, lambda: None)
        if aj.master:
            gateway.destroy()

        p = psutil.Process(os.getpid())
        for c in p.children(recursive=True):
            try:
                os.killpg(c.pid, signal.SIGTERM)
                os.killpg(c.pid, signal.SIGKILL)
            except OSError:
                pass

    def signal_handler():
        cleanup()
        sys.exit(0)

    gevent.signal_handler(signal.SIGINT, signal_handler)
    gevent.signal_handler(signal.SIGTERM, signal_handler)

    aj.server.serve_forever()

    if not aj.master:
        # child process, server is stopped, wait until killed
        gevent.wait()

    if hasattr(aj.server, 'restart_marker'):
        logging.warning('Restarting by request')
        cleanup()

        fd = 20  # Close all descriptors. Creepy thing
        while fd > 2:
            try:
                os.close(fd)
                logging.debug(f'Closed descriptor #{fd:d}')
            except OSError:
                pass
            fd -= 1

        restart()
    else:
        if aj.master:
            logging.debug('Server stopped')
            cleanup()
Ejemplo n.º 12
0
import random
import string
import time
from dominion.expansions import IntrigueExpansion, ProsperityExpansion
from dominion.game import Game
from dominion.interactions import NetworkedCLIInteraction, BrowserInteraction, AutoInteraction
from socketio import Server, WSGIApp

# socketio = Server(async_mode='eventlet', async_handlers=True, cors_allowed_origins='*')
socketio = Server(async_mode='eventlet', async_handlers=True)

static_files = {
    '/': 'static/index.html',
    '/static/socket.io.js': 'static/socket.io.js',
    '/static/socket.io.js.map': 'static/socket.io.js.map',
    '/static/client.js': 'static/client.js',
    # '/static/style.css': 'static/style.css',
}

app = WSGIApp(socketio, static_files=static_files)

# Global dictionary of games, indexed by room ID
games = {}

# Global dictionary of sids, {sid: (room, data)}
sids = {}

# Global dictionary of CPUs, indexed by room ID, {room: CPU_COUNT}
cpus = {}

Ejemplo n.º 13
0
def main():
    args = parse_args()
    logger, wsgi_logger = get_logger(args.debug)

    if args.setup:
        if platform.system() == 'Linux':
            setup(args.user)
        else:
            setup()
        sys.exit(0)
        return

    CLIENTS = {}
    DEVICES = {}

    sio = Server(logger=args.debug,
                 engineio_logger=args.debug,
                 cors_allowed_origins='*')
    app = WSGIApp(sio)

    @sio.event
    def connect(sid, environ):
        CLIENTS[sid] = environ['REMOTE_ADDR']
        logger.info(f'Client connected from {environ["REMOTE_ADDR"]}')
        logger.debug(f'Client {environ["REMOTE_ADDR"]} sessionId: {sid}')

    @sio.event
    def intro(sid, data):
        if data['id'] == 'x360':
            DEVICES[sid] = X360Device(data['device'], CLIENTS[sid])
        else:
            DEVICES[sid] = DS4Device(data['device'], CLIENTS[sid])
        logger.info(
            f'Created virtual {data["type"]} gamepad for {data["device"]} '
            f'at {CLIENTS[sid]}')

    @sio.event
    def input(sid, data):
        logger.debug(f'Received INPUT event::{data["key"]}: {data["value"]}')
        DEVICES[sid].send(data['key'], data['value'])

    @sio.event
    def disconnect(sid):
        device = DEVICES.pop(sid)
        logger.info(f'Disconnected device {device.device} at {device.address}')
        device.close()

    try:
        host = args.host or default_host()
        sock = listen((host, args.port))
    except PermissionError:
        sys.exit(f'Port {args.port} is not available. '
                 f'Please specify a different port with -p option.')
    logger.info(f'Listening on http://{host}:{args.port}/')
    logger.info(f'Frontend Port on http://{host}:{args.frontend_port}/')
    qr = qrcode.QRCode()
    qr.add_data(f'http://{host}:{args.frontend_port}/')
    if platform.system() == 'Windows':
        import colorama
        colorama.init()
    qr.print_ascii(tty=True)
    wsgi.server(sock, app, log=wsgi_logger, log_output=args.debug, debug=False)
# -*- coding: utf-8 -*-
"""
sio.py

Created on Tue Sep 17 13:01:26 2019

@author: Sarah
"""

from socketio import Server, WSGIApp
from .wsgi import application

server = Server()


@server.event
def double(sid, data):
    number = int(data.number)
    number *= 2
    server.emit('double response', {'result': number}, room=sid)


sioApp = WSGIApp(server, application)
Ejemplo n.º 15
0
from __future__ import absolute_import
from socketio import Server
from SuperFarmer import settings
from helpers.jwt import extract_socket_user
from .handlers import handlers

io = Server(logger=settings.DEBUG,
            cors_allowed_origins=settings.SOCKETIO_CORS_ALLOWED_ORIGINS)


@io.event
def connect(sid, env, auth):
    if not auth or not auth.get("token"):
        return False

    user = extract_socket_user(auth["token"])

    if not user:
        return False

    io.save_session(sid, {"id": user.id})
    return True


for handle in handlers:
    handle(io)
Ejemplo n.º 16
0
 def register_sockets(app: Server):
     app.register_namespace(Notifications('/v1/notifications', app))