Skip to content

Instantly share code, notes, and snippets.

@robertknight
Created June 16, 2017 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertknight/fb0d8c1507032b45424888a756b6c669 to your computer and use it in GitHub Desktop.
Save robertknight/fb0d8c1507032b45424888a756b6c669 to your computer and use it in GitHub Desktop.
Convert UUIDs from the annotations table in Hypothesis' database to annotation IDs as seen in the API
#!/usr/bin/env python
import argparse
import base64
import binascii
import sys
import uuid
ES_FLAKE_MAGIC_BYTE = ['e', '5']
def ann_id(u):
hexstring = uuid.UUID(u).hex
return _get_urlsafe_from_hex(hexstring)
def _get_urlsafe_from_hex(value):
# Validate and normalise hex string
hexstring = uuid.UUID(hex=value).hex
is_flake_id = (hexstring[12] == ES_FLAKE_MAGIC_BYTE[0] and
hexstring[16] == ES_FLAKE_MAGIC_BYTE[1])
if is_flake_id:
# The hex representation of the flake ID is simply the UUID without the
# two magic nibbles.
data = binascii.unhexlify(hexstring[0:12] +
hexstring[13:16] +
hexstring[17:32])
return base64.urlsafe_b64encode(data)
# Encode UUID bytes and strip two bytes of padding
data = binascii.unhexlify(hexstring)
return base64.urlsafe_b64encode(data)[:-2]
if __name__ == '__main__':
p = argparse.ArgumentParser()
p.add_argument('--permalink', dest='permalink', action='store_true')
p.add_argument('--direct-link', dest='direct_link', action='store_true')
args = p.parse_args()
for line in sys.stdin:
id_ = ann_id(line.strip())
if args.permalink:
print('https://hypothes.is/a/{}'.format(id_))
elif args.direct_link:
print('https://hyp.is/{}'.format(id_))
else:
print(id_)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment