<commit_before>from flask import g, has_request_context, request, current_app
from frasco.ext import *
from frasco.users import is_user_logged_in, current_user
from frasco.models import delayed_tx_calls
from frasco.ctx import ContextStack
from frasco.assets import expose_package
from itsdangerous import URLSafeTimedSerializer
from redis import StrictRedis
import hashlib
import logging
import subprocess
import sys
import pickle
import uuid
import click


suppress_push_events = ContextStack(False, default_item=True, ignore_nested=True)
dont_skip_self_push_events = ContextStack(False, default_item=True, ignore_nested=True)
logger = logging.getLogger('frasco.push')


class FrascoPushState(ExtensionState):
    def __init__(self, *args, **kwargs):
        super(FrascoPushState, self).__init__(*args, **kwargs)
        self.current_user_loader = default_current_user_loader


class FrascoPush(Extension):
    name = 'frasco_push'
    state_class = FrascoPushState
    defaults = {"redis_url": None,
                "server_url": None,
                "server_port": 8888,
                "server_secured": False,
                "channel": "socketio",
                "secret": None,
                "prefix_event_with_room": True,
                "default_current_user_loader": True}

    def _init_app(self, app, state):
        expose_package(app, "frasco_push", __name__)
        
        if state.options['secret'] is None:
            state.options["secret"] = app.config['SECRET_KEY']
        
        if not state.options['redis_url'] and has_extension('frasco_redis', app):
            state.options['redis_url'] = app.extensions.frasco_redis.options['url']

        state.server_cli = ["python", "-m", "frasco.push.server",
            "--channel", state.options["channel"],
            "--redis", state.options["redis_url"],
            "--port", str(state.options["server_port"])]
        if state.options['secret']:
            state.server_cli.extend(["--secret", state.options["secret"]])
        if app.debug or app.testing:
            state.server_cli.append("--debug")

        if state.options["server_url"]:
            state.server_url = state.options['server_url']
        else:
            server_name = app.config.get('SERVER_NAME') or 'localhost'
            state.server_url = "%s://%s:%s" % (
                "https" if state.options['server_secured'] else "http",
                server_name.split(':')[0], state.options['server_port'])

        state.token_serializer = URLSafeTimedSerializer(state.options['secret'])
        state.redis = StrictRedis.from_url(state.options["redis_url"])
        state.host_id = uuid.uuid4().hex

        @app.cli.command('push-server')
        @click.option('--access-logs', is_flag=True)
        def cli_server(access_logs=False):
            """Start the push server"""
            args = list(state.server_cli)
            if access_logs:
                args.append("--access-logs")
            process = subprocess.Popen(args)
            process.wait()
            sys.exit(process.returncode)

        @app.cli.command('push-server-cli')
        def cli_print_cmd():
            """Print the command line to start the push server independently from the app"""
            click.echo(" ".join(state.server_cli))

        @app.before_request
        def before_request():
            if state.options['secret']:
                user_id, user_info, allowed_rooms = state.current_user_loader()
                g.socketio_token = create_push_token(user_info, get_user_room_name(user_id), allowed_rooms)

    @ext_stateful_method
    def current_user_loader(self, state, func):
        state.current_user_loader = func
        return func


def default_current_user_loader():
    if not is_user_logged_in():
        return None, {"guest": True}, None<commit_msg>[push] Added--debug option to push-server command<commit_after>from flask import g, has_request_context, request, current_app
from frasco.ext import *
from frasco.users import is_user_logged_in, current_user
from frasco.models import delayed_tx_calls
from frasco.ctx import ContextStack
from frasco.assets import expose_package
from itsdangerous import URLSafeTimedSerializer
from redis import StrictRedis
import hashlib
import logging
import subprocess
import sys
import pickle
import uuid
import click


suppress_push_events = ContextStack(False, default_item=True, ignore_nested=True)
dont_skip_self_push_events = ContextStack(False, default_item=True, ignore_nested=True)
logger = logging.getLogger('frasco.push')


class FrascoPushState(ExtensionState):
    def __init__(self, *args, **kwargs):
        super(FrascoPushState, self).__init__(*args, **kwargs)
        self.current_user_loader = default_current_user_loader


class FrascoPush(Extension):
    name = 'frasco_push'
    state_class = FrascoPushState
    defaults = {"redis_url": None,
                "server_url": None,
                "server_port": 8888,
                "server_secured": False,
                "channel": "socketio",
                "secret": None,
                "prefix_event_with_room": True,
                "default_current_user_loader": True}

    def _init_app(self, app, state):
        expose_package(app, "frasco_push", __name__)
        
        if state.options['secret'] is None:
            state.options["secret"] = app.config['SECRET_KEY']
        
        if not state.options['redis_url'] and has_extension('frasco_redis', app):
            state.options['redis_url'] = app.extensions.frasco_redis.options['url']

        state.server_cli = ["python", "-m", "frasco.push.server",
            "--channel", state.options["channel"],
            "--redis", state.options["redis_url"],
            "--port", str(state.options["server_port"])]
        if state.options['secret']:
            state.server_cli.extend(["--secret", state.options["secret"]])
        if app.debug or app.testing:
            state.server_cli.append("--debug")

        if state.options["server_url"]:
            state.server_url = state.options['server_url']
        else:
            server_name = app.config.get('SERVER_NAME') or 'localhost'
            state.server_url = "%s://%s:%s" % (
                "https" if state.options['server_secured'] else "http",
                server_name.split(':')[0], state.options['server_port'])

        state.token_serializer = URLSafeTimedSerializer(state.options['secret'])
        state.redis = StrictRedis.from_url(state.options["redis_url"])
        state.host_id = uuid.uuid4().hex

        @app.cli.command('push-server')
        @click.option('--access-logs', is_flag=True)
        @click.option('--debug', is_flag=True)
        def cli_server(access_logs=False, debug=False):
            """Start the push server"""
            args = list(state.server_cli)
            if access_logs:
                args.append("--access-logs")
            if debug:
                args.append("--debug")
            process = subprocess.Popen(args)
            process.wait()
            sys.exit(process.returncode)

        @app.cli.command('push-server-cli')
        def cli_print_cmd():
            """Print the command line to start the push server independently from the app"""
            click.echo(" ".join(state.server_cli))

        @app.before_request
        def before_request():
            if state.options['secret']:
                user_id, user_info, allowed_rooms = state.current_user_loader()
                g.socketio_token = create_push_token(user_info, get_user_room_name(user_id), allowed_rooms)

    @ext_stateful_method
    def current_user_loader(self, state, func):
        state.current_user_loader = func
        return func


def default_current_user_loader():
    if not is_user_logged_in():
        return None, {"guest": True}, None
{'fraction_non_alphanumeric': 0.11750415547883902, 'fraction_numerical': 0.0015343306482546988, 'mean_word_length': 2.7769193626267503, 'pattern_counts': {'":': 18, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3183602', 'n_tokens_mistral': 2338, 'n_tokens_neox': 2278, 'n_words': 460}