1 line
47 KiB
JavaScript
1 line
47 KiB
JavaScript
(function(q,p,r,V,ft,$,Z,S,R){"use strict";const d={DEFAULT_APP_NAME:"Music",DEFAULT_TIME_INTERVAL:5,APPLICATION_ID:"1368513179272871956",MIN_UPDATE_INTERVAL:3,MAX_RETRY_ATTEMPTS:3,RETRY_DELAY:5e3,SERVICES:{lastfm:{name:"Last.fm",baseUrl:"https://ws.audioscrobbler.com/2.0",requiresApiKey:!0,requiresToken:!1},librefm:{name:"Libre.fm",baseUrl:"https://libre.fm/2.0",requiresApiKey:!0,requiresToken:!1},listenbrainz:{name:"ListenBrainz",baseUrl:"https://api.listenbrainz.org/1",requiresApiKey:!0,requiresToken:!0}},DEFAULT_HEADERS:{},DEFAULT_COVER_HASHES:["2a96cbd8b46e442fc41c2b86b821562f"],DEFAULT_SETTINGS:{username:"",apiKey:"",appName:"Music",timeInterval:5,showTimestamp:!0,listeningTo:!0,showLargeText:!0,ignoreYouTubeMusic:!1,verboseLogging:!1,service:void 0,librefmUsername:"",librefmApiKey:"",listenbrainzUsername:"",listenbrainzToken:""},API_ERROR_CODES:{2:"Invalid service",3:"Invalid method",4:"Invalid format",5:"Invalid parameters",6:"Invalid resource specified",7:"Invalid session key",8:"Invalid API key",9:"Invalid session",10:"Invalid API signature",11:"Service offline",13:"Invalid method signature supplied",16:"Service temporarily unavailable",26:"Suspended API key",29:"Rate limit exceeded"}};function F(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function ce(e,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}function B(e,t,n){return t&&ce(e.prototype,t),n&&ce(e,n),e}const{SET_ACTIVITY:dt}=V.findByProps("SET_ACTIVITY"),Ve=V.findByProps("getAssetIds"),Fe=V.findByStoreName("SelfPresenceStore"),ue=V.findByStoreName("UserStore");function ee(){return ge(null)}function ge(e){v.pluginStopped&&(se(),e=null),v.lastActivity=e,r.FluxDispatcher.dispatch({type:"LOCAL_ACTIVITY_UPDATE",activity:e,pid:2312,socketId:"Multi-Scrobbler@Vendetta"})}async function Be(e,t=d.APPLICATION_ID){if(!e?.length)return[];try{return await Ve.fetchAssetIds(t,e)}catch(n){return console.error("[Multi-Scrobbler] Failed to fetch assets:",n),[]}}const w={};w.componentMountErrors=[],w.componentMountCount=0,w.settingsLoadAttempts=0,w.serviceErrors={lastfm:[],librefm:[],listenbrainz:[]},w.apiCallCount=0,w.connectionAttempts=0,w.lastCredentialValidation={lastfm:!1,librefm:!1,listenbrainz:!1};const X=function(...e){return console.log("[Debug]",...e)},fe=function(...e){return console.error("[Debug] Error:",...e)};function j(e,t){w[e]=t,e==="lastError"&&t?fe("Error recorded:",t.message):e==="lastTrack"&&t?X("Track updated:",`${t.artist} - ${t.name}`):e==="currentService"&&t&&X("Service changed to:",t)}function de(){w.apiCallCount=(w.apiCallCount||0)+1,X(`API call count: ${w.apiCallCount}`)}function H(e,t){w.serviceErrors=w.serviceErrors||{lastfm:[],librefm:[],listenbrainz:[]},w.serviceErrors[e]=w.serviceErrors[e]||[],w.serviceErrors[e].push(`${new Date().toISOString()}: ${t}`),w.serviceErrors[e].length>10&&(w.serviceErrors[e]=w.serviceErrors[e].slice(-10)),fe(`${e} error:`,t)}function pe(){w.lastSuccessfulUpdate=new Date().toISOString(),X("Successful update recorded at:",w.lastSuccessfulUpdate)}function Q(e){return Q=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Q(e)}function be(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(be=function(){return!!e})()}function Oe(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Ke(e){"@swc/helpers - typeof";return e&&typeof Symbol<"u"&&e.constructor===Symbol?"symbol":typeof e}function je(e,t){return t&&(Ke(t)==="object"||typeof t=="function")?t:Oe(e)}function te(e,t,n){return t=Q(t),je(e,be()?Reflect.construct(t,n||[],Q(e).constructor):t.apply(e,n))}function re(e,t){return re=Object.setPrototypeOf||function(a,i){return a.__proto__=i,a},re(e,t)}function ne(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&re(e,t)}let ae=(function(){function e(){F(this,e)}return B(e,[{key:"log",value:function(...t){console.log(`[${this.getServiceName()}]`,...t)}},{key:"logError",value:function(...t){console.error(`[${this.getServiceName()}] Error:`,...t)}},{key:"logVerbose",value:function(...t){console.log(`[${this.getServiceName()}] Verbose:`,...t)}},{key:"handleError",value:async function(t){this.lastError=t.error||0;const n=this.getErrorMessage(t);throw this.logError(n),H(this.getServiceName().toLowerCase(),n),new Error(`${this.getServiceName()} API Error: ${n}`)}},{key:"getErrorMessage",value:function(t){return t.error&&d.API_ERROR_CODES[t.error]?d.API_ERROR_CODES[t.error]:t.message||t.toString()||"Unknown error"}},{key:"makeRequest",value:async function(t,n={}){try{this.logVerbose(`Making request to: ${t}`),de();const a=await fetch(t,{...n,headers:{"User-Agent":"Vendetta Multi-Service Scrobbler/3.0.0",...n.headers}});if(!a.ok){const s=new Error(`HTTP ${a.status}: ${a.statusText}`);throw H(this.getServiceName().toLowerCase(),s.message),s}const i=await a.json();return i.error&&await this.handleError(i),this.retryCount=0,i}catch(a){if(this.retryCount++,this.retryCount>d.MAX_RETRY_ATTEMPTS)throw this.retryCount=0,H(this.getServiceName().toLowerCase(),`Max retries exceeded: ${a.message}`),a;return this.logVerbose(`Request failed, retrying (${this.retryCount}/${d.MAX_RETRY_ATTEMPTS})`),await new Promise(function(i){return setTimeout(i,d.RETRY_DELAY)}),this.makeRequest(t,n)}}},{key:"isDefaultCover",value:function(t){return t?d.DEFAULT_COVER_HASHES.some(function(n){return t.includes(n)}):!0}},{key:"processAlbumArt",value:function(t){return!t||this.isDefaultCover(t)?null:t}},{key:"getLastError",value:function(){return this.lastError}},{key:"resetRetryCount",value:function(){this.retryCount=0}}]),e})(),Ge=(function(e){ne(t,e);function t(){return F(this,t),te(this,t,arguments)}return B(t,[{key:"getServiceName",value:function(){return"Last.fm"}},{key:"logVerbose",value:function(...n){l.verboseLogging&&console.log(`[${this.getServiceName()}] Verbose:`,...n)}},{key:"validateCredentials",value:async function(){try{if(!l.username||!l.apiKey)throw new Error("Username or API key not set");const n=new URLSearchParams({method:"user.getinfo",user:l.username,api_key:l.apiKey,format:"json"}),a=`${d.SERVICES.lastfm.baseUrl}?${n}`;return await this.makeRequest(a),this.log("Credentials validation successful"),!0}catch(n){return this.logError("Credentials validation failed:",n),!1}}},{key:"fetchLatestScrobble",value:async function(){try{if(!l.username||!l.apiKey)throw new Error("Username or API key not set");this.logVerbose("Fetching latest scrobble for user:",l.username);const n=new URLSearchParams({method:"user.getrecenttracks",user:l.username,api_key:l.apiKey,limit:"1",extended:"1",format:"json"}),a=`${d.SERVICES.lastfm.baseUrl}?${n}`,i=(await this.makeRequest(a))?.recenttracks?.track?.[0];if(!i)throw new Error("No tracks found");this.logVerbose("Raw track data:",i);const s=!!i["@attr"]?.nowplaying,o=i.date?.uts?parseInt(i.date.uts):Math.floor(Date.now()/1e3);let g=null,b=null;if(s)try{const C=new URLSearchParams({method:"track.getInfo",track:i.name,artist:i.artist.name,api_key:l.apiKey,format:"json"}),N=`${d.SERVICES.lastfm.baseUrl}?${C}`,h=await this.makeRequest(N);h?.track?.duration&&(g=parseInt(h.track.duration),g>0&&(g=Math.floor(g/1e3),b=o+g))}catch(C){this.logVerbose("Failed to fetch track duration:",C)}const k=this.processAlbumArt(i.image?.find(function(C){return C.size==="large"})?.["#text"]),U={name:i.name,artist:i.artist.name,album:i.album["#text"],albumArt:k,url:i.url,date:i.date?.["#text"]??"now",nowPlaying:s,loved:i.loved==="1",from:o,to:b,duration:g};return this.logVerbose("Processed track:",U),this.log(`${s?"Now playing":"Last played"}:`,`${U.artist} - ${U.name}`),U}catch(n){throw this.logError("Failed to fetch latest scrobble:",n),n}}}]),t})(ae),qe=(function(e){ne(t,e);function t(){return F(this,t),te(this,t,arguments)}return B(t,[{key:"getServiceName",value:function(){return"Libre.fm"}},{key:"logVerbose",value:function(...n){l.verboseLogging&&console.log(`[${this.getServiceName()}] Verbose:`,...n)}},{key:"validateCredentials",value:async function(){try{const n=l.librefmUsername,a=l.librefmApiKey;if(!n||!a)throw new Error("Username or API key not set for Libre.fm");const i=new URLSearchParams({method:"user.getinfo",user:n,api_key:a,format:"json"}),s=`${d.SERVICES.librefm.baseUrl}?${i}`;return await this.makeRequest(s),this.log("Credentials validation successful"),!0}catch(n){return this.logError("Credentials validation failed:",n),!1}}},{key:"fetchLatestScrobble",value:async function(){try{const n=l.librefmUsername,a=l.librefmApiKey;if(!n||!a)throw new Error("Username or API key not set for Libre.fm");this.logVerbose("Fetching latest scrobble for user:",n);const i=new URLSearchParams({method:"user.getrecenttracks",user:n,api_key:a,limit:"1",extended:"1",format:"json"}),s=`${d.SERVICES.librefm.baseUrl}?${i}`,o=(await this.makeRequest(s))?.recenttracks?.track?.[0];if(!o)throw new Error("No tracks found");this.logVerbose("Raw track data:",o);const g=!!o["@attr"]?.nowplaying,b=o.date?.uts?parseInt(o.date.uts):Math.floor(Date.now()/1e3);let k=null,U=null;if(g)try{const h=new URLSearchParams({method:"track.getInfo",track:o.name,artist:o.artist.name,api_key:a,format:"json"}),D=`${d.SERVICES.librefm.baseUrl}?${h}`,A=await this.makeRequest(D);A?.track?.duration&&(k=parseInt(A.track.duration),k>0&&(k=Math.floor(k/1e3),U=b+k))}catch(h){this.logVerbose("Failed to fetch track duration:",h)}const C=this.processAlbumArt(o.image?.find(function(h){return h.size==="large"})?.["#text"]),N={name:o.name,artist:o.artist.name,album:o.album["#text"],albumArt:C,url:o.url,date:o.date?.["#text"]??"now",nowPlaying:g,loved:o.loved==="1",from:b,to:U,duration:k};return this.logVerbose("Processed track:",N),this.log(`${g?"Now playing":"Last played"}:`,`${N.artist} - ${N.name}`),N}catch(n){throw this.logError("Failed to fetch latest scrobble:",n),n}}}]),t})(ae),Ye=(function(e){ne(t,e);function t(){return F(this,t),te(this,t,arguments)}return B(t,[{key:"getServiceName",value:function(){return"ListenBrainz"}},{key:"logVerbose",value:function(...n){l.verboseLogging&&console.log(`[${this.getServiceName()}] Verbose:`,...n)}},{key:"validateCredentials",value:async function(){try{const n=l.listenbrainzUsername,a=l.listenbrainzToken;if(!n)throw new Error("Username not set for ListenBrainz");const i=`${d.SERVICES.listenbrainz.baseUrl}/user/${encodeURIComponent(n)}/listens?count=1`,s={};return a&&(s.Authorization=`Token ${a}`),await this.makeRequest(i,{headers:s}),this.log("Credentials validation successful"),!0}catch(n){return this.logError("Credentials validation failed:",n),!1}}},{key:"fetchLatestScrobble",value:async function(){try{const n=l.listenbrainzUsername,a=l.listenbrainzToken;if(!n)throw new Error("Username not set for ListenBrainz");this.logVerbose("Fetching latest scrobble for user:",n);let i=null;const s=function(h){if(h){if(Array.isArray(h.listens))return h.listens;if(h.payload&&Array.isArray(h.payload.listens))return h.payload.listens;if(h.data&&Array.isArray(h.data.listens))return h.data.listens}};try{const h=`${d.SERVICES.listenbrainz.baseUrl}/user/${encodeURIComponent(n)}/playing-now`,D={};a&&(D.Authorization=`Token ${a}`);const A=await this.makeRequest(h,{headers:D}),x=s(A);x&&x.length>0&&(i=x[0],i.playing_now=!0)}catch(h){this.logVerbose("No currently playing track or failed to fetch:",h)}let o;if(i)o=i,this.logVerbose("Using currently playing track");else{const h=`${d.SERVICES.listenbrainz.baseUrl}/user/${encodeURIComponent(n)}/listens?count=1`,D={};a&&(D.Authorization=`Token ${a}`);const A=await this.makeRequest(h,{headers:D}),x=(function(){if(A){if(Array.isArray(A.listens))return A.listens;if(A.payload&&Array.isArray(A.payload.listens))return A.payload.listens;if(A.data&&Array.isArray(A.data.listens))return A.data.listens}})();if(!x||x.length===0)throw new Error("No listens found");o=x[0],this.logVerbose("Using latest completed listen")}this.logVerbose("Raw listen data:",o);const g=!!o.playing_now,b=o.listened_at||Math.floor(Date.now()/1e3);let k=null,U=null;o.track_metadata.additional_info?.duration_ms&&(k=Math.floor(o.track_metadata.additional_info.duration_ms/1e3),g&&k>0&&(U=b+k));const C=null;o.track_metadata.additional_info?.release_mbid;const N={name:o.track_metadata.track_name,artist:o.track_metadata.artist_name,album:o.track_metadata.release_name||"",albumArt:C,url:o.track_metadata.additional_info?.origin_url||`https://listenbrainz.org/player/${o.track_metadata.additional_info?.recording_mbid||`${encodeURIComponent(o.track_metadata.artist_name)}/${encodeURIComponent(o.track_metadata.track_name)}`}`,date:g?"now":new Date(b*1e3).toISOString(),nowPlaying:g,loved:!1,from:b,to:U,duration:k};return this.logVerbose("Processed track:",N),this.log(`${g?"Now playing":"Last played"}:`,`${N.artist} - ${N.name}`),N}catch(n){throw this.logError("Failed to fetch latest listen:",n),n}}},{key:"getErrorMessage",value:function(n){return n.error?n.error:n.message?n.message:n.toString()||"Unknown error"}}]),t})(ae);const O=(function(){function e(){F(this,e),this.serviceInstances=new Map}return B(e,[{key:"getService",value:function(t){this.serviceInstances||(this.serviceInstances=new Map);const n=t||l.service;if(!n)throw new Error("[ServiceFactory] No service type specified and no default service configured");return this.serviceInstances.has(n)||this.serviceInstances.set(n,this.createService(n)),this.serviceInstances.get(n)}},{key:"getCurrentService",value:function(){return this.getService(l.service)}},{key:"createService",value:function(t){switch(t){case"lastfm":return new Ge;case"librefm":return new qe;case"listenbrainz":return new Ye;default:throw new Error(`[ServiceFactory] Unknown service type: ${t}`)}}},{key:"clearCache",value:function(){this.serviceInstances?this.serviceInstances.clear():this.serviceInstances=new Map}},{key:"validateCurrentService",value:function(){return this.getCurrentService().validateCredentials()}},{key:"testService",value:async function(t){try{return await this.getService(t).validateCredentials()}catch(n){return console.error(`[ServiceFactory] Failed to test ${t}:`,n),!1}}},{key:"getSupportedServices",value:function(){return["lastfm","librefm","listenbrainz"]}},{key:"getServiceDisplayName",value:function(t){return this.getService(t).getServiceName()}}],[{key:"getInstance",value:function(){return e.instance||(e.instance=new e),e.instance}}]),e})().getInstance();function he(e){if(!e||e<0)return"0:00";const t=Math.floor(e/3600),n=Math.floor(e%3600/60),a=Math.floor(e%60);return t>0?`${t}:${n.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`:`${n}:${a.toString().padStart(2,"0")}`}function ye(){return Math.floor(Date.now()/1e3)}var We=(function(e){return e[e.PLAYING=0]="PLAYING",e[e.STREAMING=1]="STREAMING",e[e.LISTENING=2]="LISTENING",e[e.COMPETING=5]="COMPETING",e})(We||{});const I=function(...e){return console.log("[Scrobble Plugin]",...e)},z=function(...e){return console.error("[Scrobble Plugin] Error:",...e)},L=function(...e){return l.verboseLogging&&console.log("[Scrobble Plugin] Verbose:",...e)},ie=(function(){function e(){F(this,e)}return B(e,[{key:"updateActivity",value:async function(){if(v.pluginStopped){I("Plugin is stopped; skipping activity updates and clearing timers"),L("Plugin is stopped, skipping update");try{this.stopUpdates(),L("Update timers cleared due to stopped plugin")}catch(a){z("Error while stopping updates for stopped plugin:",a)}return}const t=O.getCurrentService().getServiceName();L(`Fetching latest track from ${t}...`);let n=!1;try{if(l.ignoreList&&l.ignoreList.length>0){const o=Fe.findActivity(function(g){return g.name?l.ignoreList.some(function(b){return g.name.toLowerCase().includes(b.toLowerCase())}):!1});if(o){I(`Ignored app (${o.name}) is currently active; clearing activity and skipping updates`),L(`Ignored app (${o.name}) is currently playing, clearing activity`);try{j("ignoredActivity",o.name)}catch(g){L("Failed to set debug info for ignored activity:",g)}ee();return}}de();const a=await O.getCurrentService().fetchLatestScrobble();if(j("lastTrack",a),!a.nowPlaying){I("No currently playing track reported by service; clearing activity and skipping RPC update"),L("Track is not currently playing");try{j("lastTrack_nowPlaying",!1)}catch(o){L("Failed to set debug info for nowPlaying:",o)}ee();return}if(v.lastTrackUrl===a.url){I("Track unchanged; skipping Discord RPC update"),L("Track hasn't changed"),pe(),this.consecutiveFailures=0;return}n=!0,I(`\u{1F3B5} Track changed: ${a.artist} - ${a.name}`);let i;if(a.nowPlaying&&l.showTimestamp&&a.from){const o=ye();let g=a.from;if(g<o-3600){if(a.duration&&a.duration>0){const b=Math.min(a.duration*.1,30);g=o-b}else g=o;L("had to estimate start time")}i={start:g*1e3},a.to&&(i.end=a.to*1e3)}L(`\u{1F3AF} Preparing RPC update for: ${a.artist} - ${a.name}`);const s={name:l.appName||d.DEFAULT_APP_NAME,flags:0,type:l.listeningTo?2:0,details:a.name,state:`${a.artist}`,status_display_type:1,application_id:d.APPLICATION_ID};if(s.name.includes("{{")){const o={artist:a.artist,name:a.name,album:a.album,service:t};for(const[g,b]of Object.entries(o))s.name=s.name.replace(new RegExp(`{{${g}}}`,"g"),b||"")}if(i&&(s.timestamps=i,L("Timestamps set:",{start:new Date(i.start).toISOString(),end:i.end?new Date(i.end).toISOString():"none",duration:a.duration?he(a.duration):"unknown"})),a.album||a.albumArt){const o=a.albumArt?[a.albumArt]:[];let g=(await Be(o))[0];if(g){if(s.assets={large_image:g},l.showLargeText){let b="";if(l.showAlbumInTooltip&&a.album&&(b+=`on ${a.album}`),l.showDurationInTooltip&&a.duration){const k=he(a.duration);b?b+=` \u2022 ${k}`:b=k}b&&(s.assets.large_text=b)}L("Album art set:",g),s.assets.large_text&&L("Tooltip text set:",s.assets.large_text)}else a.album&&l.showLargeText&&l.showAlbumInTooltip&&(s.assets={large_text:`on ${a.album}`})}L("Setting Discord activity:",s),j("lastActivity",s),await ge(s),v.lastTrackUrl=a.url,this.currentActivity=s,v.lastActivity=s,this.consecutiveFailures=0,this.lastUpdateTime=ye(),pe(),I(`\u2705 RPC updated successfully: ${a.artist} - ${a.name}`)}catch(a){z("Update failed:",a);try{H(l.service,a.message)}catch(i){z("Failed to record service error:",i)}try{j("lastUpdateError",{message:a.message,service:l.service,lastTrackUrl:v.lastTrackUrl})}catch(i){L("Failed to set debug info for last update error:",i)}this.handleError(a)}}},{key:"handleError",value:function(t){this.consecutiveFailures++,j("lastError",t),z(`Failure ${this.consecutiveFailures}/${d.MAX_RETRY_ATTEMPTS}:`,t.message),this.consecutiveFailures>=d.MAX_RETRY_ATTEMPTS&&(z("Max retry attempts reached, initiating reconnection..."),this.startReconnection())}},{key:"startReconnection",value:function(){var t=this;this.isReconnecting||(this.isReconnecting=!0,this.stopUpdates(),I("Starting reconnection process..."),this.reconnectTimer=setInterval(function(){I("Attempting to reconnect..."),t.initialize().then(function(){I("Reconnection successful!"),t.stopReconnection()}).catch(function(n){z("Reconnection attempt failed:",n.message)})},d.RETRY_DELAY))}},{key:"stopReconnection",value:function(){try{this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=void 0),this.isReconnecting=!1,this.consecutiveFailures=0}catch(t){console.error("[Scrobble Plugin] Reconnection cleanup error:",t)}}},{key:"stopUpdates",value:function(){try{this.updateTimer&&(clearInterval(this.updateTimer),this.updateTimer=void 0)}catch(t){console.error("[Scrobble Plugin] Timer cleanup error:",t)}}},{key:"initialize",value:async function(){var t=this;if(v.pluginStopped)throw new Error("Plugin is stopped");const n=O.getCurrentService().getServiceName();I(`Initializing with ${n}...`);try{if(!await O.validateCurrentService())throw new Error(`Invalid credentials for ${n}`);I(`${n} credentials validated successfully`)}catch(i){throw z(`Failed to validate ${n} credentials:`,i),i}this.stopUpdates(),I("\u{1F3B5} checking for already playing songs..."),await this.updateActivity();const a=Math.max((Number(l.timeInterval)||d.DEFAULT_SETTINGS.timeInterval)*1e3,d.MIN_UPDATE_INTERVAL*1e3);this.updateTimer=setInterval(function(){return t.updateActivity()},a),I(`Update timer started with interval: ${a}ms (${a/1e3}s)`)}},{key:"stop",value:function(){if(!v.pluginStopped){I("Stopping plugin..."),v.pluginStopped=!0;try{this.stopUpdates(),this.stopReconnection(),ee(),I("Plugin stopped successfully")}catch(t){console.error("[Scrobble Plugin] Stop error:",t)}}}},{key:"switchService",value:async function(t){if(v.pluginStopped)return;I(`Switching to ${t}...`);const n=!v.pluginStopped;this.stop();try{O.clearCache(),v.lastTrackUrl=void 0,this.currentActivity=void 0,this.lastUpdateTime=0,n&&(v.pluginStopped=!1,await this.initialize())}catch(a){z("Failed to switch service:",a)}}},{key:"getStatus",value:function(){const t=O.getCurrentService().getServiceName();return{running:!v.pluginStopped,service:t,consecutiveFailures:this.consecutiveFailures,isReconnecting:this.isReconnecting,lastTrackUrl:v.lastTrackUrl,updateInterval:this.updateTimer?"Active":"Inactive"}}}],[{key:"getInstance",value:function(){return e.instance||(e.instance=new e),e.instance}}]),e})().getInstance(),Xe=function(){return ie.initialize()},se=function(){return ie.stop()},He=function(e){return ie.switchService(e)},{ScrollView:M}=V.findByProps("ScrollView"),{TableRowGroup:E,TableSwitchRow:me,TableCheckboxRow:G,Stack:P,TableRow:u}=V.findByProps("TableSwitchRow","TableCheckboxRow","TableRowGroup","Stack","TableRow"),{TextInput:_}=V.findByProps("TextInput");function Qe(){$.useProxy(p.plugin.storage);const[,e]=r.React.useReducer(function(n){return n+1},0),t=async function(){S.showToast("Testing Last.fm connection...",R.getAssetIDByName("ClockIcon"));try{await Y.testService("lastfm")?S.showToast("\u2705 Last.fm connection successful!",R.getAssetIDByName("CheckIcon")):S.showToast("\u274C Last.fm connection failed",R.getAssetIDByName("XIcon"))}catch{S.showToast("\u274C Connection error",R.getAssetIDByName("XIcon"))}};return r.React.createElement(M,{style:{flex:1},contentContainerStyle:{padding:10}},r.React.createElement(P,{spacing:8},r.React.createElement(E,{title:"Credentials"},r.React.createElement(P,{spacing:4},r.React.createElement(_,{placeholder:"Last.fm Username",value:c("username"),onChange:function(n){T("username",n),e()},isClearable:!0}),r.React.createElement(_,{placeholder:"Last.fm API Key",value:c("apiKey"),onChange:function(n){T("apiKey",n),e()},secureTextEntry:!0,isClearable:!0}))),r.React.createElement(E,{title:"Actions"},r.React.createElement(u,{label:"Test Connection",subLabel:"Verify your Last.fm credentials",trailing:r.React.createElement(u.Arrow,null),onPress:t}),r.React.createElement(u,{label:"Get API Key",subLabel:"Create a Last.fm API key at last.fm/api/account/create",trailing:r.React.createElement(u.Arrow,null),onPress:async function(){try{await Z.Linking.openURL("https://www.last.fm/api/account/create")}catch(n){console.error("Failed to open Last.fm API URL:",n),S.showToast("Failed to open web browser. Please visit: https://www.last.fm/api/account/create",R.getAssetIDByName("XIcon"))}}}))))}function Je(){$.useProxy(p.plugin.storage);const[,e]=r.React.useReducer(function(n){return n+1},0),t=async function(){S.showToast("Testing Libre.fm connection...",R.getAssetIDByName("ClockIcon"));try{await Y.testService("librefm")?S.showToast("\u2705 Libre.fm connection successful!",R.getAssetIDByName("CheckIcon")):S.showToast("\u274C Libre.fm connection failed",R.getAssetIDByName("XIcon"))}catch{S.showToast("\u274C Connection error",R.getAssetIDByName("XIcon"))}};return r.React.createElement(M,{style:{flex:1},contentContainerStyle:{padding:10}},r.React.createElement(P,{spacing:8},r.React.createElement(E,{title:"Credentials"},r.React.createElement(P,{spacing:4},r.React.createElement(_,{placeholder:"Libre.fm Username",value:c("librefmUsername"),onChange:function(n){T("librefmUsername",n),e()},isClearable:!0}),r.React.createElement(_,{placeholder:"Libre.fm API Key",value:c("librefmApiKey"),onChange:function(n){T("librefmApiKey",n),e()},secureTextEntry:!0,isClearable:!0}))),r.React.createElement(E,{title:"Actions"},r.React.createElement(u,{label:"Test Connection",subLabel:"Verify your Libre.fm credentials",trailing:r.React.createElement(u.Arrow,null),onPress:t}),r.React.createElement(u,{label:"Get API Key",subLabel:"Create a Last.fm API key (compatible with Libre.fm)",trailing:r.React.createElement(u.Arrow,null),onPress:async function(){try{await Z.Linking.openURL("https://www.last.fm/api/account/create")}catch(n){console.error("Failed to open Last.fm API URL:",n),S.showToast("Failed to open web browser. Please visit: https://www.last.fm/api/account/create",R.getAssetIDByName("XIcon"))}}}))))}function Ze(){$.useProxy(p.plugin.storage);const[,e]=r.React.useReducer(function(n){return n+1},0),t=async function(){S.showToast("Testing ListenBrainz connection...",R.getAssetIDByName("ClockIcon"));try{await Y.testService("listenbrainz")?S.showToast("\u2705 ListenBrainz connection successful!",R.getAssetIDByName("CheckIcon")):S.showToast("\u274C ListenBrainz connection failed",R.getAssetIDByName("XIcon"))}catch{S.showToast("\u274C Connection error",R.getAssetIDByName("XIcon"))}};return r.React.createElement(M,{style:{flex:1},contentContainerStyle:{padding:10}},r.React.createElement(P,{spacing:8},r.React.createElement(E,{title:"Credentials"},r.React.createElement(P,{spacing:4},r.React.createElement(_,{placeholder:"ListenBrainz Username",value:c("listenbrainzUsername"),onChange:function(n){T("listenbrainzUsername",n),e()},isClearable:!0}),r.React.createElement(_,{placeholder:"ListenBrainz Token",value:c("listenbrainzToken"),onChange:function(n){T("listenbrainzToken",n),e()},secureTextEntry:!0,isClearable:!0}))),r.React.createElement(E,{title:"Actions"},r.React.createElement(u,{label:"Test Connection",subLabel:"Verify your ListenBrainz credentials",trailing:r.React.createElement(u.Arrow,null),onPress:t}),r.React.createElement(u,{label:"Get User Token",subLabel:"Get your ListenBrainz user token at listenbrainz.org/settings/",trailing:r.React.createElement(u.Arrow,null),onPress:async function(){try{await Z.Linking.openURL("https://listenbrainz.org/settings/")}catch(n){console.error("Failed to open ListenBrainz settings URL:",n),S.showToast("Failed to open web browser. Please visit: https://listenbrainz.org/settings/",R.getAssetIDByName("XIcon"))}}}))))}function et(){$.useProxy(p.plugin.storage);const[,e]=r.React.useReducer(function(t){return t+1},0);return r.React.createElement(M,{style:{flex:1},contentContainerStyle:{padding:10}},r.React.createElement(P,{spacing:8},r.React.createElement(E,{title:"Activity Display"},r.React.createElement(P,{spacing:4},r.React.createElement(_,{placeholder:`App Name (Default: ${d.DEFAULT_SETTINGS.appName})`,value:c("appName",d.DEFAULT_SETTINGS.appName),onChange:function(t){T("appName",t),e()},isClearable:!0}),r.React.createElement(_,{placeholder:`Update Interval (Default: ${d.DEFAULT_SETTINGS.timeInterval}s)`,value:String(c("timeInterval",d.DEFAULT_SETTINGS.timeInterval)),onChange:function(t){const n=Number(t);n>=d.MIN_UPDATE_INTERVAL&&(T("timeInterval",n),e())},keyboardType:"numeric",isClearable:!0}))),r.React.createElement(E,{title:"About Display Settings"},r.React.createElement(u,{label:"App Name",subLabel:"The name shown in Discord for your activity"}),r.React.createElement(u,{label:"Update Interval",subLabel:"How often the plugin checks for new tracks (in seconds)"}),r.React.createElement(u,{label:"Minimum Interval",subLabel:`The plugin will never check more frequently than ${d.MIN_UPDATE_INTERVAL} seconds`}))))}function tt(){$.useProxy(p.plugin.storage);const[e,t]=r.React.useState(null),[n,a]=r.React.useState(!0),[i,s]=r.React.useState(0),[o,g]=r.React.useState(!1),b={name:"Bohemian Rhapsody",artist:"Queen",artists:["Queen"],album:"A Night at the Opera",image:null,nowPlaying:!0,duration:354,startTime:Math.floor(Date.now()/1e3)-120},k=function(f){return f?Array.isArray(f)?f.filter(function(y){return y&&typeof y=="string"}):f["#text"]?f["#text"].split(/[,;&]/).map(function(y){return y.trim()}).filter(function(y){return y.length>0}):typeof f=="string"?f.split(/[,;&]/).map(function(y){return y.trim()}).filter(function(y){return y.length>0}):["Unknown Artist"]:["Unknown Artist"]},U=function(f){return!f||f.length===0?"Unknown Artist":f.length===1?f[0]:f.length===2?`${f[0]} & ${f[1]}`:`${f.slice(0,-1).join(", ")} & ${f[f.length-1]}`};r.React.useEffect(function(){(async function(){if(!c("username")||!c("apiKey")){t(b),g(!0),a(!1);return}try{a(!0);const f=await(await fetch(`https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=${c("username")}&api_key=${c("apiKey")}&format=json&limit=1`)).json();if(f.recenttracks&&f.recenttracks.track&&f.recenttracks.track.length>0){const y=f.recenttracks.track[0],K=k(y.artist);let Me=180;try{const gt=K[0]||"Unknown Artist",le=await(await fetch(`https://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=${c("apiKey")}&artist=${encodeURIComponent(gt)}&track=${encodeURIComponent(y.name)}&format=json&u[...]`)).json();le.track&&le.track.duration&&(Me=Math.floor(le.track.duration/1e3))}catch{console.log("Could not fetch track duration, using default")}t({name:y.name||"Unknown Track",artist:U(K),artists:K,album:y.album?.["#text"]||"Unknown Album",image:y.image?.[2]?.["#text"]||y.image?.[1]?.["#text"]||null,nowPlaying:y["@attr"]?.nowplaying==="true",duration:Me,startTime:y["@attr"]?.nowplaying==="true"?Math.floor(Date.now()/1e3)-60:null}),g(!1)}else t(b),g(!0)}catch(f){console.error("Failed to fetch preview data, using fallback:",f),t(b),g(!0)}finally{a(!1)}})()},[c("username"),c("apiKey")]),r.React.useEffect(function(){if(!e?.nowPlaying||!c("showTimestamp"))return;const f=setInterval(function(){if(e.startTime&&e.duration){const y=Math.floor(Date.now()/1e3)-e.startTime,K=Math.min(y/e.duration,1);s(K)}},1e3);return function(){return clearInterval(f)}},[e,c("showTimestamp")]);const C=function(f){const y=Math.floor(f/60),K=Math.floor(f%60);return`${y}:${K.toString().padStart(2,"0")}`},N=function(){let f="";if(c("showAlbumInTooltip")&&e?.album&&(f+=`on ${e.album}`),c("showDurationInTooltip")&&e?.duration){const y=` \u2022 ${C(e.duration)}`;f?f+=y:f=C(e.duration)}return f||"No tooltip text"},h=function(){return e?.duration?e.nowPlaying?{current:i*e.duration,total:e.duration,progress:i}:{current:e.duration*.3,total:e.duration,progress:.3}:{current:0,total:0,progress:0}},D=c("listeningTo")?"Listening to":"Playing",A=c("appName")||"Music",x=c("showLargeText",!0),ut=c("showTimestamp",!1);if(n)return r.React.createElement(r.ReactNative.View,{style:m.container},r.React.createElement(r.ReactNative.View,{style:m.loadingContent},r.React.createElement(r.ReactNative.View,{style:m.loadingSpinner}),r.React.createElement(r.ReactNative.Text,{style:m.loadingText},"Loading preview...")));if(!e)return r.React.createElement(r.ReactNative.View,{style:m.container},r.React.createElement(r.ReactNative.Text,{style:m.centeredText},"Unable to load preview"));const oe=h(),ze=N();return r.React.createElement(r.ReactNative.View,{style:m.previewContainer},r.React.createElement(r.ReactNative.View,{style:m.header},r.React.createElement(r.ReactNative.Text,{style:m.activityType},D," ",A),r.React.createElement(r.ReactNative.Text,{style:m.rpcPreviewText,numberOfLines:1},"RPC Preview")),r.React.createElement(r.ReactNative.View,{style:m.content},r.React.createElement(r.ReactNative.View,{style:m.albumArt},e.image?r.React.createElement(r.ReactNative.Image,{source:{uri:e.image},style:m.albumImage,resizeMode:"cover"}):r.React.createElement(r.ReactNative.Text,{style:m.musicIcon},"\u{1F3B5}")),r.React.createElement(r.ReactNative.View,{style:m.trackInfo},r.React.createElement(r.ReactNative.Text,{style:m.trackName,numberOfLines:1},e.name),r.React.createElement(r.ReactNative.Text,{style:m.artistName,numberOfLines:1},e.artist),x&&ze!=="No tooltip text"&&r.React.createElement(r.ReactNative.Text,{style:m.tooltipText,numberOfLines:1},ze),ut&&e.duration?r.React.createElement(r.ReactNative.View,{style:m.progressContainer},r.React.createElement(r.ReactNative.Text,{style:m.timeText},C(oe.current)),r.React.createElement(r.ReactNative.View,{style:m.progressBar},r.React.createElement(r.ReactNative.View,{style:[m.progressFill,{width:`${oe.progress*100}%`}]})),r.React.createElement(r.ReactNative.Text,{style:m.timeText},C(oe.total))):null)))}const m=r.ReactNative.StyleSheet.create({container:{backgroundColor:"#1e1f22",borderRadius:12,padding:16,marginHorizontal:10,marginBottom:16,borderWidth:1,borderColor:"#3a3c41",alignItems:"center",justifyContent:"center",minHeight:120},loadingContent:{alignItems:"center",justifyContent:"center"},loadingSpinner:{width:20,height:20,borderRadius:10,borderWidth:2,borderColor:"#5865f2",borderTopColor:"transparent",marginBottom:8},previewContainer:{backgroundColor:"#1e1f22",borderRadius:12,padding:16,marginHorizontal:10,marginBottom:16,borderWidth:1,borderColor:"#3a3c41"},header:{flexDirection:"row",justifyContent:"space-between",alignItems:"center",marginBottom:12,gap:8},content:{flexDirection:"row",alignItems:"center"},albumArt:{width:80,height:80,backgroundColor:"#2b2d31",borderRadius:12,justifyContent:"center",alignItems:"center",marginRight:16,borderWidth:1,borderColor:"#40444b",overflow:"hidden",flexShrink:0},trackInfo:{flex:1,minWidth:0},progressContainer:{flexDirection:"row",alignItems:"center",gap:8,marginTop:6},progressBar:{flex:1,height:2,backgroundColor:"#2b2d31",borderRadius:3,overflow:"hidden"},progressFill:{height:2,backgroundColor:"#5865f2",borderRadius:3},loadingText:{color:"#949ba4",fontSize:14,fontWeight:"500"},centeredText:{color:"#949ba4",fontSize:14,fontWeight:"500",textAlign:"center"},activityType:{color:"#dbdee1",fontSize:14,fontWeight:"600",flex:1},rpcPreviewText:{color:"#80848e",fontSize:12,fontStyle:"italic",flexShrink:0},albumImage:{width:80,height:80,borderRadius:12},musicIcon:{color:"#80848e",fontSize:32},trackName:{color:"#ffffff",fontSize:16,fontWeight:"700",marginBottom:4},artistName:{color:"#b5bac1",fontSize:14,fontWeight:"500",marginBottom:4},tooltipText:{color:"#80848e",fontSize:12,fontStyle:"italic",marginBottom:6},timeText:{color:"#80848e",fontSize:11,fontWeight:"500",minWidth:35,textAlign:"center"}});function rt(){$.useProxy(p.plugin.storage);const[,e]=r.React.useReducer(function(s){return s+1},0),t=c("listeningTo",d.DEFAULT_SETTINGS.listeningTo),n=c("showTimestamp",d.DEFAULT_SETTINGS.showTimestamp),a=function(){const s=!t;T("listeningTo",s),!s&&n&&T("showTimestamp",!1),e()},i=function(){t&&(T("showTimestamp",!n),e())};return r.React.createElement(M,{style:{flex:1},contentContainerStyle:{padding:10}},r.React.createElement(tt,null),r.React.createElement(P,{spacing:8},r.React.createElement(E,{title:"RPC Display Options"},r.React.createElement(G,{label:"Show as Listening",subLabel:"Display as 'Listening to' instead of 'Playing'",checked:t,onPress:a}),r.React.createElement(G,{label:"Show Tooltip Text",subLabel:"Show album name and track duration in Discord activity tooltip",checked:c("showLargeText",!0),onPress:function(){const s=c("showLargeText",!0);T("showLargeText",!s),e()}}),!t&&r.React.createElement(u,{label:"Timestamp Unavailable",subLabel:"Enable 'Show as Listening' to use timestamp feature",disabled:!0,dimmed:!0}),r.React.createElement(G,{label:"Show Timestamp",subLabel:"Display track progress and duration",checked:n,onPress:i,disabled:!t}),r.React.createElement(G,{label:"Show Album in Tooltip",subLabel:"Include album name in the tooltip text",checked:c("showAlbumInTooltip",!0),onPress:function(){const s=c("showAlbumInTooltip",!0);T("showAlbumInTooltip",!s),e()}}),r.React.createElement(G,{label:"Show Duration in Tooltip",subLabel:"Include track duration in the tooltip text",checked:c("showDurationInTooltip",!0),onPress:function(){const s=c("showDurationInTooltip",!0);T("showDurationInTooltip",!s),e()}}))))}function nt(){$.useProxy(p.plugin.storage);const[,e]=r.React.useReducer(function(s){return s+1},0),[t,n]=r.React.useState(""),a=function(){if(!t.trim()){S.showToast("Please enter an app name",R.getAssetIDByName("Small"));return}const s=c("ignoreList",[]);s.includes(t.trim())?S.showToast("App already in ignore list",R.getAssetIDByName("Warning")):(T("ignoreList",[...s,t.trim()]),n(""),e(),S.showToast("App added to ignore list",R.getAssetIDByName("Check")))},i=function(s){const o=c("ignoreList",[]);T("ignoreList",o.filter(function(g){return g!==s})),e(),S.showToast("App removed from ignore list",R.getAssetIDByName("Check"))};return r.React.createElement(M,{style:{flex:1},contentContainerStyle:{padding:10}},r.React.createElement(P,{spacing:8},r.React.createElement(E,{title:"Add App to Ignore"},r.React.createElement(P,{spacing:4},r.React.createElement(_,{placeholder:"Enter app name",value:t,onChange:n,isClearable:!0,onSubmitEditing:a,returnKeyType:"done"}))),r.React.createElement(E,null,r.React.createElement(u,{label:"Add to Ignore List",subLabel:"Add the current app name to your ignore list",trailing:r.React.createElement(u.Arrow,null),onPress:a})),c("ignoreList",[]).length>0&&r.React.createElement(E,{title:"Ignored Apps"},c("ignoreList",[]).map(function(s,o){return r.React.createElement(u,{key:o,label:s,trailing:r.React.createElement(r.ReactNative.TouchableOpacity,{onPress:function(){return i(s)},style:{padding:8,backgroundColor:"#ff4d4d",borderRadius:12,width:24,height:24,justifyContent:"center",alignItems:"center"}},r.React.createElement(r.ReactNative.Image,{source:R.getAssetIDByName("TrashIcon"),style:{width:14,height:14,tintColor:"#ffffff"}}))})})),r.React.createElement(E,{title:"About Ignore List"},r.React.createElement(u,{label:"How it Works",subLabel:"When any app in your ignore list is active, your music status will be hidden"}),r.React.createElement(u,{label:"Detection",subLabel:"Apps are detected by their Discord activity name"}),r.React.createElement(u,{label:"Examples",subLabel:"Spotify, YouTube Music, Kizzy, Metrolist, echo"}))))}function at(){$.useProxy(p.plugin.storage);const[,e]=r.React.useReducer(function(t){return t+1},0);return r.React.createElement(M,{style:{flex:1},contentContainerStyle:{padding:10}},r.React.createElement(P,{spacing:8},r.React.createElement(E,{title:"Logging Options"},r.React.createElement(me,{label:"Verbose Logging",subLabel:"Enable detailed console logging for debugging",value:c("verboseLogging",d.DEFAULT_SETTINGS.verboseLogging),onValueChange:function(t){T("verboseLogging",t),e()}})),r.React.createElement(E,{title:"Debug Information"},r.React.createElement(u,{label:"Console Logging",subLabel:"Logs are written to the browser/app console when verbose is enabled"}),r.React.createElement(u,{label:"Error Tracking",subLabel:"Connection errors and API failures are automatically logged"})),r.React.createElement(E,{title:"Log Information"},r.React.createElement(u,{label:"API Calls",subLabel:"All API requests are logged when verbose is enabled"}),r.React.createElement(u,{label:"Track Updates",subLabel:"Song changes and RPC updates are logged"}),r.React.createElement(u,{label:"Error Details",subLabel:"Connection errors and retries are logged"}))))}var we,ve,Re,Ee,Se,Te,ke,Ie,Ae,Le,Ce,Pe,Ne,Ue,$e,_e,De;(we=p.plugin.storage).username??(we.username=""),(ve=p.plugin.storage).apiKey??(ve.apiKey=""),(Re=p.plugin.storage).appName??(Re.appName="Music"),(Ee=p.plugin.storage).timeInterval??(Ee.timeInterval=5),(Se=p.plugin.storage).showTimestamp??(Se.showTimestamp=!0),(Te=p.plugin.storage).listeningTo??(Te.listeningTo=!0),(ke=p.plugin.storage).verboseLogging??(ke.verboseLogging=!1),(Ie=p.plugin.storage).service??(Ie.service="lastfm"),(Ae=p.plugin.storage).librefmUsername??(Ae.librefmUsername=""),(Le=p.plugin.storage).librefmApiKey??(Le.librefmApiKey=""),(Ce=p.plugin.storage).listenbrainzUsername??(Ce.listenbrainzUsername=""),(Pe=p.plugin.storage).listenbrainzToken??(Pe.listenbrainzToken=""),(Ne=p.plugin.storage).addToSidebar??(Ne.addToSidebar=!0),(Ue=p.plugin.storage).showLargeText??(Ue.showLargeText=!0),($e=p.plugin.storage).ignoreList??($e.ignoreList=[]),(_e=p.plugin.storage).showAlbumInTooltip??(_e.showAlbumInTooltip=!0),(De=p.plugin.storage).showDurationInTooltip??(De.showDurationInTooltip=!0);const c=function(e,t){return p.plugin.storage[e]??t},T=function(e,t){return p.plugin.storage[e]=t},Y=(function(){function e(){F(this,e)}return B(e,null,[{key:"getServiceDisplayName",value:function(t){switch(t){case"lastfm":return"Last.fm";case"librefm":return"Libre.fm";case"listenbrainz":return"ListenBrainz";default:return"Unknown"}}},{key:"testService",value:async function(t){try{switch(t){case"lastfm":return await this.testLastFmConnection();case"librefm":return await this.testLibreFmConnection();case"listenbrainz":return await this.testListenBrainzConnection();default:return!1}}catch(n){return console.error(`Error testing ${t}:`,n),!1}}},{key:"testLastFmConnection",value:async function(){const t=c("username"),n=c("apiKey");if(!t||!n)return!1;try{return!(await(await fetch(`https://ws.audioscrobbler.com/2.0/?method=user.getinfo&user=${t}&api_key=${n}&format=json`)).json()).error}catch(a){return console.error("Last.fm connection test failed:",a),!1}}},{key:"testLibreFmConnection",value:async function(){const t=c("librefmUsername"),n=c("librefmApiKey");if(!t||!n)return!1;try{return!(await(await fetch(`https://libre.fm/2.0/?method=user.getinfo&user=${t}&api_key=${n}&format=json`)).json()).error}catch(a){return console.error("Libre.fm connection test failed:",a),!1}}},{key:"testListenBrainzConnection",value:async function(){const t=c("listenbrainzUsername"),n=c("listenbrainzToken");if(!t)return!1;try{const a={"Content-Type":"application/json"};return n&&(a.Authorization=`Token ${n}`),(await fetch(`https://api.listenbrainz.org/1/user/${t}/listen-count`,{headers:a})).status===200}catch(a){return console.error("ListenBrainz connection test failed:",a),!1}}}]),e})();function it(){$.useProxy(p.plugin.storage);const e=r.NavigationNative.useNavigation(),[,t]=r.React.useReducer(function(i){return i+1},0),n=c("service"),a=function(i){switch(i){case"lastfm":return c("username")&&c("apiKey")?"\u2705 Configured":"\u274C Missing credentials";case"librefm":return c("librefmUsername")&&c("librefmApiKey")?"\u2705 Configured":"\u274C Missing credentials";case"listenbrainz":return c("listenbrainzUsername")?"\u2705 Configured":"\u274C Missing username";default:return"\u2753 Unknown"}};return r.React.createElement(M,{style:{flex:1},contentContainerStyle:{padding:10}},r.React.createElement(P,{spacing:8},r.React.createElement(E,{title:"Active Service"},r.React.createElement(u,{label:"Current Service",subLabel:n?`Using: ${Y.getServiceDisplayName(n)}`:"No service selected"}),["lastfm","librefm","listenbrainz"].map(function(i){return r.React.createElement(G,{key:i,label:Y.getServiceDisplayName(i),subLabel:a(i),checked:n===i,onPress:function(){i!==n&&(T("service",i),t())}})})),r.React.createElement(E,{title:"Service Configuration"},r.React.createElement(u,{label:"Last.fm Settings",subLabel:"Configure Last.fm credentials and options",trailing:r.React.createElement(u.Arrow,null),onPress:function(){return e.push("VendettaCustomPage",{title:"Last.fm Settings",render:Qe})}}),r.React.createElement(u,{label:"Libre.fm Settings",subLabel:"Configure Libre.fm credentials and options",trailing:r.React.createElement(u.Arrow,null),onPress:function(){return e.push("VendettaCustomPage",{title:"Libre.fm Settings",render:Je})}}),r.React.createElement(u,{label:"ListenBrainz Settings",subLabel:"Configure ListenBrainz credentials and options",trailing:r.React.createElement(u.Arrow,null),onPress:function(){return e.push("VendettaCustomPage",{title:"ListenBrainz Settings",render:Ze})}})),r.React.createElement(E,{title:"Plugin Configuration"},r.React.createElement(u,{label:"Display Settings",subLabel:"Customize app name and update interval",trailing:r.React.createElement(u.Arrow,null),onPress:function(){return e.push("VendettaCustomPage",{title:"Display Settings",render:et})}}),r.React.createElement(u,{label:"RPC Customization",subLabel:"Customize Discord rich presence display options",trailing:r.React.createElement(u.Arrow,null),onPress:function(){return e.push("VendettaCustomPage",{title:"RPC Customization",render:rt})}}),r.React.createElement(u,{label:"Ignore List",subLabel:"Configure apps that should hide your status",trailing:r.React.createElement(u.Arrow,null),onPress:function(){return e.push("VendettaCustomPage",{title:"Ignore List Settings",render:nt})}}),r.React.createElement(u,{label:"Logging Settings",subLabel:"Configure logging and debugging options",trailing:r.React.createElement(u.Arrow,null),onPress:function(){return e.push("VendettaCustomPage",{title:"Logging Settings",render:at})}}),r.React.createElement(me,{label:"Add to Sidebar",subLabel:"Show plugin in Discord settings",value:c("addToSidebar",!1),onValueChange:function(i){T("addToSidebar",i),t()},disabled:!0})),r.React.createElement(E,{title:"About"},r.React.createElement(u,{label:"Multi Scrobbler",subLabel:"Show off your music status from multiple services"}),r.React.createElement(u,{label:"Author",subLabel:"kmmiio99o"}),r.React.createElement(u,{label:"Version",subLabel:"1.3.2"}))))}const v={pluginStopped:!1,lastActivity:void 0,updateInterval:void 0,lastTrackUrl:void 0},xe=d.DEFAULT_SETTINGS;Object.keys(xe).forEach(function(e){p.plugin.storage[e]=p.plugin.storage[e]??xe[e]});const l=new Proxy(p.plugin.storage,{get(e,t){return e[t]},set(e,t,n){return e[t]=n,!0}});let J=0;const st=3,ot=5e3;async function W(){try{await Xe(),J=0,console.log("[Multi-Scrobbler] Successfully connected")}catch(e){console.error("[Multi-Scrobbler] Initialization error:",e),J++,J<st?(console.log(`[Multi-Scrobbler] Retrying connection... (attempt ${J})`),setTimeout(W,ot)):console.error("[Multi-Scrobbler] Failed to connect after multiple attempts")}}async function lt(){if(!l.service){console.log("[Multi-Scrobbler] No service selected. Please configure a service in settings.");return}let e="Unknown";try{e=O.getCurrentService().getServiceName()}catch(a){console.error("[Multi-Scrobbler] Failed to determine current service name:",a)}const t=l.service;let n=!1;switch(t){case"lastfm":n=!!(l.username&&l.apiKey);break;case"librefm":n=!!(l.librefmUsername&&l.librefmApiKey);break;case"listenbrainz":n=!!l.listenbrainzUsername;break}if(!n){console.error(`[Multi-Scrobbler] Missing credentials for ${e}. Please configure in settings.`);return}if(console.log(`[Multi-Scrobbler] Starting with ${e}...`),ue.getCurrentUser())W();else{const a=function(){ue.getCurrentUser()&&(W(),r.FluxDispatcher.unsubscribe("CONNECTION_OPEN",a))};r.FluxDispatcher.subscribe("CONNECTION_OPEN",a)}}var ct={onLoad(){console.log("[Multi-Scrobbler] Loading..."),v.pluginStopped=!1,lt()},onUnload(){console.log("[Multi-Scrobbler] Unloading..."),v.pluginStopped=!0,se()},async onSettingsUpdate(e){const t=l.service,n=e.service;if(Object.assign(l,e),t!==n&&n){console.log(`[Multi-Scrobbler] Service changed from ${t||"none"} to ${n}`);try{await He(n)}catch(a){console.error("[Multi-Scrobbler] Failed to switch service:",a)}}else if(!v.pluginStopped&&l.service)W();else if(!l.service){console.log("[Multi-Scrobbler] Service unselected, stopping plugin...");try{se()}catch(a){console.error("[Multi-Scrobbler] Error while stopping due to service unselected:",a)}}},onDiscordReconnect(){v.pluginStopped||(console.log("[Multi-Scrobbler] Discord reconnected, reinitializing..."),W())},settings:it};return q.currentSettings=l,q.default=ct,q.pluginState=v,Object.defineProperty(q,"__esModule",{value:!0}),q})({},vendetta,vendetta.metro.common,vendetta.metro,window.React,vendetta.storage,vendetta.metro.common.ReactNative,vendetta.ui.toasts,vendetta.ui.assets);
|