예제 #1
0
파일: views.py 프로젝트: fnets/portal
    def get(self, request, file_mgr_name=None, system_id=None, offset=None, limit=None):
        """
        Returns a list of Projects for the current user.
        :param request:
        :return: A list of Projects to which the current user has access
        :rtype: JsonResponse
        """
        #raise HTTPError('Custom Error')
        ag = request.user.agave_oauth.client

        # Add metadata fields to project listings for workspace browser
        if system_id:
            projects = Project.list_projects(agave_client=ag, **{'path': '', 'type': 'dir', 'system': system_id})
            for p in projects:
                p.path = ''
                p.name = p.value['title']
                p.system = 'project-{}'.format(p.uuid)
            data = {
                'children': projects,
                'path': 'Projects',
            }
        else:
            offset = request.GET.get('offset', 0)
            limit = request.GET.get('limit', 100)
            projects = Project.list_projects(agave_client=ag, **{'offset':offset, 'limit':limit})
            data = {'projects': projects}
            
        return JsonResponse(data, encoder=AgaveJSONEncoder)
예제 #2
0
def index_or_update_project(self, uuid):
    """
    Takes a project UUID and either creates a new document in the 
    des-projects index or updates the document if one already exists for that
    project.
    """
    from designsafe.apps.api.projects.models import Project

    client = get_service_account_client()
    project_model = Project(client)
    project = project_model.search({'uuid': uuid}, client)[0]
    project_meta = project.to_dict()

    to_index = {
        key: value
        for key, value in project_meta.iteritems() if key != '_links'
    }
    to_index['value'] = {
        key: value
        for key, value in project_meta['value'].iteritems()
        if key != 'teamMember'
    }
    if not isinstance(to_index['value'].get('awardNumber', []), list):
        to_index['value']['awardNumber'] = [{
            'number':
            to_index['value']['awardNumber']
        }]
    if to_index['value'].get('guestMembers', []) == [None]:
        to_index['value']['guestMembers'] = []
    project_search = IndexedProject.search().filter(
        Q({'term': {
            'uuid._exact': uuid
        }}))
    res = project_search.execute()

    if res.hits.total.value == 0:
        # Create an ES record for the new metadata.
        # project_info_args = {key:value for key,value in project_info.iteritems() if key != '_links'}
        project_ES = IndexedProject(**to_index)
        project_ES.save()
    elif res.hits.total.value == 1:
        # Update the record.
        doc = res[0]
        doc.update(**to_index)
    else:
        # If we're here we've somehow indexed the same project multiple times.
        # Delete all records and replace with the metadata passed to the task.
        for doc in res:
            IndexedProject.get(doc.meta.id).delete()
        project_ES = IndexedProject(**to_index)
        project_ES.save()
예제 #3
0
    def get(self, request, username):
        """Returns a list of Project for a specific user.

        If the requesting user is a super user then we can 'impersonate'
        another user. Else this is an unauthorized request.

        """
        if not request.user.is_superuser:
            return HttpResponseForbidden()

        user = get_user_model().objects.get(username=username)
        ag = user.agave_oauth.client
        q = request.GET.get('q', None)
        if not q:
            projects = Project.list_projects(agave_client=ag)
        else:
            projects = Project.search(q=q, agave_client=ag)
        return JsonResponse({'projects': projects}, encoder=AgaveJSONEncoder)
예제 #4
0
    def get(self, request, project_id):
        """

        :return:
        :rtype: JsonResponse
        """
        ag = request.user.agave_oauth.client
        project = Project.from_uuid(agave_client=ag, uuid=project_id)
        return JsonResponse(project, encoder=AgaveJSONEncoder, safe=False)
예제 #5
0
 def get(self, request):
     """
     Returns a list of Projects for the current user.
     :param request:
     :return: A list of Projects to which the current user has access
     :rtype: JsonResponse
     """
     ag = request.user.agave_oauth.client
     projects = Project.list_projects(agave_client=ag)
     data = {'projects': projects}
     return JsonResponse(data, encoder=AgaveJSONEncoder)
예제 #6
0
def zip_project_files(self, project_uuid):
    from designsafe.apps.projects.models.agave.base import Project
    from designsafe.apps.api.agave import get_service_account_client

    try:
        ag = get_service_account_client()
        proj = Project.manager().get(ag, uuid=project_uuid)
        proj.archive()
    except Exception as exc:
        logger.error('Zip Proj UUID: %s. %s', project_uuid, exc, exc_info=True)
        raise self.retry(exc=exc)
예제 #7
0
    def delete(self, request, project_id):
        if request.is_ajax():
            post_data = json.loads(request.body)
        else:
            post_data = request.POST.copy()

        ag = get_service_account_client()
        project = Project.from_uuid(agave_client=ag, uuid=project_id)

        project.remove_collaborator(post_data.get('username'))
        tasks.check_project_files_meta_pems(project.uuid)
        return JsonResponse({'status': 'ok'})
예제 #8
0
파일: views.py 프로젝트: fnets/portal
    def get(self, request, file_path='', project_id=None, system_id=None, project_system_id=None, file_mgr_name=None):
        """

        :return: The root directory for the Project's data
        :rtype: JsonResponse
        """
        ag = request.user.agave_oauth.client
        if project_system_id is None:
            p = Project(ag, uuid=project_id)
            project_system_id = p.project_system_id
        
        listing = BaseFileResource.listing(ag, project_system_id, file_path)

        return JsonResponse(listing, encoder=AgaveJSONEncoder, safe=False)
예제 #9
0
    def search_projects(self,
                        username,
                        query_string,
                        file_path=None,
                        offset=0,
                        limit=100):
        user = get_user_model().objects.get(username=username)
        ag = user.agave_oauth.client

        projects = Project.list_projects(agave_client=ag)

        split_query = query_string.split(" ")
        for i, c in enumerate(split_query):
            if c.upper() not in ["AND", "OR", "NOT"]:
                split_query[i] = "*" + c + "*"

        query_string = " ".join(split_query)

        children = []
        for project in projects:

            search = IndexedFile.search()\
                .query("query_string", query=query_string, fields=["name", "name._exact", "keywords"])\
                .filter(Q({'term': {'system._exact': 'project-' + project.uuid}}))\
                .extra(from_=offset, size=limit)

            res = search.execute()

            if res.hits.total:
                for o in search[offset:limit]:
                    child = Object(wrap=o).to_dict()
                    child.update({'title': project.title})
                    children.append(child)

        result = {
            'trail': [{
                'name': '$SEARCH',
                'path': '/$SEARCH'
            }],
            'name': '$SEARCH',
            'path': '/$SEARCH',
            'system': 'designsafe.projects',
            'type': 'dir',
            'children': children,
            'permissions': 'READ'
        }

        return result
예제 #10
0
    def post(self, request, project_id):
        """

        :param request:
        :return:
        """
        ag = get_service_account_client()

        if request.is_ajax():
            post_data = json.loads(request.body)
        else:
            post_data = request.POST.copy()

        # save Project (metadata)
        p = Project.from_uuid(ag, project_id)
        p.title = post_data.get('title')
        new_pi = post_data.get('pi', None)
        if p.pi != new_pi:
            p.pi = new_pi
            p.add_collaborator(new_pi)
        p.save()
        return JsonResponse(p, encoder=AgaveJSONEncoder, safe=False)
예제 #11
0
    def post(self, request):
        """
        Create a new Project. Projects and the root File directory for a Project should
        be owned by the portal, with roles/permissions granted to the creating user.

        1. Create the metadata record for the project
        2. Create a directory on the projects storage system named after the metadata uuid
        3. Associate the metadata uuid and file uuid

        :param request:
        :return: The newly created project
        :rtype: JsonResponse
        """

        # portal service account needs to create the objects on behalf of the user
        ag = get_service_account_client()

        if request.is_ajax():
            post_data = json.loads(request.body)
        else:
            post_data = request.POST.copy()

        # create Project (metadata)
        metrics.info('projects',
                     extra={'user' : request.user.username,
                            'sessionId': getattr(request.session, 'session_key', ''),
                            'operation': 'metadata_create',
                            'info': {'postData': post_data} })
        p = Project(ag)
        p.title = post_data.get('title')
        p.pi = post_data.get('pi', None)
        p.save()

        # create Project Directory on Managed system
        metrics.info('projects',
                     extra={'user' : request.user.username,
                            'sessionId': getattr(request.session, 'session_key', ''),
                            'operation': 'base_directory_create',
                            'info': {
                                'systemId': Project.STORAGE_SYSTEM_ID,
                                'uuid': p.uuid
                            }})
        project_storage_root = BaseFileResource(ag, Project.STORAGE_SYSTEM_ID, '/')
        project_storage_root.mkdir(p.uuid)

        # Wrap Project Directory as private system for project
        project_system_tmpl = template_project_storage_system(p)
        metrics.info('projects',
                     extra={'user' : request.user.username,
                            'sessionId': getattr(request.session, 'session_key', ''),
                            'operation': 'private_system_create',
                            'info': {
                                'id': project_system_tmpl.get('id'),
                                'site': project_system_tmpl.get('site'),
                                'default': project_system_tmpl.get('default'),
                                'status': project_system_tmpl.get('status'),
                                'description': project_system_tmpl.get('description'),
                                'name': project_system_tmpl.get('name'),
                                'globalDefault': project_system_tmpl.get('globalDefault'),
                                'available': project_system_tmpl.get('available'),
                                'public': project_system_tmpl.get('public'),
                                'type': project_system_tmpl.get('type'),
                                'storage': {
                                    'homeDir': project_system_tmpl.get('storage', {}).get('homeDir'),
                                    'rootDir': project_system_tmpl.get('storage', {}).get('rootDir')
                                }
                             }})
        ag.systems.add(body=project_system_tmpl)

        # grant initial permissions for creating user and PI, if exists
        project_system_tmpl = template_project_storage_system(p)
        metrics.info('projects',
                     extra={'user' : request.user.username,
                            'sessionId': getattr(request.session, 'session_key', ''),
                            'operation': 'initial_pems_create',
                            'info': {'collab': request.user.username, 'pi': p.pi} })
        p.add_collaborator(request.user.username)
        if p.pi and p.pi != request.user.username:
            p.add_collaborator(p.pi)

        return JsonResponse(p, encoder=AgaveJSONEncoder, safe=False)