add a shitiverse client
2 files changed, 82 insertions(+), 0 deletions(-)

M .profile
A => bin/shitiverse
M .profile +2 -0
@@ 14,6 14,8 @@ export WWW_HOME=duckduckgo.com/html/
 export NNN_OPTS="a"
 export NNN_PLUG="t:preview-tui;x:preview-tabbed"
 
+export SHITIVERSE_POD="soc.punktrash.club"
+
 export XDG_DESKTOP_DIR="$HOME/desktop"
 export XDG_DOWNLOAD_DIR="$HOME/downloads"
 export XDG_DOCUMENTS_DIR="$HOME/documents"

          
A => bin/shitiverse +80 -0
@@ 0,0 1,80 @@ 
+#!/usr/bin/env sh
+
+notice() {
+	echo "$@" > /dev/stderr
+}
+
+if [ -z "$SHITIVERSE_POD" ]; then
+	notice "Setup SHITIVERSE_POD first"
+	exit 1
+fi
+
+SHITIVERSE_POD_URL="https://$SHITIVERSE_POD"
+CACHEDIR="${XDG_DATA_HOME:-~/.local/share}/shitiverse/$SHITIVERSE_POD"
+mkdir -p "$CACHEDIR"
+
+APP_TOKEN_FILE="$CACHEDIR/app_token"
+APP_CLIENT_FILE="$CACHEDIR/app_client"
+
+is_token_expired() {
+	created_at="$(jq -r .created_at "$APP_TOKEN_FILE")"
+	expires_delta="$(jq -r .expires_in "$APP_TOKEN_FILE")"
+	expires_at="$(expr "$created_at" + "$expires_delta")"
+	[ "$(date +%s)" -gt "$expires_at" ]
+}
+
+if [ ! -r "$APP_CLIENT_FILE" ]; then
+	curl -s -X POST "$SHITIVERSE_POD_URL/api/v1/apps" \
+		-d client_name="Shitiverse" \
+		-d redirect_uris="urn:ietf:wg:oauth:2.0:oob" \
+		-d scopes="read+write+follow" \
+		-d website="https://sr.ht/~reedwade/shitiverse" \
+		> "$APP_CLIENT_FILE"
+fi
+
+CLIENT_ID="$(jq -r .client_id "$APP_CLIENT_FILE")"
+CLIENT_SECRET="$(jq -r .client_secret "$APP_CLIENT_FILE")"
+
+APP_TOKEN=
+if [ ! -r "$APP_TOKEN_FILE" ]; then
+	request_url="$SHITIVERSE_POD_URL/oauth/authorize?response_type=code&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&scope=read+write+follow&client_id=$CLIENT_ID"
+	notice "Requesting access token:"
+	notice "$request_url"
+	xdg-open "$request_url"
+	read -r AUTHORIZATION_CODE
+
+	if curl -sf -X POST \
+		-d client_id="$CLIENT_ID" \
+		-d client_secret="$CLIENT_SECRET" \
+		-d redirect_uris="urn:ietf:wg:oauth:2.0:oob" \
+		-d scope="read+write+follow" \
+		-d code="$AUTHORIZATION_CODE" \
+		-d grant_type="authorization_code" \
+		"$SHITIVERSE_POD_URL/oauth/token" \
+		> "$APP_TOKEN_FILE"; then
+		notice "Registration done"
+	else
+		notice "An error occured when fetching token"
+		exit 1
+	fi
+fi
+
+if is_token_expired; then
+	REFRESH_TOKEN="$(jq -r .refresh_token "$APP_TOKEN_FILE")"
+	if curl -X POST \
+		-d client_id="$CLIENT_ID" \
+		-d client_secret="$CLIENT_SECRET" \
+		-d grant_type="refresh_token" \
+		-d refresh_token="$REFRESH_TOKEN" \
+		"$SHITIVERSE_POD_URL/oauth/token" \
+		> "$APP_TOKEN_FILE"; then
+		notice "Token refreshed"
+	else
+		notice "An error occured when refreshing token"
+		exit 1
+	fi
+fi
+
+APP_TOKEN="$(jq -r .access_token "$APP_TOKEN_FILE")"
+
+curl -sH "Authorization: Bearer $APP_TOKEN" "$SHITIVERSE_POD_URL/$1"