Skip to main content

Push my “get browser URL” TextExpander snippet into this repo

ID
98bb938
date
2023-12-17 18:41:31+00:00
author
Alex Chan <alex@alexwlchan.net>
parent
a105f19
message
Push my "get browser URL" TextExpander snippet into this repo
changed files
2 files, 67 additions

Changed files

textexpander/README.md (437) → textexpander/README.md (791)

diff --git a/textexpander/README.md b/textexpander/README.md
index c215b88..d70e24b 100644
--- a/textexpander/README.md
+++ b/textexpander/README.md
@@ -13,4 +13,14 @@ These scripts I invoke as text expansion macros in [TextExpander](https://textex
   <dd>
     print a Markdown-formatted blockquote of a Mastodon I've got open in Safari, suitable for pasting into Obsidian
   </dd>
+
+  <dt>
+    <a href="https://github.com/alexwlchan/scripts/blob/main/obsidian/get_safari_url.py">
+      <code>get_safari_url.py</code>
+    </a>
+  </dt>
+  <dd>
+    print the URL in my frontmost Safari window.
+    This makes a couple of tweaks to tidy up the URL, e.g. remove tracking parameters and tidy up some Jekyll stuff for my personal site.
+  </dd>
 </dl>

textexpander/get_safari_url.py (0) → textexpander/get_safari_url.py (1537)

diff --git a/textexpander/get_safari_url.py b/textexpander/get_safari_url.py
new file mode 100755
index 0000000..d470bea
--- /dev/null
+++ b/textexpander/get_safari_url.py
@@ -0,0 +1,57 @@
+#!/usr/bin/python3
+
+import os
+import subprocess
+import sys
+
+import httpx
+
+
+def get_safari_url(window: str) -> str:
+    cmd = ["/Users/alexwlchan/.cargo/bin/safari", "url", "--window", window]
+
+    url = subprocess.check_output(cmd).decode("utf8")
+
+    # If this is a URL at http://localhost:5757, it's probably the
+    # local web server for Jekyll running my personal site.
+    #
+    # Rather than printing the raw URL, print the {% post_url %} syntax
+    # required to do an inter-site link in Jekyll.
+    if url.startswith("http://localhost:5757/"):
+        *_, year, slug, _ = url.split("/")
+
+        matching_files = [
+            f
+            for f in os.listdir(
+                f"/Users/alexwlchan/repos/alexwlchan.net/src/_posts/{year}"
+            )
+            if f.endswith(f"{slug}.md")
+        ]
+
+        if len(matching_files) == 1:
+            return (
+                "{% post_url "
+                + f'{year}/{matching_files[0].replace(".md", "")}'
+                + " %}"
+            )
+
+    # If it's a Mastodon post, we want to retrieve the URL of the original
+    # post rather than the copy of it on my server.
+    if url.startswith("https://social.alexwlchan.net") and not url.startswith(
+        "https://social.alexwlchan.net/@alex/"
+    ):
+        r = httpx.head(url)
+
+        try:
+            return r.headers["location"]
+            sys.exit(0)
+        except Exception:
+            pass
+
+    return url
+
+
+if __name__ == "__main__":
+    window = sys.argv[1]
+
+    print(get_safari_url(window=window), end="")