Last active
January 4, 2024 09:58
-
-
Save 0xN1/2af1b442a371fa5d7aeb8145e2e26b69 to your computer and use it in GitHub Desktop.
cc0-lib scriptable iOS widget
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Variables used by Scriptable. | |
// These must be at the very top of the file. Do not edit. | |
// icon-color: deep-blue; icon-glyph: magic; | |
const refreshInterval = 5; | |
let data; | |
const widget = await createWidget(); | |
if (widget) { | |
if (!config.runsInWidget) { | |
await widget.presentLarge(); | |
} | |
Script.setWidget(widget); | |
Script.complete(); | |
} | |
async function createWidget() { | |
const widget = new ListWidget(); | |
const img = await getRandomImage(); | |
widget.backgroundImage = img; | |
widget.applyFittingContentMode = true; | |
// if (data) console.log(data); | |
if (!img) return null; | |
const { Title } = data.data; | |
const url = `https://cc0-lib.wtf/${slugify(Title)}`; | |
widget.url = url; | |
const interval = 1000 * 60 * refreshInterval; | |
widget.refreshAfterDate = new Date(Date.now() + interval); | |
return widget; | |
} | |
async function getRandomImage() { | |
try { | |
const url = "https://cc0-lib.wtf/api/random"; | |
const req = new Request(url); | |
const res = await req.loadJSON(); | |
data = res; | |
const imgUrl = res.image.url; | |
if (imgUrl.includes("svg")) { | |
return null; | |
} | |
if (res && imgUrl) { | |
return loadImage(imgUrl); | |
} else { | |
console.log("error"); | |
return null; | |
} | |
} catch (err) { | |
console.log(err); | |
return null; | |
} | |
} | |
async function loadImage(imageUrl) { | |
try { | |
const req = new Request(imageUrl); | |
const img = await req.loadImage(); | |
return img; | |
} catch (err) { | |
console.log(err); | |
return null; | |
} | |
} | |
function slugify(text) { | |
return text | |
.toString() | |
.toLowerCase() | |
.replace(/[^a-z0-9]+/g, "-") | |
.replace(/(^-|-$)+/g, ""); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment