Skip to content

Instantly share code, notes, and snippets.

@marco79cgn
Last active December 4, 2021 07:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marco79cgn/42052277bb7b02ca80cb2484ab46fb9e to your computer and use it in GitHub Desktop.
Save marco79cgn/42052277bb7b02ca80cb2484ab46fb9e to your computer and use it in GitHub Desktop.
A scriptable widget that shows a random episode of "Die drei ???" and opens it in Spotify or Sonos
// insert your Spotify client id and secret here
let clientId = "xxx"
let clientSecret = "xxx"
// 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/Arbeitszimmer"
let openWith = args.widgetParameter
let widget = new ListWidget()
// widget.setPadding(0,0,0,0)
widget.backgroundColor = new Color("#000000")
let searchToken = await getSpotifySearchToken()
await getRandomEpisode()
widget.presentSmall()
Script.setWidget(widget)
Script.complete()
// query spotify api
async function getRandomEpisode() {
let uri = ""
let externalUrl = ""
let coverUrl = ""
if(searchToken != null) {
do {
let randomEpisodeNumber = getRandomEpisodeNumber(1,207)
let result = await searchAlbumAtSpotify(randomEpisodeNumber, "Die drei ???")
// console.log(result)
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)
}
}
// random number, min and max included
function getRandomEpisodeNumber(min, max) {
let randomNumber = Math.floor(Math.random() * (max - min + 1) + min)
return add_zero(randomNumber, 3)
}
// add leading zeros to a number
function add_zero(number, length) {
var num = '' + number;
while (num.length < length) {
num = '0' + num;
}
return num;
}
// helper function to download an image
async function loadImage(imageUrl) {
let req = new Request(imageUrl)
let image = await req.loadImage()
// widget.backgroundImage = image
let widgetImage = widget.addImage(image)
widgetImage.imageSize = new Size(150,150)
widgetImage.centerAlignImage()
widgetImage.cornerRadius = 16
}
// 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
}
// 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=DE&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
}
@marco79cgn
Copy link
Author

marco79cgn commented Aug 23, 2020

Intro

iOS 14 Custom Widget made with the help of the Scriptable app.
It shuffles a random episode of the audiobook „Die drei ???“ and shows the cover art.
Upon tapping on the widget it opens the album either in Spotify or plays it on your Sonos system.

Requirements

  • iOS 14 Developer Beta 5 (or above)
  • Scriptable TestFlight version 1.5 (152)
    Join the beta here
  • Spotify Web Developer API
    Please create a client to get your client id and client_secret credentials. They are needed for the search.
    Insert them at the top of the script.
  • Optional:
    The node-sonos-http-api in order to play the episode on your Sonos system.
    Insert your ip address in the script and set the run script command to 'sonos' in the widget settings

Thanks

A big Thank you to @simonbs for making great apps like Scriptable, DataJar or Jayson.

@veraverto
Copy link

Tolle Idee für ein Widget! Scriptable lässt es wahrscheinlich nicht zu, durch weitere zufällig Alben zu wechseln und dieses dann durch Antippen abzuspielen, oder wäre das möglich?

@3xXxTr3mE
Copy link

Mega! Das habe ich gesucht - bin aber leider Apple Music Kunde und kann das Widget
So nicht nutzen -> wird es da eine Option geben? :)

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