Skip to content

Instantly share code, notes, and snippets.

@rsalzer
Last active January 9, 2023 10:06
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rsalzer/598e9c59e3911fe02871e2be515e589b to your computer and use it in GitHub Desktop.
Save rsalzer/598e9c59e3911fe02871e2be515e589b to your computer and use it in GitHub Desktop.
Scriptable to show a random painting from the Metropolitan Museum of Art
//Fetches Random Images from the metmuseum-api ; Stores the ids in the keychain in order to prevent multiple calls
//Department ID = 11 is paintings ; use other if you wish
var keychainkey = "paintingIDs"
var res
if(!Keychain.contains(keychainkey)) {
console.log("Keychainentry does not exist... create it");
const url = 'https://collectionapi.metmuseum.org/public/collection/v1/search?hasImages=true&medium=Paintings&departmentId=11&q=Painting'
const req = new Request(url)
res = await req.loadJSON()
let stringified = JSON.stringify(res)
Keychain.set(keychainkey, stringified)
}
else {
console.log("Using keychainentry now")
var idsFromKeychain = Keychain.get(keychainkey)
// console.log(idsFromKeychain)
res = JSON.parse(idsFromKeychain)
// console.log(res)
}
const max = res.total-1
console.log("Max: "+max);
const min = 0
const random = Math.floor(Math.random() * (max - min + 1)) + min
console.log("Random: "+random);
const picked = res.objectIDs[random]
console.log("Picked: "+picked);
const req2 = new Request('https://collectionapi.metmuseum.org/public/collection/v1/objects/'+picked)
// const req2 = new Request("https://collectionapi.metmuseum.org/public/collection/v1/objects/436978")
const res2 = await req2.loadJSON()
const i = new Request(res2.primaryImageSmall);
const img = await i.loadImage();
let widget = createWidget(img, res2.objectURL)
if (config.runsInWidget) {
// create and show widget
Script.setWidget(widget)
Script.complete()
}
else {
widget.presentLarge()
}
function createWidget(img, widgeturl) {
let w = new ListWidget()
w.backgroundImage = img
w.url = widgeturl
return w
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment