utils.py 13 KB

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