Skip to content

Instantly share code, notes, and snippets.

@5minpause
Created February 3, 2021 09:25
Show Gist options
  • Save 5minpause/26f5c44ef58d006016cedb48c5759fdd to your computer and use it in GitHub Desktop.
Save 5minpause/26f5c44ef58d006016cedb48c5759fdd to your computer and use it in GitHub Desktop.
This is the code for a YouTube playlist script for Scriptable.app
let playlistID, startDay, API_KEY
if (args.widgetParameter) {
[playlistID, startDay, API_KEY] = args.widgetParameter.split(",")
}
const url = `https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&maxResults=30&playlistId=${playlistID}&key=${API_KEY}`
const getCurrentDay = () => {
const today = new Date()
const startDate = new Date(startDay)
const differenceInTime = today.getTime() - startDate.getTime()
return parseInt(differenceInTime / (1000 * 3600 * 24), 10)
}
const getTodaysVideo = async () => {
if (!playlistID || !startDay || !API_KEY) {
return new Promise((resolve) => resolve(["Bitte das Widget mit Playlist-ID, Startdatum und API_KEY konfigurieren", null, null]))
}
const request = new Request(url)
request.headers = {"Accept": "application/json"}
const response = await request.loadJSON()
const allVideos = response.items
const todaysVideo = allVideos[getCurrentDay()]
let title, image, videoId
if (todaysVideo) {
videoId = todaysVideo.snippet.resourceId.videoId
const thumbnailUrl = todaysVideo.snippet.thumbnails.high.url
const imageRequest = new Request(thumbnailUrl)
const thumbnailData = await imageRequest.load()
image = Image.fromData(thumbnailData)
} else {
title = "Playlist ohne heutiges Video.\nIst die Playlist beendet?\n😱"
}
return [title, image, videoId]
}
async function createWidget(title, image, videoId) {
const widget = new ListWidget()
widget.backgroundColor = new Color("#eeeee4")
if (image) {
const widgetImage = widget.addImage(image)
widgetImage.applyFillingContentMode()
let gradient = new LinearGradient()
gradient.locations = [0, 1]
gradient.colors = [
new Color("#eeeee4"),
new Color("#eab676")
]
widget.backgroundGradient = gradient
// Add spacer above content to center it vertically.
widget.addSpacer()
}
if (videoId) {
widget.url = `https://m.youtube.com/watch?v=${videoId}`
}
if (title) {
const widgetText = widget.addText(title)
widgetText.textColor = new Color("#000000")
}
return widget
}
const [title, image, videoId] = await getTodaysVideo()
let widget = await createWidget(title, image, videoId)
Script.setWidget(widget)
Script.complete()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment