<commit_before>import json

from communities.models import CommunityGroup
from django.contrib import messages
from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.forms import PasswordResetForm
from django.contrib.auth.tokens import default_token_generator
from django.core.urlresolvers import reverse
from django.http.response import HttpResponse, HttpResponseBadRequest, Http404, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.template.response import TemplateResponse
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext_lazy as _, gettext
from django.views.decorators.csrf import csrf_protect
from django.views.generic import FormView, CreateView
from django.views.generic.detail import DetailView
from django.views.generic.edit import DeleteView
from django.views.generic.list import ListView
from ocd import settings
from ocd.base_views import CommunityMixin, AjaxFormView
from users import models
from acl.default_roles import DefaultGroups
from users.forms import InvitationForm, QuickSignupForm, ImportInvitationsForm, MembersGroupsForm, \
    MembersCommunityRemoveForm
from users.models import Invitation, OCUser, Membership


class MembershipMixin(CommunityMixin):
    model = models.Membership

    def get_queryset(self):
        return models.Membership.objects.filter(community=self.community)

    def validate_invitation(self, email):
        # somewhat of a privacy problem next line. should probably fail silently
        if Membership.objects.filter(community=self.community,
                                     user__email=email).exists():
            return HttpResponseBadRequest(
                _("This user already a member of this community."))

        if Invitation.objects.filter(community=self.community,
                                     email=email).exists():
            return HttpResponseBadRequest(
                _("This user is already invited to this community."))
        return None


class MembershipList(MembershipMixin, ListView):
    required_permission = 'invite_member'

    def get_context_data(self, **kwargs):
        d = super(MembershipList, self).get_context_data(**kwargs)

        d['invites'] = Invitation.objects.filter(community=self.community)
        d['form'] = InvitationForm(initial={'message':
                                                Invitation.DEFAULT_MESSAGE %
                                                self.community.name})
        d['form'].fields['groups'].queryset = CommunityGroup.objects.filter(community=self.community).exclude(
            title='administrator')
        d['members'] = Membership.objects.filter(community=self.community).order_by('group_name')
        # d['board_list'] = Membership.objects.board().filter(community=self.community)
        # d['member_list'] = Membership.objects.none_board().filter(community=self.community)
        # d['board_name'] = self.community.name

        return d

    def post(self, request, *args, **kwargs):

        form = InvitationForm(request.POST)

        if not form.is_valid():
            return HttpResponseBadRequest(
                _("Form error. Please supply a valid email."))

        v_err = self.validate_invitation(form.instance.email)
        if v_err:
            return v_err

        form.instance.community = self.community
        form.instance.created_by = request.user

        i = form.save()
        i.send(sender=request.user, recipient_name=form.cleaned_data['name'])

        return render(request, 'users/_invitation.html', {'object': i})


class DeleteInvitationView(CommunityMixin, DeleteView):
    required_permission = 'invite_member'

    model = models.Invitation

    def get_queryset(self):
        return self.model.objects.filter(community=self.community)

    def get(self, request, *args, **kwargs):
        return HttpResponse("?")

    def delete(self, request, *args, **kwargs):
        self.object = self.get_object()
        self.object.delete()
        return HttpResponse("OK")


class AcceptInvitationView(DetailView):
    slug_field = 'code'
    slug_url_kwarg = 'code'
    model = models.Invitation

    form = None

    def get_form(self):
        if self.request.method == "POST":
            return QuickSignupForm(self.request.POST)
        else:
            return QuickSignupForm(initial={'display_name': self.get_object().name})

    def get_context_data(self, **kwargs):
        d = super(AcceptInvitationView, self).get_context_data(**kwargs)
        d['user_exists'] = OCUser.objects.filter(email=self.get_object().email).exists()
        d['path'] = self.request.path
        d['login_path'] = reverse('login') + "?next=" + self.request.path
        d['form'] = self.form if self.form else self.get_form()
        return d

    def get(self, request, *args, **kwargs):
        try:
            self.object = self.get_object()
        except Http404:
            return render(request, 'users/invitation404.html', {'base_url': settings.HOST_URL})
        context = self.get_context_data(object=self.object)
        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):

        i = self.get_object()

        def create_membership(user):
            # Create selected membership type
            for group in i.groups.all():
                obj, created = Membership.objects.get_or_create(user=user, community=i.community, group_name=group)
                if created:
                    obj.invited_by = i.created_by
                    obj.save()
            # Create all member group
            # TODO: Fix this process. !!!!!
            try:
                member_group = CommunityGroup.objects.get(community=i.community, title=gettext('member'))
                obj, created = Membership.objects.get_or_create(user=user, community=i.community, group_name=member_group)
                if created:
                    obj.invited_by = i.created_by
                    obj.save()
            except:
                pass
            i.delete()
            return m

        if request.user.is_authenticated():
            if 'join' in request.POST:
                m = create_membership(request.user)
                return redirect(m.community.get_absolute_url())

        else:
            if 'signup' in request.POST:
                self.form = self.get_form()
                if self.form.is_valid():
                    # Quickly create a user :-)
                    self.form.instance.email = i.email
                    u = self.form.save()<commit_msg>Quick fix for membership creation with multi committees.<commit_after>import json

from communities.models import CommunityGroup
from django.contrib import messages
from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.forms import PasswordResetForm
from django.contrib.auth.tokens import default_token_generator
from django.core.urlresolvers import reverse
from django.http.response import HttpResponse, HttpResponseBadRequest, Http404, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.template.response import TemplateResponse
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext_lazy as _, gettext
from django.views.decorators.csrf import csrf_protect
from django.views.generic import FormView, CreateView
from django.views.generic.detail import DetailView
from django.views.generic.edit import DeleteView
from django.views.generic.list import ListView
from ocd import settings
from ocd.base_views import CommunityMixin, AjaxFormView
from users import models
from acl.default_roles import DefaultGroups
from users.forms import InvitationForm, QuickSignupForm, ImportInvitationsForm, MembersGroupsForm, \
    MembersCommunityRemoveForm
from users.models import Invitation, OCUser, Membership


class MembershipMixin(CommunityMixin):
    model = models.Membership

    def get_queryset(self):
        return models.Membership.objects.filter(community=self.community)

    def validate_invitation(self, email):
        # somewhat of a privacy problem next line. should probably fail silently
        if Membership.objects.filter(community=self.community,
                                     user__email=email).exists():
            return HttpResponseBadRequest(
                _("This user already a member of this community."))

        if Invitation.objects.filter(community=self.community,
                                     email=email).exists():
            return HttpResponseBadRequest(
                _("This user is already invited to this community."))
        return None


class MembershipList(MembershipMixin, ListView):
    required_permission = 'invite_member'

    def get_context_data(self, **kwargs):
        d = super(MembershipList, self).get_context_data(**kwargs)

        d['invites'] = Invitation.objects.filter(community=self.community)
        d['form'] = InvitationForm(initial={'message':
                                                Invitation.DEFAULT_MESSAGE %
                                                self.community.name})
        d['form'].fields['groups'].queryset = CommunityGroup.objects.filter(community=self.community).exclude(
            title='administrator')
        d['members'] = Membership.objects.filter(community=self.community).order_by('group_name')
        # d['board_list'] = Membership.objects.board().filter(community=self.community)
        # d['member_list'] = Membership.objects.none_board().filter(community=self.community)
        # d['board_name'] = self.community.name

        return d

    def post(self, request, *args, **kwargs):

        form = InvitationForm(request.POST)

        if not form.is_valid():
            return HttpResponseBadRequest(
                _("Form error. Please supply a valid email."))

        v_err = self.validate_invitation(form.instance.email)
        if v_err:
            return v_err

        form.instance.community = self.community
        form.instance.created_by = request.user

        i = form.save()
        i.send(sender=request.user, recipient_name=form.cleaned_data['name'])

        return render(request, 'users/_invitation.html', {'object': i})


class DeleteInvitationView(CommunityMixin, DeleteView):
    required_permission = 'invite_member'

    model = models.Invitation

    def get_queryset(self):
        return self.model.objects.filter(community=self.community)

    def get(self, request, *args, **kwargs):
        return HttpResponse("?")

    def delete(self, request, *args, **kwargs):
        self.object = self.get_object()
        self.object.delete()
        return HttpResponse("OK")


class AcceptInvitationView(DetailView):
    slug_field = 'code'
    slug_url_kwarg = 'code'
    model = models.Invitation

    form = None

    def get_form(self):
        if self.request.method == "POST":
            return QuickSignupForm(self.request.POST)
        else:
            return QuickSignupForm(initial={'display_name': self.get_object().name})

    def get_context_data(self, **kwargs):
        d = super(AcceptInvitationView, self).get_context_data(**kwargs)
        d['user_exists'] = OCUser.objects.filter(email=self.get_object().email).exists()
        d['path'] = self.request.path
        d['login_path'] = reverse('login') + "?next=" + self.request.path
        d['form'] = self.form if self.form else self.get_form()
        return d

    def get(self, request, *args, **kwargs):
        try:
            self.object = self.get_object()
        except Http404:
            return render(request, 'users/invitation404.html', {'base_url': settings.HOST_URL})
        context = self.get_context_data(object=self.object)
        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):

        i = self.get_object()

        def create_membership(user):
            # Create selected membership type
            for group in i.groups.all():
                obj, created = Membership.objects.get_or_create(user=user, community=i.community, group_name=group)
                if created:
                    obj.invited_by = i.created_by
                    obj.save()
            # Create all member group
            # TODO: Fix this process. !!!!!
            try:
                member_group = CommunityGroup.objects.get(community=i.community, title=gettext('member'))
                obj, created = Membership.objects.get_or_create(user=user, community=i.community, group_name=member_group)
                if created:
                    obj.invited_by = i.created_by
                    obj.save()
            except:
                pass
            i.delete()
            return obj

        if request.user.is_authenticated():
            if 'join' in request.POST:
                m = create_membership(request.user)
                return redirect(m.community.get_absolute_url())

        else:
            if 'signup' in request.POST:
                self.form = self.get_form()
                if self.form.is_valid():
                    # Quickly create a user :-)
                    self.form.instance.email = i.email
                    u = self.form.save()
{'fraction_non_alphanumeric': 0.09699096542970208, 'fraction_numerical': 0.0013439856641529156, 'mean_word_length': 2.620978642876453, 'pattern_counts': {'":': 2, '<': 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': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4582047', 'n_tokens_mistral': 3644, 'n_tokens_neox': 3447, 'n_words': 802}