1
0
mirror of https://github.com/netbox-community/netbox.git synced 2024-05-10 07:54:54 +00:00

215 lines
7.5 KiB
Python
Raw Normal View History

import collections
import inspect
from django.apps import AppConfig
from django.template.loader import get_template
from django.utils.module_loading import import_string
from extras.registry import registry
2020-03-26 11:26:11 -04:00
from utilities.choices import ButtonColorChoices
# Initialize plugin registry stores
registry['plugin_template_extensions'] = collections.defaultdict(list)
2020-03-26 12:25:36 -04:00
registry['plugin_menu_items'] = {}
2020-03-20 15:13:25 -04:00
#
# Plugin AppConfig class
#
class PluginConfig(AppConfig):
"""
Subclass of Django's built-in AppConfig class, to be used for NetBox plugins.
"""
# Plugin metadata
author = ''
author_email = ''
2020-03-20 15:13:25 -04:00
description = ''
version = ''
# Root URL path under /plugins. If not set, the plugin's label will be used.
2020-03-24 16:20:47 -04:00
base_url = None
2020-03-20 15:13:25 -04:00
# Minimum/maximum compatible versions of NetBox
min_version = None
max_version = None
# Default configuration parameters
default_settings = {}
# Mandatory configuration parameters
required_settings = []
# Middleware classes provided by the plugin
middleware = []
# Caching configuration
caching_config = {}
# Default integration paths. Plugin authors can override these to customize the paths to
# integrated components.
template_extensions = 'template_content.template_extensions'
menu_items = 'navigation.menu_items'
def ready(self):
# Register template content
try:
template_extensions = import_string(f"{self.__module__}.{self.template_extensions}")
register_template_extensions(template_extensions)
except ImportError:
pass
# Register navigation menu items (if defined)
try:
menu_items = import_string(f"{self.__module__}.{self.menu_items}")
register_menu_items(self.verbose_name, menu_items)
except ImportError:
pass
2020-03-20 15:13:25 -04:00
2020-03-17 02:35:12 -04:00
#
# Template content injection
#
class PluginTemplateExtension:
"""
This class is used to register plugin content to be injected into core NetBox templates. It contains methods
that are overridden by plugin authors to return template content.
The `model` attribute on the class defines the which model detail page this class renders content for. It
should be set as a string in the form '<app_label>.<model_name>'. render() provides the following context data:
* object - The object being viewed
* request - The current request
* settings - Global NetBox settings
* config - Plugin-specific configuration parameters
"""
model = None
def __init__(self, context):
self.context = context
def render(self, template_name, extra_context=None):
"""
Convenience method for rendering the specified Django template using the default context data. An additional
context dictionary may be passed as `extra_context`.
"""
if extra_context is None:
extra_context = {}
elif not isinstance(extra_context, dict):
raise TypeError("extra_context must be a dictionary")
return get_template(template_name).render({**self.context, **extra_context})
def left_page(self):
"""
Content that will be rendered on the left of the detail page view. Content should be returned as an
HTML string. Note that content does not need to be marked as safe because this is automatically handled.
"""
raise NotImplementedError
def right_page(self):
"""
Content that will be rendered on the right of the detail page view. Content should be returned as an
HTML string. Note that content does not need to be marked as safe because this is automatically handled.
"""
raise NotImplementedError
def full_width_page(self):
"""
Content that will be rendered within the full width of the detail page view. Content should be returned as an
HTML string. Note that content does not need to be marked as safe because this is automatically handled.
"""
raise NotImplementedError
def buttons(self):
"""
Buttons that will be rendered and added to the existing list of buttons on the detail page view. Content
should be returned as an HTML string. Note that content does not need to be marked as safe because this is
automatically handled.
"""
raise NotImplementedError
def register_template_extensions(class_list):
2020-03-17 02:35:12 -04:00
"""
Register a list of PluginTemplateExtension classes
2020-03-17 02:35:12 -04:00
"""
# Validation
for template_extension in class_list:
if not inspect.isclass(template_extension):
raise TypeError(f"PluginTemplateExtension class {template_extension} was passes as an instance!")
if not issubclass(template_extension, PluginTemplateExtension):
raise TypeError(f"{template_extension} is not a subclass of extras.plugins.PluginTemplateExtension!")
if template_extension.model is None:
raise TypeError(f"PluginTemplateExtension class {template_extension} does not define a valid model!")
registry['plugin_template_extensions'][template_extension.model].append(template_extension)
2020-03-17 02:35:12 -04:00
#
# Navigation menu links
2020-03-17 02:35:12 -04:00
#
class PluginMenuItem:
2020-03-17 02:35:12 -04:00
"""
2020-03-26 12:25:36 -04:00
This class represents a navigation menu item. This constitutes primary link and its text, but also allows for
2020-03-17 02:35:12 -04:00
specifying additional link buttons that appear to the right of the item in the van menu.
Links are specified as Django reverse URL strings.
Buttons are each specified as a list of PluginMenuButton instances.
2020-03-17 02:35:12 -04:00
"""
permissions = []
buttons = []
def __init__(self, link, link_text, permissions=None, buttons=None):
self.link = link
self.link_text = link_text
if permissions is not None:
if type(permissions) not in (list, tuple):
raise TypeError("Permissions must be passed as a tuple or list.")
self.permissions = permissions
if buttons is not None:
2020-03-27 13:12:58 -04:00
if type(buttons) not in (list, tuple):
raise TypeError("Buttons must be passed as a tuple or list.")
self.buttons = buttons
2020-03-17 02:35:12 -04:00
class PluginMenuButton:
2020-03-17 02:35:12 -04:00
"""
2020-03-26 12:25:36 -04:00
This class represents a button within a PluginMenuItem. Note that button colors should come from
ButtonColorChoices.
2020-03-17 02:35:12 -04:00
"""
2020-03-26 11:26:11 -04:00
color = ButtonColorChoices.DEFAULT
permissions = []
2020-03-26 11:26:11 -04:00
def __init__(self, link, title, icon_class, color=None, permissions=None):
2020-03-17 02:35:12 -04:00
self.link = link
self.title = title
self.icon_class = icon_class
if permissions is not None:
if type(permissions) not in (list, tuple):
raise TypeError("Permissions must be passed as a tuple or list.")
self.permissions = permissions
2020-03-26 11:26:11 -04:00
if color is not None:
2020-03-27 13:12:58 -04:00
if color not in ButtonColorChoices.values():
raise ValueError("Button color must be a choice within ButtonColorChoices.")
2020-03-26 11:26:11 -04:00
self.color = color
2020-03-17 02:35:12 -04:00
def register_menu_items(section_name, class_list):
2020-03-17 02:35:12 -04:00
"""
Register a list of PluginMenuItem instances for a given menu section (e.g. plugin name)
2020-03-17 02:35:12 -04:00
"""
# Validation
for menu_link in class_list:
if not isinstance(menu_link, PluginMenuItem):
raise TypeError(f"{menu_link} must be an instance of extras.plugins.PluginMenuItem")
for button in menu_link.buttons:
if not isinstance(button, PluginMenuButton):
raise TypeError(f"{button} must be an instance of extras.plugins.PluginMenuButton")
2020-03-17 02:35:12 -04:00
2020-03-26 12:25:36 -04:00
registry['plugin_menu_items'][section_name] = class_list