Skip to content

Instantly share code, notes, and snippets.

@marco79cgn
Last active February 21, 2024 03:26
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save marco79cgn/ecd1cfe3da06008da9fb9f5d1fa37a1d to your computer and use it in GitHub Desktop.
Save marco79cgn/ecd1cfe3da06008da9fb9f5d1fa37a1d to your computer and use it in GitHub Desktop.
A scriptable widget that shows a random Top 500 album and opens it in Spotify
// insert your Spotify client id and secret here
let clientId = "xxx"
let clientSecret = "xxx"
// use your spotify country iso code to optimize search results
let spotifyCountry = "DE"
// optional: the ip of your node-sonos-http-api and room name; use "sonos" as parameter in your widget settings to activate it
let sonosUrl = "http://192.168.178.10:5005/Kitchen"
let openWith = args.widgetParameter
let widget = new ListWidget()
widget.setPadding(0,0,0,0)
widget.backgroundColor = new Color("#000000")
let searchToken = await getSpotifySearchToken()
await getRandomAlbum()
Script.setWidget(widget)
Script.complete()
async function getRandomAlbum() {
// load json from iCloud Drive
// source: https://gist.github.com/marco79cgn/92092f4a4f05434efe84f7191e55a8de
let fm = FileManager.iCloud()
let dir = fm.documentsDirectory()
let path = fm.joinPath(dir, "top_500_albums.json")
let contents = Data.fromFile(path)
let jsonTop500 = JSON.parse(contents.toRawString())
let uri = ""
let externalUrl = ""
let coverUrl = ""
do {
let randomNumber = getRandomNumber(1, 500)
let result = await searchAlbumAtSpotify(jsonTop500[randomNumber-1].Album, jsonTop500[randomNumber-1].Artist)
// verify spotify result and query next album if empty/not available
if (result != null && result.albums != null && result.albums.items != null && result.albums.items.length == 1) {
let item = result.albums.items[0]
coverUrl = item.images[0].url
uri = item.uri
externalUrl = item.external_urls.spotify
}
} while(coverUrl.length == 0)
if(openWith != null && openWith === "sonos") {
widget.url = sonosUrl + "/spotify/now/" + uri
} else {
widget.url = externalUrl
}
await loadImage(coverUrl)
}
// gets a spotify search token
async function getSpotifySearchToken() {
let url = "https://accounts.spotify.com/api/token"
let req = new Request(url)
req.method = "POST"
req.body = "grant_type=client_credentials"
let authHeader = "Basic " + btoa(clientId+":"+clientSecret)
req.headers = {"Authorization": authHeader, "Content-Type":"application/x-www-form-urlencoded"}
let token = await req.loadJSON()
return token.access_token
}
// random number, min and max included
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}
// search for the album at Spotify
async function searchAlbumAtSpotify(album, artist) {
let searchString = encodeURIComponent("album:" + album +" artist:" + artist)
let searchUrl = "https://api.spotify.com/v1/search?q=" + searchString + "&type=album&market=" + spotifyCountry + "&limit=1"
req = new Request(searchUrl)
req.headers = {"Authorization": "Bearer " + searchToken, "Content-Type":"application/json", "Accept":"application/json"}
let result = await req.loadJSON()
return result
}
// download and display the cover
async function loadImage(imageUrl) {
let req = new Request(imageUrl)
let image = await req.loadImage()
widget.backgroundImage = image
}
@marco79cgn
Copy link
Author

I’ve worked on this from the start on my phone, but I put the line in and it’s now giving me another error.
2021-01-17 16:54:12: Error on line 29: SyntaxError: Unexpected string literal "top_500_albums.json". Expected ')' to end an argument list.

Something seems to be broken in your script. Either a copy/paste error or an edit by accident. The log claims that there is no closing perenthesis in line 29
let path = fm.joinPath(dir, "top_500_albums.json")

I would recommend to start from scratch and copy it again.

@ShadeSlayer45
Copy link

Will do, do you think I should redownload the top 500 json as well as redoing the Spotify stuff?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment