models.py 27 KB

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