Skip to content

Instantly share code, notes, and snippets.

@aerobounce
Created October 23, 2021 18:49
Show Gist options
  • Save aerobounce/813c564297504968255749e1fe01c88a to your computer and use it in GitHub Desktop.
Save aerobounce/813c564297504968255749e1fe01c88a to your computer and use it in GitHub Desktop.
convert iCloud tabs into html that lazily load its URL
#!/usr/bin/env bash
set -Ceu -o pipefail
TEMP_HTML_DIR="$(mktemp -d -t "open-icloudtabs")"
echo "Session directory:
$TEMP_HTML_DIR
"
DID_MAKE_WINDOW=0
makeWindowIfNeeded() {
if [[ $DID_MAKE_WINDOW == 0 ]]; then
cat << EOL
-- Make a new window if needed
set hasWindow to false
repeat with aWindow in every windows
if document of aWindow is not missing value
set hasWindow to true
stop
end
end repeat
if not hasWindow
make new document
end
EOL
fi
DID_MAKE_WINDOW=1
}
python << EOL |
from json import loads
from sqlite3 import connect
from zlib import decompress
from urllib import quote_plus
db = connect("$HOME/Library/Safari/CloudTabs.db")
device_uuids = []
tabs = [] # Tuples (position, tab_uuid, url, title)
# Extract iCloud Devices other than this computer
for row in db.execute("SELECT device_name, device_uuid from cloud_tab_devices"):
if row[0] != "$(scutil --get LocalHostName)":
device_uuids.append(row[1])
for row in db.execute("SELECT position, tab_uuid, url, title, device_uuid FROM cloud_tabs"):
if row[4] in device_uuids:
position = loads(decompress(str(row[0])))
tabs.append([position["sortValues"][0]["sortValue"],
row[1],
row[2],
row[3]])
for row in sorted(tabs, key=lambda k: k[0]):
tab_uuid = row[1].encode("utf-8")
encoded_url = quote_plus(row[2].encode("utf-8"), safe='\n:/?&=+%#')
title = row[3].encode("utf-8")
print("{0}|{1}|{2}".format(tab_uuid, encoded_url, title))
EOL
while read -r; do
TAB_UUID="$(cut -d "|" -f1 <<< "$REPLY")" # Tab UUID
ENCODED_URL="$(cut -d "|" -f2 <<< "$REPLY")" # Encoded URL
TAB_TITLE="$(cut -d "|" -f3 <<< "$REPLY")" # Tab Title
TAB_HTML_FILE="$TEMP_HTML_DIR/$TAB_UUID.html"
cat << EOL >| "$TAB_HTML_FILE"
<!DOCTYPE HTML>
<html lang="en">
<meta charset="utf-8">
<title>$TAB_TITLE</title>
<script>
document.addEventListener("visibilitychange", function() {
if (document.visibilityState !== 'visible') { return }
window.location="$ENCODED_URL"
});
</script>
<body style="background: #222"></body>
EOL
osascript << EOL
tell application "Safari"
$(makeWindowIfNeeded)
tell front window
set newTab to make new tab at after the last tab
-- set the URL of newTab to "about:blank"
set the URL of newTab to "file://$TAB_HTML_FILE"
-- set current tab to newTab
end tell
end tell
EOL
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment