diff --git a/src/services/lastfm/ScrobblingMixin.mjs b/src/services/lastfm/ScrobblingMixin.mjs index ef589fe..fe01d50 100644 --- a/src/services/lastfm/ScrobblingMixin.mjs +++ b/src/services/lastfm/ScrobblingMixin.mjs @@ -38,7 +38,7 @@ const ScrobblingMixin = { } catch (err) { if (isLastFmUserNotFound(err)) { if (noteStaleUser(this, userId)) { - logger.warn(`[LastFm] Now-playing updates paused for ${userId}: Last.fm user not found (account renamed or deleted? re-link required)`); + logger.warn(`[LastFm] Now-playing updates paused for ${userId}: Last.fm user not found (account renamed or deleted? attempting auto-recovery)`); } return; } @@ -73,7 +73,7 @@ const ScrobblingMixin = { } catch (err) { if (isLastFmUserNotFound(err)) { if (noteStaleUser(this, userId)) { - logger.warn(`[LastFm] Scrobbling paused for ${userId}: Last.fm user not found (account renamed or deleted? re-link required)`); + logger.warn(`[LastFm] Scrobbling paused for ${userId}: Last.fm user not found (account renamed or deleted? attempting auto-recovery)`); } return; } @@ -102,7 +102,7 @@ const ScrobblingMixin = { } catch (e) { if (isLastFmUserNotFound(e)) { if (noteStaleUser(this, userId)) { - logger.warn(`[LastFm] Scrobble count sync skipped for ${userId}: Last.fm user not found (account renamed or deleted? re-link required)`); + logger.warn(`[LastFm] Scrobble count sync skipped for ${userId}: Last.fm user not found (account renamed or deleted? attempting auto-recovery)`); } return 0; } diff --git a/src/services/lastfm/ServerStatsMixin.mjs b/src/services/lastfm/ServerStatsMixin.mjs index d3a0720..6635c15 100644 --- a/src/services/lastfm/ServerStatsMixin.mjs +++ b/src/services/lastfm/ServerStatsMixin.mjs @@ -47,7 +47,7 @@ const ServerStatsMixin = { } catch (e) { if (isLastFmUserNotFound(e)) { if (noteStaleUser(this, uid)) { - logger.warn(`[LastFm] Skipping ${uid}: Last.fm user not found (account renamed or deleted? re-link required)`); + logger.warn(`[LastFm] Skipping ${uid}: Last.fm user not found (account renamed or deleted? attempting auto-recovery)`); } return null; } @@ -106,7 +106,7 @@ const ServerStatsMixin = { } catch (e) { if (isLastFmUserNotFound(e)) { if (noteStaleUser(this, uid)) { - logger.warn(`[LastFm] Skipping ${uid}: Last.fm user not found (account renamed or deleted? re-link required)`); + logger.warn(`[LastFm] Skipping ${uid}: Last.fm user not found (account renamed or deleted? attempting auto-recovery)`); } return null; } @@ -165,7 +165,7 @@ const ServerStatsMixin = { } catch (e) { if (isLastFmUserNotFound(e)) { if (noteStaleUser(this, uid)) { - logger.warn(`[LastFm] Skipping ${uid}: Last.fm user not found (account renamed or deleted? re-link required)`); + logger.warn(`[LastFm] Skipping ${uid}: Last.fm user not found (account renamed or deleted? attempting auto-recovery)`); } return null; } @@ -487,7 +487,7 @@ const ServerStatsMixin = { } catch (e) { if (isLastFmUserNotFound(e)) { if (noteStaleUser(this, uid)) { - logger.warn(`[LastFm] Skipping ${uid}: Last.fm user not found (account renamed or deleted? re-link required)`); + logger.warn(`[LastFm] Skipping ${uid}: Last.fm user not found (account renamed or deleted? attempting auto-recovery)`); } return null; } diff --git a/src/services/lastfm/UserStoreMixin.mjs b/src/services/lastfm/UserStoreMixin.mjs index c9ebb1f..1585ffb 100644 --- a/src/services/lastfm/UserStoreMixin.mjs +++ b/src/services/lastfm/UserStoreMixin.mjs @@ -7,7 +7,7 @@ */ import { logger } from "../../core/Logger.mjs"; -import { apiCall } from "./constants.mjs"; +import { apiCall, clearStaleUserFlag, isLastFmFatalLinkError } from "./constants.mjs"; /** * @type {object} @@ -68,9 +68,57 @@ const UserStoreMixin = { logger.warn("[LastFm] Stats update warning:", e?.message); } + clearStaleUserFlag(this, userId); + return data; }, + /** + * @private @async Self-heal a stale link detected by a background flow: if + * the linked account was renamed, refresh the stored username through the + * still-valid session; if the account is gone or the session was revoked, + * remove the dead binding so background flows stop retrying until the user + * re-links. Transient API/network failures keep the link untouched and are + * retried on the next stale detection. + * @param {string} userId + * @returns {Promise} The refreshed username, or null when the link was removed or nothing is linked. + */ + async recoverStaleUser(userId) { + const id = String(userId); + const user = await this.getUser(id); + if (!user?.sessionKey) return null; + + try { + const data = await apiCall( + { method: "user.getinfo", api_key: this.apiKey, sk: user.sessionKey }, + this.apiSecret + ); + const freshName = String(data?.user?.name ?? "").trim(); + if (!freshName) throw new Error("Last.fm returned no user name"); + if (freshName === user.username) throw new Error("Last.fm session still resolves to the missing name"); + + const pool = await this._getPool(); + const f = this._botIdFilter(); + await pool.execute( + `UPDATE lastfm_users SET username = ? WHERE user_id = ?${f.where}`, + [freshName, id, ...f.params] + ); + this._userCache.set(id, { ...user, username: freshName }); + logger.settings(`[LastFm] Re-linked ${id} to renamed Last.fm account "${freshName}"`); + return freshName; + } catch (e) { + if (!isLastFmFatalLinkError(e)) { + logger.warn(`[LastFm] Stale-link recovery for ${id} failed (link kept): ${e?.message}`); + return null; + } + try { await this.removeUser(id); } catch (_) { } + logger.warn(`[LastFm] Auto-unlinked stale Last.fm account for ${id}: ${e?.message ?? "unknown error"} (re-link required)`); + return null; + } finally { + clearStaleUserFlag(this, id); + } + }, + /** @async Remove a user's Last.fm session from cache and DB. @param {string} userId */ async removeUser(userId) { const pool = await this._getPool(); diff --git a/src/services/lastfm/constants.mjs b/src/services/lastfm/constants.mjs index 2e324c0..d0298bc 100644 --- a/src/services/lastfm/constants.mjs +++ b/src/services/lastfm/constants.mjs @@ -63,11 +63,27 @@ function isLastFmUserNotFound(err) { return /user not found/i.test(String(err?.message ?? "")); } +/** + * Check whether an error means the stored Last.fm link is unrecoverable — + * the linked account no longer exists or its session was revoked. Deliberately + * distinct from transient failures (timeouts, 5xx, network errors), which must + * never trigger an unlink. + * @param {Error} err + * @returns {boolean} + */ +function isLastFmFatalLinkError(err) { + if (isLastFmUserNotFound(err)) return true; + const msg = String(err?.message ?? ""); + return /Last\.fm error 4:/.test(msg) || /authentication failed/i.test(msg); +} + /** @type {Set} @description Users already warned about as stale (dedup for background flows). */ const _staleUserWarned = new Set(); /** - * Report a stale linked user only once per bot+user pair (per process). + * Report a stale linked user only once per bot+user pair (per process) and + * kick a fire-and-forget recovery: refresh the stored username when the + * account was renamed, or unlink the dead binding when the account is gone. * @param {object} manager - LastFmManager instance (used for botId scoping). * @param {string} userId * @returns {boolean} True the first time this user is reported. @@ -77,9 +93,24 @@ function noteStaleUser(manager, userId) { if (_staleUserWarned.has(key)) return false; if (_staleUserWarned.size >= 1000) _staleUserWarned.clear(); _staleUserWarned.add(key); + try { + const recovery = manager?.recoverStaleUser?.(String(userId)); + if (recovery && typeof recovery.catch === "function") recovery.catch(() => {}); + } catch (_) { } return true; } +/** + * Forget the stale-user flag for a user — called when a link is (re-)saved so + * future stale detections warn and recover again, and after each recovery + * attempt so transient failures are retried on the next detection. + * @param {object} manager - LastFmManager instance (used for botId scoping). + * @param {string} userId + */ +function clearStaleUserFlag(manager, userId) { + _staleUserWarned.delete(`${manager?.botId ?? ""}:${userId}`); +} + /** @private Make an authenticated Last.fm API call. @async @param {object} params @param {string} apiSecret @param {boolean} [post=false] @returns {Promise} @throws {LastFmApiError} On HTTP or Last.fm API error. */ async function apiCall(params, apiSecret, post = false) { const allParams = { ...params }; @@ -121,4 +152,4 @@ async function apiCall(params, apiSecret, post = false) { return data; } -export { BASE_URL, normalizeTrackText, buildSignature, apiCall, LastFmApiError, isLastFmUserNotFound, noteStaleUser }; +export { BASE_URL, normalizeTrackText, buildSignature, apiCall, LastFmApiError, isLastFmUserNotFound, isLastFmFatalLinkError, noteStaleUser, clearStaleUserFlag };