utils.py 17 KB

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