models.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. import json
  2. import os
  3. import urllib.parse
  4. from django.conf import settings
  5. from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
  6. from django.contrib.postgres.fields import ArrayField
  7. from django.core.validators import ValidationError
  8. from django.db import models
  9. from django.urls import reverse
  10. from django.utils import timezone
  11. from django.utils.html import escape
  12. from django.utils.safestring import mark_safe
  13. from django.utils.translation import gettext_lazy as _
  14. from rest_framework.utils.encoders import JSONEncoder
  15. from extras.choices import *
  16. from extras.conditions import ConditionSet, InvalidCondition
  17. from extras.constants import *
  18. from extras.models.mixins import RenderTemplateMixin
  19. from extras.utils import image_upload
  20. from netbox.config import get_config
  21. from netbox.events import get_event_type_choices
  22. from netbox.models import ChangeLoggedModel
  23. from netbox.models.features import (
  24. CloningMixin, CustomFieldsMixin, CustomLinksMixin, ExportTemplatesMixin, SyncedDataMixin, TagsMixin, has_feature
  25. )
  26. from utilities.html import clean_html
  27. from utilities.jinja2 import render_jinja2
  28. from utilities.querydict import dict_to_querydict
  29. from utilities.querysets import RestrictedQuerySet
  30. from utilities.tables import get_table_for_model
  31. __all__ = (
  32. 'Bookmark',
  33. 'CustomLink',
  34. 'EventRule',
  35. 'ExportTemplate',
  36. 'ImageAttachment',
  37. 'JournalEntry',
  38. 'SavedFilter',
  39. 'TableConfig',
  40. 'Webhook',
  41. )
  42. class EventRule(CustomFieldsMixin, ExportTemplatesMixin, TagsMixin, ChangeLoggedModel):
  43. """
  44. An EventRule defines an action to be taken automatically in response to a specific set of events, such as when a
  45. specific type of object is created, modified, or deleted. The action to be taken might entail transmitting a
  46. webhook or executing a custom script.
  47. """
  48. object_types = models.ManyToManyField(
  49. to='contenttypes.ContentType',
  50. related_name='event_rules',
  51. verbose_name=_('object types'),
  52. help_text=_("The object(s) to which this rule applies.")
  53. )
  54. name = models.CharField(
  55. verbose_name=_('name'),
  56. max_length=150,
  57. unique=True
  58. )
  59. description = models.CharField(
  60. verbose_name=_('description'),
  61. max_length=200,
  62. blank=True
  63. )
  64. event_types = ArrayField(
  65. base_field=models.CharField(max_length=50, choices=get_event_type_choices),
  66. help_text=_("The types of event which will trigger this rule.")
  67. )
  68. enabled = models.BooleanField(
  69. verbose_name=_('enabled'),
  70. default=True
  71. )
  72. conditions = models.JSONField(
  73. verbose_name=_('conditions'),
  74. blank=True,
  75. null=True,
  76. help_text=_("A set of conditions which determine whether the event will be generated.")
  77. )
  78. # Action to take
  79. action_type = models.CharField(
  80. max_length=30,
  81. choices=EventRuleActionChoices,
  82. default=EventRuleActionChoices.WEBHOOK,
  83. verbose_name=_('action type')
  84. )
  85. action_object_type = models.ForeignKey(
  86. to='contenttypes.ContentType',
  87. related_name='eventrule_actions',
  88. on_delete=models.CASCADE
  89. )
  90. action_object_id = models.PositiveBigIntegerField(
  91. blank=True,
  92. null=True
  93. )
  94. action_object = GenericForeignKey(
  95. ct_field='action_object_type',
  96. fk_field='action_object_id'
  97. )
  98. action_data = models.JSONField(
  99. verbose_name=_('data'),
  100. blank=True,
  101. null=True,
  102. help_text=_("Additional data to pass to the action object")
  103. )
  104. comments = models.TextField(
  105. verbose_name=_('comments'),
  106. blank=True
  107. )
  108. class Meta:
  109. ordering = ('name',)
  110. indexes = (
  111. models.Index(fields=('action_object_type', 'action_object_id')),
  112. )
  113. verbose_name = _('event rule')
  114. verbose_name_plural = _('event rules')
  115. def __str__(self):
  116. return self.name
  117. def get_absolute_url(self):
  118. return reverse('extras:eventrule', args=[self.pk])
  119. def clean(self):
  120. super().clean()
  121. # Validate that any conditions are in the correct format
  122. if self.conditions:
  123. try:
  124. ConditionSet(self.conditions)
  125. except ValueError as e:
  126. raise ValidationError({'conditions': e})
  127. def eval_conditions(self, data):
  128. """
  129. Test whether the given data meets the conditions of the event rule (if any). Return True
  130. if met or no conditions are specified.
  131. """
  132. if not self.conditions:
  133. return True
  134. logger = logging.getLogger('netbox.event_rules')
  135. try:
  136. result = ConditionSet(self.conditions).eval(data)
  137. logger.debug(f'{self.name}: Evaluated as {result}')
  138. return result
  139. except InvalidCondition as e:
  140. logger.error(f"{self.name}: Evaluation failed. {e}")
  141. return False
  142. class Webhook(CustomFieldsMixin, ExportTemplatesMixin, TagsMixin, ChangeLoggedModel):
  143. """
  144. A Webhook defines a request that will be sent to a remote application when an object is created, updated, and/or
  145. delete in NetBox. The request will contain a representation of the object, which the remote application can act on.
  146. Each Webhook can be limited to firing only on certain actions or certain object types.
  147. """
  148. name = models.CharField(
  149. verbose_name=_('name'),
  150. max_length=150,
  151. unique=True
  152. )
  153. description = models.CharField(
  154. verbose_name=_('description'),
  155. max_length=200,
  156. blank=True
  157. )
  158. payload_url = models.CharField(
  159. max_length=500,
  160. verbose_name=_('URL'),
  161. help_text=_(
  162. "This URL will be called using the HTTP method defined when the webhook is called. Jinja2 template "
  163. "processing is supported with the same context as the request body."
  164. )
  165. )
  166. http_method = models.CharField(
  167. max_length=30,
  168. choices=WebhookHttpMethodChoices,
  169. default=WebhookHttpMethodChoices.METHOD_POST,
  170. verbose_name=_('HTTP method')
  171. )
  172. http_content_type = models.CharField(
  173. max_length=100,
  174. default=HTTP_CONTENT_TYPE_JSON,
  175. verbose_name=_('HTTP content type'),
  176. help_text=_(
  177. 'The complete list of official content types is available '
  178. '<a href="https://www.iana.org/assignments/media-types/media-types.xhtml">here</a>.'
  179. )
  180. )
  181. additional_headers = models.TextField(
  182. verbose_name=_('additional headers'),
  183. blank=True,
  184. help_text=_(
  185. "User-supplied HTTP headers to be sent with the request in addition to the HTTP content type. Headers "
  186. "should be defined in the format <code>Name: Value</code>. Jinja2 template processing is supported with "
  187. "the same context as the request body (below)."
  188. )
  189. )
  190. body_template = models.TextField(
  191. verbose_name=_('body template'),
  192. blank=True,
  193. help_text=_(
  194. "Jinja2 template for a custom request body. If blank, a JSON object representing the change will be "
  195. "included. Available context data includes: <code>event</code>, <code>model</code>, "
  196. "<code>timestamp</code>, <code>username</code>, <code>request_id</code>, and <code>data</code>."
  197. )
  198. )
  199. secret = models.CharField(
  200. verbose_name=_('secret'),
  201. max_length=255,
  202. blank=True,
  203. help_text=_(
  204. "When provided, the request will include a <code>X-Hook-Signature</code> header containing a HMAC hex "
  205. "digest of the payload body using the secret as the key. The secret is not transmitted in the request."
  206. )
  207. )
  208. ssl_verification = models.BooleanField(
  209. default=True,
  210. verbose_name=_('SSL verification'),
  211. help_text=_("Enable SSL certificate verification. Disable with caution!")
  212. )
  213. ca_file_path = models.CharField(
  214. max_length=4096,
  215. null=True,
  216. blank=True,
  217. verbose_name=_('CA File Path'),
  218. help_text=_(
  219. "The specific CA certificate file to use for SSL verification. Leave blank to use the system defaults."
  220. )
  221. )
  222. events = GenericRelation(
  223. EventRule,
  224. content_type_field='action_object_type',
  225. object_id_field='action_object_id'
  226. )
  227. class Meta:
  228. ordering = ('name',)
  229. verbose_name = _('webhook')
  230. verbose_name_plural = _('webhooks')
  231. def __str__(self):
  232. return self.name
  233. def get_absolute_url(self):
  234. return reverse('extras:webhook', args=[self.pk])
  235. @property
  236. def docs_url(self):
  237. return f'{settings.STATIC_URL}docs/models/extras/webhook/'
  238. def clean(self):
  239. super().clean()
  240. # CA file path requires SSL verification enabled
  241. if not self.ssl_verification and self.ca_file_path:
  242. raise ValidationError({
  243. 'ca_file_path': _('Do not specify a CA certificate file if SSL verification is disabled.')
  244. })
  245. def render_headers(self, context):
  246. """
  247. Render additional_headers and return a dict of Header: Value pairs.
  248. """
  249. if not self.additional_headers:
  250. return {}
  251. ret = {}
  252. data = render_jinja2(self.additional_headers, context)
  253. for line in data.splitlines():
  254. header, value = line.split(':', 1)
  255. ret[header.strip()] = value.strip()
  256. return ret
  257. def render_body(self, context):
  258. """
  259. Render the body template, if defined. Otherwise, jump the context as a JSON object.
  260. """
  261. if self.body_template:
  262. return render_jinja2(self.body_template, context)
  263. else:
  264. return json.dumps(context, cls=JSONEncoder)
  265. def render_payload_url(self, context):
  266. """
  267. Render the payload URL.
  268. """
  269. return render_jinja2(self.payload_url, context)
  270. class CustomLink(CloningMixin, ExportTemplatesMixin, ChangeLoggedModel):
  271. """
  272. A custom link to an external representation of a NetBox object. The link text and URL fields accept Jinja2 template
  273. code to be rendered with an object as context.
  274. """
  275. object_types = models.ManyToManyField(
  276. to='contenttypes.ContentType',
  277. related_name='custom_links',
  278. help_text=_('The object type(s) to which this link applies.')
  279. )
  280. name = models.CharField(
  281. verbose_name=_('name'),
  282. max_length=100,
  283. unique=True
  284. )
  285. enabled = models.BooleanField(
  286. verbose_name=_('enabled'),
  287. default=True
  288. )
  289. link_text = models.TextField(
  290. verbose_name=_('link text'),
  291. help_text=_("Jinja2 template code for link text")
  292. )
  293. link_url = models.TextField(
  294. verbose_name=_('link URL'),
  295. help_text=_("Jinja2 template code for link URL")
  296. )
  297. weight = models.PositiveSmallIntegerField(
  298. verbose_name=_('weight'),
  299. default=100
  300. )
  301. group_name = models.CharField(
  302. verbose_name=_('group name'),
  303. max_length=50,
  304. blank=True,
  305. help_text=_("Links with the same group will appear as a dropdown menu")
  306. )
  307. button_class = models.CharField(
  308. verbose_name=_('button class'),
  309. max_length=30,
  310. choices=CustomLinkButtonClassChoices,
  311. default=CustomLinkButtonClassChoices.DEFAULT,
  312. help_text=_("The class of the first link in a group will be used for the dropdown button")
  313. )
  314. new_window = models.BooleanField(
  315. verbose_name=_('new window'),
  316. default=False,
  317. help_text=_("Force link to open in a new window")
  318. )
  319. clone_fields = (
  320. 'object_types', 'enabled', 'weight', 'group_name', 'button_class', 'new_window',
  321. )
  322. class Meta:
  323. ordering = ['group_name', 'weight', 'name']
  324. verbose_name = _('custom link')
  325. verbose_name_plural = _('custom links')
  326. def __str__(self):
  327. return self.name
  328. def get_absolute_url(self):
  329. return reverse('extras:customlink', args=[self.pk])
  330. @property
  331. def docs_url(self):
  332. return f'{settings.STATIC_URL}docs/models/extras/customlink/'
  333. def render(self, context):
  334. """
  335. Render the CustomLink given the provided context, and return the text, link, and link_target.
  336. :param context: The context passed to Jinja2
  337. """
  338. text = render_jinja2(self.link_text, context).strip()
  339. if not text:
  340. return {}
  341. link = render_jinja2(self.link_url, context).strip()
  342. link_target = ' target="_blank"' if self.new_window else ''
  343. # Sanitize link text
  344. allowed_schemes = get_config().ALLOWED_URL_SCHEMES
  345. text = clean_html(text, allowed_schemes)
  346. # Sanitize link
  347. link = urllib.parse.quote(link, safe='/:?&=%+[]@#,;!')
  348. # Verify link scheme is allowed
  349. result = urllib.parse.urlparse(link)
  350. if result.scheme and result.scheme not in allowed_schemes:
  351. link = ""
  352. return {
  353. 'text': text,
  354. 'link': link,
  355. 'link_target': link_target,
  356. }
  357. class ExportTemplate(SyncedDataMixin, CloningMixin, ExportTemplatesMixin, ChangeLoggedModel, RenderTemplateMixin):
  358. object_types = models.ManyToManyField(
  359. to='contenttypes.ContentType',
  360. related_name='export_templates',
  361. help_text=_('The object type(s) to which this template applies.')
  362. )
  363. name = models.CharField(
  364. verbose_name=_('name'),
  365. max_length=100
  366. )
  367. description = models.CharField(
  368. verbose_name=_('description'),
  369. max_length=200,
  370. blank=True
  371. )
  372. clone_fields = (
  373. 'object_types', 'template_code', 'mime_type', 'file_name', 'file_extension', 'as_attachment',
  374. )
  375. class Meta:
  376. ordering = ('name',)
  377. verbose_name = _('export template')
  378. verbose_name_plural = _('export templates')
  379. def __str__(self):
  380. return self.name
  381. def get_absolute_url(self):
  382. return reverse('extras:exporttemplate', args=[self.pk])
  383. @property
  384. def docs_url(self):
  385. return f'{settings.STATIC_URL}docs/models/extras/exporttemplate/'
  386. def clean(self):
  387. super().clean()
  388. if self.name.lower() == 'table':
  389. raise ValidationError({
  390. 'name': _('"{name}" is a reserved name. Please choose a different name.').format(name=self.name)
  391. })
  392. def sync_data(self):
  393. """
  394. Synchronize template content from the designated DataFile (if any).
  395. """
  396. self.template_code = self.data_file.data_as_string
  397. sync_data.alters_data = True
  398. def get_context(self, context=None, queryset=None):
  399. _context = {
  400. 'queryset': queryset,
  401. }
  402. # Apply the provided context data, if any
  403. if context is not None:
  404. _context.update(context)
  405. return _context
  406. class SavedFilter(CloningMixin, ExportTemplatesMixin, ChangeLoggedModel):
  407. """
  408. A set of predefined keyword parameters that can be reused to filter for specific objects.
  409. """
  410. object_types = models.ManyToManyField(
  411. to='contenttypes.ContentType',
  412. related_name='saved_filters',
  413. help_text=_('The object type(s) to which this filter applies.')
  414. )
  415. name = models.CharField(
  416. verbose_name=_('name'),
  417. max_length=100,
  418. unique=True
  419. )
  420. slug = models.SlugField(
  421. verbose_name=_('slug'),
  422. max_length=100,
  423. unique=True
  424. )
  425. description = models.CharField(
  426. verbose_name=_('description'),
  427. max_length=200,
  428. blank=True
  429. )
  430. user = models.ForeignKey(
  431. to=settings.AUTH_USER_MODEL,
  432. on_delete=models.SET_NULL,
  433. blank=True,
  434. null=True
  435. )
  436. weight = models.PositiveSmallIntegerField(
  437. verbose_name=_('weight'),
  438. default=100
  439. )
  440. enabled = models.BooleanField(
  441. verbose_name=_('enabled'),
  442. default=True
  443. )
  444. shared = models.BooleanField(
  445. verbose_name=_('shared'),
  446. default=True
  447. )
  448. parameters = models.JSONField(
  449. verbose_name=_('parameters')
  450. )
  451. clone_fields = (
  452. 'object_types', 'weight', 'enabled', 'parameters',
  453. )
  454. class Meta:
  455. ordering = ('weight', 'name')
  456. verbose_name = _('saved filter')
  457. verbose_name_plural = _('saved filters')
  458. def __str__(self):
  459. return self.name
  460. def get_absolute_url(self):
  461. return reverse('extras:savedfilter', args=[self.pk])
  462. @property
  463. def docs_url(self):
  464. return f'{settings.STATIC_URL}docs/models/extras/savedfilter/'
  465. def clean(self):
  466. super().clean()
  467. # Verify that `parameters` is a JSON object
  468. if type(self.parameters) is not dict:
  469. raise ValidationError(
  470. {'parameters': _('Filter parameters must be stored as a dictionary of keyword arguments.')}
  471. )
  472. @property
  473. def url_params(self):
  474. qd = dict_to_querydict(self.parameters)
  475. return qd.urlencode()
  476. class TableConfig(CloningMixin, ChangeLoggedModel):
  477. """
  478. A saved configuration of columns and ordering which applies to a specific table.
  479. """
  480. object_type = models.ForeignKey(
  481. to='contenttypes.ContentType',
  482. on_delete=models.CASCADE,
  483. related_name='table_configs',
  484. help_text=_("The table's object type"),
  485. )
  486. table = models.CharField(
  487. verbose_name=_('table'),
  488. max_length=100,
  489. )
  490. name = models.CharField(
  491. verbose_name=_('name'),
  492. max_length=100,
  493. )
  494. description = models.CharField(
  495. verbose_name=_('description'),
  496. max_length=200,
  497. blank=True,
  498. )
  499. user = models.ForeignKey(
  500. to=settings.AUTH_USER_MODEL,
  501. on_delete=models.SET_NULL,
  502. blank=True,
  503. null=True,
  504. )
  505. weight = models.PositiveSmallIntegerField(
  506. verbose_name=_('weight'),
  507. default=1000,
  508. )
  509. enabled = models.BooleanField(
  510. verbose_name=_('enabled'),
  511. default=True
  512. )
  513. shared = models.BooleanField(
  514. verbose_name=_('shared'),
  515. default=True
  516. )
  517. columns = ArrayField(
  518. base_field=models.CharField(max_length=100),
  519. )
  520. ordering = ArrayField(
  521. base_field=models.CharField(max_length=100),
  522. blank=True,
  523. null=True,
  524. )
  525. clone_fields = ('object_type', 'table', 'enabled', 'shared', 'columns', 'ordering')
  526. class Meta:
  527. ordering = ('weight', 'name')
  528. verbose_name = _('table config')
  529. verbose_name_plural = _('table configs')
  530. def __str__(self):
  531. return self.name
  532. def get_absolute_url(self):
  533. return reverse('extras:tableconfig', args=[self.pk])
  534. @property
  535. def docs_url(self):
  536. return f'{settings.STATIC_URL}docs/models/extras/tableconfig/'
  537. @property
  538. def table_class(self):
  539. return get_table_for_model(self.object_type.model_class(), name=self.table)
  540. @property
  541. def ordering_items(self):
  542. """
  543. Return a list of two-tuples indicating the column(s) by which the table is to be ordered and a boolean for each
  544. column indicating whether its ordering is ascending.
  545. """
  546. items = []
  547. for col in self.ordering or []:
  548. if col.startswith('-'):
  549. ascending = False
  550. col = col[1:]
  551. else:
  552. ascending = True
  553. items.append((col, ascending))
  554. return items
  555. def clean(self):
  556. super().clean()
  557. # Validate table
  558. if self.table_class is None:
  559. raise ValidationError({
  560. 'table': _("Unknown table: {name}").format(name=self.table)
  561. })
  562. table = self.table_class([])
  563. # Validate ordering columns
  564. for name in self.ordering:
  565. if name.startswith('-'):
  566. name = name[1:] # Strip leading hyphen
  567. if name not in table.columns:
  568. raise ValidationError({
  569. 'ordering': _('Unknown column: {name}').format(name=name)
  570. })
  571. # Validate selected columns
  572. for name in self.columns:
  573. if name not in table.columns:
  574. raise ValidationError({
  575. 'columns': _('Unknown column: {name}').format(name=name)
  576. })
  577. class ImageAttachment(ChangeLoggedModel):
  578. """
  579. An uploaded image which is associated with an object.
  580. """
  581. object_type = models.ForeignKey(
  582. to='contenttypes.ContentType',
  583. on_delete=models.CASCADE
  584. )
  585. object_id = models.PositiveBigIntegerField()
  586. parent = GenericForeignKey(
  587. ct_field='object_type',
  588. fk_field='object_id'
  589. )
  590. image = models.ImageField(
  591. upload_to=image_upload,
  592. height_field='image_height',
  593. width_field='image_width'
  594. )
  595. image_height = models.PositiveSmallIntegerField(
  596. verbose_name=_('image height'),
  597. )
  598. image_width = models.PositiveSmallIntegerField(
  599. verbose_name=_('image width'),
  600. )
  601. name = models.CharField(
  602. verbose_name=_('name'),
  603. max_length=50,
  604. blank=True
  605. )
  606. description = models.CharField(
  607. verbose_name=_('description'),
  608. max_length=200,
  609. blank=True
  610. )
  611. objects = RestrictedQuerySet.as_manager()
  612. clone_fields = ('object_type', 'object_id')
  613. class Meta:
  614. ordering = ('name', 'pk') # name may be non-unique
  615. indexes = (
  616. models.Index(fields=('object_type', 'object_id')),
  617. )
  618. verbose_name = _('image attachment')
  619. verbose_name_plural = _('image attachments')
  620. def __str__(self):
  621. return self.name or self.filename
  622. def get_absolute_url(self):
  623. return reverse('extras:imageattachment', args=[self.pk])
  624. def clean(self):
  625. super().clean()
  626. # Validate the assigned object type
  627. if not has_feature(self.object_type, 'image_attachments'):
  628. raise ValidationError(
  629. _("Image attachments cannot be assigned to this object type ({type}).").format(type=self.object_type)
  630. )
  631. def delete(self, *args, **kwargs):
  632. _name = self.image.name
  633. super().delete(*args, **kwargs)
  634. # Delete file from disk
  635. self.image.delete(save=False)
  636. # Deleting the file erases its name. We restore the image's filename here in case we still need to reference it
  637. # before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
  638. self.image.name = _name
  639. @property
  640. def filename(self):
  641. return os.path.basename(self.image.name).split('_', 2)[2]
  642. @property
  643. def html_tag(self):
  644. """
  645. Returns a complete <img> tag suitable for embedding in an HTML document.
  646. """
  647. return mark_safe('<img src="{url}" height="{height}" width="{width}" alt="{alt_text}" />'.format(
  648. url=self.image.url,
  649. height=self.image_height,
  650. width=self.image_width,
  651. alt_text=escape(self.description or self.name),
  652. ))
  653. @property
  654. def size(self):
  655. """
  656. Wrapper around `image.size` to suppress an OSError in case the file is inaccessible. Also opportunistically
  657. catch other exceptions that we know other storage back-ends to throw.
  658. """
  659. expected_exceptions = [OSError]
  660. try:
  661. from botocore.exceptions import ClientError
  662. expected_exceptions.append(ClientError)
  663. except ImportError:
  664. pass
  665. try:
  666. return self.image.size
  667. except tuple(expected_exceptions):
  668. return None
  669. def to_objectchange(self, action):
  670. objectchange = super().to_objectchange(action)
  671. objectchange.related_object = self.parent
  672. return objectchange
  673. class JournalEntry(CustomFieldsMixin, CustomLinksMixin, TagsMixin, ExportTemplatesMixin, ChangeLoggedModel):
  674. """
  675. A historical remark concerning an object; collectively, these form an object's journal. The journal is used to
  676. preserve historical context around an object, and complements NetBox's built-in change logging. For example, you
  677. might record a new journal entry when a device undergoes maintenance, or when a prefix is expanded.
  678. """
  679. assigned_object_type = models.ForeignKey(
  680. to='contenttypes.ContentType',
  681. on_delete=models.CASCADE
  682. )
  683. assigned_object_id = models.PositiveBigIntegerField()
  684. assigned_object = GenericForeignKey(
  685. ct_field='assigned_object_type',
  686. fk_field='assigned_object_id'
  687. )
  688. created_by = models.ForeignKey(
  689. to=settings.AUTH_USER_MODEL,
  690. on_delete=models.SET_NULL,
  691. blank=True,
  692. null=True
  693. )
  694. kind = models.CharField(
  695. verbose_name=_('kind'),
  696. max_length=30,
  697. choices=JournalEntryKindChoices,
  698. default=JournalEntryKindChoices.KIND_INFO
  699. )
  700. comments = models.TextField(
  701. verbose_name=_('comments'),
  702. )
  703. class Meta:
  704. ordering = ('-created',)
  705. indexes = (
  706. models.Index(fields=('assigned_object_type', 'assigned_object_id')),
  707. )
  708. verbose_name = _('journal entry')
  709. verbose_name_plural = _('journal entries')
  710. def __str__(self):
  711. created = timezone.localtime(self.created)
  712. return (
  713. f"{created.date().isoformat()} {created.time().isoformat(timespec='minutes')} "
  714. f"({self.get_kind_display()})"
  715. )
  716. def get_absolute_url(self):
  717. return reverse('extras:journalentry', args=[self.pk])
  718. def clean(self):
  719. super().clean()
  720. # Validate the assigned object type
  721. if not has_feature(self.assigned_object_type, 'journaling'):
  722. raise ValidationError(
  723. _("Journaling is not supported for this object type ({type}).").format(type=self.assigned_object_type)
  724. )
  725. def get_kind_color(self):
  726. return JournalEntryKindChoices.colors.get(self.kind)
  727. class Bookmark(models.Model):
  728. """
  729. An object bookmarked by a User.
  730. """
  731. created = models.DateTimeField(
  732. verbose_name=_('created'),
  733. auto_now_add=True
  734. )
  735. object_type = models.ForeignKey(
  736. to='contenttypes.ContentType',
  737. on_delete=models.PROTECT
  738. )
  739. object_id = models.PositiveBigIntegerField()
  740. object = GenericForeignKey(
  741. ct_field='object_type',
  742. fk_field='object_id'
  743. )
  744. user = models.ForeignKey(
  745. to=settings.AUTH_USER_MODEL,
  746. on_delete=models.CASCADE
  747. )
  748. objects = RestrictedQuerySet.as_manager()
  749. class Meta:
  750. ordering = ('created', 'pk')
  751. indexes = (
  752. models.Index(fields=('object_type', 'object_id')),
  753. )
  754. constraints = (
  755. models.UniqueConstraint(
  756. fields=('object_type', 'object_id', 'user'),
  757. name='%(app_label)s_%(class)s_unique_per_object_and_user'
  758. ),
  759. )
  760. verbose_name = _('bookmark')
  761. verbose_name_plural = _('bookmarks')
  762. def __str__(self):
  763. if self.object:
  764. return str(self.object)
  765. return super().__str__()
  766. def clean(self):
  767. super().clean()
  768. # Validate the assigned object type
  769. if not has_feature(self.object_type, 'bookmarks'):
  770. raise ValidationError(
  771. _("Bookmarks cannot be assigned to this object type ({type}).").format(type=self.object_type)
  772. )