Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. import base64, uuid, binascii, traceback
  2.  
  3. ES_FLAKE_MAGIC_BYTE = ['e', '5']
  4.  
  5. def _must_b64_decode(data, expected_size=None):
  6. result = base64.urlsafe_b64decode(data)
  7. if expected_size is not None and len(result) != expected_size:
  8. raise TypeError('incorrect data size')
  9. return result
  10.  
  11. def _get_hex_from_urlsafe(value):
  12. bytestr = bytes(value)
  13.  
  14. def _fail():
  15. raise Exception('{0!r} is not a valid encoded UUID'.format(value))
  16.  
  17. if len(bytestr) == 22:
  18. # 22-char inputs represent 16 bytes of data, which when normally
  19. # base64-encoded would have two bytes of padding on the end, so we add
  20. # that back before decoding.
  21. try:
  22. data = _must_b64_decode(bytestr + b'==', expected_size=16)
  23. except TypeError:
  24. _fail()
  25. return binascii.hexlify(data)
  26.  
  27. if len(bytestr) == 20:
  28. # 20-char inputs represent 15 bytes of data, which requires no padding
  29. # corrections.
  30. try:
  31. data = _must_b64_decode(bytestr, expected_size=15)
  32. except TypeError:
  33. _fail()
  34. hexstring = binascii.hexlify(data)
  35. # These are ElasticSearch flake IDs, so to convert them into UUIDs we
  36. # insert the magic nibbles at the appropriate points. See the comments
  37. # on ES_FLAKE_MAGIC_BYTE for details.
  38. return (hexstring[0:12] +
  39. ES_FLAKE_MAGIC_BYTE[0] +
  40. hexstring[12:15] +
  41. ES_FLAKE_MAGIC_BYTE[1] +
  42. hexstring[15:30])
  43.  
  44. # Fallthrough: we must have a received a string of invalid length
  45. _fail()
  46.  
  47.  
  48. def _get_urlsafe_from_hex(value):
  49. # Validate and normalise hex string
  50. hexstring = uuid.UUID(hex=value).hex
  51.  
  52. is_flake_id = (hexstring[12] == ES_FLAKE_MAGIC_BYTE[0] and
  53. hexstring[16] == ES_FLAKE_MAGIC_BYTE[1])
  54.  
  55. if is_flake_id:
  56. # The hex representation of the flake ID is simply the UUID without the
  57. # two magic nibbles.
  58. data = binascii.unhexlify(hexstring[0:12] +
  59. hexstring[13:16] +
  60. hexstring[17:32])
  61. return base64.urlsafe_b64encode(data)
  62.  
  63. # Encode UUID bytes and strip two bytes of padding
  64. data = binascii.unhexlify(hexstring)
  65. return base64.urlsafe_b64encode(data)[:-2]
  66.  
  67. urlsafe = _get_urlsafe_from_hex('4517bf22-51c6-11e9-9efe-03f1897c9411')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement