<commit_before># -*- coding: utf-8 -*-
"""
    1flow "core" application. It's an Ember.JS based application, which
    explains why we don't have much things here. Everything takes place
    in the static/ and templates/ directories.

"""

import logging
import humanize

from constance import config

from django.http import (HttpResponseRedirect,
                         HttpResponseForbidden,
                         HttpResponseBadRequest,
                         HttpResponse)
from django.core.urlresolvers import reverse
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
from django.contrib import messages
from django.shortcuts import render
from django.template import add_to_builtins
#from django.views.generic import ListView
from django.contrib.auth import authenticate, login, get_user_model
from django.utils.translation import ugettext_lazy as _

from oneflow.core.forms import UserProfileEditForm

#from infinite_pagination.paginator import InfinitePaginator
from endless_pagination.utils import get_page_number_from_request

from sparks.django.utils import HttpResponseTemporaryServerError

from .forms import FullUserCreationForm
from .tasks import import_google_reader_trigger
from .models.nonrel import Feed, Read
from .models.reldb import HelpContent
from ..base.utils.dateutils import now

from .gr_import import GoogleReaderImport

LOGGER = logging.getLogger(__name__)
User = get_user_model()

# Avoid repetitive {% load … %} in templates.
add_to_builtins('django.templatetags.i18n')
add_to_builtins('djangojs.templatetags.js')
add_to_builtins('pipeline.templatetags.compressed')
add_to_builtins('absolute.templatetags.absolute_future')
add_to_builtins('markdown_deux.templatetags.markdown_deux_tags')
add_to_builtins('oneflow.base.templatetags.base_utils')
add_to_builtins('oneflow.core.templatetags.coretags')

if settings.TEMPLATE_DEBUG:
    add_to_builtins('template_debug.templatetags.debug_tags')


def home(request):
    """ root of the application. """

    home_style = request.user.mongo.preferences.home.style

    if home_style and home_style == 'T1':
        return HttpResponseRedirect(reverse(u'read'))

    return render(request, 'home.html', {
        'gr_import': GoogleReaderImport(request.user.id),
    })


def read_with_endless_pagination(request, **kwargs):

    query_kwargs = {}
    combinations = ()
    attributes   = Read.status_data.keys()

    def check_order_by(value):
        if value in (u'id', ):
            return

        raise RuntimeError()

    # First, get the view mode we were called from.
    if kwargs.get('all', False):
        # No particular kwargs for this one, but we
        # needed to pass in the 'if' to avoid the
        # default case where we get only the unread.
        pass

    else:
        for attrname in attributes:
            if kwargs.get(attrname, False):
                query_kwargs[attrname] = True

                if request.user.is_superuser or request.user.is_staff:
                    combinations = (
                        (attr2, request.GET.get(attr2, None), bool)
                            for attr2 in attributes if attr2 != attrname
                    )

                break

    # Then allow the user to mix with manual query
    # parameters, but check them to avoid crashes.
    for parameter, value, checker in combinations:
        if value is None:
            continue

        try:
            checked_value = checker(value)

        except:
            LOGGER.exception(u'Check %s on value "%s" of parameter %s '
                             u'failed; skipped.', checker, value, parameter)
            continue

        if checker == bool and not checked_value:
            # For 2 reasons we need to negate:
            # - old reads don't have default attribute because some
            #   didn't exist at the time, thus the value is None in
            #   the database.
            # - all Reads (old and new) can have `.is_starred` == None
            #   because False and True mean "I don't like" and "I like",
            #   None meaning "like status not set".
            query_kwargs[parameter + '__ne'] = True

        else:
            query_kwargs[parameter] = checked_value

    if request.user.is_superuser or request.user.is_staff:
        order_by = unicode(request.GET.get('order_by', u'-id'))
    else:
        order_by = u'-id'

    try:
        if order_by.startswith(u'-'):
            check_order_by(order_by[1:])
        else:
            check_order_by(order_by)
    except:
        LOGGER.exception(u'order_by check failed (value "%s"); using "-id".',
                         order_by)
        order_by = u'-id'

    LOGGER.info(query_kwargs)

    reads = Read.objects(user=request.user.mongo,
                         **query_kwargs).order_by(order_by).no_cache()

    context = {
        u'reads': reads,

        # are we rendering the first "main"
        # page, or just a subset via ajax?
        u'initial': False,
    }

    #preferences = request.user.mongo.preferences

    if request.is_ajax():

        if request.GET.get('count', False):
            template = u'snippets/read/read-endless-count.html'
            context[u'reads_count'] = reads.count()

        else:
            template = u'snippets/read/read-endless-page.html'

            # Computing tenths_counter here is much efficient than doing:
            # {% captureas tenths_counter %}{{ request.GET['page']|mul:10 }}{% endcaptureas %} # NOQA<commit_msg>Correctly handle multiple kwargs in read view, and don't overwrite them in inner loop.<commit_after># -*- coding: utf-8 -*-
"""
    1flow "core" application. It's an Ember.JS based application, which
    explains why we don't have much things here. Everything takes place
    in the static/ and templates/ directories.

"""

import logging
import humanize

from constance import config

from django.http import (HttpResponseRedirect,
                         HttpResponseForbidden,
                         HttpResponseBadRequest,
                         HttpResponse)
from django.core.urlresolvers import reverse
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
from django.contrib import messages
from django.shortcuts import render
from django.template import add_to_builtins
#from django.views.generic import ListView
from django.contrib.auth import authenticate, login, get_user_model
from django.utils.translation import ugettext_lazy as _

from oneflow.core.forms import UserProfileEditForm

#from infinite_pagination.paginator import InfinitePaginator
from endless_pagination.utils import get_page_number_from_request

from sparks.django.utils import HttpResponseTemporaryServerError

from .forms import FullUserCreationForm
from .tasks import import_google_reader_trigger
from .models.nonrel import Feed, Read
from .models.reldb import HelpContent
from ..base.utils.dateutils import now

from .gr_import import GoogleReaderImport

LOGGER = logging.getLogger(__name__)
User = get_user_model()

# Avoid repetitive {% load … %} in templates.
add_to_builtins('django.templatetags.i18n')
add_to_builtins('djangojs.templatetags.js')
add_to_builtins('pipeline.templatetags.compressed')
add_to_builtins('absolute.templatetags.absolute_future')
add_to_builtins('markdown_deux.templatetags.markdown_deux_tags')
add_to_builtins('oneflow.base.templatetags.base_utils')
add_to_builtins('oneflow.core.templatetags.coretags')

if settings.TEMPLATE_DEBUG:
    add_to_builtins('template_debug.templatetags.debug_tags')


def home(request):
    """ root of the application. """

    home_style = request.user.mongo.preferences.home.style

    if home_style and home_style == 'T1':
        return HttpResponseRedirect(reverse(u'read'))

    return render(request, 'home.html', {
        'gr_import': GoogleReaderImport(request.user.id),
    })


def read_with_endless_pagination(request, **kwargs):

    query_kwargs = {}
    combinations = ()
    attributes   = Read.status_data.keys()

    def check_order_by(value):
        if value in (u'id', ):
            return

        raise RuntimeError()

    # First, get the view mode we were called from.
    if kwargs.get('all', False):
        # No particular kwargs for this one, but we
        # needed to pass in the 'if' to avoid the
        # default case where we get only the unread.
        pass

    else:
        combinations = set()

        for attrname in attributes:
            mykwarg = kwargs.get(attrname, None)

            if mykwarg is not None:
                if mykwarg:
                    query_kwargs[attrname] = mykwarg

                else:
                    # For 2 reasons we need to negate:
                    # - old reads don't have default attribute because some
                    #   didn't exist at the time, thus the value is None in
                    #   the database.
                    # - all Reads (old and new) can have `.is_starred` == None
                    #   because False and True mean "I don't like" and "I like",
                    #   None meaning "like status not set".
                    query_kwargs[attrname + '__ne'] = True

                if request.user.is_superuser or request.user.is_staff:
                    combinations.union(set(
                        attr2, request.GET.get(attr2, None), bool)
                            for attr2 in attributes if attr2 not in attributes
                    )

    # Then allow the user to mix with manual query
    # parameters, but check them to avoid crashes.
    for parameter, value, checker in combinations:
        if value is None:
            continue

        try:
            checked_value = checker(value)

        except:
            LOGGER.exception(u'Check %s on value "%s" of parameter %s '
                             u'failed; skipped.', checker, value, parameter)
            continue

        if checker == bool and not checked_value:
            # See before, in the for loop.
            query_kwargs[parameter + '__ne'] = True

        else:
            query_kwargs[parameter] = checked_value

    if request.user.is_superuser or request.user.is_staff:
        order_by = unicode(request.GET.get('order_by', u'-id'))
    else:
        order_by = u'-id'

    try:
        if order_by.startswith(u'-'):
            check_order_by(order_by[1:])
        else:
            check_order_by(order_by)
    except:
        LOGGER.exception(u'order_by check failed (value "%s"); using "-id".',
                         order_by)
        order_by = u'-id'

    #LOGGER.info(query_kwargs)

    reads = Read.objects(user=request.user.mongo,
                         **query_kwargs).order_by(order_by).no_cache()

    context = {
        u'reads': reads,

        # are we rendering the first "main"
        # page, or just a subset via ajax?
        u'initial': False,
    }

    #preferences = request.user.mongo.preferences

    if request.is_ajax():

        if request.GET.get('count', False):
            template = u'snippets/read/read-endless-count.html'
            context[u'reads_count'] = reads.count()

        else:
            template = u'snippets/read/read-endless-page.html'

            # Computing tenths_counter here is much efficient than doing:
            # {% captureas tenths_counter %}{{ request.GET['page']|mul:10 }}{% endcaptureas %} # NOQA
{'fraction_non_alphanumeric': 0.08727304622401544, 'fraction_numerical': 0.002280501710376283, 'mean_word_length': 2.4561988481357986, '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': '5682265', 'n_tokens_mistral': 3313, 'n_tokens_neox': 3182, 'n_words': 896}