utils.py 16 KB

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