utils.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. import datetime
  2. import decimal
  3. import json
  4. import re
  5. from decimal import Decimal
  6. from itertools import count, groupby
  7. import bleach
  8. from django.contrib.contenttypes.models import ContentType
  9. from django.core import serializers
  10. from django.db.models import Count, OuterRef, Subquery
  11. from django.db.models.functions import Coalesce
  12. from django.http import QueryDict
  13. from django.utils.html import escape
  14. from django.utils import timezone
  15. from django.utils.timezone import localtime
  16. from jinja2.sandbox import SandboxedEnvironment
  17. from mptt.models import MPTTModel
  18. from dcim.choices import CableLengthUnitChoices, WeightUnitChoices
  19. from extras.plugins import PluginConfig
  20. from extras.utils import is_taggable
  21. from netbox.config import get_config
  22. from urllib.parse import urlencode
  23. from utilities.constants import HTTP_REQUEST_META_SAFE_COPY
  24. def title(value):
  25. """
  26. Improved implementation of str.title(); retains all existing uppercase letters.
  27. """
  28. return ' '.join([w[0].upper() + w[1:] for w in str(value).split()])
  29. def get_viewname(model, action=None, rest_api=False):
  30. """
  31. Return the view name for the given model and action, if valid.
  32. :param model: The model or instance to which the view applies
  33. :param action: A string indicating the desired action (if any); e.g. "add" or "list"
  34. :param rest_api: A boolean indicating whether this is a REST API view
  35. """
  36. is_plugin = isinstance(model._meta.app_config, PluginConfig)
  37. app_label = model._meta.app_label
  38. model_name = model._meta.model_name
  39. if rest_api:
  40. if is_plugin:
  41. viewname = f'plugins-api:{app_label}-api:{model_name}'
  42. else:
  43. viewname = f'{app_label}-api:{model_name}'
  44. # Append the action, if any
  45. if action:
  46. viewname = f'{viewname}-{action}'
  47. else:
  48. viewname = f'{app_label}:{model_name}'
  49. # Prepend the plugins namespace if this is a plugin model
  50. if is_plugin:
  51. viewname = f'plugins:{viewname}'
  52. # Append the action, if any
  53. if action:
  54. viewname = f'{viewname}_{action}'
  55. return viewname
  56. def csv_format(data):
  57. """
  58. Encapsulate any data which contains a comma within double quotes.
  59. """
  60. csv = []
  61. for value in data:
  62. # Represent None or False with empty string
  63. if value is None or value is False:
  64. csv.append('')
  65. continue
  66. # Convert dates to ISO format
  67. if isinstance(value, (datetime.date, datetime.datetime)):
  68. value = value.isoformat()
  69. # Force conversion to string first so we can check for any commas
  70. if not isinstance(value, str):
  71. value = '{}'.format(value)
  72. # Double-quote the value if it contains a comma or line break
  73. if ',' in value or '\n' in value:
  74. value = value.replace('"', '""') # Escape double-quotes
  75. csv.append('"{}"'.format(value))
  76. else:
  77. csv.append('{}'.format(value))
  78. return ','.join(csv)
  79. def foreground_color(bg_color, dark='000000', light='ffffff'):
  80. """
  81. Return the ideal foreground color (dark or light) for a given background color in hexadecimal RGB format.
  82. :param dark: RBG color code for dark text
  83. :param light: RBG color code for light text
  84. """
  85. THRESHOLD = 150
  86. bg_color = bg_color.strip('#')
  87. r, g, b = [int(bg_color[c:c + 2], 16) for c in (0, 2, 4)]
  88. if r * 0.299 + g * 0.587 + b * 0.114 > THRESHOLD:
  89. return dark
  90. else:
  91. return light
  92. def dynamic_import(name):
  93. """
  94. Dynamically import a class from an absolute path string
  95. """
  96. components = name.split('.')
  97. mod = __import__(components[0])
  98. for comp in components[1:]:
  99. mod = getattr(mod, comp)
  100. return mod
  101. def count_related(model, field):
  102. """
  103. Return a Subquery suitable for annotating a child object count.
  104. """
  105. subquery = Subquery(
  106. model.objects.filter(
  107. **{field: OuterRef('pk')}
  108. ).order_by().values(
  109. field
  110. ).annotate(
  111. c=Count('*')
  112. ).values('c')
  113. )
  114. return Coalesce(subquery, 0)
  115. def serialize_object(obj, resolve_tags=True, extra=None):
  116. """
  117. Return a generic JSON representation of an object using Django's built-in serializer. (This is used for things like
  118. change logging, not the REST API.) Optionally include a dictionary to supplement the object data. A list of keys
  119. can be provided to exclude them from the returned dictionary. Private fields (prefaced with an underscore) are
  120. implicitly excluded.
  121. """
  122. json_str = serializers.serialize('json', [obj])
  123. data = json.loads(json_str)[0]['fields']
  124. # Exclude any MPTTModel fields
  125. if issubclass(obj.__class__, MPTTModel):
  126. for field in ['level', 'lft', 'rght', 'tree_id']:
  127. data.pop(field)
  128. # Include custom_field_data as "custom_fields"
  129. if hasattr(obj, 'custom_field_data'):
  130. data['custom_fields'] = data.pop('custom_field_data')
  131. # Resolve any assigned tags to their names. Check for tags cached on the instance;
  132. # fall back to using the manager.
  133. if resolve_tags and is_taggable(obj):
  134. tags = getattr(obj, '_tags', None) or obj.tags.all()
  135. data['tags'] = sorted([tag.name for tag in tags])
  136. # Append any extra data
  137. if extra is not None:
  138. data.update(extra)
  139. # Copy keys to list to avoid 'dictionary changed size during iteration' exception
  140. for key in list(data):
  141. # Private fields shouldn't be logged in the object change
  142. if isinstance(key, str) and key.startswith('_'):
  143. data.pop(key)
  144. return data
  145. def deserialize_object(model, fields, pk=None):
  146. """
  147. Instantiate an object from the given model and field data. Functions as
  148. the complement to serialize_object().
  149. """
  150. content_type = ContentType.objects.get_for_model(model)
  151. if 'custom_fields' in fields:
  152. fields['custom_field_data'] = fields.pop('custom_fields')
  153. data = {
  154. 'model': '.'.join(content_type.natural_key()),
  155. 'pk': pk,
  156. 'fields': fields,
  157. }
  158. instance = list(serializers.deserialize('python', [data]))[0]
  159. return instance
  160. def dict_to_filter_params(d, prefix=''):
  161. """
  162. Translate a dictionary of attributes to a nested set of parameters suitable for QuerySet filtering. For example:
  163. {
  164. "name": "Foo",
  165. "rack": {
  166. "facility_id": "R101"
  167. }
  168. }
  169. Becomes:
  170. {
  171. "name": "Foo",
  172. "rack__facility_id": "R101"
  173. }
  174. And can be employed as filter parameters:
  175. Device.objects.filter(**dict_to_filter(attrs_dict))
  176. """
  177. params = {}
  178. for key, val in d.items():
  179. k = prefix + key
  180. if isinstance(val, dict):
  181. params.update(dict_to_filter_params(val, k + '__'))
  182. else:
  183. params[k] = val
  184. return params
  185. def normalize_querydict(querydict):
  186. """
  187. Convert a QueryDict to a normal, mutable dictionary, preserving list values. For example,
  188. QueryDict('foo=1&bar=2&bar=3&baz=')
  189. becomes:
  190. {'foo': '1', 'bar': ['2', '3'], 'baz': ''}
  191. This function is necessary because QueryDict does not provide any built-in mechanism which preserves multiple
  192. values.
  193. """
  194. return {
  195. k: v if len(v) > 1 else v[0] for k, v in querydict.lists()
  196. }
  197. def deepmerge(original, new):
  198. """
  199. Deep merge two dictionaries (new into original) and return a new dict
  200. """
  201. merged = dict(original)
  202. for key, val in new.items():
  203. if key in original and isinstance(original[key], dict) and val and isinstance(val, dict):
  204. merged[key] = deepmerge(original[key], val)
  205. else:
  206. merged[key] = val
  207. return merged
  208. def drange(start, end, step=decimal.Decimal(1)):
  209. """
  210. Decimal-compatible implementation of Python's range()
  211. """
  212. start, end, step = decimal.Decimal(start), decimal.Decimal(end), decimal.Decimal(step)
  213. if start < end:
  214. while start < end:
  215. yield start
  216. start += step
  217. else:
  218. while start > end:
  219. yield start
  220. start += step
  221. def to_meters(length, unit):
  222. """
  223. Convert the given length to meters.
  224. """
  225. try:
  226. if length < 0:
  227. raise ValueError("Length must be a positive number")
  228. except TypeError:
  229. raise TypeError(f"Invalid value '{length}' for length (must be a number)")
  230. valid_units = CableLengthUnitChoices.values()
  231. if unit not in valid_units:
  232. raise ValueError(f"Unknown unit {unit}. Must be one of the following: {', '.join(valid_units)}")
  233. if unit == CableLengthUnitChoices.UNIT_KILOMETER:
  234. return length * 1000
  235. if unit == CableLengthUnitChoices.UNIT_METER:
  236. return length
  237. if unit == CableLengthUnitChoices.UNIT_CENTIMETER:
  238. return length / 100
  239. if unit == CableLengthUnitChoices.UNIT_MILE:
  240. return length * Decimal(1609.344)
  241. if unit == CableLengthUnitChoices.UNIT_FOOT:
  242. return length * Decimal(0.3048)
  243. if unit == CableLengthUnitChoices.UNIT_INCH:
  244. return length * Decimal(0.3048) * 12
  245. raise ValueError(f"Unknown unit {unit}. Must be 'km', 'm', 'cm', 'mi', 'ft', or 'in'.")
  246. def to_grams(weight, unit):
  247. """
  248. Convert the given weight to kilograms.
  249. """
  250. try:
  251. if weight < 0:
  252. raise ValueError("Weight must be a positive number")
  253. except TypeError:
  254. raise TypeError(f"Invalid value '{weight}' for weight (must be a number)")
  255. valid_units = WeightUnitChoices.values()
  256. if unit not in valid_units:
  257. raise ValueError(f"Unknown unit {unit}. Must be one of the following: {', '.join(valid_units)}")
  258. if unit == WeightUnitChoices.UNIT_KILOGRAM:
  259. return weight * 1000
  260. if unit == WeightUnitChoices.UNIT_GRAM:
  261. return weight
  262. if unit == WeightUnitChoices.UNIT_POUND:
  263. return weight * Decimal(453.592)
  264. if unit == WeightUnitChoices.UNIT_OUNCE:
  265. return weight * Decimal(28.3495)
  266. raise ValueError(f"Unknown unit {unit}. Must be 'kg', 'g', 'lb', 'oz'.")
  267. def render_jinja2(template_code, context):
  268. """
  269. Render a Jinja2 template with the provided context. Return the rendered content.
  270. """
  271. environment = SandboxedEnvironment()
  272. environment.filters.update(get_config().JINJA2_FILTERS)
  273. return environment.from_string(source=template_code).render(**context)
  274. def prepare_cloned_fields(instance):
  275. """
  276. Generate a QueryDict comprising attributes from an object's clone() method.
  277. """
  278. # Generate the clone attributes from the instance
  279. if not hasattr(instance, 'clone'):
  280. return QueryDict(mutable=True)
  281. attrs = instance.clone()
  282. # Prepare querydict parameters
  283. params = []
  284. for key, value in attrs.items():
  285. if type(value) in (list, tuple):
  286. params.extend([(key, v) for v in value])
  287. elif value not in (False, None):
  288. params.append((key, value))
  289. else:
  290. params.append((key, ''))
  291. # Return a QueryDict with the parameters
  292. return QueryDict(urlencode(params), mutable=True)
  293. def shallow_compare_dict(source_dict, destination_dict, exclude=tuple()):
  294. """
  295. Return a new dictionary of the different keys. The values of `destination_dict` are returned. Only the equality of
  296. the first layer of keys/values is checked. `exclude` is a list or tuple of keys to be ignored.
  297. """
  298. difference = {}
  299. for key, value in destination_dict.items():
  300. if key in exclude:
  301. continue
  302. if source_dict.get(key) != value:
  303. difference[key] = value
  304. return difference
  305. def flatten_dict(d, prefix='', separator='.'):
  306. """
  307. Flatten netsted dictionaries into a single level by joining key names with a separator.
  308. :param d: The dictionary to be flattened
  309. :param prefix: Initial prefix (if any)
  310. :param separator: The character to use when concatenating key names
  311. """
  312. ret = {}
  313. for k, v in d.items():
  314. key = separator.join([prefix, k]) if prefix else k
  315. if type(v) is dict:
  316. ret.update(flatten_dict(v, prefix=key, separator=separator))
  317. else:
  318. ret[key] = v
  319. return ret
  320. def array_to_ranges(array):
  321. """
  322. Convert an arbitrary array of integers to a list of consecutive values. Nonconsecutive values are returned as
  323. single-item tuples. For example:
  324. [0, 1, 2, 10, 14, 15, 16] => [(0, 2), (10,), (14, 16)]"
  325. """
  326. group = (
  327. list(x) for _, x in groupby(sorted(array), lambda x, c=count(): next(c) - x)
  328. )
  329. return [
  330. (g[0], g[-1])[:len(g)] for g in group
  331. ]
  332. def array_to_string(array):
  333. """
  334. Generate an efficient, human-friendly string from a set of integers. Intended for use with ArrayField.
  335. For example:
  336. [0, 1, 2, 10, 14, 15, 16] => "0-2, 10, 14-16"
  337. """
  338. ret = []
  339. ranges = array_to_ranges(array)
  340. for value in ranges:
  341. if len(value) == 1:
  342. ret.append(str(value[0]))
  343. else:
  344. ret.append(f'{value[0]}-{value[1]}')
  345. return ', '.join(ret)
  346. def content_type_name(ct, include_app=True):
  347. """
  348. Return a human-friendly ContentType name (e.g. "DCIM > Site").
  349. """
  350. try:
  351. meta = ct.model_class()._meta
  352. app_label = title(meta.app_config.verbose_name)
  353. model_name = title(meta.verbose_name)
  354. if include_app:
  355. return f'{app_label} > {model_name}'
  356. return model_name
  357. except AttributeError:
  358. # Model no longer exists
  359. return f'{ct.app_label} > {ct.model}'
  360. def content_type_identifier(ct):
  361. """
  362. Return a "raw" ContentType identifier string suitable for bulk import/export (e.g. "dcim.site").
  363. """
  364. return f'{ct.app_label}.{ct.model}'
  365. #
  366. # Fake request object
  367. #
  368. class NetBoxFakeRequest:
  369. """
  370. A fake request object which is explicitly defined at the module level so it is able to be pickled. It simply
  371. takes what is passed to it as kwargs on init and sets them as instance variables.
  372. """
  373. def __init__(self, _dict):
  374. self.__dict__ = _dict
  375. def copy_safe_request(request):
  376. """
  377. Copy selected attributes from a request object into a new fake request object. This is needed in places where
  378. thread safe pickling of the useful request data is needed.
  379. """
  380. meta = {
  381. k: request.META[k]
  382. for k in HTTP_REQUEST_META_SAFE_COPY
  383. if k in request.META and isinstance(request.META[k], str)
  384. }
  385. return NetBoxFakeRequest({
  386. 'META': meta,
  387. 'COOKIES': request.COOKIES,
  388. 'POST': request.POST,
  389. 'GET': request.GET,
  390. 'FILES': request.FILES,
  391. 'user': request.user,
  392. 'path': request.path,
  393. 'id': getattr(request, 'id', None), # UUID assigned by middleware
  394. })
  395. def clean_html(html, schemes):
  396. """
  397. Sanitizes HTML based on a whitelist of allowed tags and attributes.
  398. Also takes a list of allowed URI schemes.
  399. """
  400. ALLOWED_TAGS = [
  401. "div", "pre", "code", "blockquote", "del",
  402. "hr", "h1", "h2", "h3", "h4", "h5", "h6",
  403. "ul", "ol", "li", "p", "br",
  404. "strong", "em", "a", "b", "i", "img",
  405. "table", "thead", "tbody", "tr", "th", "td",
  406. "dl", "dt", "dd",
  407. ]
  408. ALLOWED_ATTRIBUTES = {
  409. "div": ['class'],
  410. "h1": ["id"], "h2": ["id"], "h3": ["id"], "h4": ["id"], "h5": ["id"], "h6": ["id"],
  411. "a": ["href", "title"],
  412. "img": ["src", "title", "alt"],
  413. }
  414. return bleach.clean(
  415. html,
  416. tags=ALLOWED_TAGS,
  417. attributes=ALLOWED_ATTRIBUTES,
  418. protocols=schemes
  419. )
  420. def highlight_string(value, highlight, trim_pre=None, trim_post=None, trim_placeholder='...'):
  421. """
  422. Highlight a string within a string and optionally trim the pre/post portions of the original string.
  423. Args:
  424. value: The body of text being searched against
  425. highlight: The string of compiled regex pattern to highlight in `value`
  426. trim_pre: Maximum length of pre-highlight text to include
  427. trim_post: Maximum length of post-highlight text to include
  428. trim_placeholder: String value to swap in for trimmed pre/post text
  429. """
  430. # Split value on highlight string
  431. try:
  432. if type(highlight) is re.Pattern:
  433. pre, match, post = highlight.split(value, maxsplit=1)
  434. else:
  435. highlight = re.escape(highlight)
  436. pre, match, post = re.split(fr'({highlight})', value, maxsplit=1, flags=re.IGNORECASE)
  437. except ValueError as e:
  438. # Match not found
  439. return escape(value)
  440. # Trim pre/post sections to length
  441. if trim_pre and len(pre) > trim_pre:
  442. pre = trim_placeholder + pre[-trim_pre:]
  443. if trim_post and len(post) > trim_post:
  444. post = post[:trim_post] + trim_placeholder
  445. return f'{escape(pre)}<mark>{escape(match)}</mark>{escape(post)}'
  446. def local_now():
  447. """
  448. Return the current date & time in the system timezone.
  449. """
  450. return localtime(timezone.now())