vd-plugins/Last.fm/index.js
2025-09-19 21:06:42 +02:00

1 line
12 KiB
JavaScript

(function(T,S,O,f,p,a,h,g,V,$){"use strict";const s={DEFAULT_APP_NAME:"Music",DEFAULT_TIME_INTERVAL:5,APPLICATION_ID:"1054951789318909972",MIN_UPDATE_INTERVAL:3,MAX_RETRY_ATTEMPTS:3,RETRY_DELAY:5e3,LFM_API_BASE_URL:"https://ws.audioscrobbler.com/2.0",LFM_DEFAULT_COVER_HASHES:["2a96cbd8b46e442fc41c2b86b821562f","c6f59c1e5e7240a4c0d427abd71f3dbb"],DEFAULT_SETTINGS:{username:"",apiKey:"",appName:"Music",timeInterval:5,showTimestamp:!0,listeningTo:!0,ignoreSpotify:!0,verboseLogging:!1},GITHUB_URL:"https://github.com/kmmiio99o/letup",GITHUB_COMMITS_URL:"https://github.com/kmmiio99o/letup/commits/main/"};function L(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _(e,t){for(var n=0;n<t.length;n++){var l=t[n];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(e,l.key,l)}}function N(e,t,n){return t&&_(e.prototype,t),n&&_(e,n),e}g.findByProps("SET_ACTIVITY");const B=g.findByProps("getAssetIds"),x=g.findByStoreName("SelfPresenceStore"),P=g.findByStoreName("UserStore");function v(){return k(null)}function k(e){c.pluginStopped&&(F(),e=null),c.lastActivity=e,a.FluxDispatcher.dispatch({type:"LOCAL_ACTIVITY_UPDATE",activity:e,pid:2312,socketId:"Last.fm@Vendetta"})}async function Y(e,t=s.APPLICATION_ID){if(!e?.length)return[];try{return await B.fetchAssetIds(t,e)}catch(n){return console.error("[Last.fm] Failed to fetch assets:",n),[]}}const A={};A.componentMountErrors=[],A.componentMountCount=0,A.settingsLoadAttempts=0;function d(e,t){A[e]=t}const U=function(){function e(){L(this,e)}return N(e,[{key:"validateSettings",value:function(){if(!i.username)throw new Error("Last.fm username is not set");if(!i.apiKey)throw new Error("Last.fm API key is not set")}},{key:"handleError",value:async function(t){this.lastError=t.error;const n={2:"Invalid API key",6:"User not found",11:"Service temporarily unavailable",16:"Service temporarily unavailable",29:"Rate limit exceeded"}[t.error]||t.message||"Unknown error";throw p.showToast(`Last.fm Error: ${n}`,f.getAssetIDByName("Small")),new Error(`Last.fm API Error ${t.error}: ${n}`)}},{key:"makeRequest",value:async function(t){const n=new URLSearchParams({...t,api_key:i.apiKey,format:"json"}).toString(),l=await fetch(`${s.LFM_API_BASE_URL}?${n}`),r=await l.json();return(!l.ok||r.error)&&await this.handleError(r),r}},{key:"fetchLatestScrobble",value:async function(){try{this.validateSettings();const t=(await this.makeRequest({method:"user.getrecenttracks",user:i.username,limit:"1",extended:"1"}))?.recenttracks?.track?.[0];if(d("lastAPIResponse",t),!t)throw new Error("No tracks found");return this.retryCount=0,{name:t.name,artist:t.artist.name,album:t.album["#text"],albumArt:await this.handleAlbumCover(t.image?.find(function(n){return n.size==="large"})?.["#text"]),url:t.url,date:t.date?.["#text"]??"now",nowPlaying:!!t["@attr"]?.nowplaying,loved:t.loved==="1"}}catch(t){if(this.retryCount++,this.retryCount>s.MAX_RETRY_ATTEMPTS)throw this.retryCount=0,t;return await new Promise(function(n){return setTimeout(n,s.RETRY_DELAY)}),this.fetchLatestScrobble()}}},{key:"handleAlbumCover",value:async function(t){return!t||s.LFM_DEFAULT_COVER_HASHES.some(function(n){return t.includes(n)})?null:t}},{key:"getLastError",value:function(){return this.lastError}},{key:"resetRetryCount",value:function(){this.retryCount=0}}],[{key:"getInstance",value:function(){return e.instance||(e.instance=new e),e.instance}}]),e}().getInstance();var K=function(e){return e[e.PLAYING=0]="PLAYING",e[e.STREAMING=1]="STREAMING",e[e.LISTENING=2]="LISTENING",e[e.COMPETING=5]="COMPETING",e}(K||{});const o=function(...e){return i.verboseLogging&&console.log("[Last.fm]",...e)},C=function(){function e(){L(this,e)}return N(e,[{key:"updateActivity",value:async function(){if(c.pluginStopped){o("Plugin is stopped, skipping update"),this.stopUpdates();return}o("Fetching last track...");try{if(!i.username||!i.apiKey)throw new Error("Username or API key not set");if(i.ignoreSpotify){if(x.findActivity(function(l){return l.sync_id})){o("Spotify is currently playing, clearing activity"),d("isSpotifyIgnored",!0),v();return}d("isSpotifyIgnored",!1)}const t=await U.fetchLatestScrobble();if(d("lastTrack",t),!t.nowPlaying){o("Last track is not currently playing"),v();return}if(c.lastTrackUrl===t.url){o("Track hasn't changed");return}const n={name:i.appName||s.DEFAULT_APP_NAME,flags:0,type:i.listeningTo?2:0,details:t.name,state:t.artist,status_display_type:1,application_id:s.APPLICATION_ID};if(n.name.includes("{{"))for(const l in t)n.name=n.name.replace(`{{${l}}}`,t[l]||"");if(i.showTimestamp&&(n.timestamps={start:Date.now()|0}),t.album){const l=await Y([t.albumArt]);l[0]&&(n.assets={large_image:l[0],large_text:t.album})}o("Setting activity:",n),d("lastActivity",n),await k(n),c.lastTrackUrl=t.url,c.lastActivity=n,this.consecutiveFailures=0,o("Activity set successfully!")}catch(t){console.error("[Last.fm] Update error:",t),this.handleError(t)}}},{key:"handleError",value:function(t){this.consecutiveFailures++,d("lastError",t),this.consecutiveFailures>=s.MAX_RETRY_ATTEMPTS&&(o(`Failed ${this.consecutiveFailures} times, initiating reconnection...`),this.startReconnection())}},{key:"startReconnection",value:function(){var t=this;this.isReconnecting||(this.isReconnecting=!0,this.stopUpdates(),o("Starting reconnection process"),this.reconnectTimer=setInterval(function(){o("Attempting to reconnect..."),t.initialize().then(function(){o("Reconnection successful"),t.stopReconnection()}).catch(function(n){o("Reconnection failed:",n)})},s.RETRY_DELAY))}},{key:"stopReconnection",value:function(){this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=void 0),this.isReconnecting=!1,this.consecutiveFailures=0}},{key:"stopUpdates",value:function(){this.updateTimer&&(clearInterval(this.updateTimer),this.updateTimer=void 0)}},{key:"initialize",value:async function(){var t=this;if(c.pluginStopped)throw new Error("Plugin is stopped");this.stopUpdates(),await this.updateActivity();const n=Math.max((Number(i.timeInterval)||s.DEFAULT_SETTINGS.timeInterval)*1e3,s.MIN_UPDATE_INTERVAL*1e3);this.updateTimer=setInterval(function(){return t.updateActivity()},n),o(`Update timer started with interval: ${n}ms`)}},{key:"stop",value:function(){c.pluginStopped=!0,this.stopUpdates(),this.stopReconnection(),v()}}],[{key:"getInstance",value:function(){return e.instance||(e.instance=new e),e.instance}}]),e}().getInstance(),D=function(){return C.initialize()},F=function(){return C.stop()},{FormText:M}=V.Forms,c={pluginStopped:!1,lastActivity:void 0,updateInterval:void 0,lastTrackUrl:void 0},G=s.DEFAULT_SETTINGS;for(const e in G)S.plugin.storage[e]=S.plugin.storage[e]??G[e];const i=new Proxy(S.plugin.storage,{get(e,t){return e[t]},set(e,t,n){return e[t]=n,!0}}),z=$.lazy(function(){return Promise.resolve().then(function(){return Q}).catch(function(e){return console.error("[Last.fm] Failed to load settings:",e),{default:function(){return a.React.createElement(h.ScrollView,{style:{flex:1},contentContainerStyle:{padding:16}},a.React.createElement(M,{style:{color:"#ED4245"}},"Failed to load Last.fm settings. Please check your connection and reload Discord."))}}})});let b=0;const H=3,j=5e3;async function y(){try{await D(),b=0}catch(e){console.error("[Last.fm] Initialization error:",e),b++,b<H?(p.showToast("Retrying connection...",f.getAssetIDByName("ic_clock")),setTimeout(y,j)):p.showToast("Failed to connect to Last.fm",f.getAssetIDByName("Small"))}}var q={settings:function(){return a.React.createElement(a.React.Suspense,{fallback:a.React.createElement(h.ScrollView,{style:{flex:1},contentContainerStyle:{padding:16}},a.React.createElement(M,null,"Loading Last.fm settings..."))},a.React.createElement(z,null))},onLoad(){if(c.pluginStopped=!1,!i.username||!i.apiKey){p.showToast("Please configure Last.fm username and API key in settings",f.getAssetIDByName("ic_warning"));return}if(P.getCurrentUser())y();else{const e=function(){P.getCurrentUser()&&(y(),a.FluxDispatcher.unsubscribe("CONNECTION_OPEN",e))};a.FluxDispatcher.subscribe("CONNECTION_OPEN",e)}},onUnload(){c.pluginStopped=!0,F()},onSettingsUpdate(e){Object.assign(i,e),y()},onDiscordReconnect(){c.pluginStopped||y()}};const X="2.2.0",{TableRowGroup:E,TableSwitchRow:I,Stack:w,TableRow:u}=g.findByProps("TableSwitchRow","TableRowGroup","Stack","TableRow"),{TextInput:R}=g.findByProps("TextInput");function J(){O.useProxy(i);const[e,t]=a.React.useState(!1),n=function(r,m){i[r]=m,S.plugin.storage[r]=m},l=async function(){if(!i.username||!i.apiKey){p.showToast("Please enter both username and API key",f.getAssetIDByName("Small"));return}t(!0);try{await U.fetchLatestScrobble(),p.showToast("Connection successful!",f.getAssetIDByName("Check")),await D()}catch(r){p.showToast(`Connection failed: ${r.message}`,f.getAssetIDByName("Small"))}finally{t(!1)}};return a.React.createElement(h.ScrollView,{style:{flex:1},contentContainerStyle:{padding:10}},a.React.createElement(w,{spacing:8},a.React.createElement(E,{title:"Account Settings"},a.React.createElement(w,{spacing:4},a.React.createElement(R,{placeholder:"Last.fm Username",value:i.username,onChange:function(r){return n("username",r)},isClearable:!0}),a.React.createElement(R,{placeholder:"API Key",value:i.apiKey,onChange:function(r){return n("apiKey",r)},secureTextEntry:!0,isClearable:!0}),a.React.createElement(u,{label:"Get API Key",subLabel:"https://www.last.fm/api/",onPress:function(){return h.Linking.openURL("https://www.last.fm/api/")}})),a.React.createElement(u,{label:"Test Connection",trailing:e?a.React.createElement(u.Arrow,{loading:!0}):a.React.createElement(u.Arrow,null),onPress:l,disabled:e})),a.React.createElement(E,{title:"Display Settings"},a.React.createElement(w,{spacing:4},a.React.createElement(R,{placeholder:`App Name (Default: ${s.DEFAULT_SETTINGS.appName})`,value:i.appName,onChange:function(r){return n("appName",r)},isClearable:!0}),a.React.createElement(R,{placeholder:`Update Interval (Default: ${s.DEFAULT_SETTINGS.timeInterval}s)`,value:String(i.timeInterval),onChange:function(r){const m=Number(r);m>=s.MIN_UPDATE_INTERVAL?n("timeInterval",m):p.showToast(`Minimum interval is ${s.MIN_UPDATE_INTERVAL} seconds`,f.getAssetIDByName("Small"))},keyboardType:"numeric",isClearable:!0}))),a.React.createElement(E,{title:"Options"},a.React.createElement(I,{label:"Show 'Listening to' instead of 'Playing'",value:i.listeningTo??s.DEFAULT_SETTINGS.listeningTo,onValueChange:function(r){return n("listeningTo",r)}}),a.React.createElement(I,{label:"Show Timestamp",value:i.showTimestamp??s.DEFAULT_SETTINGS.showTimestamp,onValueChange:function(r){return n("showTimestamp",r)}}),a.React.createElement(I,{label:"Ignore when Spotify is playing",value:i.ignoreSpotify??s.DEFAULT_SETTINGS.ignoreSpotify,onValueChange:function(r){return n("ignoreSpotify",r)}}),a.React.createElement(I,{label:"Verbose Logging",value:i.verboseLogging??s.DEFAULT_SETTINGS.verboseLogging,onValueChange:function(r){return n("verboseLogging",r)}})),a.React.createElement(E,{title:"Plugin Status"},a.React.createElement(u,{label:"Status",subLabel:c.pluginStopped?"Stopped":"Running"}),a.React.createElement(u,{label:"Last Update",subLabel:c.lastTrackUrl?"Success":"No track data"})),a.React.createElement(E,{title:"About"},a.React.createElement(u,{label:"Version",subLabel:X}),a.React.createElement(u,{label:"View Changelog",trailing:a.React.createElement(u.Arrow,null),onPress:function(){h.Linking.openURL(s.GITHUB_COMMITS_URL)}}))))}var Q=Object.freeze({__proto__:null,default:J});return T.currentSettings=i,T.default=q,T.pluginState=c,Object.defineProperty(T,"__esModule",{value:!0}),T})({},vendetta,vendetta.storage,vendetta.ui.assets,vendetta.ui.toasts,vendetta.metro.common,vendetta.metro.common.ReactNative,vendetta.metro,vendetta.ui.components,window.React);