Skip to content

Instantly share code, notes, and snippets.

@fobin
Last active June 25, 2023 16:08
Show Gist options
  • Save fobin/879dd66ec78f151b63792061deb2637d to your computer and use it in GitHub Desktop.
Save fobin/879dd66ec78f151b63792061deb2637d to your computer and use it in GitHub Desktop.
Get latest news from hs.fi
// To run this on your iOS device,
// check that you are running iOS 14
// and get Scriptable app from App
// Store.
// https://apps.apple.com/us/app/scriptable/id1405459188
// The script shows the latest article
// from Helsingin Sanomat in a widget on
// Home screen. Go to your Home screen
// to set up the script in a widget.
// The script will present a preview
// of the widget when running in the
// app.
let items = await loadItems()
let widget = await createWidget(items)
// Check if the script is running in
// a widget. If not, show a preview of
// the widget to easier debug it.
if (!config.runsInWidget) {
await widget.presentMedium()
}
// Tell the system to show the widget.
Script.setWidget(widget)
Script.complete()
async function createWidget(items) {
let item = items[0]
let w = new ListWidget()
w.backgroundColor = new Color("#000000")
let hs = w.addText("HS")
hs.font = Font.boldSystemFont(16)
w.addSpacer()
let titleTxt = w.addText(item.title)
titleTxt.font = Font.boldSystemFont(12)
titleTxt.textColor = Color.white()
let rawDate = item.pubDate
let dateFormatter = new DateFormatter()
let date = new Date(Date.parse(rawDate))
let strDate = dateFormatter.string(date)
let dates = w.addDate(date)
dates.applyTimeStyle()
dates.font = Font.footnote()
return w
}
async function loadItems() {
let url = "http://www.hs.fi/rss/tuoreimmat.xml"
let req = new Request(url)
let str = await req.loadString()
let items = []
let currentItem = null
let elementName = ""
let titlefound = 0
const xmlParser = new XMLParser(str)
xmlParser.didStartElement = name => {
currentValue = ""
if (name == 'title') {
if (titlefound > 0) {
currentItem = {}
}
titlefound++
}
}
xmlParser.didEndElement = name => {
const hasItem = currentItem != null
if (hasItem && name == 'title') {
currentItem['title'] = currentValue
}
if (hasItem && name == 'pubDate') {
currentItem['pubDate'] = currentValue
}
if (hasItem && name == 'pubDate') {
items.push(currentItem)
currentItem = null
}
}
xmlParser.foundCharacters = str => {
currentValue += str
}
xmlParser.didEndDocument = name => {
}
xmlParser.parse()
return items
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment