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

1 line
12 KiB
JavaScript

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