Example #1
0
def _switch_user_right(user_id, action, value, workspace, request_user):
    """ Change the user rights to the workspace.

    Args:
        user_id:
        action:
        value:
        workspace:
        request_user:

    Returns:
    """
    user = user_api.get_user_by_id(user_id)

    if action == ACTION_READ:
        if value:
            workspace_api.add_user_read_access_to_workspace(
                workspace, user, request_user)
        else:
            workspace_api.remove_user_read_access_to_workspace(
                workspace, user, request_user)
    elif action == ACTION_WRITE:
        if value:
            workspace_api.add_user_write_access_to_workspace(
                workspace, user, request_user)
        else:
            workspace_api.remove_user_write_access_to_workspace(
                workspace, user, request_user)
Example #2
0
def load_add_user_form(request):
    """ Load the form to list the users with no access to the workspace.

    Args:
        request:

    Returns:
    """
    workspace_id = request.POST.get('workspace_id', None)
    try:
        workspace = workspace_api.get_by_id(str(workspace_id))
    except exceptions.ModelError:
        return HttpResponseBadRequest('Invalid input.')
    except Exception:
        return HttpResponseBadRequest('An unexpected error occurred.')

    try:
        # We retrieve all users with no access
        users_with_no_access = list(
            workspace_api.get_list_user_with_no_access_workspace(
                workspace, request.user))

        # We remove the owner of the workspace
        if len(users_with_no_access) > 0:
            users_with_no_access.remove(
                user_api.get_user_by_id(workspace.owner))

        if len(users_with_no_access) == 0:
            return HttpResponseBadRequest(
                "There is no users that can be added.")

        form = UserRightForm(users_with_no_access)
    except AccessControlError, ace:
        return HttpResponseBadRequest(ace.message)
    def _get_detailed_queries(self, queries):
        detailed_queries = []
        for query in queries:
            try:
                user = user_api.get_user_by_id(query.user_id)
            except ObjectDoesNotExist:
                user = None
            except ValueError:
                user = None
            detailed_queries.append({"query": query, "user": user})

        return list(reversed(detailed_queries))
Example #4
0
def _remove_user_rights(object_id, workspace, request_user):
    """ Remove all user rights on the workspace.

    Args:
        object_id:
        workspace:
        request_user:

    Returns:
    """
    user = user_api.get_user_by_id(object_id)
    workspace_api.remove_user_read_access_to_workspace(workspace, user, request_user)
    workspace_api.remove_user_write_access_to_workspace(workspace, user, request_user)
Example #5
0
def load_add_user_form(request):
    """Load the form to list the users with no access to the workspace.

    Args:
        request:

    Returns:
    """
    workspace_id = request.POST.get("workspace_id", None)
    try:
        workspace = workspace_api.get_by_id(str(workspace_id))
    except exceptions.ModelError:
        return HttpResponseBadRequest("Invalid input.")
    except Exception:
        return HttpResponseBadRequest("An unexpected error occurred.")

    try:
        # We retrieve all users with no access
        users_with_no_access = list(
            workspace_api.get_list_user_with_no_access_workspace(
                workspace, request.user))

        # We remove the owner of the workspace
        if len(users_with_no_access) > 0:
            users_with_no_access.remove(
                user_api.get_user_by_id(workspace.owner))

        if len(users_with_no_access) == 0:
            return HttpResponseBadRequest(
                "There is no users that can be added.")

        form = UserRightForm(users_with_no_access)
    except AccessControlError as ace:
        return HttpResponseBadRequest(escape(str(ace)))
    except DoesNotExist as dne:
        return HttpResponseBadRequest(escape(str(dne)))
    except:
        return HttpResponseBadRequest("Something wrong happened.")

    context = {"add_user_form": form}

    return HttpResponse(
        json.dumps({
            "form":
            loader.render_to_string(
                "core_main_app/user/workspaces/list/modals/add_user_form.html",
                context,
            )
        }),
        "application/javascript",
    )
Example #6
0
    def __init__(
        self,
        user,
        list_current_workspace=[],
        is_administration=False,
        show_global_workspace=False,
    ):
        self.WORKSPACES_OPTIONS = []
        self.WORKSPACES_OPTIONS.append(("", "-----------"))

        # We retrieve all workspaces with write access, or all workspaces if administration
        if is_administration:
            all_workspaces = workspace_api.get_all()
        else:
            all_workspaces = list(
                workspace_api.get_all_workspaces_with_write_access_by_user(
                    user))
            if show_global_workspace:
                workspace_global = workspace_api.get_global_workspace()
                if workspace_global not in all_workspaces:
                    all_workspaces.append(workspace_global)

        if len(all_workspaces) == 0:
            raise DoesNotExist(
                "You don't have access to any workspaces with sufficient rights to assign a "
                + get_data_label() + ".")

        # We sort by title, case insensitive
        sort_workspaces = sorted(all_workspaces, key=lambda s: s.title.lower())

        # We add them
        for workspace in sort_workspaces:
            is_workspace_global = workspace_api.is_workspace_global(workspace)
            if (list_current_workspace == [] or
                (len(list_current_workspace) > 0
                 and workspace not in list_current_workspace)) and (
                     (show_global_workspace and is_workspace_global)
                     or not is_workspace_global):

                self.WORKSPACES_OPTIONS.append((
                    workspace.id,
                    workspace.title + " (" +
                    ("GLOBAL" if is_workspace_global else
                     user_api.get_user_by_id(workspace.owner).username) + ")",
                ))

        super(ChangeWorkspaceForm, self).__init__()
        self.fields["workspaces"].choices = []
        self.fields["workspaces"].choices = self.WORKSPACES_OPTIONS
Example #7
0
def get_all_workspace_permissions_user_can_write(user_id):
    """ Get a list of permission ids of workspaces that the user has write access.

    Args:
        user_id

    Return:

    """
    user = user_api.get_user_by_id(user_id)
    return [
        str(perm.id) for perm in Permission.objects.filter(
            (Q(user=user) | Q(group__in=user.groups.all())),
            content_type__app_label=CONTENT_TYPE_APP_LABEL,
            codename__startswith=CAN_WRITE_CODENAME)
    ]
Example #8
0
    def get_user(self, user_id):
        """ Retrieve a User

        Args:

            user_id: ObjectId

        Returns:

            - code: 404
              content: Object was not found
        """
        try:
            return user_api.get_user_by_id(user_id)
        except exceptions.DoesNotExist:
            raise Http404
Example #9
0
 def _format_document_context(self, request, document_list, user_can_read,
                              user_can_write, tab_selected):
     detailed_documents = []
     user = request.user
     for document in document_list:
         is_owner = str(document.user_id) == str(
             user.id) or self.administration
         document_context = {
             "can_read": user_can_read or is_owner,
             "can_write": user_can_write or is_owner,
         }
         if tab_selected == "data":
             document_context.update({
                 "data": document,
                 "is_owner": is_owner
             })
         elif tab_selected == "file":
             try:
                 username = user_api.get_user_by_id(
                     document.user_id).username
             except ObjectDoesNotExist:
                 username = "******"
             document_context.update({
                 "file":
                 document,
                 "url":
                 blob_utils.get_blob_download_uri(document, request),
                 "user":
                 username,
                 "date":
                 document.id.generation_time,
                 "is_owner":
                 is_owner,
             })
         detailed_documents.append(document_context)
     return detailed_documents
Example #10
0
def async_migration_task(data_list, xslt_id, template_id, user_id, migrate):
    """Async task which perform a migration / validation of the data list for the given target template id

    Args:
        data_list:
        xslt_id:
        template_id:
        user_id:
        migrate: (boolean) Perform the migration

    Return:
        {"valid": ["id"...], "wrong": ["id"...]}
    """
    success = []
    errors = []
    current_progress = 0
    total_data = len(data_list)

    try:
        user = user_api.get_user_by_id(user_id)
        target_template = system_api.get_template_by_id(template_id)

        # get xsl transformation if selected
        if xslt_id is not None:
            xslt = xsl_transformation_api.get_by_id(str(xslt_id))

        for data_id in data_list:
            data = data_api.get_by_id(data_id, user=user)
            # modify the data temporarily with the new targeted template
            data.template = target_template

            if xslt_id is not None:
                # modify the xml content temporarily with the transformed data content
                data.xml_content = xsl_transformation_api.xsl_transform(
                    data.xml_content, xslt.name)

            try:
                # save the new template for the data if the migration is True
                if migrate:
                    system_api.upsert_data(data)
                else:
                    # check if the data is valid
                    data_api.check_xml_file_is_valid(data)

                success.append(str(data.id))
            except Exception as e:
                errors.append(str(data.id))
            finally:
                # increase the current progress and update the task state
                current_progress += 1
                async_migration_task.update_state(
                    state="PROGRESS",
                    meta={
                        "current": current_progress,
                        "total": total_data
                    },
                )
    except Exception as e:
        async_migration_task.update_state(state="ABORT",
                                          meta={
                                              "current": current_progress,
                                              "total": total_data
                                          })
        raise Exception(f"Something went wrong: {str(e)}")

    return {"valid": success, "wrong": errors}
    def get(self, request, *args, **kwargs):
        """ Method GET

        Args:
            request:
            args:
            kwargs:

        Returns:
        """

        if self.administration:
            user_workspaces = workspace_api.get_all()
        else:
            # Get the workspace the user can read
            user_workspace_read = list(
                workspace_api.get_all_workspaces_with_read_access_by_user(
                    request.user))
            # Get the workspace the user can write
            user_workspace_write = list(
                workspace_api.get_all_workspaces_with_write_access_by_user(
                    request.user))
            # Get the merged list without doublons
            user_workspaces = user_workspace_read + list(
                set(user_workspace_write) - set(user_workspace_read))

        detailed_user_workspaces = []
        for user_workspace in user_workspaces:
            detailed_user_workspaces.append({
                'user':
                user_api.get_user_by_id(user_workspace.owner).username
                if not workspace_api.is_workspace_global(user_workspace) else
                "GLOBAL",
                'is_owner':
                self.administration
                or user_workspace.owner == str(request.user.id),
                'name':
                user_workspace.title,
                'workspace':
                user_workspace,
                'can_read':
                self.administration or user_workspace in user_workspace_read,
                'can_write':
                self.administration or user_workspace in user_workspace_write,
                'is_public':
                workspace_api.is_workspace_public(user_workspace),
                'is_global':
                workspace_api.is_workspace_global(user_workspace)
            })

        context = {
            'number_total': len(user_workspaces),
            'workspace_form': WorkspaceForm(),
            'user_data': detailed_user_workspaces,
            'document': dashboard_constants.FUNCTIONAL_OBJECT_ENUM.WORKSPACE,
            'template':
            dashboard_constants.DASHBOARD_WORKSPACES_TEMPLATE_TABLE,
            'create_workspace': not self.administration,
            'can_set_public': settings.CAN_SET_WORKSPACE_PUBLIC
        }

        modals = [dashboard_constants.MODALS_COMMON_DELETE]

        assets = {
            "css":
            copy.deepcopy(dashboard_constants.CSS_COMMON),
            "js": [
                {
                    "path": dashboard_constants.JS_USER_SELECTED_ELEMENT,
                    "is_raw": True
                },
                {
                    "path": dashboard_constants.JS_COMMON_FUNCTION_DELETE,
                    "is_raw": False
                },
                {
                    "path": 'core_dashboard_common_app/user/js/init.raw.js',
                    "is_raw": True
                },
            ]
        }

        if not self.administration:
            modals.append(
                "core_main_app/user/workspaces/list/create_workspace.html")
            assets['js'].append({
                "path": 'core_main_app/user/js/workspaces/create_workspace.js',
                "is_raw": False
            })

        if settings.CAN_SET_WORKSPACE_PUBLIC:
            modals.append(
                "core_main_app/user/workspaces/list/modals/set_public.html")
            assets['js'].append({
                "path":
                'core_main_app/user/js/workspaces/list/modals/set_public.js',
                "is_raw": False
            })
            modals.append(
                "core_main_app/user/workspaces/list/modals/set_private.html")
            assets['js'].append({
                "path":
                'core_main_app/user/js/workspaces/list/modals/set_private.js',
                "is_raw": False
            })

        return self.common_render(request,
                                  self.template,
                                  context=context,
                                  assets=assets,
                                  modals=modals)
    def get(self, request, *args, **kwargs):
        """ Method GET

        Args:
            request:
            args:
            kwargs:

        Returns:
        """

        # Get types
        if self.administration:
            type_versions = type_version_manager_api.get_all_version_manager()
        else:
            type_versions = type_version_manager_api.get_version_managers_by_user(
                request.user.id)

        detailed_types = []
        for type_version in type_versions:

            # If the version manager doesn't have a user, the type is global.
            if type_version.user is not None:
                detailed_types.append({
                    'type_version':
                    type_version,
                    'type':
                    type_api.get(type_version.current),
                    'user':
                    user_api.get_user_by_id(type_version.user).username,
                    'title':
                    type_version.title
                })

        context = {
            'number_total': len(type_versions),
            'user_form': UserForm(request.user),
            'document': dashboard_constants.FUNCTIONAL_OBJECT_ENUM.TYPE,
            'object_name': dashboard_constants.FUNCTIONAL_OBJECT_ENUM.TYPE,
            'template': dashboard_constants.DASHBOARD_TYPES_TEMPLATE_TABLE,
            'menu': False,
            'user_data': detailed_types
        }

        modals = [
            "core_main_app/admin/templates/list/modals/disable.html",
            EditTemplateVersionManagerView.get_modal_html_path()
        ]

        assets = {
            "css":
            dashboard_constants.CSS_COMMON,
            "js": [{
                "path": 'core_main_app/common/js/templates/list/restore.js',
                "is_raw": False
            }, {
                "path":
                'core_main_app/common/js/templates/list/modals/disable.js',
                "is_raw": False
            },
                   EditTemplateVersionManagerView.get_modal_js_path()]
        }

        return self.common_render(request,
                                  self.template,
                                  context=context,
                                  assets=assets,
                                  modals=modals)
    def get(self, request, *args, **kwargs):
        """ Method GET

        Args:
            request:
            args:
            kwargs:

        Returns:
        """
        if self.administration:
            files = blob_api.get_all()
        else:
            files = blob_api.get_all_by_user_id(request.user.id)

        detailed_file = []
        for file in files:
            detailed_file.append({
                'user':
                user_api.get_user_by_id(file.user_id).username,
                'date':
                file.id.generation_time,
                'file':
                file,
                'url':
                blob_utils.get_blob_download_uri(file, request)
            })

        context = {
            'administration': self.administration,
            'number_total': len(files),
            'user_data': detailed_file,
            'document': dashboard_constants.FUNCTIONAL_OBJECT_ENUM.FILE,
            'template': dashboard_constants.DASHBOARD_FILES_TEMPLATE_TABLE,
            'menu': self.administration,
        }

        if self.administration:
            context.update(
                {'action_form': ActionForm([('1', 'Delete selected files')])})

        modals = [dashboard_constants.MODALS_COMMON_DELETE]

        assets = {
            "css":
            dashboard_constants.CSS_COMMON,
            "js": [{
                "path": 'core_dashboard_common_app/user/js/init.raw.js',
                "is_raw": True
            }, {
                "path": dashboard_constants.JS_COMMON_FUNCTION_DELETE,
                "is_raw": False
            }, {
                "path": dashboard_constants.JS_USER_SELECTED_ELEMENT,
                "is_raw": True
            }]
        }

        # Admin
        if self.administration:
            assets['js'].append({
                "path":
                'core_dashboard_common_app/common/js/init_pagination.js',
                "is_raw": False
            })
            assets['js'].append({
                "path": dashboard_constants.JS_ADMIN_ACTION_DASHBOARD,
                "is_raw": True
            })
            assets['js'].append({
                "path": dashboard_constants.JS_ADMIN_COUNT_CHECK,
                "is_raw": True
            })
            assets['js'].append({
                "path": dashboard_constants.JS_ADMIN_RESET_CHECKBOX,
                "is_raw": True
            })
            assets['js'].append({
                "path": dashboard_constants.JS_ADMIN_SELECT_ALL,
                "is_raw": True
            })
            assets['js'].append({
                "path": dashboard_constants.JS_ADMIN_SELETED_ELEMENT,
                "is_raw": False
            })
            assets['js'].append({
                "path": dashboard_constants.JS_ADMIN_INIT_MENU,
                "is_raw": False
            })

        return self.common_render(request,
                                  self.template,
                                  context=context,
                                  assets=assets,
                                  modals=modals)
Example #14
0
    Returns:
    """
    workspace_id = request.POST.get('workspace_id', None)
    try:
        workspace = workspace_api.get_by_id(str(workspace_id))
    except Exception, exc:
        return HttpResponseBadRequest(exc.message)

    try:
        # We retrieve all users with no access
        users_with_no_access = list(
            workspace_api.get_list_user_with_no_access_workspace(
                workspace, request.user))

        # We remove the owner of the workspace
        users_with_no_access.remove(user_api.get_user_by_id(workspace.owner))

        if len(users_with_no_access) == 0:
            return HttpResponseBadRequest(
                "There is no users that can be added.")

        form = UserRightForm(users_with_no_access)
    except AccessControlError, ace:
        return HttpResponseBadRequest(ace.message)
    except DoesNotExist, dne:
        return HttpResponseBadRequest(dne.message)
    except:
        return HttpResponseBadRequest("Something wrong happened.")

    context = {"add_user_form": form}
Example #15
0
    workspace_id = request.POST.get('workspace_id', None)
    try:
        workspace = workspace_api.get_by_id(str(workspace_id))
    except Exception, exc:
        return HttpResponseBadRequest(exc.message)

    try:
        # We retrieve all users with no access
        users_with_no_access = list(
            workspace_api.get_list_user_with_no_access_workspace(
                workspace, request.user))

        # We remove the owner of the workspace
        if len(users_with_no_access) > 0:
            users_with_no_access.remove(
                user_api.get_user_by_id(workspace.owner))

        if len(users_with_no_access) == 0:
            return HttpResponseBadRequest(
                "There is no users that can be added.")

        form = UserRightForm(users_with_no_access)
    except AccessControlError, ace:
        return HttpResponseBadRequest(ace.message)
    except DoesNotExist, dne:
        return HttpResponseBadRequest(dne.message)
    except:
        return HttpResponseBadRequest("Something wrong happened.")

    context = {"add_user_form": form}
    def get(self, request, *args, **kwargs):
        """Method GET

        Args:
            request:
            args:
            kwargs:

        Returns:
        """
        if self.administration:
            try:
                files = blob_api.get_all(request.user)

            except AccessControlError as ace:
                files = blob_api.get_none()
        else:
            files = blob_api.get_all_by_user(request.user)

        # Paginator
        page = request.GET.get("page", 1)
        results_paginator = ResultsPaginator.get_results(
            files, page, settings.FILE_PER_PAGE_PAGINATION
        )
        detailed_file = []
        for file in results_paginator:
            try:
                username = user_api.get_user_by_id(file.user_id).username
            except ObjectDoesNotExist:
                username = "******"
            detailed_file.append(
                {
                    "user": username,
                    "date": file.id.generation_time,
                    "file": file,
                    "url": blob_utils.get_blob_download_uri(file, request),
                    "can_change_workspace": check_if_workspace_can_be_changed(file),
                    "is_owner": True,
                }
            )

        # Add user_form for change owner
        user_form = UserForm(request.user)
        context = {
            "administration": self.administration,
            "number_total": files.count(),
            "user_data": detailed_file,
            "user_form": user_form,
            "document": dashboard_constants.FUNCTIONAL_OBJECT_ENUM.FILE.value,
            "template": dashboard_constants.DASHBOARD_FILES_TEMPLATE_TABLE,
            "menu": self.administration,
            "share_pid_button": "core_linked_records_app" in settings.INSTALLED_APPS,
            "pagination": _get_pagination_document(
                page,
                results_paginator,
                files.count(),
                settings.FILE_PER_PAGE_PAGINATION,
            ),
        }

        if self.administration:
            context.update(
                {
                    "action_form": ActionForm(
                        [
                            ("1", "Delete selected files"),
                            ("2", "Change owner of selected files"),
                        ]
                    )
                }
            )

        modals = [
            "core_main_app/user/workspaces/list/modals/assign_workspace.html",
            dashboard_constants.MODALS_COMMON_DELETE,
            dashboard_constants.MODALS_COMMON_CHANGE_OWNER,
        ]

        assets = {
            "css": dashboard_constants.CSS_COMMON,
            "js": [
                {
                    "path": "core_dashboard_common_app/user/js/init.raw.js",
                    "is_raw": True,
                },
                {
                    "path": dashboard_constants.JS_COMMON_FUNCTION_DELETE,
                    "is_raw": False,
                },
                {"path": dashboard_constants.JS_USER_SELECTED_ELEMENT, "is_raw": True},
                {
                    "path": "core_main_app/user/js/workspaces/list/modals/assign_workspace.js",
                    "is_raw": False,
                },
                {
                    "path": "core_main_app/user/js/workspaces/list/modals/assign_blob_workspace.raw.js",
                    "is_raw": True,
                },
                {
                    "path": dashboard_constants.JS_COMMON_FUNCTION_CHANGE_OWNER,
                    "is_raw": False,
                },
                {
                    "path": "core_dashboard_common_app/common/js/init_pagination.js",
                    "is_raw": False,
                },
            ],
        }

        if "core_file_preview_app" in INSTALLED_APPS:
            assets["js"].extend(
                [
                    {
                        "path": "core_file_preview_app/user/js/file_preview.js",
                        "is_raw": False,
                    }
                ]
            )
            assets["css"].append("core_file_preview_app/user/css/file_preview.css")
            modals.append("core_file_preview_app/user/file_preview_modal.html")

        if context["share_pid_button"]:
            modals.append("core_linked_records_app/user/sharing/data_detail/modal.html")

            assets["js"] += [
                {
                    "path": "core_main_app/user/js/sharing_modal.js",
                    "is_raw": False,
                },
                {
                    "path": "core_linked_records_app/user/js/sharing/common_list.js",
                    "is_raw": False,
                },
                {
                    "path": "core_linked_records_app/user/js/sharing/blob_list.js",
                    "is_raw": False,
                },
            ]

        # Admin
        if self.administration:
            assets["js"].append(
                {
                    "path": "core_dashboard_common_app/common/js/init_pagination.js",
                    "is_raw": False,
                }
            )
            assets["js"].append(
                {"path": dashboard_constants.JS_ADMIN_ACTION_DASHBOARD, "is_raw": True}
            )
            assets["js"].append(
                {"path": dashboard_constants.JS_ADMIN_COUNT_CHECK, "is_raw": True}
            )
            assets["js"].append(
                {"path": dashboard_constants.JS_ADMIN_RESET_CHECKBOX, "is_raw": True}
            )
            assets["js"].append(
                {"path": dashboard_constants.JS_ADMIN_SELECT_ALL, "is_raw": True}
            )
            assets["js"].append(
                {"path": dashboard_constants.JS_ADMIN_SELETED_ELEMENT, "is_raw": False}
            )
            assets["js"].append(
                {"path": dashboard_constants.JS_ADMIN_INIT_MENU, "is_raw": False}
            )

        return self.common_render(
            request, self.template, context=context, assets=assets, modals=modals
        )
Example #17
0
def async_template_migration_task(templates, xslt_id, target_template_id,
                                  user_id, migrate):
    """Async task which perform a migration / validation of all the data which belong to the given template id list

    Args:
        templates:
        xslt_id:
        target_template_id:
        user_id
        migrate: (boolean) Perform the migration

    Return:
        {"valid": <number>, "wrong": <number>}
    """
    # get the data list to check
    current_data_progress = 0
    current_template_progress = -1
    total_data = 0
    total_template = len(templates)
    success = []
    error = []
    try:
        if target_template_id and total_template > 0:
            # get the user
            user = user_api.get_user_by_id(user_id)
            # get the target template
            target_template = system_api.get_template_by_id(target_template_id)
            # get xsl transformation if selected
            if xslt_id is not None:
                xslt = xsl_transformation_api.get_by_id(str(xslt_id))

            for template_id in templates:

                # increase the number of processed template
                current_template_progress += 1
                # rest de number of data
                current_data_progress = 0

                # get a QuerySet of all the data with the given template
                data_list = data_api.execute_query(
                    {"template": ObjectId(template_id)}, user=user)

                total_data = data_list.count()

                # extract the data id from the list
                data_list_id = data_list.values_list("id")

                for data_id in data_list_id:

                    # get the data
                    data = data_api.get_by_id(data_id, user)

                    # modify the data temporarily with the new targeted template
                    data.template = target_template

                    if xslt_id is not None:
                        # modify the xml content temporarily with the transformed data content
                        data.xml_content = xsl_transformation_api.xsl_transform(
                            data.xml_content, xslt.name)

                    # check if the data is valid
                    try:
                        # save the new template for the data if the migration is True
                        if migrate:
                            system_api.upsert_data(data)
                        else:
                            data_api.check_xml_file_is_valid(data)

                        success.append(str(data.id))
                    except Exception as e:
                        error.append(str(data.id))
                    finally:
                        # increase the current progress and update the task state
                        current_data_progress += 1
                        async_template_migration_task.update_state(
                            state="PROGRESS",
                            meta={
                                "template_current": current_template_progress,
                                "template_total": total_template,
                                "data_current": current_data_progress,
                                "data_total": total_data,
                            },
                        )

            return {"valid": success, "wrong": error}

        else:
            async_template_migration_task.update_state(
                state="ABORT",
                meta={
                    "template_current": current_template_progress,
                    "template_total": total_template,
                    "data_current": current_data_progress,
                    "data_total": total_data,
                },
            )
            raise Exception("Wrong template id." if not target_template_id else
                            "Please provide template id.")
    except Exception as e:
        async_template_migration_task.update_state(
            state="ABORT",
            meta={
                "template_current": current_template_progress,
                "template_total": total_data,
                "data_current": current_data_progress,
                "data_total": total_data,
            },
        )
        raise Exception(f"Something went wrong: {str(e)}")
def _change_owner_record(request, data_ids, user_id):
    """ Change the owner of a record.

    Args:
        request:
        data_ids:
        user_id:

    Returns:
    """
    try:
        list_data = _get_data(data_ids, request.user)
    except Exception, e:
        return HttpResponseBadRequest(e.message)
    try:
        new_user = user_api.get_user_by_id(user_id)
        for data in list_data:
            data_api.change_owner(data, new_user, request.user)
    except Exception, e:
        return HttpResponseBadRequest(e.message)

    return HttpResponse(json.dumps({}), content_type='application/javascript')


def edit_record(request):
    """ Edit a record.

    Args:
        request:

    Returns:
    def get(self, request, *args, **kwargs):
        """Method GET

        Args:
            request:
            args:
            kwargs:

        Returns:
        """

        if self.administration:
            user_workspaces = workspace_api.get_all()
            user_workspaces_count = user_workspaces.count()
        else:
            # Get the workspace the user can read
            user_workspace_read = list(
                workspace_api.get_all_workspaces_with_read_access_by_user(request.user)
            )
            # Get the workspace the user can write
            user_workspace_write = list(
                workspace_api.get_all_workspaces_with_write_access_by_user(request.user)
            )
            # Get the merged list without doublons
            user_workspaces = user_workspace_read + list(
                set(user_workspace_write) - set(user_workspace_read)
            )
            user_workspaces_count = len(user_workspaces)

        detailed_user_workspaces = []
        for user_workspace in user_workspaces:
            try:
                username = (
                    user_api.get_user_by_id(user_workspace.owner).username
                    if not workspace_api.is_workspace_global(user_workspace)
                    else "GLOBAL"
                )
            except ObjectDoesNotExist:
                username = "******"
            detailed_user_workspaces.append(
                {
                    "user": username,
                    "is_owner": self.administration
                    or user_workspace.owner == str(request.user.id),
                    "name": user_workspace.title,
                    "workspace": user_workspace,
                    "can_read": self.administration
                    or user_workspace in user_workspace_read,
                    "can_write": self.administration
                    or user_workspace in user_workspace_write,
                    "is_public": workspace_api.is_workspace_public(user_workspace),
                    "is_global": workspace_api.is_workspace_global(user_workspace),
                }
            )

        context = {
            "number_total": user_workspaces_count,
            "workspace_form": WorkspaceForm(),
            "user_data": detailed_user_workspaces,
            "document": dashboard_constants.FUNCTIONAL_OBJECT_ENUM.WORKSPACE.value,
            "template": dashboard_constants.DASHBOARD_WORKSPACES_TEMPLATE_TABLE,
            "create_workspace": not self.administration,
            "can_set_public": settings.CAN_SET_WORKSPACE_PUBLIC,
        }

        modals = [dashboard_constants.MODALS_COMMON_DELETE]

        assets = {
            "css": copy.deepcopy(dashboard_constants.CSS_COMMON),
            "js": [
                {"path": dashboard_constants.JS_USER_SELECTED_ELEMENT, "is_raw": True},
                {
                    "path": dashboard_constants.JS_COMMON_FUNCTION_DELETE,
                    "is_raw": False,
                },
                {
                    "path": "core_dashboard_common_app/user/js/init.raw.js",
                    "is_raw": True,
                },
            ],
        }

        if not self.administration:
            modals.append("core_main_app/user/workspaces/list/create_workspace.html")
            assets["js"].append(
                {
                    "path": "core_main_app/user/js/workspaces/create_workspace.js",
                    "is_raw": False,
                }
            )

        if settings.CAN_SET_WORKSPACE_PUBLIC:
            modals.append("core_main_app/user/workspaces/list/modals/set_public.html")
            assets["js"].append(
                {
                    "path": "core_main_app/user/js/workspaces/list/modals/set_public.js",
                    "is_raw": False,
                }
            )
            modals.append("core_main_app/user/workspaces/list/modals/set_private.html")
            assets["js"].append(
                {
                    "path": "core_main_app/user/js/workspaces/list/modals/set_private.js",
                    "is_raw": False,
                }
            )

        return self.common_render(
            request, self.template, context=context, assets=assets, modals=modals
        )
    def get(self, request, *args, **kwargs):
        """Method GET

        Args:
            request:
            args:
            kwargs:

        Returns:
        """

        try:
            # Get types
            if self.administration:
                type_versions = type_version_manager_api.get_all_version_manager(
                    request=request
                )
            else:
                type_versions = type_version_manager_api.get_version_managers_by_user(
                    request=request
                )

            detailed_types = []
            for type_version in type_versions:
                # If the version manager doesn't have a user, the type is global.
                if type_version.user is not None:
                    try:
                        username = user_api.get_user_by_id(type_version.user).username
                    except ObjectDoesNotExist:
                        username = "******"
                    detailed_types.append(
                        {
                            "type_version": type_version,
                            "type": type_api.get(type_version.current, request=request),
                            "user": username,
                            "title": type_version.title,
                        }
                    )

            context = {
                "number_total": len(detailed_types),
                "user_form": UserForm(request.user),
                "document": dashboard_constants.FUNCTIONAL_OBJECT_ENUM.TYPE.value,
                "object_name": dashboard_constants.FUNCTIONAL_OBJECT_ENUM.TYPE.value,
                "template": dashboard_constants.DASHBOARD_TYPES_TEMPLATE_TABLE,
                "menu": False,
                "user_data": detailed_types,
            }

            modals = [
                "core_main_app/admin/templates/list/modals/disable.html",
                EditTemplateVersionManagerView.get_modal_html_path(),
            ]

            assets = {
                "css": dashboard_constants.CSS_COMMON,
                "js": [
                    {
                        "path": "core_main_app/common/js/templates/list/restore.js",
                        "is_raw": False,
                    },
                    {
                        "path": "core_main_app/common/js/templates/list/modals/disable.js",
                        "is_raw": False,
                    },
                    EditTemplateVersionManagerView.get_modal_js_path(),
                ],
            }

            return self.common_render(
                request, self.template, context=context, assets=assets, modals=modals
            )
        except AccessControlError:
            return self.common_render(
                request,
                "core_main_app/common/commons/error.html",
                context={"error": "Access Forbidden", "status_code": 403},
            )