utils.py 17 KB

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