<commit_before>import datetime

from django.conf import settings
from django.http import Http404
from django.urls import resolve, reverse
from django_prbac.utils import has_privilege
from ws4redis.context_processors import default

from corehq import feature_previews, privileges, toggles
from corehq.apps.accounting.models import BillingAccount, SubscriptionType
from corehq.apps.accounting.utils import domain_has_privilege
from corehq.apps.analytics.utils import is_hubspot_js_allowed_for_request
from corehq.apps.hqwebapp.utils import get_environment_friendly_name

COMMCARE = 'commcare'
COMMTRACK = 'commtrack'


def base_template(request):
    """This sticks the base_template variable defined in the settings
       into the request context."""
    return {
        'base_template': settings.BASE_TEMPLATE,
        'login_template': settings.LOGIN_TEMPLATE,
        'env': get_environment_friendly_name(),
        'secure_cookies': settings.SECURE_COOKIES,
    }


def get_per_domain_context(project, request=None):
    custom_logo_url = None
    if (project and project.has_custom_logo
            and domain_has_privilege(project.name, privileges.CUSTOM_BRANDING)):
        custom_logo_url = reverse('logo', args=[project.name])

    if getattr(request, 'couch_user', None) and project:
        allow_report_an_issue = request.couch_user.has_permission(project.name, 'report_an_issue')
    elif settings.ENTERPRISE_MODE:
        if not getattr(request, 'couch_user', None):
            allow_report_an_issue = False
        elif request.couch_user.is_web_user():
            allow_report_an_issue = True
        else:
            user = request.couch_user
            allow_report_an_issue = user.has_permission(user.domain, 'report_an_issue')
    else:
        allow_report_an_issue = True

    return {
        'CUSTOM_LOGO_URL': custom_logo_url,
        'allow_report_an_issue': allow_report_an_issue,
        'EULA_COMPLIANCE': getattr(settings, 'EULA_COMPLIANCE', False),
    }


def domain(request):
    """Global per-domain context variables"""
    project = getattr(request, 'project', None)
    return get_per_domain_context(project, request=request)


def domain_billing_context(request):
    is_domain_billing_admin = False
    restrict_domain_creation = settings.RESTRICT_DOMAIN_CREATION
    if (getattr(request, 'couch_user', None)
            and getattr(request, 'domain', None)
            and not settings.ENTERPRISE_MODE):
        account = BillingAccount.get_account_by_domain(request.domain)
        if account:
            if has_privilege(request, privileges.ACCOUNTING_ADMIN):
                is_domain_billing_admin = True
            elif account.has_enterprise_admin(request.couch_user.username):
                is_domain_billing_admin = True
            if not is_domain_billing_admin:
                restrict_domain_creation = restrict_domain_creation or account.restrict_domain_creation
    return {
        'IS_DOMAIN_BILLING_ADMIN': is_domain_billing_admin,
        'restrict_domain_creation': restrict_domain_creation,
    }


def current_url_name(request):
    """
    Adds the name for the matched url pattern for the current request to the
    request context.
    """
    try:
        match = resolve(request.path)
        url_name = match.url_name
    except Http404:
        url_name = None

    return {
        'current_url_name': url_name,
    }


def js_api_keys(request):
    if getattr(request, 'couch_user', None) and not request.couch_user.analytics_enabled:
        return {}  # disable js analytics
    api_keys = {
        'ANALYTICS_IDS': settings.ANALYTICS_IDS,
        'ANALYTICS_CONFIG': settings.ANALYTICS_CONFIG,
        'MAPBOX_ACCESS_TOKEN': settings.MAPBOX_ACCESS_TOKEN,
    }
    if getattr(request, 'project', None) and request.project.ga_opt_out and api_keys['ANALYTICS_IDS'].get('GOOGLE_ANALYTICS_API_ID'):
        del api_keys['ANALYTICS_IDS']['GOOGLE_ANALYTICS_API_ID']

    if (api_keys['ANALYTICS_IDS'].get('HUBSPOT_API_ID')
            and not is_hubspot_js_allowed_for_request(request)):
        del api_keys['ANALYTICS_IDS']['HUBSPOT_API_ID']

    return api_keys


def js_toggles(request):
    if not getattr(request, 'couch_user', None):
        return {}

    domain = None
    if getattr(request, 'project', None):
        domain = request.project.name
    elif getattr(request, 'domain', None):
        domain = request.domain

    if not domain:
        return {}

    return {
        'toggles_dict': toggles.toggle_values_by_name(username=request.couch_user.username, domain=domain),
        'previews_dict': feature_previews.preview_values_by_name(domain=domain)
    }


def websockets_override(request):
    # for some reason our proxy setup doesn't properly detect these things, so manually override them
    try:
        context = default(request)
        context['WEBSOCKET_URI'] = context['WEBSOCKET_URI'].replace(request.get_host(), settings.BASE_ADDRESS)
        if settings.DEFAULT_PROTOCOL == 'https':
            context['WEBSOCKET_URI'] = context['WEBSOCKET_URI'].replace('ws://', 'wss://')<commit_msg>fix strange error that appears to happen if I delete the key vs set it to an empty string<commit_after>import datetime

from django.conf import settings
from django.http import Http404
from django.urls import resolve, reverse
from django_prbac.utils import has_privilege
from ws4redis.context_processors import default

from corehq import feature_previews, privileges, toggles
from corehq.apps.accounting.models import BillingAccount, SubscriptionType
from corehq.apps.accounting.utils import domain_has_privilege
from corehq.apps.analytics.utils import is_hubspot_js_allowed_for_request
from corehq.apps.hqwebapp.utils import get_environment_friendly_name

COMMCARE = 'commcare'
COMMTRACK = 'commtrack'


def base_template(request):
    """This sticks the base_template variable defined in the settings
       into the request context."""
    return {
        'base_template': settings.BASE_TEMPLATE,
        'login_template': settings.LOGIN_TEMPLATE,
        'env': get_environment_friendly_name(),
        'secure_cookies': settings.SECURE_COOKIES,
    }


def get_per_domain_context(project, request=None):
    custom_logo_url = None
    if (project and project.has_custom_logo
            and domain_has_privilege(project.name, privileges.CUSTOM_BRANDING)):
        custom_logo_url = reverse('logo', args=[project.name])

    if getattr(request, 'couch_user', None) and project:
        allow_report_an_issue = request.couch_user.has_permission(project.name, 'report_an_issue')
    elif settings.ENTERPRISE_MODE:
        if not getattr(request, 'couch_user', None):
            allow_report_an_issue = False
        elif request.couch_user.is_web_user():
            allow_report_an_issue = True
        else:
            user = request.couch_user
            allow_report_an_issue = user.has_permission(user.domain, 'report_an_issue')
    else:
        allow_report_an_issue = True

    return {
        'CUSTOM_LOGO_URL': custom_logo_url,
        'allow_report_an_issue': allow_report_an_issue,
        'EULA_COMPLIANCE': getattr(settings, 'EULA_COMPLIANCE', False),
    }


def domain(request):
    """Global per-domain context variables"""
    project = getattr(request, 'project', None)
    return get_per_domain_context(project, request=request)


def domain_billing_context(request):
    is_domain_billing_admin = False
    restrict_domain_creation = settings.RESTRICT_DOMAIN_CREATION
    if (getattr(request, 'couch_user', None)
            and getattr(request, 'domain', None)
            and not settings.ENTERPRISE_MODE):
        account = BillingAccount.get_account_by_domain(request.domain)
        if account:
            if has_privilege(request, privileges.ACCOUNTING_ADMIN):
                is_domain_billing_admin = True
            elif account.has_enterprise_admin(request.couch_user.username):
                is_domain_billing_admin = True
            if not is_domain_billing_admin:
                restrict_domain_creation = restrict_domain_creation or account.restrict_domain_creation
    return {
        'IS_DOMAIN_BILLING_ADMIN': is_domain_billing_admin,
        'restrict_domain_creation': restrict_domain_creation,
    }


def current_url_name(request):
    """
    Adds the name for the matched url pattern for the current request to the
    request context.
    """
    try:
        match = resolve(request.path)
        url_name = match.url_name
    except Http404:
        url_name = None

    return {
        'current_url_name': url_name,
    }


def js_api_keys(request):
    if getattr(request, 'couch_user', None) and not request.couch_user.analytics_enabled:
        return {}  # disable js analytics
    api_keys = {
        'ANALYTICS_IDS': settings.ANALYTICS_IDS,
        'ANALYTICS_CONFIG': settings.ANALYTICS_CONFIG,
        'MAPBOX_ACCESS_TOKEN': settings.MAPBOX_ACCESS_TOKEN,
    }
    if getattr(request, 'project', None) and request.project.ga_opt_out and api_keys['ANALYTICS_IDS'].get('GOOGLE_ANALYTICS_API_ID'):
        del api_keys['ANALYTICS_IDS']['GOOGLE_ANALYTICS_API_ID']

    if (api_keys['ANALYTICS_IDS'].get('HUBSPOT_API_ID')
            and not is_hubspot_js_allowed_for_request(request)):
        # set to an empty string rather than delete. otherwise a strange race
        # happens in redis, throwing an error
        api_keys['ANALYTICS_IDS']['HUBSPOT_API_ID'] = ''

    return api_keys


def js_toggles(request):
    if not getattr(request, 'couch_user', None):
        return {}

    domain = None
    if getattr(request, 'project', None):
        domain = request.project.name
    elif getattr(request, 'domain', None):
        domain = request.domain

    if not domain:
        return {}

    return {
        'toggles_dict': toggles.toggle_values_by_name(username=request.couch_user.username, domain=domain),
        'previews_dict': feature_previews.preview_values_by_name(domain=domain)
    }


def websockets_override(request):
    # for some reason our proxy setup doesn't properly detect these things, so manually override them
    try:
        context = default(request)
        context['WEBSOCKET_URI'] = context['WEBSOCKET_URI'].replace(request.get_host(), settings.BASE_ADDRESS)
        if settings.DEFAULT_PROTOCOL == 'https':
            context['WEBSOCKET_URI'] = context['WEBSOCKET_URI'].replace('ws://', 'wss://')
{'fraction_non_alphanumeric': 0.08640076886112447, 'fraction_numerical': 0.0013455069678039405, 'mean_word_length': 3.5660377358490565, 'pattern_counts': {'":': 0, '<': 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': '225878', 'n_tokens_mistral': 3249, 'n_tokens_neox': 3170, 'n_words': 662}