Skip to content

Instantly share code, notes, and snippets.

@BryantD
Created December 12, 2020 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BryantD/9e6714e733e2b60542cee17543a758b1 to your computer and use it in GitHub Desktop.
Save BryantD/9e6714e733e2b60542cee17543a758b1 to your computer and use it in GitHub Desktop.
Scriptable: Get Random Unsplash Image
// Keywords to limit the Unsplash search; format is {keyword},{keyword}
// See https://source.unsplash.com
const keywords = 'nature'
// Refresh interval in hours
const refreshInterval = 6
// URL prototype to use for loading the image
const imgUrlPrototype = (keywords) => `https://source.unsplash.com/random/featured/?${keywords}`
const widget = await createWidget()
if (!config.runsInWidget)
{
await widget.presentMedium()
}
Script.setWidget(widget)
Script.complete()
/*
* Returns an instance of ListWidget that contains the contents of this widget.
* The widget returned consists of a background image, a greyscaled gradient and
* the image title in the slightly darker part of the grandient in the lower
* left corner of the widget.
*/
async function createWidget(items)
{
let widget = new ListWidget()
let selection = await getRandomPic()
widget.backgroundImage = selection.image
widget.addSpacer()
let startColor = new Color("#1c1c1c00")
let endColor = new Color("#1c1c1cb4")
let gradient = new LinearGradient()
gradient.colors = [startColor, endColor]
gradient.locations = [0.25, 1]
widget.backgroundGradient = gradient
widget.backgroundColor = new Color("1c1c1c")
let interval = 1000 * 60 * 60 * refreshInterval
widget.refreshAfterDate = new Date(Date.now() + interval)
return widget
}
/*
* Get a random image. Images inside of the JSON file are addressed in the
* following way:
*
* server: 7372
* id: 12502775644
* secret: acfd415fa7
*/
async function getRandomPic()
{
try
{
let imgUrl = buildImgUrl(keywords)
console.log(`Loading img ${imgUrl}`)
let imgRequest = new Request(imgUrl)
let img = await imgRequest.loadImage()
return {image: img}
}
catch (e)
{
console.error(e)
return null
}
}
/*
* Gets the complete image URL by inserting values into the placeholders of
* the defined image URL prototype.
*/
function buildImgUrl(keywords)
{
return imgUrlPrototype(keywords)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment