This script takes two URLs, the permalink URL for a hub profile, and a user-direct URL (e.g. an nbgitpuller URL), and fuses them together.
python ./permalink.py <USER-URL> <PERMALINK-URL>The output is the fixed URL.
| import urllib.parse | |
| import argparse | |
| def main(argv=None): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("url", type=str) | |
| parser.add_argument("permalink", type=str) | |
| args = parser.parse_args(args=argv) | |
| # Parse nbgitpuller URL from https://nbgitpuller.readthedocs.io/en/latest/link.html | |
| redirect_url = urllib.parse.urlparse(args.url) | |
| assert "/hub/user-redirect" in redirect_url.path, ( | |
| "expected user-redirect URL of form /hub/user-redirect" | |
| ) | |
| # Parse the permalink URL (that first hits login) of the form generated by | |
| # the Permalink feature | |
| login_url = urllib.parse.urlparse(args.permalink) | |
| assert redirect_url.netloc == login_url.netloc, ( | |
| "permalink and url args must share the same domain" | |
| ) | |
| # Extract the profile URL | |
| login_query = urllib.parse.parse_qs(login_url.query) | |
| profile_url = urllib.parse.urlparse(login_query["next"][0]) | |
| # Build new destination redirect URL that drops the domain | |
| adusted_redirect_url = urllib.parse.urlunparse( | |
| redirect_url._replace(scheme="", netloc="") | |
| ) | |
| # Build new profile permalink URL that includes the redirect URL | |
| adjusted_profile_url_query = urllib.parse.urlencode({"next": adusted_redirect_url}) | |
| adjusted_profile_url = urllib.parse.urlunparse( | |
| profile_url._replace(query=adjusted_profile_url_query) | |
| ) | |
| # Build a new login URL from amended permalink URL | |
| adjusted_login_query = urllib.parse.urlencode({"next": adjusted_profile_url}) | |
| adjusted_login_url = urllib.parse.urlunparse( | |
| login_url._replace(query=adjusted_login_query) | |
| ) | |
| print(adjusted_login_url) | |
| if __name__ == "__main__": | |
| main() |