Ejemplo n.º 1
0
class ComponentGroupEdit(View):
    """Component Group Edit Page Controller"""

    template_name = 'templates/admin/component_group/edit.html'

    @login_if_not_authenticated
    def get(self, request, group_id):

        self.__context = Context()
        self.__component_group = ComponentGroupModule()
        self.__correlation_id = request.META[
            "X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        group = self.__component_group.get_one_by_id(group_id)

        if not group:
            raise Http404("Component group not found.")

        self.__context.autoload_options()
        self.__context.autoload_user(
            request.user.id if request.user.is_authenticated else None)
        self.__context.push({
            "page_title":
            _("Edit Component Group · %s") % self.__context.get(
                "app_name", os.getenv("APP_NAME", "Silverback")),
            "group":
            group
        })

        return render(request, self.template_name, self.__context.get())
Ejemplo n.º 2
0
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__form = Form()
     self.__component_group = ComponentGroupModule()
     self.__logger = self.__helpers.get_logger(__name__)
     self.__form.add_validator(ExtraRules())
Ejemplo n.º 3
0
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__settings = Settings()
     self.__component = ComponentModule()
     self.__component_group = ComponentGroupModule()
     self.__form = Form()
     self.__logger = self.__helpers.get_logger(__name__)
     self.__user_id = None
     self.__correlation_id = ""
     self.__form.add_validator(ExtraRules())
Ejemplo n.º 4
0
    def get(self, request, group_id):

        self.__component_group = ComponentGroupModule()
        group = self.__component_group.get_one_by_id(group_id)

        if not group:
            raise Http404("Component group not found.")

        self.autoload_options()
        self.autoload_user(request.user.id if request.user.is_authenticated else None)
        self.context_push({
            "page_title": _("Edit Component Group · %s") % self.context_get("app_name", os.getenv("APP_NAME", "Silverback")),
            "group": group
        })

        return render(request, self.template_name, self.context_get())
Ejemplo n.º 5
0
 def __init__(self):
     self.__settings = Settings()
     self.__component = ComponentModule()
     self.__component_group = ComponentGroupModule()
Ejemplo n.º 6
0
class BuilderComponents(View, Controller):
    """Add and Remove Builder Components Private Endpoint Controller"""
    def __init__(self):
        self.__settings = Settings()
        self.__component = ComponentModule()
        self.__component_group = ComponentGroupModule()

    @allow_if_authenticated_and_has_permission("manage_settings")
    def post(self, request):

        request_data = self.get_request_data(request, "post",
                                             {"component_id": ""})

        if request_data["component_id"] == "" or (
                "c-" not in request_data["component_id"]
                and "g-" not in request_data["component_id"]):
            return self.json([{
                "type":
                "error",
                "message":
                _("Error! Compnent or compnent group is required.")
            }])

        if "c-" in request_data[
                "component_id"] and not self.__component.get_one_by_id(
                    request_data["component_id"].replace("c-", "")):
            return self.json([{
                "type":
                "error",
                "message":
                _("Error! Compnent or compnent group is required.")
            }])

        if "g-" in request_data[
                "component_id"] and not self.__component_group.get_one_by_id(
                    request_data["component_id"].replace("g-", "")):
            return self.json([{
                "type":
                "error",
                "message":
                _("Error! Compnent or compnent group is required.")
            }])

        components = self.__settings.get_value_by_key("builder_components",
                                                      json.dumps([]))

        components = json.loads(components)

        if request_data["component_id"] in components:
            return self.json([{
                "type": "success",
                "message": _("Component added successfully.")
            }])

        components.append(request_data["component_id"])

        result = self.__settings.update_options(
            {"builder_components": json.dumps(components)})

        if result:
            return self.json([{
                "type": "success",
                "message": _("Component added successfully.")
            }])

        else:
            return self.json([{
                "type":
                "error",
                "message":
                _("Error! Something goes wrong while adding component.")
            }])

    @allow_if_authenticated_and_has_permission("manage_settings")
    def delete(self, request, component_id):

        components = self.__settings.get_value_by_key("builder_components",
                                                      json.dumps([]))

        components = json.loads(components)

        if component_id not in components:
            return self.json([{
                "type": "success",
                "message": _("Component deleted successfully.")
            }])

        components.remove(component_id)

        result = self.__settings.update_options(
            {"builder_components": json.dumps(components)})

        if result:
            return self.json([{
                "type": "success",
                "message": _("Component deleted successfully.")
            }])

        else:
            return self.json([{
                "type":
                "error",
                "message":
                _("Error! Something goes wrong while deleting component.")
            }])
Ejemplo n.º 7
0
class Components(View):
    """Create and List Components Private Endpoint Controller"""
    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__component = ComponentModule()
        self.__component_group = ComponentGroupModule()
        self.__logger = self.__helpers.get_logger(__name__)
        self.__form.add_validator(ExtraRules())
        self.__user_id = None
        self.__correlation_id = ""

    @allow_if_authenticated
    def post(self, request):

        self.__correlation_id = request.META[
            "X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__request.set_request(request)

        request_data = self.__request.get_request_data("post", {
            "name": "",
            "description": "",
            "uptime": "",
            "group": ""
        })

        self.__form.add_inputs({
            'name': {
                'value': request_data["name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between': {
                        'param': [1, 60],
                        'error':
                        _('Error! Component name must be 1 to 60 characters long.'
                          )
                    }
                }
            },
            'description': {
                'value': request_data["description"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between': {
                        'param': [0, 150],
                        'error':
                        _('Error! Component name description must be less than 150 characters long.'
                          )
                    },
                    'optional': {}
                }
            },
            'uptime': {
                'value': request_data["uptime"],
                'validate': {
                    'any_of': {
                        'param': [["on", "off"]],
                        'error': _('Error! Uptime is invalid.')
                    }
                }
            },
            'group': {
                'value': int(request_data["group"]),
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'greater_than': {
                        'error': _('Error! Component group is invalid.'),
                        'param': [0]
                    },
                    'optional': {}
                }
            }
        })

        self.__form.process()

        if not self.__form.is_passed():
            return JsonResponse(
                self.__response.send_errors_failure(self.__form.get_errors(),
                                                    {}, self.__correlation_id))

        # Check if component name not used
        if self.__component.get_one_by_name(self.__form.get_sinput("name")):
            return JsonResponse(
                self.__response.send_private_failure(
                    [{
                        "type": "error",
                        "message": _("Error! Component name is used before.")
                    }], {}, self.__correlation_id))

        # Check if group id is valid
        if self.__form.get_sinput(
                "group") and not self.__component_group.get_one_by_id(
                    self.__form.get_sinput("group")):
            return JsonResponse(
                self.__response.send_private_failure(
                    [{
                        "type": "error",
                        "message": _("Error! Component group is invalid.")
                    }], {}, self.__correlation_id))

        result = self.__component.insert_one({
            "name":
            self.__form.get_sinput("name"),
            "description":
            self.__form.get_sinput("description"),
            "uptime":
            self.__form.get_sinput("uptime"),
            "group_id":
            None if self.__form.get_sinput("group") == "" else
            self.__form.get_sinput("group")
        })

        if result:
            return JsonResponse(
                self.__response.send_private_success(
                    [{
                        "type": "success",
                        "message": _("Component created successfully.")
                    }], {}, self.__correlation_id))
        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while creating component.")
                }], {}, self.__correlation_id))

    @allow_if_authenticated
    def get(self, request):

        self.__correlation_id = request.META[
            "X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__request.set_request(request)

        request_data = self.__request.get_request_data("get", {
            "offset": 0,
            "limit": 20
        })

        try:
            offset = int(request_data["offset"])
            limit = int(request_data["limit"])
        except Exception:
            offset = 0
            limit = 20

        return JsonResponse(
            self.__response.send_private_success(
                [], {
                    'components':
                    self.__format_components(
                        self.__component.get_all(offset, limit)),
                    'metadata': {
                        'offset': offset,
                        'limit': limit,
                        'count': self.__component.count_all()
                    }
                }, self.__correlation_id))

    def __format_components(self, components):
        components_list = []

        for component in components:
            components_list.append({
                "id":
                component.id,
                "name":
                component.name,
                "description":
                component.description,
                "uptime":
                component.uptime,
                "group":
                "---" if component.group is None else component.group.name,
                "created_at":
                component.created_at.strftime("%b %d %Y %H:%M:%S"),
                "edit_url":
                reverse("app.web.admin.component.edit",
                        kwargs={'component_id': component.id}),
                "delete_url":
                reverse("app.api.private.v1.admin.component.endpoint",
                        kwargs={'component_id': component.id})
            })

        return components_list
Ejemplo n.º 8
0
class Component(View):
    """Update and Delete Component Private Endpoint Controller"""
    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__component = ComponentModule()
        self.__component_group = ComponentGroupModule()
        self.__logger = self.__helpers.get_logger(__name__)
        self.__form.add_validator(ExtraRules())
        self.__user_id = None
        self.__correlation_id = ""

    @allow_if_authenticated
    def post(self, request, component_id):

        self.__correlation_id = request.META[
            "X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__request.set_request(request)

        request_data = self.__request.get_request_data("post", {
            "name": "",
            "description": "",
            "uptime": "",
            "group": ""
        })

        self.__form.add_inputs({
            'name': {
                'value': request_data["name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between': {
                        'param': [1, 60],
                        'error':
                        _('Error! Component name must be 1 to 60 characters long.'
                          )
                    }
                }
            },
            'description': {
                'value': request_data["description"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between': {
                        'param': [0, 150],
                        'error':
                        _('Error! Component name description must be less than 150 characters long.'
                          )
                    },
                    'optional': {}
                }
            },
            'uptime': {
                'value': request_data["uptime"],
                'validate': {
                    'any_of': {
                        'param': [["on", "off"]],
                        'error': _('Error! Uptime is invalid.')
                    }
                }
            },
            'group': {
                'value': int(request_data["group"]),
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'greater_than': {
                        'error': _('Error! Component group is invalid.'),
                        'param': [0]
                    },
                    'optional': {}
                }
            }
        })

        self.__form.process()

        if not self.__form.is_passed():
            return JsonResponse(
                self.__response.send_errors_failure(self.__form.get_errors(),
                                                    {}, self.__correlation_id))

        # Check if component name not used elsewhere
        current_component = self.__component.get_one_by_name(
            self.__form.get_sinput("name"))

        if current_component and not current_component["id"] == component_id:
            return JsonResponse(
                self.__response.send_private_failure(
                    [{
                        "type": "error",
                        "message": _("Error! Component name is used before.")
                    }], {}, self.__correlation_id))

        # Check if group id is valid
        if self.__form.get_sinput(
                "group") and not self.__component_group.get_one_by_id(
                    self.__form.get_sinput("group")):
            return JsonResponse(
                self.__response.send_private_failure(
                    [{
                        "type": "error",
                        "message": _("Error! Component group is invalid.")
                    }], {}, self.__correlation_id))

        result = self.__component.update_one_by_id(
            component_id, {
                "name":
                self.__form.get_sinput("name"),
                "description":
                self.__form.get_sinput("description"),
                "uptime":
                self.__form.get_sinput("uptime"),
                "group_id":
                None if self.__form.get_sinput("group") == "" else
                self.__form.get_sinput("group")
            })

        if result:
            return JsonResponse(
                self.__response.send_private_success(
                    [{
                        "type": "success",
                        "message": _("Component updated successfully.")
                    }], {}, self.__correlation_id))
        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while updating component.")
                }], {}, self.__correlation_id))

    @allow_if_authenticated
    def delete(self, request, component_id):

        self.__correlation_id = request.META[
            "X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__user_id = request.user.id

        if self.__component.delete_one_by_id(component_id):
            return JsonResponse(
                self.__response.send_private_success(
                    [{
                        "type": "success",
                        "message": _("Component deleted successfully.")
                    }], {}, self.__correlation_id))

        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while deleting component.")
                }], {}, self.__correlation_id))
Ejemplo n.º 9
0
class BuilderComponents(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __settings = None
    __component = None
    __component_group = None
    __correlation_id = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__settings = Settings()
        self.__component = ComponentModule()
        self.__component_group = ComponentGroupModule()
        self.__form = Form()
        self.__logger = self.__helpers.get_logger(__name__)
        self.__form.add_validator(ExtraRules())

    @allow_if_authenticated_and_has_permission("manage_settings")
    def post(self, request):

        self.__correlation_id = request.META[
            "X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__request.set_request(request)
        request_data = self.__request.get_request_data("post",
                                                       {"component_id": ""})

        if request_data["component_id"] == "":
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Compnent or compnent group is required.")
                }], {}, self.__correlation_id))

        if not self.__component.get_one_by_id(
                request_data["component_id"]
        ) and not self.__component_group.get_one_by_id(
                request_data["component_id"]):
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Compnent or compnent group is required.")
                }], {}, self.__correlation_id))

        components = self.__settings.get_value_by_key("builder_components",
                                                      json.dumps([]))

        components = json.loads(components)

        if request_data["component_id"] in components:
            return JsonResponse(
                self.__response.send_private_success(
                    [{
                        "type": "success",
                        "message": _("Component added successfully.")
                    }], {}, self.__correlation_id))

        components.append(request_data["component_id"])

        result = self.__settings.update_options(
            {"builder_components": json.dumps(components)})

        if result:
            return JsonResponse(
                self.__response.send_private_success(
                    [{
                        "type": "success",
                        "message": _("Component added successfully.")
                    }], {}, self.__correlation_id))

        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while adding component.")
                }], {}, self.__correlation_id))

    @allow_if_authenticated_and_has_permission("manage_settings")
    def delete(self, request, component_id):

        self.__correlation_id = request.META[
            "X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        components = self.__settings.get_value_by_key("builder_components",
                                                      json.dumps([]))

        components = json.loads(components)

        if component_id not in components:
            return JsonResponse(
                self.__response.send_private_success(
                    [{
                        "type": "success",
                        "message": _("Component deleted successfully.")
                    }], {}, self.__correlation_id))

        components.remove(component_id)

        result = self.__settings.update_options(
            {"builder_components": json.dumps(components)})

        if result:
            return JsonResponse(
                self.__response.send_private_success(
                    [{
                        "type": "success",
                        "message": _("Component deleted successfully.")
                    }], {}, self.__correlation_id))

        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while deleting component.")
                }], {}, self.__correlation_id))
Ejemplo n.º 10
0
class ComponentGroups(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __component_group = None
    __correlation_id = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__component_group = ComponentGroupModule()
        self.__logger = self.__helpers.get_logger(__name__)
        self.__form.add_validator(ExtraRules())

    @allow_if_authenticated
    def post(self, request):

        self.__correlation_id = request.META["X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__request.set_request(request)

        request_data = self.__request.get_request_data("post", {
            "name": "",
            "description": "",
            "uptime": "",
        })

        self.__form.add_inputs({
            'name': {
                'value': request_data["name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between': {
                        'param': [1, 90],
                        'error': _('Error! Component group name must be 1 to 90 characters long.')
                    }
                }
            },
            'description': {
                'value': request_data["description"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {}
            },
            'uptime': {
                'value': request_data["uptime"],
                'validate': {
                    'any_of': {
                        'param': [["on", "off"]],
                        'error': _('Error! Uptime is invalid.')
                    }
                }
            }
        })

        self.__form.process()

        if not self.__form.is_passed():
            return JsonResponse(self.__response.send_errors_failure(self.__form.get_errors(), {}, self.__correlation_id))

        result = self.__component_group.insert_one({
            "name": self.__form.get_sinput("name"),
            "description": self.__form.get_sinput("description"),
            "uptime": self.__form.get_sinput("uptime")
        })

        if result:
            return JsonResponse(self.__response.send_private_success([{
                "type": "success",
                "message": _("Component group created successfully.")
            }], {}, self.__correlation_id))
        else:
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Something goes wrong while creating group.")
            }], {}, self.__correlation_id))

    @allow_if_authenticated
    def get(self, request):

        self.__correlation_id = request.META["X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__request.set_request(request)

        request_data = self.__request.get_request_data("get", {
            "offset": "",
            "limit": ""
        })

        try:
            offset = int(request_data["offset"])
            limit = int(request_data["limit"])
        except Exception:
            offset = 0
            limit = 0

        return JsonResponse(self.__response.send_private_success([], {
            'groups': self.__format_groups(self.__component_group.get_all(offset, limit)),
            'metadata': {
                'offset': offset,
                'limit': limit,
                'count': self.__component_group.count_all()
            }
        }, self.__correlation_id))

    def __format_groups(self, groups):
        groups_list = []

        for group in groups:
            groups_list.append({
                "id": group.id,
                "name": group.name,
                "description": group.description,
                "components": self.__component_group.count_components(group.id),
                "created_at": group.created_at.strftime("%b %d %Y %H:%M:%S"),
                "edit_url": reverse("app.web.admin.component_group.edit", kwargs={'group_id': group.id}),
                "delete_url": reverse("app.api.private.v1.admin.component_group.endpoint", kwargs={'group_id': group.id})
            })

        return groups_list
Ejemplo n.º 11
0
class ComponentGroup(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __component_group = None
    __correlation_id = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__component_group = ComponentGroupModule()
        self.__logger = self.__helpers.get_logger(__name__)
        self.__form.add_validator(ExtraRules())

    @allow_if_authenticated
    def post(self, request, group_id):

        self.__correlation_id = request.META["X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__request.set_request(request)

        request_data = self.__request.get_request_data("post", {
            "name": "",
            "description": "",
            "uptime": ""
        })

        self.__form.add_inputs({
            'name': {
                'value': request_data["name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between': {
                        'param': [1, 90],
                        'error': _('Error! Component group name must be 1 to 90 characters long.')
                    }
                }
            },
            'description': {
                'value': request_data["description"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {}
            },
            'uptime': {
                'value': request_data["uptime"],
                'validate': {
                    'any_of': {
                        'param': [["on", "off"]],
                        'error': _('Error! Uptime is invalid.')
                    }
                }
            }
        })

        self.__form.process()

        if not self.__form.is_passed():
            return JsonResponse(self.__response.send_errors_failure(self.__form.get_errors(), {}, self.__correlation_id))

        result = self.__component_group.update_one_by_id(group_id, {
            "name": self.__form.get_sinput("name"),
            "description": self.__form.get_sinput("description"),
            "uptime": self.__form.get_sinput("uptime")
        })

        if result:
            return JsonResponse(self.__response.send_private_success([{
                "type": "success",
                "message": _("Component group updated successfully.")
            }], {}, self.__correlation_id))
        else:
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Something goes wrong while updating group.")
            }], {}, self.__correlation_id))

    @allow_if_authenticated
    def delete(self, request, group_id):

        self.__correlation_id = request.META["X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__user_id = request.user.id

        if self.__component_group.delete_one_by_id(group_id):
            return JsonResponse(self.__response.send_private_success([{
                "type": "success",
                "message": _("Component group deleted successfully.")
            }], {}, self.__correlation_id))

        else:
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Something goes wrong while deleting group.")
            }], {}, self.__correlation_id))
Ejemplo n.º 12
0
 def __init__(self):
     self.__component_group = ComponentGroupModule()
Ejemplo n.º 13
0
class ComponentGroups(View, Controller):
    """Create and List Component Groups Private Endpoint Controller"""

    def __init__(self):
        self.__component_group = ComponentGroupModule()

    @allow_if_authenticated
    def post(self, request):

        request_data = self.get_request_data(request, "post", {
            "name": "",
            "description": "",
            "uptime": "",
        })

        self.form().add_inputs({
            'name': {
                'value': request_data["name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between': {
                        'param': [1, 60],
                        'error': _('Error! Component name must be 1 to 60 characters long.')
                    }
                }
            },
            'description': {
                'value': request_data["description"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between': {
                        'param': [0, 150],
                        'error': _('Error! Component name description must be less than 150 characters long.')
                    },
                    'optional': {}
                }
            },
            'uptime': {
                'value': request_data["uptime"],
                'validate': {
                    'any_of': {
                        'param': [["on", "off"]],
                        'error': _('Error! Uptime is invalid.')
                    }
                }
            }
        })

        self.form().process()

        if not self.form().is_passed():
            return self.json(self.form().get_errors())

        # Check if group name not used
        if self.__component_group.get_one_by_name(self.form().get_sinput("name")):
            return self.json([{
                "type": "error",
                "message": _("Error! Component group name is used before.")
            }])

        result = self.__component_group.insert_one({
            "name": self.form().get_sinput("name"),
            "description": self.form().get_sinput("description"),
            "uptime": self.form().get_sinput("uptime")
        })

        if result:
            return self.json([{
                "type": "success",
                "message": _("Component group created successfully.")
            }])
        else:
            return self.json([{
                "type": "error",
                "message": _("Error! Something goes wrong while creating group.")
            }])

    @allow_if_authenticated
    def get(self, request):

        request_data = self.get_request_data(request, "get", {
            "offset": 0,
            "limit": 20
        })

        try:
            offset = int(request_data["offset"])
            limit = int(request_data["limit"])
        except Exception:
            offset = 0
            limit = 20

        return self.json([], {
            'groups': self.__format_groups(self.__component_group.get_all(offset, limit)),
            'metadata': {
                'offset': offset,
                'limit': limit,
                'count': self.__component_group.count_all()
            }
        })

    def __format_groups(self, groups):
        groups_list = []

        for group in groups:
            groups_list.append({
                "id": group.id,
                "name": group.name,
                "description": group.description,
                "components": self.__component_group.count_components(group.id),
                "created_at": group.created_at.strftime("%b %d %Y %H:%M:%S"),
                "edit_url": reverse("app.web.admin.component_group.edit", kwargs={'group_id': group.id}),
                "delete_url": reverse("app.api.private.v1.admin.component_group.endpoint", kwargs={'group_id': group.id})
            })

        return groups_list
Ejemplo n.º 14
0
class ComponentGroup(View, Controller):
    """Update and Delete Component Group Private Endpoint Controller"""

    def __init__(self):
        self.__component_group = ComponentGroupModule()

    @allow_if_authenticated
    def post(self, request, group_id):

        request_data = self.get_request_data(request, "post", {
            "name": "",
            "description": "",
            "uptime": ""
        })

        self.form().add_inputs({
            'name': {
                'value': request_data["name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between': {
                        'param': [1, 60],
                        'error': _('Error! Component name must be 1 to 60 characters long.')
                    }
                }
            },
            'description': {
                'value': request_data["description"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between': {
                        'param': [0, 150],
                        'error': _('Error! Component name description must be less than 150 characters long.')
                    },
                    'optional': {}
                }
            },
            'uptime': {
                'value': request_data["uptime"],
                'validate': {
                    'any_of': {
                        'param': [["on", "off"]],
                        'error': _('Error! Uptime is invalid.')
                    }
                }
            }
        })

        self.form().process()

        if not self.form().is_passed():
            return self.json(self.form().get_errors())

        # Check if group name not used elsewhere
        current_group = self.__component_group.get_one_by_name(self.form().get_sinput("name"))

        if current_group and not current_group["id"] == group_id:
            return self.json([{
                "type": "error",
                "message": _("Error! Component group name is used before.")
            }])

        result = self.__component_group.update_one_by_id(group_id, {
            "name": self.form().get_sinput("name"),
            "description": self.form().get_sinput("description"),
            "uptime": self.form().get_sinput("uptime")
        })

        if result:
            return self.json([{
                "type": "success",
                "message": _("Component group updated successfully.")
            }])
        else:
            return self.json([{
                "type": "error",
                "message": _("Error! Something goes wrong while updating group.")
            }])

    @allow_if_authenticated
    def delete(self, request, group_id):

        if self.__component_group.delete_one_by_id(group_id):
            return self.json([{
                "type": "success",
                "message": _("Component group deleted successfully.")
            }])

        else:
            return self.json([{
                "type": "error",
                "message": _("Error! Something goes wrong while deleting group.")
            }])