<commit_before>from django.contrib.auth.models import User
from django.utils.translation import ugettext as _

from rest_framework import status
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action
from rest_framework.response import Response

from onadata.apps.api.models.organization_profile import OrganizationProfile
from onadata.apps.api.tools import (get_organization_members,
                                    add_user_to_organization,
                                    remove_user_from_organization)
from onadata.apps.api import permissions
from onadata.libs.filters import OrganizationPermissionFilter
from onadata.libs.mixins.last_modified_mixin import LastModifiedMixin
from onadata.libs.mixins.object_lookup_mixin import ObjectLookupMixin
from onadata.libs.permissions import ROLES
from onadata.libs.serializers.organization_serializer import(
    OrganizationSerializer)


def _try_function_org_username(f, organization, username, args=None):
    data = []

    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        status_code = status.HTTP_400_BAD_REQUEST
        data = {'username':
                [_(u"User `%(username)s` does not exist."
                   % {'username': username})]}
    else:
        if args:
            f(organization, user, *args)
        else:
            f(organization, user)
        status_code = status.HTTP_201_CREATED

    return [data, status_code]


def _update_username_role(organization, username, role_cls):
    f = lambda org, user, role_cls: role_cls.add(user, organization)
    return _try_function_org_username(f,
                                      organization,
                                      username,
                                      [role_cls])


def _add_username_to_organization(organization, username):
    return _try_function_org_username(add_user_to_organization,
                                      organization,
                                      username)


def _remove_username_to_organization(organization, username):
    return _try_function_org_username(remove_user_from_organization,
                                      organization,
                                      username)


class OrganizationProfileViewSet(LastModifiedMixin,
                                 ObjectLookupMixin,
                                 ModelViewSet):

    """
List, Retrieve, Update, Create/Register Organizations

## Register a new Organization
<pre class="prettyprint"><b>POST</b> /api/v1/orgs</pre>
> Example
>
>        {
>            "org": "modilabs",
>            "name": "<NAME>",
>            "email": "<EMAIL>",
>            "city": "New York",
>            "country": "US",
>            ...
>        }

## List of Organizations
<pre class="prettyprint"><b>GET</b> /api/v1/orgs</pre>
> Example
>
>       curl -X GET https://ona.io/api/v1/orgs

> Response
>
>       [
>        {
>            "url": "https://ona.io/api/v1/orgs/modilabs",
>            "org": "modilabs",
>            "name": "<NAME>",
>            "email": "<EMAIL>",
>            "city": "New York",
>            "country": "US",
>            "website": "",
>            "twitter": "",
>            "gravatar": "https://secure.gravatar.com/avatar/xxxxxx",
>            "require_auth": false,
>            "user": "https://ona.io/api/v1/users/modilabs"
>            "creator": "https://ona.io/api/v1/users/demo"
>        },
>        {
>           ...}, ...
>       ]

## Retrieve Organization Profile Information

<pre class="prettyprint"><b>GET</b> /api/v1/orgs/{username}</pre>
> Example
>
>       curl -X GET https://ona.io/api/v1/orgs/modilabs

> Response
>
>        {
>            "url": "https://ona.io/api/v1/orgs/modilabs",
>            "org": "modilabs",
>            "name": "<NAME>",
>            "email": "<EMAIL>",
>            "city": "New York",
>            "country": "US",
>            "website": "",
>            "twitter": "",
>            "gravatar": "https://secure.gravatar.com/avatar/xxxxxx",
>            "require_auth": false,
>            "user": "https://ona.io/api/v1/users/modilabs"
>            "creator": "https://ona.io/api/v1/users/demo"
>        }

## List Organization members

Get a list of organization members.

<pre class="prettyprint"><b>GET</b> /api/v1/orgs/{username}/members</pre>
> Example
>
>       curl -X GET https://ona.io/api/v1/orgs/modilabs/members

> Response
>
>       ["member1", "member2"]

## Add a user to an organization

To add a user to an organization requires a JSON payload of
`{"username": "member1"}`.

<pre class="prettyprint"><b>POST</b> /api/v1/orgs/{username}/members</pre>
> Example
>
>       curl -X POST -d '{"username": "member1"}' \
https://ona.io/api/v1/orgs/modilabs/members -H "Content-Type: application/json"

> Response
>
>       ["member1"]

## Change the role of a user in an organization

To change the role of a user in an organization pass the username and role
`{"username": "member1", "role": "owner|manager|editor|dataentry|readonly"}`.

<pre class="prettyprint"><b>PUT</b> /api/v1/orgs/{username}/members</pre>
> Example
>
>       curl -X PUT -d '{"username": "member1", "role": "editor"}' \
https://ona.io/api/v1/orgs/modilabs/members -H "Content-Type: application/json"

> Response
>
>       ["member1"]

## Remove a user from an organization

To remove a user from an organization requires a JSON payload of
`{"username": "member1"}`.

<pre class="prettyprint"><b>DELETE</b> /api/v1/orgs/{username}/members</pre>
> Example
>
>       curl -X DELETE -d '{"username": "member1"}' \
https://ona.io/api/v1/orgs/modilabs/members -H "Content-Type: application/json"

> Response
>
>       []
"""
    queryset = OrganizationProfile.objects.all()
    serializer_class = OrganizationSerializer
    lookup_field = 'user'
    permission_classes = [permissions.DjangoObjectPermissionsAllowAnon]
    filter_backends = (OrganizationPermissionFilter,)

    last_modified_field = 'joined'

    @action(methods=['DELETE', 'GET', 'POST', 'PUT'])
    def members(self, request, *args, **kwargs):
        organization = self.get_object()
        status_code = status.HTTP_200_OK
        data = []<commit_msg>ME: removed 'last_modified_field' property<commit_after>from django.contrib.auth.models import User
from django.utils.translation import ugettext as _

from rest_framework import status
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action
from rest_framework.response import Response

from onadata.apps.api.models.organization_profile import OrganizationProfile
from onadata.apps.api.tools import (get_organization_members,
                                    add_user_to_organization,
                                    remove_user_from_organization)
from onadata.apps.api import permissions
from onadata.libs.filters import OrganizationPermissionFilter
from onadata.libs.mixins.last_modified_mixin import LastModifiedMixin
from onadata.libs.mixins.object_lookup_mixin import ObjectLookupMixin
from onadata.libs.permissions import ROLES
from onadata.libs.serializers.organization_serializer import(
    OrganizationSerializer)


def _try_function_org_username(f, organization, username, args=None):
    data = []

    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        status_code = status.HTTP_400_BAD_REQUEST
        data = {'username':
                [_(u"User `%(username)s` does not exist."
                   % {'username': username})]}
    else:
        if args:
            f(organization, user, *args)
        else:
            f(organization, user)
        status_code = status.HTTP_201_CREATED

    return [data, status_code]


def _update_username_role(organization, username, role_cls):
    f = lambda org, user, role_cls: role_cls.add(user, organization)
    return _try_function_org_username(f,
                                      organization,
                                      username,
                                      [role_cls])


def _add_username_to_organization(organization, username):
    return _try_function_org_username(add_user_to_organization,
                                      organization,
                                      username)


def _remove_username_to_organization(organization, username):
    return _try_function_org_username(remove_user_from_organization,
                                      organization,
                                      username)


class OrganizationProfileViewSet(LastModifiedMixin,
                                 ObjectLookupMixin,
                                 ModelViewSet):

    """
List, Retrieve, Update, Create/Register Organizations

## Register a new Organization
<pre class="prettyprint"><b>POST</b> /api/v1/orgs</pre>
> Example
>
>        {
>            "org": "modilabs",
>            "name": "<NAME>",
>            "email": "<EMAIL>",
>            "city": "New York",
>            "country": "US",
>            ...
>        }

## List of Organizations
<pre class="prettyprint"><b>GET</b> /api/v1/orgs</pre>
> Example
>
>       curl -X GET https://ona.io/api/v1/orgs

> Response
>
>       [
>        {
>            "url": "https://ona.io/api/v1/orgs/modilabs",
>            "org": "modilabs",
>            "name": "<NAME>",
>            "email": "<EMAIL>",
>            "city": "New York",
>            "country": "US",
>            "website": "",
>            "twitter": "",
>            "gravatar": "https://secure.gravatar.com/avatar/xxxxxx",
>            "require_auth": false,
>            "user": "https://ona.io/api/v1/users/modilabs"
>            "creator": "https://ona.io/api/v1/users/demo"
>        },
>        {
>           ...}, ...
>       ]

## Retrieve Organization Profile Information

<pre class="prettyprint"><b>GET</b> /api/v1/orgs/{username}</pre>
> Example
>
>       curl -X GET https://ona.io/api/v1/orgs/modilabs

> Response
>
>        {
>            "url": "https://ona.io/api/v1/orgs/modilabs",
>            "org": "modilabs",
>            "name": "<NAME>",
>            "email": "<EMAIL>",
>            "city": "New York",
>            "country": "US",
>            "website": "",
>            "twitter": "",
>            "gravatar": "https://secure.gravatar.com/avatar/xxxxxx",
>            "require_auth": false,
>            "user": "https://ona.io/api/v1/users/modilabs"
>            "creator": "https://ona.io/api/v1/users/demo"
>        }

## List Organization members

Get a list of organization members.

<pre class="prettyprint"><b>GET</b> /api/v1/orgs/{username}/members</pre>
> Example
>
>       curl -X GET https://ona.io/api/v1/orgs/modilabs/members

> Response
>
>       ["member1", "member2"]

## Add a user to an organization

To add a user to an organization requires a JSON payload of
`{"username": "member1"}`.

<pre class="prettyprint"><b>POST</b> /api/v1/orgs/{username}/members</pre>
> Example
>
>       curl -X POST -d '{"username": "member1"}' \
https://ona.io/api/v1/orgs/modilabs/members -H "Content-Type: application/json"

> Response
>
>       ["member1"]

## Change the role of a user in an organization

To change the role of a user in an organization pass the username and role
`{"username": "member1", "role": "owner|manager|editor|dataentry|readonly"}`.

<pre class="prettyprint"><b>PUT</b> /api/v1/orgs/{username}/members</pre>
> Example
>
>       curl -X PUT -d '{"username": "member1", "role": "editor"}' \
https://ona.io/api/v1/orgs/modilabs/members -H "Content-Type: application/json"

> Response
>
>       ["member1"]

## Remove a user from an organization

To remove a user from an organization requires a JSON payload of
`{"username": "member1"}`.

<pre class="prettyprint"><b>DELETE</b> /api/v1/orgs/{username}/members</pre>
> Example
>
>       curl -X DELETE -d '{"username": "member1"}' \
https://ona.io/api/v1/orgs/modilabs/members -H "Content-Type: application/json"

> Response
>
>       []
"""
    queryset = OrganizationProfile.objects.all()
    serializer_class = OrganizationSerializer
    lookup_field = 'user'
    permission_classes = [permissions.DjangoObjectPermissionsAllowAnon]
    filter_backends = (OrganizationPermissionFilter,)

    @action(methods=['DELETE', 'GET', 'POST', 'PUT'])
    def members(self, request, *args, **kwargs):
        organization = self.get_object()
        status_code = status.HTTP_200_OK
        data = []
{'fraction_non_alphanumeric': 0.13836376799935646, 'fraction_numerical': 0.0061137478883436566, 'mean_word_length': 2.3800978792822187, 'pattern_counts': {'":': 74, '<': 71, '<?xml version=': 0, '>': 223, 'https://': 28, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 22, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7056566', 'n_tokens_mistral': 3808, 'n_tokens_neox': 3692, 'n_words': 775}