# @name LautFM Data # @desc Zentrale laut.fm-Abfrage für Song und Hörerzahl # @headless true # @config station text "laut.fm Sender" default="HIER_DEINEN_SENDER_EINTRAGEN" maxlen=64 # @config every number "Aktualisierung" default=60 min=30 max=3600 unit=s import json class LautFmData var station var url_song var url_listeners var period var ticks var in_flight var song var listeners def init() self.station = store.get("station") self.period = store.get("every") self.url_song = "https://api.laut.fm/station/" + self.station + "/current_song" self.url_listeners = "https://api.laut.fm/station/" + self.station + "/listeners" self.ticks = 10 self.in_flight = false self.song = "" self.listeners = nil end def setup() self.fetch_song() end # ================================================ # Aktuellen Song holen # ================================================ def fetch_song() if self.in_flight return end self.in_flight = true http.get( self.url_song, /body, status -> self.on_song(body, status) ) end def on_song(body, status) if body == nil || status < 200 || status >= 300 self.in_flight = false self.ticks = 10 return end var data = json.load(body) if data == nil self.in_flight = false self.ticks = 10 return end var title = data.find("title", "") var artist = "" var artist_data = data.find("artist", nil) if artist_data != nil artist = artist_data.find("name", "") end if artist != "" && title != "" self.song = str(artist) + " - " + str(title) elif title != "" self.song = str(title) elif artist != "" self.song = str(artist) else self.song = "Kein Titel" end # Danach Hörerzahl abfragen http.get( self.url_listeners, /listener_body, listener_status -> self.on_listeners(listener_body, listener_status) ) end # ================================================ # Hörerzahl holen # ================================================ def on_listeners(body, status) self.in_flight = false if body != nil && status >= 200 && status < 300 # Die listeners-Antwort ist eine Zahl/Text, # kein JSON-Objekt. var value = num(body) if value != nil self.listeners = value end end # ============================================ # Ergebnisse veröffentlichen # ============================================ shared.set("song", self.song) if self.listeners != nil shared.set("listeners", self.listeners) end shared.set("ok", true) # Nächste Aktualisierung self.ticks = self.period end # ================================================ # Polling # ================================================ def loop() if self.ticks <= 0 if !self.in_flight self.fetch_song() end else self.ticks -= 1 end end end return LautFmData()