paul@95 | 1 | #!/usr/bin/env python |
paul@95 | 2 | |
paul@95 | 3 | # See: https://answers.atlassian.com/questions/87971/what-is-the-algorithm-used-to-create-the-tiny-links |
paul@95 | 4 | |
paul@95 | 5 | from base64 import b64decode, b64encode |
paul@95 | 6 | from struct import pack, unpack |
paul@95 | 7 | import sys |
paul@95 | 8 | |
paul@95 | 9 | def tiny_url(s): |
paul@95 | 10 | return b64encode(pack("<I", int(s)).rstrip("\x00")).rstrip("=").replace("+", "_").replace("/", "-") |
paul@95 | 11 | |
paul@95 | 12 | def identifier(s): |
paul@95 | 13 | bytes = b64decode(s.replace("-", "/").replace("_", "+") + "=" * (6 - len(s))) |
paul@95 | 14 | return unpack("<I", bytes + "\x00" * (4 - len(bytes)))[0] |
paul@95 | 15 | |
paul@95 | 16 | arg = sys.argv[1] |
paul@95 | 17 | reverse = len(sys.argv) > 2 and sys.argv[2] in ("-r", "--reverse") |
paul@95 | 18 | fn = reverse and identifier or tiny_url |
paul@95 | 19 | |
paul@95 | 20 | if arg == "-": |
paul@95 | 21 | for line in sys.stdin.readlines(): |
paul@95 | 22 | line = line.strip() |
paul@95 | 23 | if line: |
paul@95 | 24 | print "%s\t%s" % (fn(line), line) |
paul@95 | 25 | else: |
paul@95 | 26 | print fn(arg) |
paul@95 | 27 | |
paul@95 | 28 | # vim: tabstop=4 expandtab shiftwidth=4 |