1 line
12 KiB
JavaScript
1 line
12 KiB
JavaScript
(function(d,S,O,f,p,a,h,g,V,x){"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 b(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 c=t[n];c.enumerable=c.enumerable||!1,c.configurable=!0,"value"in c&&(c.writable=!0),Object.defineProperty(e,c.key,c)}}function N(e,t,n){return t&&_(e.prototype,t),n&&_(e,n),e}g.findByProps("SET_ACTIVITY");const B=g.findByProps("getAssetIds"),$=g.findByStoreName("SelfPresenceStore"),P=g.findByStoreName("UserStore");function v(){return k(null)}function k(e){o.pluginStopped&&(F(),e=null),o.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 T(e,t){A[e]=t}const U=function(){function e(){b(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(),c=await fetch(`${s.LFM_API_BASE_URL}?${n}`),r=await c.json();return(!c.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(T("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 l=function(...e){return i.verboseLogging&&console.log("[Last.fm]",...e)},C=function(){function e(){b(this,e)}return N(e,[{key:"updateActivity",value:async function(){if(o.pluginStopped){l("Plugin is stopped, skipping update"),this.stopUpdates();return}l("Fetching last track...");try{if(!i.username||!i.apiKey)throw new Error("Username or API key not set");if(i.ignoreSpotify){if($.findActivity(function(c){return c.sync_id})){l("Spotify is currently playing, clearing activity"),T("isSpotifyIgnored",!0),v();return}T("isSpotifyIgnored",!1)}const t=await U.fetchLatestScrobble();if(T("lastTrack",t),!t.nowPlaying){l("Last track is not currently playing"),v();return}if(o.lastTrackUrl===t.url){l("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 c in t)n.name=n.name.replace(`{{${c}}}`,t[c]||"");if(i.showTimestamp&&(n.timestamps={start:Date.now()|0}),t.album){const c=await Y([t.albumArt]);c[0]&&(n.assets={large_image:c[0],large_text:t.album})}l("Setting activity:",n),T("lastActivity",n),await k(n),o.lastTrackUrl=t.url,o.lastActivity=n,this.consecutiveFailures=0,l("Activity set successfully!")}catch(t){console.error("[Last.fm] Update error:",t),this.handleError(t)}}},{key:"handleError",value:function(t){this.consecutiveFailures++,T("lastError",t),this.consecutiveFailures>=s.MAX_RETRY_ATTEMPTS&&(l(`Failed ${this.consecutiveFailures} times, initiating reconnection...`),this.startReconnection())}},{key:"startReconnection",value:function(){var t=this;this.isReconnecting||(this.isReconnecting=!0,this.stopUpdates(),l("Starting reconnection process"),this.reconnectTimer=setInterval(function(){l("Attempting to reconnect..."),t.initialize().then(function(){l("Reconnection successful"),t.stopReconnection()}).catch(function(n){l("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(o.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),l(`Update timer started with interval: ${n}ms`)}},{key:"stop",value:function(){o.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,o={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=x.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 w=0;const H=3,j=5e3;async function y(){try{await D(),w=0}catch(e){console.error("[Last.fm] Initialization error:",e),w++,w<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(o.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(){o.pluginStopped=!0,F()},onSettingsUpdate(e){Object.assign(i,e),y()},onDiscordReconnect(){o.pluginStopped||y()}};const X="2.2.0",{TableRowGroup:E,TableSwitchRow:I,Stack:L,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},c=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(L,{spacing:8},a.React.createElement(E,{title:"Account Settings"},a.React.createElement(L,{spacing:4},a.React.createElement(R,{placeholder:"Last.fm Username",value:i.username,onChangeText:function(r){return n("username",r)}}),a.React.createElement(R,{placeholder:"API Key",value:i.apiKey,onChangeText:function(r){return n("apiKey",r)},secureTextEntry:!0}),a.React.createElement(u,{label:"Get API Key",subLabel:"https://www.last.fm/api/account/create",onPress:function(){return h.Linking.openURL("https://www.last.fm/api/account/create")}})),a.React.createElement(u,{label:"Test Connection",trailing:e?a.React.createElement(u.Arrow,{loading:!0}):a.React.createElement(u.Arrow,null),onPress:c,disabled:e})),a.React.createElement(E,{title:"Display Settings"},a.React.createElement(L,{spacing:4},a.React.createElement(R,{placeholder:`App Name (Default: ${s.DEFAULT_SETTINGS.appName})`,value:i.appName,onChangeText:function(r){return n("appName",r)}}),a.React.createElement(R,{placeholder:`Update Interval (Default: ${s.DEFAULT_SETTINGS.timeInterval}s)`,value:String(i.timeInterval),onChangeText: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"}))),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:o.pluginStopped?"Stopped":"Running"}),a.React.createElement(u,{label:"Last Update",subLabel:o.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 d.currentSettings=i,d.default=q,d.pluginState=o,Object.defineProperty(d,"__esModule",{value:!0}),d})({},vendetta,vendetta.storage,vendetta.ui.assets,vendetta.ui.toasts,vendetta.metro.common,vendetta.metro.common.ReactNative,vendetta.metro,vendetta.ui.components,window.React);
|