Cloudflare Worker for parsing LastFM in Neos
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Simple Worker that fetches what you are listening to from LastFM | |
* then parses it for use inside of NeosVR (or your other app) | |
* Note: Make sure you create a Worker Encrypted Environment Variable | |
* with your LastFM API Key, this scripts expects you to use key "API_KEY" | |
*/ | |
// Reach out and get your data from LastFM | |
async function gatherResponse(response) { | |
const { headers } = response | |
const contentType = headers.get("content-type") || "" | |
if (contentType.includes("application/json")) { | |
let lastfm = await response.json() | |
let getArtist = JSON.stringify(lastfm.recenttracks.track[0].artist) | |
let fixBadJSON = JSON.parse(getArtist.replace('#','')) // LastFM uses dumb symbols | |
let artistName = JSON.stringify(fixBadJSON.text) | |
let bsNowPlaying = JSON.stringify(lastfm.recenttracks.track[0]) | |
let fixBadJSON2 = JSON.parse(bsNowPlaying.replace('@','')) // LastFM uses dumb symbols | |
let getNowPlaying = JSON.stringify(fixBadJSON2.attr) | |
let getAlbumArt = JSON.stringify(fixBadJSON3.image[3].text) | |
let songName = JSON.stringify(lastfm.recenttracks.track[0].name) | |
let songURL = JSON.stringify(lastfm.recenttracks.track[0].url) | |
// See if the latest song listed is being currently played | |
if (getNowPlaying == null) { | |
nowPlaying = false | |
}else{ | |
nowPlaying = true | |
} | |
let CSV = songName + "," + artistName + "," + songURL + "," + nowPlaying | |
return CSV | |
}else{ | |
return response.text('something went wrong') | |
} | |
} | |
async function handleRequest(request) { | |
const init = { | |
headers: { | |
"content-type": "application/json;charset=UTF-8", | |
}, | |
} | |
// Make it so that I can read params I pass | |
const myURL = new URL(request.url) | |
const myURLParams = new URLSearchParams(myURL.search) | |
// Check if you passed a username or not | |
if (myURLParams.has("username")) { | |
const username = myURLParams.get("username") | |
const url = "https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=" + username + "&&limit=1&api_key=" + API_KEY + "&format=json" | |
const response = await fetch(url, init) | |
const results = await gatherResponse(response) | |
return new Response(results, init) | |
}else{ | |
return new Response("Please supply a username!") | |
} | |
} | |
addEventListener("fetch", event => { | |
event.respondWith(handleRequest(event.request)) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment