diff --git a/.env b/.env index f05f42b3..f63e6164 100644 --- a/.env +++ b/.env @@ -1,2 +1,3 @@ -ATPROTO_CLIENT_ID=https://cimd-service.fly.dev/clients/bafyreidf2esqfai4xh2osfrq6oekkkvburcjvomebn4age7hks7teb77fi +ATPROTO_CLIENT_ID=https://cimd-service.fly.dev/clients/bafyreiafqw2fao73uzdvg7rzvvcq7d4z5fvjhqc5qcqo6yzqq3p5dh6j2y +ROCKSKY_ATPROTO_CLIENT_ID=https://cimd-service.fly.dev/clients/bafyreihmrs2hsh5fp535lbidz4yt3f63pyh42d6gwpchf3vrr2kxie3cpu # DISABLE_AUTOMATIC_TRACKS_PROCESSING=t diff --git a/.zed/settings.json b/.zed/settings.json index 74dc2b9e..be27dd7e 100644 --- a/.zed/settings.json +++ b/.zed/settings.json @@ -3,39 +3,39 @@ "deno": { "settings": { "deno": { - "enable": true - } - } + "enable": true, + }, + }, }, "json-language-server": { "settings": { "json": { "schemas": [ { - "fileMatch": ["deno.json"], - "url": "https://raw.githubusercontent.com/denoland/deno/refs/heads/main/cli/schemas/config-file.v1.json" + "fileMatch": ["deno.json", "deno.jsonc"], + "url": "https://raw.githubusercontent.com/denoland/deno/refs/heads/main/cli/schemas/config-file.v1.json", }, { "fileMatch": ["package.json"], - "url": "http://json.schemastore.org/package" - } - ] - } - } - } + "url": "http://json.schemastore.org/package", + }, + ], + }, + }, + }, }, "languages": { "JavaScript": { "language_servers": ["deno", "!typescript-language-server", "!vtsls", "!eslint"], - "formatter": "language_server" + "formatter": "language_server", }, "TypeScript": { "language_servers": ["deno", "!typescript-language-server", "!vtsls", "!eslint"], - "formatter": "language_server" + "formatter": "language_server", }, "TSX": { "language_servers": ["deno", "!typescript-language-server", "!vtsls", "!eslint"], - "formatter": "language_server" - } - } + "formatter": "language_server", + }, + }, } diff --git a/src/components/configurator/output/element.js b/src/components/configurator/output/element.js index c51e81d7..423341dd 100644 --- a/src/components/configurator/output/element.js +++ b/src/components/configurator/output/element.js @@ -408,6 +408,26 @@ class OutputConfigurator extends BroadcastableDiffuseElement { localStorage.setItem(`${STORAGE_PREFIX}/selected/id`, id); await this.#selectOutput(id); }; + + /** + * @param {string} label + * @returns {Promise<{ id: string, label: string, element: OutputElement }>} + */ + waitForOption = (label) => { + return new Promise((resolve) => { + const check = async () => { + const opt = (await this.options()).find((o) => o.label === label); + if (opt) { + observer.disconnect(); + resolve(opt); + } + }; + + const observer = new MutationObserver(check); + observer.observe(this, { childList: true }); + check(); + }); + }; } export default OutputConfigurator; diff --git a/src/components/configurator/output/types.d.ts b/src/components/configurator/output/types.d.ts index 18271e72..b093fc1e 100644 --- a/src/components/configurator/output/types.d.ts +++ b/src/components/configurator/output/types.d.ts @@ -10,6 +10,7 @@ export type OutputConfiguratorElement = loadSelected: () => Promise; options: () => Promise>>; select: (id: string) => Promise; + waitForOption: (label: string) => Promise>; /** Output-element ids that have been selected earlier. */ activated: SignalReader>; diff --git a/src/components/orchestrator/output/element.js b/src/components/orchestrator/output/element.js index a5206284..97dbb21b 100644 --- a/src/components/orchestrator/output/element.js +++ b/src/components/orchestrator/output/element.js @@ -111,6 +111,10 @@ class OutputOrchestrator extends DiffuseElement { return this.outputConfigurator.selected.bind(this.outputConfigurator); } + get waitForOption() { + return this.outputConfigurator.waitForOption.bind(this.outputConfigurator); + } + // RENDER /** diff --git a/src/oauth-client-metadata.json b/src/components/output/raw/atproto/oauth-client-metadata.json similarity index 83% rename from src/oauth-client-metadata.json rename to src/components/output/raw/atproto/oauth-client-metadata.json index 71e98707..2e74229b 100644 --- a/src/oauth-client-metadata.json +++ b/src/components/output/raw/atproto/oauth-client-metadata.json @@ -1,5 +1,5 @@ { - "client_id": "https://elements.diffuse.sh/oauth-client-metadata.json", + "client_id": "https://elements.diffuse.sh/latest/components/output/raw/atproto/oauth-client-metadata.json", "client_name": "Diffuse", "client_uri": "https://elements.diffuse.sh", "redirect_uris": ["https://elements.diffuse.sh/oauth/callback"], diff --git a/src/components/output/raw/atproto/oauth.js b/src/components/output/raw/atproto/oauth.js index 2131262f..ca0dfa1d 100644 --- a/src/components/output/raw/atproto/oauth.js +++ b/src/components/output/raw/atproto/oauth.js @@ -1,6 +1,6 @@ import { configureOAuth } from "@atcute/oauth-browser-client"; -import metadata from "../../../../oauth-client-metadata.json" with { +import metadata from "./oauth-client-metadata.json" with { type: "json", }; @@ -29,6 +29,8 @@ export { OAuthUserAgent, TokenRefreshError }; const STORAGE_KEY = "diffuse/output/raw/atproto/did"; const SCOPE = metadata.scope; +const STORAGE_NAME = "diffuse/output/raw/atproto/atcute/oauth"; +const CLIENT_KEY = "diffuse/output/raw/atproto"; // CONFIGURE // ========= @@ -55,6 +57,7 @@ configureOAuth({ client_id, redirect_uri, }, + storageName: STORAGE_NAME, identityResolver: new LocalActorResolver({ handleResolver: new XrpcHandleResolver({ serviceUrl: "https://public.api.bsky.app", @@ -80,10 +83,8 @@ configureOAuth({ export async function login(handle) { const location = globalThis.location; - sessionStorage.setItem( - "oauth/callback/redirect_path", - location.pathname + location.search, - ); + sessionStorage.setItem("oauth/callback/redirect_path", location.pathname + location.search); + sessionStorage.setItem("oauth/pending-client", CLIENT_KEY); const authUrl = await createAuthorizationUrl({ target: { type: "account", identifier: /** @type {any} */ (handle) }, @@ -109,7 +110,9 @@ export async function restoreOrFinalize() { // so params arrive in the URL hash, not the query string) const params = new URLSearchParams(location.hash.slice(1)); - if (params.has("code")) { + if (params.has("code") && sessionStorage.getItem("oauth/pending-client") === CLIENT_KEY) { + sessionStorage.removeItem("oauth/pending-client"); + const result = await finalizeAuthorization(params); // Clean up URL (remove fragment containing OAuth params) diff --git a/src/components/supplement/rocksky/element.js b/src/components/supplement/rocksky/element.js index 19faaa3a..f3b29007 100644 --- a/src/components/supplement/rocksky/element.js +++ b/src/components/supplement/rocksky/element.js @@ -1,10 +1,17 @@ -import { md5 } from "@noble/hashes/legacy.js"; -import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js"; - -import { getSession } from "@atcute/oauth-browser-client"; +import { now as tidNow } from "@atcute/tid"; import { BroadcastableDiffuseElement, defineElement } from "~/common/element.js"; -import { computed, signal } from "~/common/signal.js"; +import { signal } from "~/common/signal.js"; + +import { + clearStoredSession, + DID_STORAGE_KEY, + getSession, + login, + logout, + OAuthUserAgent, + restoreOrFinalize, +} from "./oauth.js"; /** * @import {Track} from "~/definitions/types.d.ts" @@ -15,13 +22,8 @@ import { computed, signal } from "~/common/signal.js"; // CONSTANTS //////////////////////////////////////////// -const ROCKSKY_API_URL = "https://audioscrobbler.rocksky.app/2.0/"; -const ATPROTO_DID_KEY = "diffuse/output/raw/atproto/did"; const STORAGE_KEY = "diffuse/supplement/rocksky/session"; -const DEFAULT_API_KEY = "d21bdb464bd5e92c4dbbe814a5a9a8a4"; -const DEFAULT_API_SECRET = "4a9d15e43ad1623ee7f9dc6b12d6ba08"; - //////////////////////////////////////////// // ELEMENT //////////////////////////////////////////// @@ -32,24 +34,16 @@ const DEFAULT_API_SECRET = "4a9d15e43ad1623ee7f9dc6b12d6ba08"; class RockskyScrobbler extends BroadcastableDiffuseElement { static NAME = "diffuse/supplement/rocksky"; - get #apiKey() { - return this.getAttribute("api-key") ?? DEFAULT_API_KEY; - } - - get #apiSecret() { - return this.getAttribute("api-secret") ?? DEFAULT_API_SECRET; - } - // SIGNALS #handle = signal(/** @type {string | null} */ (null)); - #sessionKey = signal(/** @type {string | null} */ (null)); + #connected = signal(false); #isAuthenticating = signal(false); // STATE handle = this.#handle.get; - isAuthenticated = computed(() => this.#sessionKey.value !== null); + isAuthenticated = this.#connected.get; isAuthenticating = this.#isAuthenticating.get; // LIFECYCLE @@ -63,7 +57,7 @@ class RockskyScrobbler extends BroadcastableDiffuseElement { scrobble: { strategy: "leaderOnly", fn: this.scrobble }, setHandle: { strategy: "replicate", fn: this.#handle.set }, - setSession: { strategy: "replicate", fn: this.#sessionKey.set }, + setConnected: { strategy: "replicate", fn: this.#connected.set }, }); if (actions) { @@ -71,7 +65,7 @@ class RockskyScrobbler extends BroadcastableDiffuseElement { this.scrobble = actions.scrobble; this.#handle.set = actions.setHandle; - this.#sessionKey.set = actions.setSession; + this.#connected.set = actions.setConnected; } } @@ -83,17 +77,40 @@ class RockskyScrobbler extends BroadcastableDiffuseElement { async #tryRestore() { await this.whenConnected(); + try { + const session = await restoreOrFinalize(); + + if (session) { + const did = session.info.sub; + + if (await this.isLeader()) { + this.#connected.set(true); + this.#handle.set(did); + } else { + this.#connected.value = true; + this.#handle.value = did; + } + + localStorage.setItem(STORAGE_KEY, JSON.stringify({ did })); + return; + } + } catch (err) { + console.warn("Rocksky: Failed to restore/finalize session", err); + } + + // Restore previously stored connection state. const stored = localStorage.getItem(STORAGE_KEY); if (stored) { try { - const { key, name: handle } = JSON.parse(stored); + const { did } = JSON.parse(stored); + if (await this.isLeader()) { - this.#sessionKey.set(key); - this.#handle.set(handle); + this.#connected.set(true); + this.#handle.set(did); } else { - this.#sessionKey.value = key; - this.#handle.value = handle; + this.#connected.value = true; + this.#handle.value = did; } } catch { localStorage.removeItem(STORAGE_KEY); @@ -104,73 +121,48 @@ class RockskyScrobbler extends BroadcastableDiffuseElement { // AUTH /** - * Sign in to Rocksky using the existing AT Protocol session. - * Exchanges the AT Protocol access token for a Rocksky audioscrobbler session key. + * Connect to Rocksky by initiating the AT Protocol OAuth flow for the given handle. + * Navigates the browser away to the authorization server. + * + * @param {string} handle */ - async signIn() { - const did = localStorage.getItem(ATPROTO_DID_KEY); - if (!did) { - console.warn("Rocksky: No AT Protocol session found"); - return; - } - + async signIn(handle) { this.#isAuthenticating.set(true); try { - const session = await getSession( - /** @type {`did:${string}:${string}`} */ (did), - ); - const accessToken = session.token.access; - - const data = await this.#call("auth.getMobileSession", { - username: did, - password: accessToken, - }); - this.#setSession(data.session); - } catch (err) { - console.warn("Rocksky: Failed to authenticate", err); - throw err; + await login(handle); } finally { this.#isAuthenticating.set(false); } } /** - * Clear the stored session. + * Disconnect from Rocksky. */ signOut() { - this.#sessionKey.set(null); + const did = localStorage.getItem(DID_STORAGE_KEY); + + if (did) { + getSession(/** @type {`did:${string}:${string}`} */ (did)) + .then((session) => logout(new OAuthUserAgent(session))) + .catch(() => clearStoredSession()); + } else { + clearStoredSession(); + } + + this.#connected.set(false); this.#handle.set(null); localStorage.removeItem(STORAGE_KEY); } - /** @param {{ key: string, name: string }} session */ - #setSession({ key, name: handle }) { - this.#sessionKey.set(key); - this.#handle.set(handle); - localStorage.setItem(STORAGE_KEY, JSON.stringify({ key, name: handle })); - } - // SCROBBLE ACTIONS /** - * @param {Track} track + * @param {Track} _track */ - async nowPlaying(track) { - const tags = track.tags ?? {}; - /** @type {Record} */ - const params = {}; - - if (tags.title) params.track = tags.title; - if (tags.artist) params.artist = tags.artist; - if (tags.album) params.album = tags.album; - if (tags.albumartist) params.albumArtist = tags.albumartist; - if (tags.track?.no != null) params.trackNumber = String(tags.track.no); - if (track.stats?.duration != null) { - params.duration = String(Math.round(track.stats.duration / 1000)); - } - - return this.#authenticatedCall("track.updateNowPlaying", params); + // deno-lint-ignore no-unused-vars + async nowPlaying(_track) { + // Rocksky has no now-playing PDS record type; scrobbles are the source of truth. } /** @@ -178,67 +170,56 @@ class RockskyScrobbler extends BroadcastableDiffuseElement { * @param {number} startedAt Unix timestamp in milliseconds */ async scrobble(track, startedAt) { - const tags = track.tags ?? {}; - /** @type {Record} */ - const params = { - timestamp: String(Math.floor(startedAt / 1000)), - }; - - if (tags.title) params.track = tags.title; - if (tags.artist) params.artist = tags.artist; - if (tags.album) params.album = tags.album; - if (tags.albumartist) params.albumArtist = tags.albumartist; - if (tags.track?.no != null) params.trackNumber = String(tags.track.no); - if (track.stats?.duration != null) { - params.duration = String(Math.round(track.stats.duration / 1000)); - } - - return this.#authenticatedCall("track.scrobble", params); - } + if (!this.#connected.value) return; - // API + const did = localStorage.getItem(DID_STORAGE_KEY); + if (!did) return; - /** - * @param {Record} params - * @returns {string} MD5 hex digest - */ - #sign(params) { - const str = Object.keys(params) - .sort() - .map((k) => k + params[k]) - .join(""); - return bytesToHex(md5(utf8ToBytes(str + this.#apiSecret))); - } + const session = await getSession(/** @type {`did:${string}:${string}`} */ (did)); + const agent = new OAuthUserAgent(session); - /** - * @param {string} method - * @param {Record} [params] - * @returns {Promise} - */ - async #call(method, params = {}) { - const allParams = { ...params, api_key: this.#apiKey, method }; - const api_sig = this.#sign(allParams); - const body = new URLSearchParams({ ...allParams, api_sig, format: "json" }); + const tags = track.tags ?? {}; - const response = await fetch(ROCKSKY_API_URL, { method: "POST", body }); - const data = await response.json(); + // All five fields are required by the app.rocksky.scrobble lexicon. + if ( + !tags.title || + !tags.artist || + !tags.album || + !tags.albumartist || + track.stats?.duration == null + ) return; + + /** @type {Record} */ + const record = { + $type: "app.rocksky.scrobble", + title: tags.title, + artist: tags.artist, + album: tags.album, + albumArtist: tags.albumartist, + duration: Math.round(track.stats.duration / 1000), // seconds + }; - if (data.error) { - throw new Error(`rocksky error ${data.error}: ${data.message}`); + if (tags.track?.no != null) record.trackNumber = tags.track.no; + if (tags.disk?.no != null) record.discNumber = tags.disk.no; + + record.createdAt = new Date(startedAt).toISOString(); + + const response = await agent.handle("/xrpc/com.atproto.repo.putRecord", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + repo: did, + collection: "app.rocksky.scrobble", + rkey: tidNow(), + record, + validate: false, + }), + }); + + if (!response.ok) { + const error = await response.json().catch(() => ({})); + throw new Error(`rocksky: scrobble failed ${response.status}: ${error.message ?? ""}`); } - - return data; - } - - /** - * @param {string} method - * @param {Record} [params] - * @returns {Promise} - */ - async #authenticatedCall(method, params = {}) { - const sk = this.#sessionKey.value; - if (!sk) throw new Error("Not authenticated with Rocksky"); - return this.#call(method, { ...params, sk }); } } diff --git a/src/components/supplement/rocksky/oauth-client-metadata.json b/src/components/supplement/rocksky/oauth-client-metadata.json new file mode 100644 index 00000000..c14c117e --- /dev/null +++ b/src/components/supplement/rocksky/oauth-client-metadata.json @@ -0,0 +1,12 @@ +{ + "client_id": "https://elements.diffuse.sh/latest/components/supplement/rocksky/oauth-client-metadata.json", + "client_name": "Rocksky | Diffuse", + "client_uri": "https://elements.diffuse.sh", + "redirect_uris": ["https://elements.diffuse.sh/oauth/callback"], + "scope": "atproto repo?collection=app.rocksky.scrobble", + "grant_types": ["authorization_code", "refresh_token"], + "response_types": ["code"], + "token_endpoint_auth_method": "none", + "application_type": "web", + "dpop_bound_access_tokens": true +} diff --git a/src/components/supplement/rocksky/oauth.js b/src/components/supplement/rocksky/oauth.js new file mode 100644 index 00000000..5e6c8aae --- /dev/null +++ b/src/components/supplement/rocksky/oauth.js @@ -0,0 +1,156 @@ +import { + configureOAuth, + createAuthorizationUrl, + deleteStoredSession, + finalizeAuthorization, + getSession, + OAuthUserAgent, +} from "@atcute/oauth-browser-client"; + +import { + CompositeDidDocumentResolver, + LocalActorResolver, + PlcDidDocumentResolver, + WebDidDocumentResolver, + XrpcHandleResolver, +} from "@atcute/identity-resolver"; + +import metadata from "./oauth-client-metadata.json" with { + type: "json", +}; + +/** + * @import {Session} from "@atcute/oauth-browser-client" + */ + +export { OAuthUserAgent, getSession }; + +export const DID_STORAGE_KEY = "diffuse/supplement/rocksky/atproto/did"; +const CLIENT_KEY = "diffuse/supplement/rocksky"; + +const SCOPE = metadata.scope; + +// CONFIGURE +// ========= + +const location = globalThis.location; + +const redirect_uri = location.origin + location.pathname + location.search; + +const isLocalDev = redirect_uri.startsWith("http://127.0.0.1") || + redirect_uri.startsWith("http://localhost"); + +const client_id = isLocalDev + ? `http://localhost/?redirect_uri=${encodeURIComponent(redirect_uri)}&scope=${ + encodeURIComponent(SCOPE) + }` + : /** @type {any} */ (import.meta).env?.ROCKSKY_ATPROTO_CLIENT_ID ?? + "https://elements.diffuse.sh/rocksky-oauth-client-metadata.json"; + +configureOAuth({ + metadata: { client_id, redirect_uri }, + storageName: "diffuse/supplement/rocksky/atcute/oauth", + identityResolver: new LocalActorResolver({ + handleResolver: new XrpcHandleResolver({ + serviceUrl: "https://public.api.bsky.app", + }), + didDocumentResolver: new CompositeDidDocumentResolver({ + methods: { + plc: new PlcDidDocumentResolver(), + web: new WebDidDocumentResolver(), + }, + }), + }), +}); + +// LOGIN +// ===== + +/** + * Initiate the Rocksky OAuth authorization flow for a given handle. + * Navigates the browser away to the authorization server. + * + * @param {string} handle + */ +export async function login(handle) { + sessionStorage.setItem("oauth/callback/redirect_path", location.pathname + location.search); + sessionStorage.setItem("oauth/pending-client", CLIENT_KEY); + + const authUrl = await createAuthorizationUrl({ + target: { type: "account", identifier: /** @type {any} */ (handle) }, + scope: SCOPE, + }); + + location.assign(authUrl.toString()); +} + +// SESSION RESTORE / CALLBACK +// ========================== + +/** + * Attempt to restore an existing Rocksky session or finalize an OAuth callback. + * Returns the session if successful, or null if no session is available. + * + * @returns {Promise} + */ +export async function restoreOrFinalize() { + const params = new URLSearchParams(location.hash.slice(1)); + + if (params.has("code") && sessionStorage.getItem("oauth/pending-client") === CLIENT_KEY) { + sessionStorage.removeItem("oauth/pending-client"); + + const result = await finalizeAuthorization(params); + + history.replaceState(null, "", location.pathname + location.search); + localStorage.setItem(DID_STORAGE_KEY, result.session.info.sub); + + return result.session; + } + + const did = localStorage.getItem(DID_STORAGE_KEY); + + if (did) { + try { + return await getSession(/** @type {`did:${string}:${string}`} */ (did)); + } catch (err) { + console.warn(err); + clearStoredSession(); + return null; + } + } + + return null; +} + +// CLEAR SESSION +// ============= + +export function clearStoredSession() { + const did = localStorage.getItem(DID_STORAGE_KEY); + + if (did) { + deleteStoredSession(/** @type {`did:${string}:${string}`} */ (did)); + } + + localStorage.removeItem(DID_STORAGE_KEY); +} + +// LOGOUT +// ====== + +/** + * @param {OAuthUserAgent} agent + */ +export async function logout(agent) { + const did = localStorage.getItem(DID_STORAGE_KEY); + + try { + await agent.signOut(); + } catch { + if (did) { + deleteStoredSession(/** @type {`did:${string}:${string}`} */ (did)); + } + } + + localStorage.removeItem(DID_STORAGE_KEY); +} diff --git a/src/facets/connect/atproto/index.inline.js b/src/facets/connect/atproto/index.inline.js index 8834d3c5..daf78b22 100644 --- a/src/facets/connect/atproto/index.inline.js +++ b/src/facets/connect/atproto/index.inline.js @@ -23,29 +23,7 @@ const outputOrchestrator = await foundation.orchestrator.output(); await customElements.whenDefined(outputOrchestrator.localName); await customElements.whenDefined(ATPROTO_NAME); -// The AT Protocol option is added dynamically by the output-bundle facet, which -// runs in a separate script and appends the element to the output configurator -// via a signal effect. That effect may not have fired yet when this facet loads, -// so we observe the configurator for child-list mutations and resolve as soon as -// the option appears. -const outputConfigurator = outputOrchestrator.outputConfigurator; - -const atprotoOption = await new Promise((resolve) => { - const check = async () => { - const opt = (await outputOrchestrator.options()).find( - (o) => o.label === "AT Protocol", - ); - if (opt) { - observer.disconnect(); - resolve(opt); - } - }; - - const observer = new MutationObserver(check); - observer.observe(outputConfigurator, { childList: true }); - check(); -}); - +const atprotoOption = await outputOrchestrator.waitForOption("AT Protocol"); const ATPROTO_OUTPUT_ID = atprotoOption.id; const atprotoEl = /** @type {ATProtoOutputElement | undefined} */ ( diff --git a/src/facets/misc/scrobble/listenbrainz/index.html b/src/facets/misc/scrobble/listenbrainz/index.html index 82156f94..9963b201 100644 --- a/src/facets/misc/scrobble/listenbrainz/index.html +++ b/src/facets/misc/scrobble/listenbrainz/index.html @@ -37,22 +37,22 @@ Find your token at listenbrainz.org/settings/ -
+

-

+

diff --git a/src/facets/misc/scrobble/rocksky/index.html b/src/facets/misc/scrobble/rocksky/index.html index 6b2fbc17..ace6ccf2 100644 --- a/src/facets/misc/scrobble/rocksky/index.html +++ b/src/facets/misc/scrobble/rocksky/index.html @@ -13,59 +13,6 @@ } -
-
- -

Rocksky

-

Scrobble tracks to Rocksky using your AT Protocol identity.

-
- -
-
-
-

Sign in with your AT Protocol identity first, then connect to Rocksky.

-
- -

- -

-
-
- - -
- - -
-
+
diff --git a/src/facets/misc/scrobble/rocksky/index.inline.js b/src/facets/misc/scrobble/rocksky/index.inline.js index dddd9c1c..2e421605 100644 --- a/src/facets/misc/scrobble/rocksky/index.inline.js +++ b/src/facets/misc/scrobble/rocksky/index.inline.js @@ -1,5 +1,4 @@ -import { login } from "~/components/output/raw/atproto/oauth.js"; -import { finalizeAuthorization } from "@atcute/oauth-browser-client"; +import { html, nothing, render as litRender } from "lit-html"; import foundation from "~/common/foundation.js"; import { effect, signal } from "~/common/signal.js"; @@ -11,26 +10,6 @@ import { effect, signal } from "~/common/signal.js"; // Set doc title foundation.setup({ title: "Rocksky | Scrobble | Diffuse" }); -const ATPROTO_DID_KEY = "diffuse/output/raw/atproto/did"; - -// Handle AT Protocol OAuth callback if returning from it. -// The /oauth/callback page passes the #code fragment back to this page's URL. -// We only finalize if the code is actually present — never attempt session -// restoration, as its error path calls clearStoredSession() which would wipe -// the main app's AT Protocol session from localStorage and IndexedDB. -let freshAtprotoSession = null; -const hashParams = new URLSearchParams(location.hash.slice(1)); -if (hashParams.has("code")) { - try { - const result = await finalizeAuthorization(hashParams); - history.replaceState(null, "", location.pathname + location.search); - localStorage.setItem(ATPROTO_DID_KEY, result.session.info.sub); - freshAtprotoSession = result.session; - } catch (err) { - console.warn("rocksky: failed to finalize AT Protocol auth", err); - } -} - const configurator = await foundation.configurator.scrobbles(); /** @type {import("~/components/supplement/rocksky/element.js").CLASS | null} */ @@ -47,107 +26,95 @@ if (!rocksky) { await customElements.whenDefined(rocksky.localName); -// If AT Protocol was just authorized via OAuth, immediately connect to Rocksky -if (freshAtprotoSession && !rocksky.isAuthenticated()) { - rocksky.signIn().catch(() => {}); -} - -//////////////////////////////////////////// -// ELEMENTS -//////////////////////////////////////////// - -const stateConnect = /** @type {HTMLElement} */ ( - document.querySelector("#state-connect") -); - -const stateConnected = /** @type {HTMLElement} */ ( - document.querySelector("#state-connected") -); - -const stateNoAtproto = /** @type {HTMLElement} */ ( - document.querySelector("#state-no-atproto") -); - -const stateHasAtproto = /** @type {HTMLElement} */ ( - document.querySelector("#state-has-atproto") -); - -const handleParagraph = /** @type {HTMLElement} */ ( - document.querySelector("#handle-paragraph") -); - -const handleText = /** @type {HTMLElement} */ ( - document.querySelector("#handle-text") -); - -const handleInput = /** @type {HTMLInputElement} */ ( - document.querySelector("#handle-input") -); - -const atprotoSignInBtn = /** @type {HTMLElement} */ ( - document.querySelector("#atproto-sign-in-btn") -); - -const signInBtn = /** @type {HTMLElement} */ ( - document.querySelector("#sign-in-btn") -); - -const signOutBtn = /** @type {HTMLElement} */ ( - document.querySelector("#sign-out-btn") -); - //////////////////////////////////////////// // REACTIVE UI //////////////////////////////////////////// -const $hasAtprotoSession = signal(!!localStorage.getItem(ATPROTO_DID_KEY)); +const $signingIn = signal(false); + +const main = document.querySelector("main"); effect(() => { const isAuthenticated = rocksky.isAuthenticated(); const isAuthenticating = rocksky.isAuthenticating(); const handle = rocksky.handle(); - const hasAtproto = $hasAtprotoSession.value; - - stateConnect.hidden = isAuthenticated; - stateConnected.hidden = !isAuthenticated; - - stateNoAtproto.hidden = hasAtproto; - stateHasAtproto.hidden = !hasAtproto; - - handleParagraph.hidden = !handle; - signOutBtn.hidden = !isAuthenticated; - if (handle) handleText.textContent = handle; - - // @ts-ignore - signInBtn.disabled = isAuthenticating; - signInBtn.querySelector("i").className = isAuthenticating - ? "ph-bold ph-spinner animate-spin" - : "ph-bold ph-plugs"; - - // @ts-ignore - atprotoSignInBtn.disabled = isAuthenticating; - atprotoSignInBtn.querySelector("i").className = isAuthenticating - ? "ph-bold ph-spinner animate-spin" - : "ph-bold ph-at"; + const signingIn = $signingIn.value; + + litRender( + html` +
+ +

Rocksky

+

Scrobble tracks to Rocksky using your AT Protocol identity.

+
+ +
+ ${isAuthenticated + ? html` +
+ ${handle + ? html`

Connected as ${handle}.

` + : nothing} +
+ +
+
+ ` + : html` +
+

Sign in with your AT Protocol identity to connect Rocksky.

+
+ +

+ +

+
+
+ `} +
+ `, + main, + ); }); //////////////////////////////////////////// // ACTIONS //////////////////////////////////////////// -const atprotoSignInForm = /** @type {HTMLFormElement} */ ( - document.querySelector("#atproto-sign-in-form") -); - -atprotoSignInForm.onsubmit = async (e) => { +async function handleSignIn(e) { e.preventDefault(); - const handle = handleInput.value?.trim(); + const handle = e.target.querySelector("input")?.value?.trim(); if (!handle) return; - await login(handle); -}; - -signInBtn.onclick = () => rocksky.signIn().catch(() => {}); -signOutBtn.onclick = () => rocksky.signOut(); + $signingIn.value = true; + try { + await rocksky.signIn(handle); + } finally { + $signingIn.value = false; + } +} //////////////////////////////////////////// // 🚀