<commit_before>from django.utils.translation import ugettext, ugettext_lazy as _

from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator

from olympia.accounts.serializers import BaseUserSerializer
from olympia.addons.models import Addon
from olympia.addons.serializers import AddonSerializer
from olympia.amo.utils import clean_nl, has_links, slug_validator
from olympia.api.fields import (
    SlugOrPrimaryKeyRelatedField, SplitField, TranslationSerializerField)
from olympia.api.utils import is_gate_active
from olympia.bandwagon.models import Collection, CollectionAddon
from olympia.users.models import DeniedName


class CollectionSerializer(serializers.ModelSerializer):
    name = TranslationSerializerField()
    description = TranslationSerializerField(required=False)
    url = serializers.SerializerMethodField()
    author = BaseUserSerializer(default=serializers.CurrentUserDefault())
    public = serializers.BooleanField(source='listed', default=True)
    uuid = serializers.UUIDField(format='hex', required=False)

    class Meta:
        model = Collection
        fields = ('id', 'uuid', 'url', 'addon_count', 'author', 'description',
                  'modified', 'name', 'slug', 'public', 'default_locale')
        writeable_fields = (
            'description', 'name', 'slug', 'public', 'default_locale'
        )
        read_only_fields = tuple(set(fields) - set(writeable_fields))
        validators = [
            UniqueTogetherValidator(
                queryset=Collection.objects.all(),
                message=_(u'This custom URL is already in use by another one '
                          u'of your collections.'),
                fields=('slug', 'author')
            ),
        ]

    def get_url(self, obj):
        return obj.get_abs_url()

    def validate_name(self, value):
        # if we have a localised dict of values validate them all.
        if isinstance(value, dict):
            return {locale: self.validate_name(sub_value)
                    for locale, sub_value in value.items()}
        if value.strip() == u'':
            raise serializers.ValidationError(
                ugettext(u'Name cannot be empty.'))
        if DeniedName.blocked(value):
            raise serializers.ValidationError(
                ugettext(u'This name cannot be used.'))
        return value

    def validate_description(self, value):
        if has_links(clean_nl(str(value))):
            # There's some links, we don't want them.
            raise serializers.ValidationError(
                ugettext(u'No links are allowed.'))
        return value

    def validate_slug(self, value):
        slug_validator(
            value, lower=False,
            message=ugettext(u'The custom URL must consist of letters, '
                             u'numbers, underscores or hyphens.'))
        if DeniedName.blocked(value):
            raise serializers.ValidationError(
                ugettext(u'This custom URL cannot be used.'))

        return value


class ThisCollectionDefault(object):
    def set_context(self, serializer_field):
        viewset = serializer_field.context['view']
        self.collection = viewset.get_collection()

    def __call__(self):
        return self.collection

<commit_msg>update declaration of default context in accordance to DRF 3.11<commit_after>from django.utils.translation import ugettext, ugettext_lazy as _

from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator

from olympia.accounts.serializers import BaseUserSerializer
from olympia.addons.models import Addon
from olympia.addons.serializers import AddonSerializer
from olympia.amo.utils import clean_nl, has_links, slug_validator
from olympia.api.fields import (
    SlugOrPrimaryKeyRelatedField, SplitField, TranslationSerializerField)
from olympia.api.utils import is_gate_active
from olympia.bandwagon.models import Collection, CollectionAddon
from olympia.users.models import DeniedName


class CollectionSerializer(serializers.ModelSerializer):
    name = TranslationSerializerField()
    description = TranslationSerializerField(required=False)
    url = serializers.SerializerMethodField()
    author = BaseUserSerializer(default=serializers.CurrentUserDefault())
    public = serializers.BooleanField(source='listed', default=True)
    uuid = serializers.UUIDField(format='hex', required=False)

    class Meta:
        model = Collection
        fields = ('id', 'uuid', 'url', 'addon_count', 'author', 'description',
                  'modified', 'name', 'slug', 'public', 'default_locale')
        writeable_fields = (
            'description', 'name', 'slug', 'public', 'default_locale'
        )
        read_only_fields = tuple(set(fields) - set(writeable_fields))
        validators = [
            UniqueTogetherValidator(
                queryset=Collection.objects.all(),
                message=_(u'This custom URL is already in use by another one '
                          u'of your collections.'),
                fields=('slug', 'author')
            ),
        ]

    def get_url(self, obj):
        return obj.get_abs_url()

    def validate_name(self, value):
        # if we have a localised dict of values validate them all.
        if isinstance(value, dict):
            return {locale: self.validate_name(sub_value)
                    for locale, sub_value in value.items()}
        if value.strip() == u'':
            raise serializers.ValidationError(
                ugettext(u'Name cannot be empty.'))
        if DeniedName.blocked(value):
            raise serializers.ValidationError(
                ugettext(u'This name cannot be used.'))
        return value

    def validate_description(self, value):
        if has_links(clean_nl(str(value))):
            # There's some links, we don't want them.
            raise serializers.ValidationError(
                ugettext(u'No links are allowed.'))
        return value

    def validate_slug(self, value):
        slug_validator(
            value, lower=False,
            message=ugettext(u'The custom URL must consist of letters, '
                             u'numbers, underscores or hyphens.'))
        if DeniedName.blocked(value):
            raise serializers.ValidationError(
                ugettext(u'This custom URL cannot be used.'))

        return value


class ThisCollectionDefault(object):
    requires_context = True

    def __call__(self, serializer_field):
        viewset = serializer_field.context['view']
        self.collection = viewset.get_collection()
        return self.collection


{'fraction_non_alphanumeric': 0.08806262230919765, 'fraction_numerical': 0.0004516031913292187, 'mean_word_length': 2.783599088838269, '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': '5509084', 'n_tokens_mistral': 1761, 'n_tokens_neox': 1733, 'n_words': 459}