Skip to content

Commit

Permalink
Push my "get browser URL" TextExpander snippet into this repo
Browse files Browse the repository at this point in the history
  • Loading branch information
alexwlchan committed Dec 17, 2023
1 parent a105f19 commit 98bb938
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
10 changes: 10 additions & 0 deletions textexpander/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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>
57 changes: 57 additions & 0 deletions textexpander/get_safari_url.py
Original file line number Diff line number Diff line change
@@ -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="")

0 comments on commit 98bb938

Please sign in to comment.