<commit_before>'''
@author: jnaous
'''

from django.views.generic import list_detail, create_update, simple
from models import Project
from forms import ProjectCreateForm
from django.http import HttpResponseRedirect, HttpResponseNotAllowed, Http404
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404
from expedient.clearinghouse.aggregate.models import Aggregate
import logging
from expedient.common.utils.views import generic_crud
from expedient.common.messaging.models import DatedMessage
from django.db.models import Q
from expedient.common.permissions.decorators import require_objs_permissions_for_view
from expedient.common.permissions.utils import get_queryset, get_user_from_req,\
    get_queryset_from_class
from expedient.clearinghouse.roles.models import ProjectRole,\
    ProjectRoleRequest
from expedient.common.permissions.models import ObjectPermission,\
    PermissionOwnership, Permittee
from expedient.clearinghouse.project.forms import AddMemberForm, MemberForm
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
    
logger = logging.getLogger("project.views")

TEMPLATE_PATH = "project"

DEFAULT_OWNER_PERMISSIONS = [
    "can_edit_project", "can_delete_project", "can_view_project",
    "can_add_members", "can_remove_members",
    "can_create_slices", "can_edit_slices", "can_delete_slices",
    "can_start_slices", "can_stop_slices",
    "can_add_aggregates", "can_remove_aggregates",
    "can_create_roles", "can_edit_roles",
]

DEFAULT_RESEARCHER_PERMISSIONS = [
    "can_view_project",
    "can_create_slices", "can_edit_slices", "can_delete_slices",
    "can_start_slices", "can_stop_slices",
]

def list(request):
    '''Show list of projects'''
    
    qs = Project.objects.get_for_user(request.user)
    
    return list_detail.object_list(
        request,
        queryset=qs,
        template_name=TEMPLATE_PATH+"/list.html",
        template_object_name="project",
    )

@require_objs_permissions_for_view(
    perm_names=["can_delete_slices"],
    permittee_func=get_user_from_req,
    target_func=get_queryset(Project, "proj_id"),
    methods=["GET", "POST"],
)
@require_objs_permissions_for_view(
    perm_names=["can_delete_project"],
    permittee_func=get_user_from_req,
    target_func=get_queryset(Project, "proj_id"),
    methods=["GET", "POST"],
)
def delete(request, proj_id):
    '''Delete the project'''
    project = get_object_or_404(Project, id=proj_id)
    if request.method == "POST":
        for s in project.slice_set.all():
            s.stop(request.user)
        project.delete()
        DatedMessage.objects.post_message_to_user(
            "Successfully deleted project %s" % project.name,
            request.user, msg_type=DatedMessage.TYPE_SUCCESS)
        return HttpResponseRedirect(reverse("home"))
    else:
        return simple.direct_to_template(
            request,
            template=TEMPLATE_PATH+"/confirm_delete.html",
            extra_context={"object": project},
        )

@require_objs_permissions_for_view(
    perm_names=["can_view_project"],
    permittee_func=get_user_from_req,
    target_func=get_queryset(Project, "proj_id"),
)
def detail(request, proj_id):
    '''Show information about the project'''
    project = get_object_or_404(Project, id=proj_id)
    role_reqs = ProjectRoleRequest.objects.filter(
        giver=request.user, requested_role__project=project)
    return list_detail.object_detail(
        request,
        Project.objects.all(),
        object_id=proj_id,
        template_name=TEMPLATE_PATH+"/detail.html",
        template_object_name="project",
        extra_context={
            "role_requests": role_reqs,
            "breadcrumbs": (
                ("Home", reverse("home")),
                ("Project %s" % project.name, reverse("project_detail", args=[project.id])),
            )
        }
    )

@require_objs_permissions_for_view(
    perm_names=["can_create_project"],
    permittee_func=get_user_from_req,
    target_func=get_queryset_from_class(Project),
)
def create(request):
    '''Create a new project'''
    
    def post_save(instance, created):
        # Create default roles in the project
        owner_role = ProjectRole.objects.create(
            name="owner",
            description=\
                "The 'owner' role is a special role that has permission to "
                "do everything "
                "in the project and can give the permissions to everyone. "
                "In addition every time a slice is created, users with "
                "the 'owner' role get full permissions over those.",
            project=instance,
        )
        for permission in DEFAULT_OWNER_PERMISSIONS:
            obj_perm = ObjectPermission.objects.\
                get_or_create_for_object_or_class(
                    permission, instance)[0]
            owner_role.obj_permissions.add(obj_perm)
            
        researcher_role = ProjectRole.objects.create(
            name="researcher",
            description=\
                "By default users with the 'researcher' role can only "
                "create slices and "
                "delete slices they created. They have full permissions over "
                "their created slices.",
                project=instance,
        )
        for permission in DEFAULT_RESEARCHER_PERMISSIONS:
            obj_perm = ObjectPermission.objects.\
                get_or_create_for_object_or_class(
                    permission, instance)[0]
            researcher_role.obj_permissions.add(obj_perm)
        
        # give the creator of the project an owner role
        owner_role.give_to_permittee(
            request.user,
            can_delegate=True,
        )
        
    def redirect(instance):
        return reverse("project_detail", args=[instance.id])
    
    return generic_crud(
        request, None,
        model=Project,
        form_class=ProjectCreateForm,<commit_msg>separate project_role creation so other functions can use it<commit_after>'''
@author: jnaous
'''

from django.views.generic import list_detail, create_update, simple
from models import Project
from forms import ProjectCreateForm
from django.http import HttpResponseRedirect, HttpResponseNotAllowed, Http404
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404
from expedient.clearinghouse.aggregate.models import Aggregate
import logging
from expedient.common.utils.views import generic_crud
from expedient.common.messaging.models import DatedMessage
from django.db.models import Q
from expedient.common.permissions.decorators import require_objs_permissions_for_view
from expedient.common.permissions.utils import get_queryset, get_user_from_req,\
    get_queryset_from_class
from expedient.clearinghouse.roles.models import ProjectRole,\
    ProjectRoleRequest
from expedient.common.permissions.models import ObjectPermission,\
    PermissionOwnership, Permittee
from expedient.clearinghouse.project.forms import AddMemberForm, MemberForm
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
    
logger = logging.getLogger("project.views")

TEMPLATE_PATH = "project"

DEFAULT_OWNER_PERMISSIONS = [
    "can_edit_project", "can_delete_project", "can_view_project",
    "can_add_members", "can_remove_members",
    "can_create_slices", "can_edit_slices", "can_delete_slices",
    "can_start_slices", "can_stop_slices",
    "can_add_aggregates", "can_remove_aggregates",
    "can_create_roles", "can_edit_roles",
]

DEFAULT_RESEARCHER_PERMISSIONS = [
    "can_view_project",
    "can_create_slices", "can_edit_slices", "can_delete_slices",
    "can_start_slices", "can_stop_slices",
]

def list(request):
    '''Show list of projects'''
    
    qs = Project.objects.get_for_user(request.user)
    
    return list_detail.object_list(
        request,
        queryset=qs,
        template_name=TEMPLATE_PATH+"/list.html",
        template_object_name="project",
    )

@require_objs_permissions_for_view(
    perm_names=["can_delete_slices"],
    permittee_func=get_user_from_req,
    target_func=get_queryset(Project, "proj_id"),
    methods=["GET", "POST"],
)
@require_objs_permissions_for_view(
    perm_names=["can_delete_project"],
    permittee_func=get_user_from_req,
    target_func=get_queryset(Project, "proj_id"),
    methods=["GET", "POST"],
)
def delete(request, proj_id):
    '''Delete the project'''
    project = get_object_or_404(Project, id=proj_id)
    if request.method == "POST":
        for s in project.slice_set.all():
            s.stop(request.user)
        project.delete()
        DatedMessage.objects.post_message_to_user(
            "Successfully deleted project %s" % project.name,
            request.user, msg_type=DatedMessage.TYPE_SUCCESS)
        return HttpResponseRedirect(reverse("home"))
    else:
        return simple.direct_to_template(
            request,
            template=TEMPLATE_PATH+"/confirm_delete.html",
            extra_context={"object": project},
        )

@require_objs_permissions_for_view(
    perm_names=["can_view_project"],
    permittee_func=get_user_from_req,
    target_func=get_queryset(Project, "proj_id"),
)
def detail(request, proj_id):
    '''Show information about the project'''
    project = get_object_or_404(Project, id=proj_id)
    role_reqs = ProjectRoleRequest.objects.filter(
        giver=request.user, requested_role__project=project)
    return list_detail.object_detail(
        request,
        Project.objects.all(),
        object_id=proj_id,
        template_name=TEMPLATE_PATH+"/detail.html",
        template_object_name="project",
        extra_context={
            "role_requests": role_reqs,
            "breadcrumbs": (
                ("Home", reverse("home")),
                ("Project %s" % project.name, reverse("project_detail", args=[project.id])),
            )
        }
    )

def create_project_roles(project, user):
    """Create the default roles in a project."""
    owner_role = ProjectRole.objects.create(
        name="owner",
        description=\
            "The 'owner' role is a special role that has permission to "
            "do everything "
            "in the project and can give the permissions to everyone. "
            "In addition every time a slice is created, users with "
            "the 'owner' role get full permissions over those.",
        project=project,
    )
    for permission in DEFAULT_OWNER_PERMISSIONS:
        obj_perm = ObjectPermission.objects.\
            get_or_create_for_object_or_class(
                permission, project)[0]
        owner_role.obj_permissions.add(obj_perm)
        
    researcher_role = ProjectRole.objects.create(
        name="researcher",
        description=\
            "By default users with the 'researcher' role can only "
            "create slices and "
            "delete slices they created. They have full permissions over "
            "their created slices.",
            project=project,
    )
    for permission in DEFAULT_RESEARCHER_PERMISSIONS:
        obj_perm = ObjectPermission.objects.\
            get_or_create_for_object_or_class(
                permission, project)[0]
        researcher_role.obj_permissions.add(obj_perm)
    
    # give the creator of the project an owner role
    owner_role.give_to_permittee(
        user,
        can_delegate=True,
    )

@require_objs_permissions_for_view(
    perm_names=["can_create_project"],
    permittee_func=get_user_from_req,
    target_func=get_queryset_from_class(Project),
)
def create(request):
    '''Create a new project'''
    
    def post_save(instance, created):
        # Create default roles in the project
        create_project_roles(instance, request.user)
        
    def redirect(instance):
        return reverse("project_detail", args=[instance.id])
    
    return generic_crud(
        request, None,
        model=Project,
        form_class=ProjectCreateForm,
{'fraction_non_alphanumeric': 0.0910979968414928, 'fraction_numerical': 0.0023273210871914223, 'mean_word_length': 3.2202735882146616, 'pattern_counts': {'":': 8, '<': 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': '930249', 'n_tokens_mistral': 3610, 'n_tokens_neox': 3531, 'n_words': 713}