__init__.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. import collections
  2. import inspect
  3. from django.apps import AppConfig
  4. from django.template.loader import get_template
  5. from django.utils.module_loading import import_string
  6. from extras.registry import registry
  7. from .signals import register_detail_page_content_classes
  8. # Initialize plugin registry stores
  9. registry['plugin_nav_menu_links'] = {}
  10. #
  11. # Plugin AppConfig class
  12. #
  13. class PluginConfig(AppConfig):
  14. """
  15. Subclass of Django's built-in AppConfig class, to be used for NetBox plugins.
  16. """
  17. # Plugin metadata
  18. author = ''
  19. author_email = ''
  20. description = ''
  21. version = ''
  22. # Root URL path under /plugins. If not set, the plugin's label will be used.
  23. base_url = None
  24. # Minimum/maximum compatible versions of NetBox
  25. min_version = None
  26. max_version = None
  27. # Default configuration parameters
  28. default_settings = {}
  29. # Mandatory configuration parameters
  30. required_settings = []
  31. # Middleware classes provided by the plugin
  32. middleware = []
  33. # Caching configuration
  34. caching_config = {}
  35. # Default integration paths. Plugin authors can override these to customize the paths to
  36. # integrated components.
  37. menu_items = 'navigation.menu_items'
  38. def ready(self):
  39. # Register navigation menu items (if defined)
  40. try:
  41. menu_items = import_string(f"{self.__module__}.{self.menu_items}")
  42. register_menu_items(self.verbose_name, menu_items)
  43. except ImportError:
  44. pass
  45. #
  46. # Template content injection
  47. #
  48. class PluginTemplateContent:
  49. """
  50. This class is used to register plugin content to be injected into core NetBox templates.
  51. It contains methods that are overriden by plugin authors to return template content.
  52. The `model` attribute on the class defines the which model detail page this class renders
  53. content for. It should be set as a string in the form '<app_label>.<model_name>'.
  54. """
  55. model = None
  56. def __init__(self, obj, context):
  57. self.obj = obj
  58. self.context = context
  59. def render(self, template, extra_context=None):
  60. """
  61. Convenience menthod for rendering the provided template name. The detail page object is automatically
  62. passed into the template context as `obj` and the origional detail page's context is available as
  63. `obj_context`. An additional context dictionary may be passed as `extra_context`.
  64. """
  65. context = {
  66. 'obj': self.obj,
  67. 'obj_context': self.context
  68. }
  69. if isinstance(extra_context, dict):
  70. context.update(extra_context)
  71. return get_template(template).render(context)
  72. def left_page(self):
  73. """
  74. Content that will be rendered on the left of the detail page view. Content should be returned as an
  75. HTML string. Note that content does not need to be marked as safe because this is automatically handled.
  76. """
  77. raise NotImplementedError
  78. def right_page(self):
  79. """
  80. Content that will be rendered on the right of the detail page view. Content should be returned as an
  81. HTML string. Note that content does not need to be marked as safe because this is automatically handled.
  82. """
  83. raise NotImplementedError
  84. def full_width_page(self):
  85. """
  86. Content that will be rendered within the full width of the detail page view. Content should be returned as an
  87. HTML string. Note that content does not need to be marked as safe because this is automatically handled.
  88. """
  89. raise NotImplementedError
  90. def buttons(self):
  91. """
  92. Buttons that will be rendered and added to the existing list of buttons on the detail page view. Content
  93. should be returned as an HTML string. Note that content does not need to be marked as safe because this is
  94. automatically handled.
  95. """
  96. raise NotImplementedError
  97. def register_content_classes():
  98. """
  99. Helper method that populates the registry with all template content classes that have been registered by plugins
  100. """
  101. registry['plugin_template_content_classes'] = collections.defaultdict(list)
  102. responses = register_detail_page_content_classes.send('registration_event')
  103. for receiver, response in responses:
  104. if not isinstance(response, list):
  105. response = [response]
  106. for template_class in response:
  107. if not inspect.isclass(template_class):
  108. raise TypeError('Plugin content class {} was passes as an instance!'.format(template_class))
  109. if not issubclass(template_class, PluginTemplateContent):
  110. raise TypeError('{} is not a subclass of extras.plugins.PluginTemplateContent!'.format(template_class))
  111. if template_class.model is None:
  112. raise TypeError('Plugin content class {} does not define a valid model!'.format(template_class))
  113. registry['plugin_template_content_classes'][template_class.model].append(template_class)
  114. def get_content_classes(model):
  115. """
  116. Given a model string, return the list of all registered template content classes.
  117. Populate the registry if it is empty.
  118. """
  119. if 'plugin_template_content_classes' not in registry:
  120. register_content_classes()
  121. return registry['plugin_template_content_classes'].get(model, [])
  122. #
  123. # Navigation menu links
  124. #
  125. class PluginNavMenuLink:
  126. """
  127. This class represents a nav menu item. This constitutes primary link and its text, but also allows for
  128. specifying additional link buttons that appear to the right of the item in the van menu.
  129. Links are specified as Django reverse URL strings.
  130. Buttons are each specified as a list of PluginNavMenuButton instances.
  131. """
  132. def __init__(self, link, link_text, permission=None, buttons=None):
  133. self.link = link
  134. self.link_text = link_text
  135. self.link_permission = permission
  136. if buttons is None:
  137. self.buttons = []
  138. else:
  139. self.buttons = buttons
  140. class PluginNavMenuButton:
  141. """
  142. This class represents a button which is a part of the nav menu link item.
  143. Note that button colors should come from ButtonColorChoices
  144. """
  145. def __init__(self, link, title, icon_class, color, permission=None):
  146. self.link = link
  147. self.title = title
  148. self.icon_class = icon_class
  149. self.color = color
  150. self.permission = permission
  151. def register_menu_items(section_name, class_list):
  152. """
  153. Register a list of PluginNavMenuLink instances for a given menu section (e.g. plugin name)
  154. """
  155. # Validation
  156. for menu_link in class_list:
  157. if not isinstance(menu_link, PluginNavMenuLink):
  158. raise TypeError(f"{menu_link} must be an instance of extras.plugins.PluginNavMenuLink")
  159. for button in menu_link.buttons:
  160. if not isinstance(button, PluginNavMenuButton):
  161. raise TypeError(f"{button} must be an instance of extras.plugins.PluginNavMenuButton")
  162. registry['plugin_nav_menu_links'][section_name] = class_list