vd-plugins/Last.fm/index.js
2023-03-13 15:34:59 +00:00

1 line
6.7 KiB
JavaScript

(function(o,L,y,a,u,S,g,P,b){"use strict";function N(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function A(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function R(e,t,n){return t&&A(e.prototype,t),n&&A(e,n),e}function F(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const c={DEFAULT_APP_NAME:"Music",DEFAULT_TIME_INTERVAL:5,APPLICATION_ID:"1054951789318909972",LFM_API_KEY:"615322f0047e12aedbc610d9d71f7430",LFM_DEFAULT_COVER_HASHES:["2a96cbd8b46e442fc41c2b86b821562f","c6f59c1e5e7240a4c0d427abd71f3dbb"]},E=y.findByProps("getAssetIds");async function C(){const e=new URLSearchParams({method:"user.getrecenttracks",user:s.username,api_key:c.LFM_API_KEY,format:"json",limit:"1",extended:"1"}).toString(),t=await fetch(`https://ws.audioscrobbler.com/2.0/?${e}`);if(!t.ok)throw new Error(`Failed to fetch the latest scrobble: ${t.statusText}`);const n=await t.json(),r=n?.recenttracks?.track?.[0];if(!r)throw n;return{name:r.name,artist:r.artist.name,album:r.album["#text"],albumArt:await D(r.image[3]["#text"]),url:r.url,date:r.date?.["#text"]??"now",nowPlaying:!!r["@attr"]?.nowplaying,loved:r.loved==="1"}}async function D(e){return c.LFM_DEFAULT_COVER_HASHES.some(function(t){return e.includes(t)})?null:e}function d(){return i.lastActivity&&l("--> Clearing activity..."),I(null)}function I(e){i.pluginStopped&&(console.log("--> Plugin is unloaded, aborting..."),i.updateInterval&&clearInterval(i.updateInterval),e=null),i.lastActivity=e,a.FluxDispatcher.dispatch({type:"LOCAL_ACTIVITY_UPDATE",activity:e})}async function U(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:c.APPLICATION_ID;return e?typeof e=="string"?(await E.getAssetIds(t,[e]))[0]:await E.getAssetIds(t,e):null}async function w(){if(l("--> Fetching last track..."),!s.username)throw b.showToast("Last.fm username is not set!",g.getAssetIDByName("Small")),h(),new Error("Username is not set");const e=await C().catch(async function(n){throw l("--> An error occurred while fetching the last track, aborting..."),d(),n});if(!e.nowPlaying){l("--> Last track is not currently playing, aborting..."),d();return}if(l("--> Track fetched!"),i.lastTrackUrl===e.url){l("--> Last track is the same as the previous one, aborting...");return}const t={name:s.appName||c.DEFAULT_APP_NAME,flags:0,type:s.listeningTo?2:0,details:e.name,state:`by ${e.artist}`,application_id:c.APPLICATION_ID};if(i.lastTrackUrl=e.url,t.name.includes("{{"))for(const n in e)t.name=t.name.replace(`{{${n}}}`,e[n]);s.showTimestamp&&(t.timestamps={start:Date.now()/1e3|0}),e.album&&(t.assets={large_image:await U(e.albumArt),large_text:`on ${e.album}`}),l("--> Setting activity..."),l(t);try{I(t)}catch(n){throw l("--> An error occurred while setting the activity"),d(),n}l("--> Successfully set activity!")}function h(){console.log("--> Flushing..."),i.lastActivity=null,i.lastTrackUrl=null,i.updateInterval&&clearInterval(i.updateInterval),d()}async function m(){if(console.log("--> Initializing..."),i.pluginStopped)throw new Error("Plugin is already stopped!");h();let e=0;await w().catch(function(t){console.error(t),e++}),i.updateInterval=setInterval(function(){return w().then(function(){e=0}).catch(function(t){console.error(t),++e>3&&(console.error("Failed to fetch/set activity 3 times, aborting..."),h())})},(s.timeInterval||c.DEFAULT_TIME_INTERVAL)*1e3)}const{ScrollView:k,TouchableOpacity:V,Text:O}=a.ReactNative,{FormInput:p,FormDivider:f,FormSwitchRow:T,FormText:M,FormIcon:v}=P.Forms;function x(){async function e(){for(const t in u.storage)(u.storage[t]===!1||u.storage[t])&&(s[t]=u.storage[t]);console.log("Applying settings..."),await m(),b.showToast("Settings updated!",g.getAssetIDByName("Check"))}return a.React.createElement(V,{onPress:e},a.React.createElement(M,{style:{marginRight:12}},"UPDATE"))}function $(){const e=S.useProxy(u.storage),t=a.NavigationNative.useNavigation();return a.React.useEffect(function(){t.setOptions({title:"Last.fm Configuration",headerRight:x})},[]),a.React.createElement(k,null,a.React.createElement(p,{value:e.appName||void 0,onChangeText:function(n){return e.appName=n.trim()},title:"Discord Application Name",placeholder:c.DEFAULT_APP_NAME,returnKeyType:"done"}),a.React.createElement(f,null),a.React.createElement(p,{required:!0,value:e.username||void 0,onChangeText:function(n){return e.username=n.trim()},title:"Last.fm username",helpText:!e.username&&a.React.createElement(O,{style:{color:"#FF0000"}},"This field is required!"),placeholder:"wumpus123",returnKeyType:"done"}),a.React.createElement(f,null),a.React.createElement(p,{value:e.timeInterval,onChangeText:function(n){return e.timeInterval=Number(n)},title:"Update interval (in seconds)",placeholder:c.DEFAULT_TIME_INTERVAL.toString(),keyboardType:"numeric",returnKeyType:"done"}),a.React.createElement(f,null),a.React.createElement(T,{label:"Show time elapsed",subLabel:"Show the time elapsed since the song started playing",leading:a.React.createElement(v,{source:g.getAssetIDByName("clock")}),value:e.showTimestamp,onValueChange:function(n){return e.showTimestamp=n}}),a.React.createElement(f,null),a.React.createElement(T,{label:"Set status as listening",subLabel:'Set your status as "Listening to" instead of "Playing"',leading:a.React.createElement(v,{source:g.getAssetIDByName("ic_headset_neutral")}),value:e.listeningTo,onValueChange:function(n){return e.listeningTo=n}}),a.React.createElement(f,null),a.React.createElement(T,{label:"Verbose logging",subLabel:"Log more information to the console for debugging purposes",leading:a.React.createElement(v,{source:g.getAssetIDByName("pencil")}),value:e.verboseLogging,onValueChange:function(n){return e.verboseLogging=n}}))}const i={},s={...L.plugin.storage},_=y.findByStoreName("UserStore"),B=y.findByProps("SET_ACTIVITY").SET_ACTIVITY,l=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return s.verboseLogging&&console.log(...t)};var Y=new(function(){function e(){N(this,e),F(this,"settings",$)}return R(e,[{key:"onLoad",value:function(){console.log("Starting last.fm plugin.."),i.pluginStopped=!1,_.getCurrentUser()&&(console.log("User is already logged in, initializing..."),m().catch(console.error)),a.FluxDispatcher.subscribe("CONNECTION_OPEN",function(){m().catch(console.error)})}},{key:"onUnload",value:function(){console.log("Stopping last.fm..."),i.pluginStopped=!0,h()}}]),e}());return o.SET_ACTIVITY=B,o.UserStore=_,o.currentSettings=s,o.default=Y,o.global=i,o.verboseLog=l,Object.defineProperty(o,"__esModule",{value:!0}),o})({},vendetta,vendetta.metro,vendetta.metro.common,vendetta.plugin,vendetta.storage,vendetta.ui.assets,vendetta.ui.components,vendetta.ui.toasts);