def test_status_handled(self):
     try:
         webpack_manifest.load(
             os.path.join(TEST_ROOT, 'test_manifest_2.json'),
             static_url='/static',
         )
         self.assertFalse('should not reach this')
     except webpack_manifest.WebpackError as e:
         self.assertEqual(
             e.message,
             'Webpack errors: \n\nerror 1\n\nerror 2',
         )
 def test_status_handled(self):
     try:
         webpack_manifest.load(
             os.path.join(TEST_ROOT, 'test_manifest_2.json'),
             static_url='/static',
         )
         self.assertFalse('should not reach this')
     except webpack_manifest.WebpackError as e:
         self.assertEqual(
             e.args[0],
             'Webpack errors: \n\nerror 1\n\nerror 2',
         )
 def test_handles_unknown_statuses(self):
     path = os.path.join(TEST_ROOT, 'test_manifest_4.json')
     try:
         webpack_manifest.load(
             path,
             static_url='/static',
         )
         self.assertFalse('should not reach this')
     except webpack_manifest.WebpackManifestStatusError as e:
         self.assertEqual(
             e.message,
             'Unknown webpack manifest status: "unknown status"',
         )
 def test_handles_unknown_statuses(self):
     path = os.path.join(TEST_ROOT, 'test_manifest_4.json')
     try:
         webpack_manifest.load(
             path,
             static_url='/static',
         )
         self.assertFalse('should not reach this')
     except webpack_manifest.WebpackManifestStatusError as e:
         self.assertEqual(
             e.args[0],
             'Unknown webpack manifest status: "unknown status"',
         )
 def test_handles_timeouts_in_debug(self):
     path = os.path.join(TEST_ROOT, 'test_manifest_3.json')
     try:
         webpack_manifest.load(
             path,
             static_url='/static',
             debug=True,
             timeout=1,
         )
         self.assertFalse('should not reach this')
     except webpack_manifest.WebpackManifestBuildingStatusTimeout as e:
         self.assertEqual(
             e.message,
             'Timed out reading the webpack manifest at "{}"'.format(path),
         )
 def test_handles_timeouts_in_debug(self):
     path = os.path.join(TEST_ROOT, 'test_manifest_3.json')
     try:
         webpack_manifest.load(
             path,
             static_url='/static',
             debug=True,
             timeout=1,
         )
         self.assertFalse('should not reach this')
     except webpack_manifest.WebpackManifestBuildingStatusTimeout as e:
         self.assertEqual(
             e.args[0],
             'Timed out reading the webpack manifest at "{}"'.format(path),
         )
Example #7
0
    def test_manifest_provide_rendered_elements(self):
        manifest = webpack_manifest.load(
            os.path.join(TEST_ROOT, 'test_manifest_1.json'),
            static_url='/static/',
        )
        self.assertEqual(manifest.main.js, '<script src="/static/foo/bar.js"></script>')
        self.assertEqual(manifest.main.css, '<link rel="stylesheet" href="/static/woz/bar.css">')

        self.assertEqual(
            manifest.foo.js,
            (
                '<script src="/static/foo/bar.js"></script>'
                '<script src="/static/woz/bar.js"></script>'
                '<script src="/static/bar/woz.js"></script>'
            )
        )
        self.assertEqual(manifest.foo.css, '')

        self.assertEqual(manifest.bar.js, '<script src="/static/bar/woz.js"></script>')
        self.assertEqual(
            manifest.bar.css,
            (
                '<link rel="stylesheet" href="/static/foo/bar.css">'
                '<link rel="stylesheet" href="/static/woz/bar.css">'
            )
        )
Example #8
0
def admin(request, ROOT_PATH=None, **kwargs):
    ROOT_PATH = ROOT_PATH or reverse('tracker:ui:admin')
    bundle = webpack_manifest.load(
        os.path.abspath(
            os.path.join(os.path.dirname(__file__),
                         '../ui-tracker.manifest.json')),
        settings.STATIC_URL,
        debug=settings.DEBUG,
        timeout=60,
        read_retry=None,
    )

    return render(
        request,
        'ui/index.html',
        {
            'event': Event.objects.latest(),
            'events': Event.objects.all(),
            'bundle': bundle.admin,
            'CONSTANTS': constants(request.user),
            'ROOT_PATH': ROOT_PATH,
            'app_name': 'AdminApp',
            'form_errors': {},
            'props': {},
        },
    )
Example #9
0
def admin(request):
    bundle = webpack_manifest.load(os.path.abspath(
        os.path.join(os.path.dirname(__file__),
                     '../ui-tracker.manifest.json')),
                                   settings.STATIC_URL,
                                   debug=settings.DEBUG,
                                   timeout=60,
                                   read_retry=None)

    return render(
        request,
        'ui/index.html',
        {
            'event':
            Event.objects.latest(),
            'events':
            Event.objects.all(),
            'bundle':
            bundle.admin,
            'root_path':
            reverse('tracker:ui:admin'),
            'app':
            'AdminApp',
            'form_errors': {},
            'props':
            mark_safe(
                json.dumps({},
                           ensure_ascii=False,
                           cls=serializers.json.DjangoJSONEncoder)),
        },
    )
Example #10
0
 def test_non_trailing_slash_static_url_handled(self):
     manifest = webpack_manifest.load(
         os.path.join(TEST_ROOT, 'test_manifest_1.json'),
         static_url='/static',
     )
     self.assertEqual(manifest.main.js, '<script src="/static/foo/bar.js"></script>')
     self.assertEqual(manifest.main.css, '<link rel="stylesheet" href="/static/woz/bar.css">')
 def test_manifest_entry_object_string_conversion(self):
     manifest = webpack_manifest.load(
         os.path.join(TEST_ROOT, 'test_manifest_1.json'),
         static_url='/static/',
     )
     self.assertEqual(str(manifest.main.js), manifest.main.js.output)
     self.assertEqual(str(manifest.main.css), manifest.main.css.output)
Example #12
0
def index(request, **kwargs):
    bundle = webpack_manifest.load(
        os.path.abspath(
            os.path.join(os.path.dirname(__file__),
                         '../ui-tracker.manifest.json')),
        settings.STATIC_URL,
        debug=settings.DEBUG,
        timeout=60,
        read_retry=None,
    )

    return render(
        request,
        'ui/index.html',
        {
            'event': Event.objects.latest(),
            'events': Event.objects.all(),
            'bundle': bundle.tracker,
            'CONSTANTS': mark_safe(json.dumps(constants())),
            'ROOT_PATH': reverse('tracker:ui:index'),
            'app': 'TrackerApp',
            'form_errors': {},
            'props': '{}',
        },
    )
Example #13
0
def index():
    manifest = webpack_manifest.load(path=os.path.join(
        sys.path[0], 'build', 'webpack_manifest.json'),
                                     static_url='/')
    js_path = manifest.javascript.rel_js[0].split('/')[-1]
    css_path = manifest.styles.rel_css[0].split('/')[-1]
    # from pdb import set_trace; set_trace()
    return render_template('index.html', js_path=js_path, css_path=css_path)
 def test_legacy_rel_urls(self):
     manifest = webpack_manifest.load(
         os.path.join(TEST_ROOT, 'test_manifest_1.json'),
         static_url='/static/',
         static_root=os.path.dirname(__file__),
     )
     self.assertEqual(manifest.foo.rel_js,
                      ['foo/bar.js', 'woz/bar.js', 'bar/woz.js'])
     self.assertEqual(manifest.bar.rel_css, ['foo/bar.css', 'woz/bar.css'])
Example #15
0
def index(request):
    webpack = bool(request.META.get('HTTP_X_WEBPACK', False))
    admin = webpack_manifest.load(
        os.path.abspath(os.path.join(os.path.dirname(__file__), 'ui-admin.manifest.json')),
        '/webpack' if webpack else settings.STATIC_URL,
        debug=settings.DEBUG,
        timeout=60,
        read_retry=None
    )

    return render(request, 'tracker_ui/index.html', context={'event': Event.objects.latest(), 'events': Event.objects.all(), 'admin': admin})
 def test_content_output(self):
     manifest = webpack_manifest.load(
         os.path.join(TEST_ROOT, 'test_manifest_1.json'),
         static_url='/static/',
         static_root=os.path.dirname(__file__),
         debug=True,
     )
     self.assertEqual(manifest.foo.js.content,
                      'foo_bar=1\n\nwoz_bar=1\n\nbar_woz=1\n')
     self.assertEqual(manifest.foo.css.content, '')
     self.assertEqual(manifest.bar.css.content,
                      '.foo_bar {}\n\n.woz_bar {}\n')
 def test_content_inline(self):
     manifest = webpack_manifest.load(
         os.path.join(TEST_ROOT, 'test_manifest_1.json'),
         static_url='/static/',
         static_root=os.path.dirname(__file__),
         debug=True,
     )
     self.assertEqual(
         manifest.foo.js.inline,
         '<script>foo_bar=1\n\nwoz_bar=1\n\nbar_woz=1\n</script>')
     self.assertEqual(manifest.foo.css.inline, '')
     self.assertEqual(manifest.bar.css.inline,
                      '<style>.foo_bar {}\n\n.woz_bar {}\n</style>')
Example #18
0
 def test_handles_missing_entries(self):
     path = os.path.join(TEST_ROOT, 'test_manifest_1.json')
     try:
         manifest = webpack_manifest.load(
             path,
             static_url='/static',
         )
         manifest.glub
         self.assertFalse('should not reach this')
     except webpack_manifest.WebpackErrorUnknownEntryError as e:
         self.assertEqual(
             e.args[0],
             'Unknown entry "glub" in manifest "%s"' % path,
         )
 def test_missing_static_root_handled(self):
     try:
         manifest = webpack_manifest.load(
             os.path.join(TEST_ROOT, 'test_manifest_1.json'),
             static_url='/static/',
             debug=True,
         )
         manifest.main.js.content
         self.assertFalse('should not reach this')
     except webpack_manifest.WebpackManifestConfigError as e:
         self.assertEqual(
             e.args[0],
             'Provide static_root to access webpack entry content.',
         )
Example #20
0
def load_webpack_manifest(name):
    if name not in settings.WEBPACK_MANIFEST['manifests']:
        raise webpack_manifest.WebpackManifestConfigError(
            '"%s" has not been defined in `WEBPACK_MANIFEST[\'manifests\']`' %
            name, )

    conf = settings.WEBPACK_MANIFEST['manifests'][name]

    for prop in ('path', 'static_url', 'static_root'):
        if prop not in conf:
            raise webpack_manifest.WebpackManifestConfigError(
                '"%s" has not been defined in `WEBPACK_MANIFEST[\'manifests\'][\'%s\']`'
                % (prop, name), )

    return webpack_manifest.load(**conf)
Example #21
0
def admin(request):
    bundle = webpack_manifest.load(
        os.path.abspath(os.path.join(os.path.dirname(
            __file__), '../ui-tracker.manifest.json')),
        settings.STATIC_URL,
        debug=settings.DEBUG,
        timeout=60,
        read_retry=None
    )

    return render(
        request,
        'ui/index.html',
        {
            'event': Event.objects.latest(),
            'events': Event.objects.all(),
            'bundle': bundle.admin,
            'root_path': reverse('tracker:ui:admin'),
            'app': 'AdminApp',
            'form_errors': {},
            'props': mark_safe(json.dumps({}, ensure_ascii=False, cls=serializers.json.DjangoJSONEncoder)),
        },
    )
Example #22
0
def create_app(config_class=config.Config, migrating=False):
    app = Flask(__name__)
    initialize_opencensus(config_class, app)

    app.config.from_object(config_class)
    db.init_app(app)
    migrate.init_app(app, db)

    # If we're being called with migrating=True then return early to allow the migration
    if migrating:
        return app

    # If a migration is needed, try to automatically handle it, otherwise bail out
    if migration_needed(
        app.config["SQLALCHEMY_DATABASE_URI"]
    ) and not handle_db_upgrade(app):
        raise RuntimeError(
            "[!] Database migration required and DB_AUTO_UPGRADE is not enabled"
        )

    app.jinja_env.add_extension("jinja2.ext.do")
    app.elastic = ElasticInterface(app.config["ELASTICSEARCH_URL"])

    login.init_app(app)
    mail.init_app(app)
    csrf.init_app(app)
    ScopeManager.init_app(app)
    app.config["webpack"] = webpack_manifest.load(
        # An absolute path to a manifest file
        path=os.path.join(
            app.config["BASEDIR"], "app", "static", "dist", "webpack_manifest.json"
        ),
        # The root url that your static assets are served from
        static_url="/static/",
    )

    with app.app_context():
        load_config_from_db(app, db)
        ScopeManager.load_all_groups()

    register_converters(app)

    from app.cli.user import cli_group as user_cli

    app.cli.add_command(user_cli)

    from app.cli.scope import cli_group as scope_cli

    app.cli.add_command(scope_cli)

    from app.errors import bp as errors_bp

    app.register_blueprint(errors_bp)

    from app.admin import bp as admin_bp

    app.register_blueprint(admin_bp, url_prefix="/admin")

    from app.api import bp as api_bp

    app.register_blueprint(api_bp, url_prefix="/api")
    csrf.exempt(api_bp)

    from app.auth import bp as auth_bp

    app.register_blueprint(auth_bp, url_prefix="/auth")

    from app.user import bp as user_bp

    app.register_blueprint(user_bp, url_prefix="/user")

    from app.host import bp as host_bp

    app.register_blueprint(host_bp, url_prefix="/host")

    from app.main import bp as main_bp

    app.register_blueprint(main_bp)

    from app.filters import bp as filters_bp

    app.register_blueprint(filters_bp)

    return app
Example #23
0
def donate(request, event):
    event = viewutil.get_event(event)
    if event.locked:
        raise Http404

    bundle = webpack_manifest.load(os.path.abspath(
        os.path.join(os.path.dirname(__file__),
                     '../ui-tracker.manifest.json')),
                                   settings.STATIC_URL,
                                   debug=settings.DEBUG,
                                   timeout=60,
                                   read_retry=None)

    commentform, bidsform, prizesform = process_form(request, event)

    if not bidsform:
        return commentform

    def bid_parent_info(bid):
        if bid != None:
            return {
                'id': bid.id,
                'name': bid.name,
                'description': bid.description,
                'parent': bid_parent_info(bid.parent),
                'custom': bid.allowuseroptions,
            }
        else:
            return None

    def bid_info(bid):
        result = {
            'id': bid.id,
            'name': bid.name,
            'description': bid.description,
            'label': bid.full_label(not bid.allowuseroptions),
            'count': bid.count,
            'amount': bid.total,
            'goal': Decimal(bid.goal or '0.00'),
            'parent': bid_parent_info(bid.parent)
        }
        if bid.speedrun:
            result['runname'] = bid.speedrun.name
        else:
            result['runname'] = 'Event Wide'
        if bid.allowuseroptions:
            result['custom'] = True
        return result

    bids = filters.run_model_query('bidtarget',
                                   {'state': 'OPENED', 'event': event.id},
                                   user=request.user) \
        .distinct().select_related('parent', 'speedrun').prefetch_related('suggestions')

    prizes = filters.run_model_query('prize', {
        'feed': 'current',
        'event': event.id
    })

    bidsArray = [bid_info(o) for o in bids]

    def prize_info(prize):
        result = {
            'id': prize.id,
            'name': prize.name,
            'description': prize.description,
            'minimumbid': prize.minimumbid,
            'sumdonations': prize.sumdonations,
            'url': reverse('tracker:prize', args=(prize.id, )),
            'image': prize.image,
        }
        return result

    prizesArray = [prize_info(o) for o in prizes.all()]

    def to_json(value):
        if hasattr(value, 'id'):
            return value.id
        return value

    initialForm = {
        k: to_json(commentform.cleaned_data[k])
        for k, v in commentform.fields.items()
        if commentform.is_bound and k in commentform.cleaned_data
    }
    pickedIncentives = [{
        k: to_json(form.cleaned_data[k])
        for k, v in form.fields.items() if k in form.cleaned_data
    } for form in bidsform.forms if form.is_bound]

    return render(
        request,
        'ui/index.html',
        {
            'event':
            event,
            'events':
            Event.objects.all(),
            'bundle':
            bundle.donate,
            'root_path':
            reverse('tracker:ui:index'),
            'app':
            'DonateApp',
            'title':
            'Donate',
            'forms': {
                'bidsform': bidsform,
                'prizesform': prizesform
            },
            'form_errors':
            mark_safe(
                json.dumps({
                    'commentform':
                    json.loads(commentform.errors.as_json()),
                    'bidsform':
                    bidsform.errors,
                })),
            'props':
            mark_safe(
                json.dumps(
                    {
                        'event':
                        json.loads(serializers.serialize(
                            'json', [event]))[0]['fields'],
                        'prizes':
                        prizesArray,
                        'incentives':
                        bidsArray,
                        'initialForm':
                        initialForm,
                        'initialIncentives':
                        pickedIncentives,
                        'donateUrl':
                        request.get_full_path(),
                        'prizesUrl':
                        request.build_absolute_uri(
                            reverse('tracker:prizeindex', args=(event.id, ))),
                        'rulesUrl':
                        'https://gamesdonequick.com/sweepstakes',  # TODO: put in settings?
                    },
                    ensure_ascii=False,
                    cls=serializers.json.DjangoJSONEncoder)),
        },
    )
Example #24
0
def donate(request, event):
    event = viewutil.get_event(event)
    if event.locked or not event.allow_donations:
        raise Http404

    bundle = webpack_manifest.load(
        os.path.abspath(
            os.path.join(os.path.dirname(__file__),
                         '../ui-tracker.manifest.json')),
        settings.STATIC_URL,
        debug=settings.DEBUG,
        timeout=60,
        read_retry=None,
    )

    commentform, bidsform = process_form(request, event)

    if not bidsform:  # redirect
        return commentform

    def bid_parent_info(bid):
        if bid is not None:
            return {
                'id': bid.id,
                'name': bid.name,
                'description': bid.description,
                'parent': bid_parent_info(bid.parent),
                'custom': bid.allowuseroptions,
            }
        else:
            return None

    def bid_info(bid):
        result = {
            'id': bid.id,
            'name': bid.name,
            'description': bid.description,
            'label': bid.full_label(not bid.allowuseroptions),
            'count': bid.count,
            'amount': bid.total,
            'goal': Decimal(bid.goal or '0.00'),
            'parent': bid_parent_info(bid.parent),
        }
        if bid.speedrun:
            result['runname'] = bid.speedrun.name
            result['order'] = bid.speedrun.order
        else:
            result['runname'] = 'Event Wide'
            result['order'] = 0
        if bid.allowuseroptions:
            result['custom'] = True
            result['maxlength'] = bid.option_max_length
        return result

    bids = search_filters.run_model_query('allbids', {
        'state': 'OPENED',
        'event': event.id
    }).select_related('parent', 'speedrun')

    prizes = search_filters.run_model_query('prize', {
        'feed': 'current',
        'event': event.id
    })

    # You have to try really hard to get into this state so it's reasonable to blow up spectacularly when it happens
    if prizes and not getattr(settings, 'SWEEPSTAKES_URL', None):
        raise ImproperlyConfigured(
            'There are prizes available but no SWEEPSTAKES_URL is set')

    bidsArray = [bid_info(o) for o in bids]

    def prize_info(prize):
        result = {
            'id': prize.id,
            'name': prize.name,
            'description': prize.description,
            'minimumbid': prize.minimumbid,
            'sumdonations': prize.sumdonations,
            'url': reverse('tracker:prize', args=(prize.id, )),
            'image': prize.image,
        }
        return result

    prizesArray = [prize_info(o) for o in prizes.all()]

    def to_json(value):
        if hasattr(value, 'id'):
            return value.id
        return value

    initialForm = {
        k: to_json(commentform.cleaned_data[k])
        for k, v in commentform.fields.items()
        if commentform.is_bound and k in commentform.cleaned_data
    }
    pickedIncentives = [{
        k: to_json(form.cleaned_data[k])
        for k, v in form.fields.items() if k in form.cleaned_data
    } for form in bidsform.forms if form.is_bound]

    return render(
        request,
        'ui/index.html',
        {
            'event': event,
            'events': Event.objects.all(),
            'bundle': bundle.tracker,
            'CONSTANTS': constants(),
            'ROOT_PATH': reverse('tracker:ui:index'),
            'app_name': 'TrackerApp',
            'title': 'Donation Tracker',
            'forms': {
                'bidsform': bidsform
            },
            'form_errors': {
                'commentform': json.loads(commentform.errors.as_json()),
                'bidsform': bidsform.errors,
            },
            'props': {
                'event':
                json.loads(serializers.serialize('json',
                                                 [event]))[0]['fields'],
                'minimumDonation':
                float(event.minimumdonation),
                'prizes':
                prizesArray,
                'incentives':
                bidsArray,
                'initialForm':
                initialForm,
                'initialIncentives':
                pickedIncentives,
                'donateUrl':
                request.get_full_path(),
                'prizesUrl':
                request.build_absolute_uri(
                    reverse('tracker:prizeindex', args=(event.id, ))),
            },
        },
    )
Example #25
0
def create_app(config_class=config.Config, load_config=False):
    app = Flask(__name__)
    initialize_opencensus(config_class, app)

    app.config.from_object(config_class)
    app.jinja_env.add_extension("jinja2.ext.do")
    app.elastic = ElasticInterface(app.config["ELASTICSEARCH_URL"])
    db.init_app(app)
    migrate.init_app(app, db)
    login.init_app(app)
    mail.init_app(app)
    csrf.init_app(app)
    app.config["webpack"] = webpack_manifest.load(
        # An absolute path to a manifest file
        path=os.path.join(
            app.config["BASEDIR"], "app", "static", "dist", "webpack_manifest.json"
        ),
        # The root url that your static assets are served from
        static_url="/static/",
    )

    with app.app_context():
        load_natlas_config(app)
        load_natlas_services(app)
        load_agent_config(app)
        load_agent_scripts(app)

    from app.scope import ScopeManager

    app.ScopeManager = ScopeManager()

    from app.errors import bp as errors_bp

    app.register_blueprint(errors_bp)

    from app.admin import bp as admin_bp

    app.register_blueprint(admin_bp, url_prefix="/admin")

    from app.api import bp as api_bp

    app.register_blueprint(api_bp, url_prefix="/api")
    csrf.exempt(api_bp)

    from app.auth import bp as auth_bp

    app.register_blueprint(auth_bp, url_prefix="/auth")

    from app.user import bp as user_bp

    app.register_blueprint(user_bp, url_prefix="/user")

    from app.host import bp as host_bp

    app.register_blueprint(host_bp, url_prefix="/host")

    from app.main import bp as main_bp

    app.register_blueprint(main_bp)

    from app.filters import bp as filters_bp

    app.register_blueprint(filters_bp)

    return app
Example #26
0
def donate(request, event):
    event = viewutil.get_event(event)
    if event.locked or not event.allow_donations:
        raise Http404

    bundle = webpack_manifest.load(
        os.path.abspath(
            os.path.join(os.path.dirname(__file__),
                         '../ui-tracker.manifest.json')),
        settings.STATIC_URL,
        debug=settings.DEBUG,
        timeout=60,
        read_retry=None,
    )

    commentform, bidsform = process_form(request, event)

    if not bidsform:  # redirect
        return commentform

    def bid_parent_info(bid):
        if bid is not None:
            return {
                'id': bid.id,
                'name': bid.name,
                'description': bid.description,
                'parent': bid_parent_info(bid.parent),
                'custom': bid.allowuseroptions,
            }
        else:
            return None

    def bid_info(bid):
        result = {
            'id': bid.id,
            'name': bid.name,
            'description': bid.description,
            'label': bid.full_label(not bid.allowuseroptions),
            'count': bid.count,
            'amount': bid.total,
            'goal': Decimal(bid.goal or '0.00'),
            'parent': bid_parent_info(bid.parent),
        }
        if bid.speedrun:
            result['runname'] = bid.speedrun.name
            result['order'] = bid.speedrun.order
        else:
            result['runname'] = 'Event Wide'
            result['order'] = 0
        if bid.allowuseroptions:
            result['custom'] = True
            result['maxlength'] = bid.option_max_length
        return result

    bids = search_filters.run_model_query('allbids', {
        'state': 'OPENED',
        'event': event.id
    }).select_related('parent', 'speedrun')

    prizes = search_filters.run_model_query('prize', {
        'feed': 'current',
        'event': event.id
    })

    bidsArray = [bid_info(o) for o in bids]

    def prize_info(prize):
        result = {
            'id': prize.id,
            'name': prize.name,
            'description': prize.description,
            'minimumbid': prize.minimumbid,
            'sumdonations': prize.sumdonations,
            'url': reverse('tracker:prize', args=(prize.id, )),
            'image': prize.image,
        }
        return result

    prizesArray = [prize_info(o) for o in prizes.all()]

    def to_json(value):
        if hasattr(value, 'id'):
            return value.id
        return value

    initialForm = {
        k: to_json(commentform.cleaned_data[k])
        for k, v in list(commentform.fields.items())
        if commentform.is_bound and k in commentform.cleaned_data
    }
    pickedIncentives = [{
        k: to_json(form.cleaned_data[k])
        for k, v in list(form.fields.items()) if k in form.cleaned_data
    } for form in bidsform.forms if form.is_bound]

    return render(
        request,
        'ui/index.html',
        {
            'event':
            event,
            'events':
            Event.objects.all(),
            'bundle':
            bundle.tracker,
            'CONSTANTS':
            mark_safe(json.dumps(constants())),
            'ROOT_PATH':
            reverse('tracker:ui:index'),
            'app':
            'TrackerApp',
            'title':
            'Donation Tracker',
            'forms': {
                'bidsform': bidsform
            },
            'form_errors':
            mark_safe(
                json.dumps({
                    'commentform':
                    json.loads(commentform.errors.as_json()),
                    'bidsform':
                    bidsform.errors,
                })),
            'props':
            mark_safe(
                json.dumps(
                    {
                        'event':
                        json.loads(serializers.serialize(
                            'json', [event]))[0]['fields'],
                        'minimumDonation':
                        float(event.minimumdonation),
                        'prizes':
                        prizesArray,
                        'incentives':
                        bidsArray,
                        'initialForm':
                        initialForm,
                        'initialIncentives':
                        pickedIncentives,
                        'donateUrl':
                        request.get_full_path(),
                        'prizesUrl':
                        request.build_absolute_uri(
                            reverse('tracker:prizeindex', args=(event.id, ))),
                        'steamLogin':
                        request.build_absolute_uri(
                            reverse(
                                'tracker:social:begin',
                                args=["steam"],
                            )) + '?next=' + request.get_full_path(),
                        'steamDisconnect':
                        request.build_absolute_uri(
                            reverse('tracker:disconnect_steam')) + '?next=' +
                        request.get_full_path(),
                        'steamID':
                        request.session.get('uid'),
                        'totalDonated':
                        request.session['steam_donation_total'],
                    },
                    ensure_ascii=False,
                    cls=serializers.json.DjangoJSONEncoder,
                )),
        },
    )
Example #27
0
def create_app(config_class=Config, load_config=False):
    app = Flask(__name__)
    initialize_opencensus(config_class, app)

    app.config.from_object(config_class)
    app.jinja_env.add_extension('jinja2.ext.do')

    db.init_app(app)
    migrate.init_app(app, db)
    login.init_app(app)
    mail.init_app(app)
    csrf.init_app(app)
    app.config['webpack'] = webpack_manifest.load(
        # An absolute path to a manifest file
        path=os.path.join(app.config['BASEDIR'], 'app', 'static', 'dist',
                          'webpack_manifest.json'),

        # The root url that your static assets are served from
        static_url='/static/',
    )

    if load_config:
        print("Loading Config from database")
        with app.app_context():
            from app.models import ConfigItem
            # This is gross but we need it because otherwise flask db operations won't work to create the ConfigItem table in the first place.
            try:
                # Look to see if any new config items were added that aren't currently in db
                for item in get_defaults():
                    if not ConfigItem.query.filter_by(name=item[0]).first():
                        newConfItem = ConfigItem(name=item[0],
                                                 type=item[1],
                                                 value=item[2])
                        db.session.add(newConfItem)
                        db.session.commit()

                conf = ConfigItem.query.all()
                if not conf:  # We'll hit this if the table exists but there's no data
                    populate_defaults(verbose=False)
                    conf = ConfigItem.query.all(
                    )  # populate_defaults should populate data that we can query now
                    if not conf:  # if it didn't, then we don't have config items that we need in order to run, so exit.
                        raise (SystemExit())

                for item in conf:
                    if item.type == "int":
                        app.config[item.name] = int(item.value)
                    elif item.type == "bool":
                        if item.value == "True":
                            app.config[item.name] = True
                        else:
                            app.config[item.name] = False
                    elif item.type == "string":
                        app.config[item.name] = item.value
                    else:
                        print("Unsupported config type %s:%s:%s" %
                              (item.name, item.type, item.value))
            except Exception:
                print(
                    "ConfigItem table doesn't exist yet. Ignore if flask db upgrade."
                )

            from app.models import NatlasServices
            try:
                current_services = NatlasServices.query.order_by(
                    NatlasServices.id.desc()).first()
                if current_services:
                    app.current_services = current_services.as_dict()
                else:  # Let's populate server defaults
                    defaultServices = open(
                        os.path.join(
                            app.config["BASEDIR"],
                            "defaults/natlas-services")).read().rstrip('\r\n')
                    defaultSha = hashlib.sha256(
                        defaultServices.encode()).hexdigest()
                    current_services = NatlasServices(
                        sha256=defaultSha, services=defaultServices
                    )  # default values until we load something
                    db.session.add(current_services)
                    db.session.commit()
                    print(
                        "NatlasServices populated with defaults from defaults/natlas-services"
                    )
                    app.current_services = current_services.as_dict()
            except Exception:
                print(
                    "NatlasServices table doesn't exist yet. Ignore if flask db upgrade."
                )

            # Load the current agent config, otherwise create it.
            from app.models import AgentConfig
            try:
                agentConfig = AgentConfig.query.get(
                    1)  # the agent config is updated in place so only 1 record
                if agentConfig:
                    app.agentConfig = agentConfig.as_dict()
                else:
                    newAgentConfig = AgentConfig(
                    )  # populate an agent config with database defaults
                    db.session.add(newAgentConfig)
                    db.session.commit()
                    print("AgentConfig populated with defaults")
                    app.agentConfig = newAgentConfig.as_dict()
            except Exception:
                print(
                    "AgentConfig table doesn't exist yet. Ignore if flask db upgrade."
                )

            # Load the current agent config, otherwise create it.
            from app.models import AgentScript
            try:
                agentScripts = AgentScript.query.all()
                if not agentScripts:
                    defaultAgentScript = AgentScript(name="default")
                    db.session.add(defaultAgentScript)
                    db.session.commit()
                    print("AgentScript populated with default")
                    agentScripts = AgentScript.query.all()
                app.agentScripts = agentScripts
                app.agentScriptStr = AgentScript.getScriptsString(
                    scriptList=agentScripts)
            except Exception:
                print(
                    "AgentScript table doesn't exist yet. Ignore if flask db upgrade."
                )

        # Grungy thing so we can use flask db and flask shell before the config items are initially populated
        if "ELASTICSEARCH_URL" in app.config:
            app.elastic = ElasticInterface(app.config['ELASTICSEARCH_URL'])

    from app.scope import ScopeManager
    app.ScopeManager = ScopeManager()

    from app.errors import bp as errors_bp
    app.register_blueprint(errors_bp)

    from app.admin import bp as admin_bp
    app.register_blueprint(admin_bp, url_prefix='/admin')

    from app.api import bp as api_bp
    app.register_blueprint(api_bp, url_prefix='/api')
    csrf.exempt(api_bp)

    from app.auth import bp as auth_bp
    app.register_blueprint(auth_bp, url_prefix='/auth')

    from app.user import bp as user_bp
    app.register_blueprint(user_bp, url_prefix='/user')

    from app.host import bp as host_bp
    app.register_blueprint(host_bp, url_prefix='/host')

    from app.main import bp as main_bp
    app.register_blueprint(main_bp)

    from app.filters import bp as filters_bp
    app.register_blueprint(filters_bp)

    return app
Example #28
0
def donate(request, event):
    event = viewutil.get_event(event)
    if event.locked:
        raise Http404

    bundle = webpack_manifest.load(
        os.path.abspath(os.path.join(os.path.dirname(
            __file__), '../ui-tracker.manifest.json')),
        settings.STATIC_URL,
        debug=settings.DEBUG,
        timeout=60,
        read_retry=None
    )

    commentform, bidsform, prizesform = process_form(request, event)

    if not bidsform:
        return commentform

    def bid_parent_info(bid):
        if bid != None:
            return {
                'id': bid.id,
                'name': bid.name,
                'description': bid.description,
                'parent': bid_parent_info(bid.parent),
                'custom': bid.allowuseroptions,
            }
        else:
            return None

    def bid_info(bid):
        result = {
            'id': bid.id,
            'name': bid.name,
            'description': bid.description,
            'label': bid.full_label(not bid.allowuseroptions),
            'count': bid.count,
            'amount': bid.total,
            'goal': Decimal(bid.goal or '0.00'),
            'parent': bid_parent_info(bid.parent)
        }
        if bid.speedrun:
            result['runname'] = bid.speedrun.name
        else:
            result['runname'] = 'Event Wide'
        if bid.allowuseroptions:
            result['custom'] = True
        return result

    bids = filters.run_model_query('bidtarget',
                                   {'state': 'OPENED', 'event': event.id},
                                   user=request.user) \
        .distinct().select_related('parent', 'speedrun').prefetch_related('suggestions')

    prizes = filters.run_model_query(
        'prize', {'feed': 'current', 'event': event.id})

    bidsArray = [bid_info(o) for o in bids]

    def prize_info(prize):
        result = {
            'id': prize.id,
            'name': prize.name,
            'description': prize.description,
            'minimumbid': prize.minimumbid,
            'sumdonations': prize.sumdonations,
            'url': reverse('tracker:prize', args=(prize.id,)),
            'image': prize.image,
        }
        return result

    prizesArray = [prize_info(o) for o in prizes.all()]

    def to_json(value):
        if hasattr(value, 'id'):
            return value.id
        return value

    initialForm = {k: to_json(commentform.cleaned_data[k]) for k, v in commentform.fields.items() if
                   commentform.is_bound and k in commentform.cleaned_data}
    pickedIncentives = [
        {k: to_json(form.cleaned_data[k]) for k, v in form.fields.items() if k in form.cleaned_data} for
        form in bidsform.forms if form.is_bound
    ]

    return render(
        request,
        'ui/index.html',
        {
            'event': event,
            'events': Event.objects.all(),
            'bundle': bundle.donate,
            'root_path': reverse('tracker:ui:index'),
            'app': 'DonateApp',
            'title': 'Donate',
            'forms': {'bidsform': bidsform, 'prizesform': prizesform},
            'form_errors': mark_safe(json.dumps({
                'commentform': json.loads(commentform.errors.as_json()),
                'bidsform': bidsform.errors,
            })),
            'props': mark_safe(json.dumps({
                'event': json.loads(serializers.serialize('json', [event]))[0]['fields'],
                'prizes': prizesArray,
                'incentives': bidsArray,
                'initialForm': initialForm,
                'initialIncentives': pickedIncentives,
                'donateUrl': request.get_full_path(),
                'prizesUrl': request.build_absolute_uri(reverse('tracker:prizeindex', args=(event.id,))),
                'rulesUrl': 'https://gamesdonequick.com/sweepstakes',  # TODO: put in settings?
            }, ensure_ascii=False, cls=serializers.json.DjangoJSONEncoder)),
        },
    )