Skip to content

Instantly share code, notes, and snippets.

@andreasRedeker
Last active October 20, 2026 07:40
Show Gist options
  • Select an option

  • Save andreasRedeker/7fa4f1ea16c4ab66b238bfb9e971e96c to your computer and use it in GitHub Desktop.

Select an option

Save andreasRedeker/7fa4f1ea16c4ab66b238bfb9e971e96c to your computer and use it in GitHub Desktop.
A Scriptable widget, that shows you the cheapest gas station near you (for germany only)
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: deep-blue; icon-glyph: gas-pump;
// share-sheet-inputs: plain-text;
// Script by Andreas Redeker <hello@andreasredeker.de>
//
// Benzinpreis-Widget für Scriptable · Daten: Tankerkönig / MTS-K
//
// Setup: Script einmal in der Scriptable-App starten und den Tankerkönig-API-Key
// eingeben (kostenlos: https://creativecommons.tankerkoenig.de/). Er landet in der
// Keychain, nicht im Quelltext. Beim Start in der App kannst du jede Widget-Größe
// als Vorschau auswählen.
//
// Widget-Parameter (optional): Sorte und/oder Radius, z. B. "e10", "diesel;5" oder "5"
// Sorten: e5, e10, diesel · Radius: 1–25 km (Standard 10)
// "umkreis" im Parameter ignoriert die Lieblingstankstellen für dieses Widget.
//
// Lieblingstankstellen (optional): Script in der App starten → "Lieblingstankstellen…"
// und bis zu 10 Tankstellen abhaken. Dann zeigt das Widget nur noch diese, egal wie
// weit sie per Luftlinie entfernt sind. Ohne Auswahl gilt die Umkreissuche.
//
// Größen: klein, mittel, groß, extragroß (iPad) und alle drei Sperrbildschirm-Widgets.
//
// 12-Uhr-Regel: Seit 1. April 2026 dürfen Tankstellen Preise nur um 12:00 erhöhen,
// senken jederzeit. Das Widget zeigt, wie viel ein Preis seit 12 Uhr gefallen ist,
// setzt kurz vor 12 Uhr ein dezentes Symbol, aktualisiert sich kurz danach und
// markiert Tankstellen, die nach 12 Uhr trotzdem erhöht haben.
// ---------- Konfiguration ----------
const KEYCHAIN_KEY = "tankerkoenig-api-key";
const DEFAULT_FUEL = "e5";
const DEFAULT_RADIUS = 10;
const USE_GOOGLE_MAPS = false;
// Fester Standort statt GPS, z. B. { latitude: 52.516, longitude: 13.376 }
const FIXED_LOCATION = null;
// Frühester Refresh in Minuten (iOS entscheidet am Ende selbst)
const REFRESH_OK_MIN = 15;
const REFRESH_RETRY_MIN = 5;
// Wie lange zwischengespeicherte Preise bei Fehlern noch angezeigt werden
const MAX_CACHE_AGE_H = 12;
// Mindestabstand zwischen API-Anfragen. Mehrere Widgets teilen sich die Daten, statt
// gleichzeitig anzufragen (Tankerkönig erlaubt automatische Abfragen max. alle 5 Minuten).
const MIN_FETCH_INTERVAL_MIN = 5;
// Wie lange eine Preisänderung als Trend angezeigt wird (ohne 12-Uhr-Regel)
const TREND_WINDOW_H = 24;
// Lieblingstankstellen: Umkreissuche nutzen, wenn alle Favoriten geschlossen sind
const FAVORITES_FALLBACK = true;
const FAVORITES_MAX = 10; // Grenze der Tankerkönig-API (prices.php)
const FAVORITES_PICK_RADIUS = 15; // Umkreis für die Auswahlliste in der App
// 12-Uhr-Regel – auf false setzen, falls sie abgeschafft wird
const NOON_RULE = true;
const NOON_HOUR = 12;
const NOON_GRACE_MIN = 30; // Meldeverzögerungen rund um 12:00 tolerieren
const NOON_WARN_H = 2; // so lange vorher auf die nächste Erhöhungsrunde hinweisen
const NOON_REFRESH_DELAY_MIN = 5; // Refresh kurz nach 12:00 anstoßen
// ---------- Design ----------
const dyn = (light, dark, alpha = 1) =>
Color.dynamic(new Color(light, alpha), new Color(dark, alpha));
const FUEL = {
e5: { name: "Super E5", short: "E5", light: "#0066d6", dark: "#409cff" },
e10: { name: "Super E10", short: "E10", light: "#248a3d", dark: "#30d158" },
diesel: { name: "Diesel", short: "DIESEL", light: "#b25000", dark: "#ffb340" },
};
const THEME = {
bg: dyn("#ffffff", "#1c1c1e"),
card: dyn("#f2f2f7", "#2c2c2e"),
text: dyn("#1c1c1e", "#f5f5f7"),
muted: dyn("#6e6e73", "#98989d"),
up: dyn("#d70015", "#ff6961"),
down: dyn("#248a3d", "#30d158"),
warn: dyn("#c93400", "#ff9f0a"),
};
const accent = (fuel) => dyn(FUEL[fuel].light, FUEL[fuel].dark);
const accentSoft = (fuel) => dyn(FUEL[fuel].light, FUEL[fuel].dark, 0.15);
const SUPERSCRIPT = "⁰¹²³⁴⁵⁶⁷⁸⁹";
const FAMILIES = {
small: { label: "Klein", render: renderSmall, present: (w) => w.presentSmall() },
medium: { label: "Mittel", render: renderMedium, present: (w) => w.presentMedium() },
large: { label: "Groß", render: renderLarge, present: (w) => w.presentLarge() },
extraLarge: { label: "Extragroß (iPad)", render: renderExtraLarge, present: (w) => w.presentExtraLarge() },
accessoryRectangular: { label: "Sperrbildschirm: Rechteck", render: renderRectangular, present: (w) => w.presentAccessoryRectangular() },
accessoryCircular: { label: "Sperrbildschirm: Rund", render: renderCircular, present: (w) => w.presentAccessoryCircular() },
accessoryInline: { label: "Sperrbildschirm: Zeile", render: renderInline, present: (w) => w.presentAccessoryInline() },
};
const fm = FileManager.local();
const CACHE_PATH = fm.joinPath(fm.libraryDirectory(), "benzinpreis-widget-cache.json");
const FAVORITES_PATH = fm.joinPath(fm.libraryDirectory(), "benzinpreis-widget-favoriten.json");
// ---------- Main ----------
await main();
async function main() {
const params = parseParams(args.widgetParameter);
const family =
config.widgetFamily ?? (config.runsInApp ? await appMenu(params) : "small");
if (!family) {
Script.complete();
return;
}
const data = await loadData(params);
// In der App den Grund zeigen, wenn nur zwischengespeicherte Daten verfügbar sind
if (!config.runsInWidget && data.stale) {
await showMessage("Zeige zwischengespeicherte Daten", data.error);
}
const widget = buildWidget(family, data, params);
if (config.runsInWidget) {
Script.setWidget(widget);
} else {
await (FAMILIES[family] ?? FAMILIES.small).present(widget);
}
Script.complete();
}
// Menü beim Start in der App: Favoriten bearbeiten oder eine Widget-Größe ansehen
async function appMenu(params) {
const keys = Object.keys(FAMILIES).filter((k) => k !== "extraLarge" || Device.isPad());
while (true) {
const favorites = readFavorites();
const alert = new Alert();
alert.title = "Benzinpreis-Widget";
alert.message = favorites.length
? `${favorites.length} Lieblingstankstelle${favorites.length === 1 ? "" : "n"} ausgewählt`
: `Keine Lieblingstankstellen – Umkreissuche (${formatNumber(params.radius)} km)`;
alert.addAction("Lieblingstankstellen…");
keys.forEach((k) => alert.addAction(`Vorschau: ${FAMILIES[k].label}`));
alert.addCancelAction("Fertig");
const index = await alert.presentSheet();
if (index === -1) return null;
if (index === 0) {
await editFavorites(params);
continue;
}
return keys[index - 1];
}
}
function buildWidget(family, data, params) {
const spec = FAMILIES[family] ?? FAMILIES.small;
const isAccessory = family.startsWith("accessory");
const widget = new ListWidget();
if (!isAccessory) widget.backgroundColor = THEME.bg;
widget.refreshAfterDate = nextRefresh(data);
if (data.stations) spec.render(widget, data, params);
else if (isAccessory) renderAccessoryError(widget, family, data.error);
else renderError(widget, data.error, params);
return widget;
}
function nextRefresh(data) {
const retrySoon = !data.stations || data.stale;
let at = Date.now() + (retrySoon ? REFRESH_RETRY_MIN : REFRESH_OK_MIN) * 60000;
// Direkt nach der 12-Uhr-Erhöhungsrunde neu laden, nicht erst irgendwann danach
if (NOON_RULE) {
const afterNoon = noonWindow().end.getTime() + NOON_REFRESH_DELAY_MIN * 60000;
at = Math.min(at, afterNoon);
}
return new Date(at);
}
// ---------- Daten ----------
function parseParams(input) {
const params = { fuel: DEFAULT_FUEL, radius: DEFAULT_RADIUS, ignoreFavorites: false };
if (!input) return params;
for (const part of input.toLowerCase().split(/[;,\s]+/)) {
if (part === "umkreis") {
params.ignoreFavorites = true;
} else if (Object.keys(FUEL).includes(part)) {
params.fuel = part;
} else if (/^\d+([.,]\d+)?$/.test(part)) {
const radius = parseFloat(part.replace(",", "."));
params.radius = Math.min(25, Math.max(1, radius));
}
}
return params;
}
// Lädt frische Daten, pflegt Cache, Trend und 12-Uhr-Tracking und fällt bei Fehlern auf den Cache zurück.
async function loadData(params) {
const useFavorites = !params.ignoreFavorites && readFavorites().length > 0;
const cacheKey = useFavorites ? `${params.fuel}-fav` : `${params.fuel}-${params.radius}`;
const cache = readCache();
const cached = cache[cacheKey];
// Frische Daten eines anderen Widgets (oder des letzten Laufs) wiederverwenden
if (cached && config.runsInWidget) {
const fetchedAt = new Date(cached.fetchedAt);
const ageMin = (Date.now() - fetchedAt.getTime()) / 60000;
const sameWindow = !NOON_RULE || fetchedAt >= noonWindow().start;
if (ageMin >= 0 && ageMin < MIN_FETCH_INTERVAL_MIN && sameWindow) {
return {
stations: cached.stations,
fetchedAt,
source: cached.source ?? "radius",
trend: visibleTrend(cached.trend),
noon: cached.noon ?? null,
stale: false,
};
}
}
const fresh = await fetchStations(params);
if (fresh.stations) {
const trend = updateTrend(cached?.trend, fresh.stations[0]);
const noon = NOON_RULE ? trackNoon(cached?.noon, fresh.stations) : null;
cache[cacheKey] = {
stations: fresh.stations,
fetchedAt: fresh.fetchedAt.toISOString(),
source: fresh.source,
trend,
noon,
};
writeCache(cache);
return { ...fresh, trend: visibleTrend(trend), noon, stale: false };
}
if (fresh.fatal || !cached) return { error: fresh.error };
const fetchedAt = new Date(cached.fetchedAt);
if (Date.now() - fetchedAt.getTime() > MAX_CACHE_AGE_H * 3600000) return { error: fresh.error };
console.warn(`Zeige zwischengespeicherte Daten: ${fresh.error}`);
return {
stations: cached.stations,
fetchedAt,
source: cached.source ?? "radius",
trend: visibleTrend(cached.trend),
noon: cached.noon ?? null,
stale: true,
error: fresh.error,
};
}
async function fetchStations(params) {
const favorites = params.ignoreFavorites ? [] : readFavorites();
if (favorites.length) {
const result = await fetchFavorites(favorites, params);
if (!result.noneOpen || !FAVORITES_FALLBACK) return result;
}
return fetchRadius(params);
}
// Umkreissuche um den aktuellen Standort
async function fetchRadius({ fuel, radius }) {
const location = await getLocation();
if (!location) return { error: "Standort nicht verfügbar" };
const res = await callApi("list.php", {
lat: location.latitude.toFixed(3),
lng: location.longitude.toFixed(3),
rad: radius,
type: fuel,
sort: "price",
});
if (!res.data) return res;
const stations = res.data.stations
.filter((s) => s.isOpen && s.price != null)
.map(toStation)
.sort(byPrice);
if (!stations.length) {
return { fatal: true, error: `Keine offene Tankstelle im Umkreis von ${formatNumber(radius)} km` };
}
return { stations, fetchedAt: new Date(), source: "radius" };
}
// Preise der Lieblingstankstellen in einer Anfrage (prices.php, max. 10 IDs)
async function fetchFavorites(favorites, { fuel }) {
const res = await callApi("prices.php", { ids: favorites.map((f) => f.id).join(",") });
if (!res.data) return res;
const location = await getLocation(); // nur für die Entfernung, optional
const stations = favorites
.map((fav) => ({ fav, info: res.data.prices?.[fav.id] }))
.filter(({ info }) => info?.status === "open" && typeof info[fuel] === "number")
.map(({ fav, info }) => ({
id: fav.id,
name: fav.name,
place: fav.place,
lat: fav.lat,
lng: fav.lng,
price: info[fuel],
dist: location ? distanceKm(location, fav) : null,
}))
.sort(byPrice);
if (!stations.length) {
return { fatal: true, noneOpen: true, error: "Keine Lieblingstankstelle geöffnet" };
}
return { stations, fetchedAt: new Date(), source: "favorites" };
}
// Gemeinsamer API-Aufruf inkl. Key-Handling und Fehlerbehandlung
async function callApi(endpoint, query) {
const apiKey = await getApiKey();
if (!apiKey) {
return {
fatal: true,
error: config.runsInWidget
? "API-Key fehlt – Script einmal in Scriptable starten"
: "Kein gültiger API-Key eingegeben",
};
}
const qs = Object.entries({ ...query, apikey: apiKey })
.map(([k, v]) => `${k}=${encodeURIComponent(v)}`)
.join("&");
// Als Text laden und selbst parsen: so sehen wir, was der Server bei Fehlern wirklich schickt
const request = new Request(`https://creativecommons.tankerkoenig.de/json/${endpoint}?${qs}`);
request.timeoutInterval = 20;
let body;
try {
body = await request.loadString();
} catch (e) {
console.error(`${endpoint}: ${e}`);
return { error: "Keine Verbindung" };
}
const status = request.response?.statusCode;
let data;
try {
data = JSON.parse(body);
} catch (e) {
const snippet = String(body ?? "").replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim().slice(0, 200);
console.error(`${endpoint}: HTTP ${status}, keine JSON-Antwort: ${snippet || "(leer)"}`);
let error = `Tankerkönig-Fehler (HTTP ${status ?? "?"})`;
if (status === 429) error = "Zu viele Anfragen – kurz warten";
else if (status >= 500) error = `Tankerkönig gestört (HTTP ${status})`;
// In der App den Antworttext mit anzeigen, das hilft bei der Fehlersuche
if (!config.runsInWidget && snippet) error += `: ${snippet.slice(0, 120)}`;
return { error };
}
if (!data.ok) {
console.error(data.message);
const badKey = /apikey/i.test(data.message ?? "");
// Ungültigen Key beim Start in der App verwerfen, damit er neu abgefragt wird
if (badKey && !config.runsInWidget) {
Keychain.remove(KEYCHAIN_KEY);
return { fatal: true, error: "API-Key ungültig und gelöscht – Script erneut starten" };
}
return { fatal: badKey, error: badKey ? "API-Key ungültig" : data.message || "API-Fehler" };
}
return { data };
}
async function getApiKey() {
if (Keychain.contains(KEYCHAIN_KEY)) return Keychain.get(KEYCHAIN_KEY);
if (config.runsInWidget) return null; // Widgets können keine Alerts zeigen
const alert = new Alert();
alert.title = "Tankerkönig API-Key";
alert.message =
"Kostenlos erhältlich unter creativecommons.tankerkoenig.de. Der Key wird in der Keychain gespeichert.";
alert.addTextField("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
alert.addAction("Speichern");
alert.addCancelAction("Abbrechen");
if ((await alert.present()) === -1) return null;
const key = alert.textFieldValue(0).trim();
if (!/^[0-9a-f-]{36}$/i.test(key)) return null;
Keychain.set(KEYCHAIN_KEY, key);
return key;
}
async function getLocation() {
if (FIXED_LOCATION) return FIXED_LOCATION;
try {
Location.setAccuracyToKilometer();
return await Location.current();
} catch (e) {
console.error(e);
return null;
}
}
function toStation(s) {
return {
id: s.id,
name: tidy(s.brand, true) || tidy(s.name) || "Tankstelle",
place: tidy(s.place),
price: s.price,
dist: s.dist,
lat: s.lat,
lng: s.lng,
};
}
// Trend nur für dieselbe Tankstelle, sonst vergleicht man beim Herumfahren Äpfel mit Birnen.
function updateTrend(previous, top) {
if (!previous || previous.stationId !== top.id) {
return { stationId: top.id, price: top.price, prevPrice: null, changedAt: null };
}
if (previous.price === top.price) return previous;
return {
stationId: top.id,
price: top.price,
prevPrice: previous.price,
changedAt: new Date().toISOString(),
};
}
function visibleTrend(trend) {
if (!trend || trend.prevPrice == null || !trend.changedAt) return null;
const changedAt = new Date(trend.changedAt);
if (Date.now() - changedAt.getTime() > TREND_WINDOW_H * 3600000) return null;
return { ...trend, changedAt };
}
// ---------- 12-Uhr-Regel ----------
// Preisfenster von 12:00 bis zum nächsten Tag 12:00 (Gerätezeit, DST-sicher über setDate).
function noonWindow(now = new Date()) {
const todayNoon = new Date(now);
todayNoon.setHours(NOON_HOUR, 0, 0, 0);
const start = new Date(todayNoon);
if (now < todayNoon) start.setDate(start.getDate() - 1);
const end = new Date(start);
end.setDate(end.getDate() + 1);
return { start, end, key: start.toDateString() };
}
// Merkt sich je Tankstelle den ersten Preis im aktuellen Fenster (Referenz) und den
// niedrigsten seitdem. Steigt ein Preis über dieses Minimum, war das eine Erhöhung nach 12 Uhr.
function trackNoon(previous, stations, now = new Date()) {
const win = noonWindow(now);
const state = previous?.key === win.key ? previous : { key: win.key, stations: {} };
const inGrace = now - win.start < NOON_GRACE_MIN * 60000;
for (const s of stations) {
const rec = state.stations[s.id];
if (!rec || inGrace) {
state.stations[s.id] = { ref: s.price, min: s.price, at: now.toISOString(), raisedAt: null };
continue;
}
if (s.price > rec.min && !rec.raisedAt) rec.raisedAt = now.toISOString();
rec.min = Math.min(rec.min, s.price);
}
return state;
}
function noonInfo(data, station) {
const state = data.noon;
const win = noonWindow();
if (!NOON_RULE || !state || state.key !== win.key) return null;
const rec = state.stations?.[station.id];
if (!rec) return null;
const since = new Date(rec.at);
return {
diffCt: (toMilli(station.price) - toMilli(rec.ref)) / 10,
since,
sinceNoon: since - win.start < (NOON_GRACE_MIN + 15) * 60000,
raised: !!rec.raisedAt,
};
}
// Preisänderung für die Anzeige: mit 12-Uhr-Regel seit Fensterbeginn, sonst letzte Änderung.
function priceChange(data, station) {
const noon = noonInfo(data, station);
const trend = data.trend && data.trend.stationId === station.id ? data.trend : null;
const trendChange = trend
? { diffCt: (toMilli(trend.price) - toMilli(trend.prevPrice)) / 10, since: trend.changedAt }
: null;
if (noon) {
if (noon.diffCt !== 0) return noon;
// Unverändert seit 12 Uhr: dann die Erhöhung von heute Mittag zeigen, falls bekannt
return trendChange && trendChange.since >= noonWindow().start ? trendChange : null;
}
return NOON_RULE && data.noon ? null : trendChange;
}
// Kurz vor 12:00 dezent auf die nächste Erhöhungsrunde hinweisen.
function noonPhase(now = new Date()) {
if (!NOON_RULE) return null;
const hoursLeft = (noonWindow(now).end - now) / 3600000;
return { warn: hoursLeft <= NOON_WARN_H };
}
// Daten von vor 12 Uhr können die Mittagserhöhung noch nicht enthalten.
function isOutdated(data) {
return data.stale || (NOON_RULE && data.fetchedAt < noonWindow().start);
}
// ---------- Lieblingstankstellen ----------
function readFavorites() {
try {
if (!fm.fileExists(FAVORITES_PATH)) return [];
const list = JSON.parse(fm.readString(FAVORITES_PATH));
return Array.isArray(list) ? list.slice(0, FAVORITES_MAX) : [];
} catch (e) {
console.error(e);
return [];
}
}
function writeFavorites(list) {
try {
fm.writeString(FAVORITES_PATH, JSON.stringify(list));
} catch (e) {
console.error(e);
}
}
// Auswahlliste in der App: Tankstellen in der Nähe plus bereits gespeicherte, zum Abhaken
async function editFavorites({ fuel }) {
const location = await getLocation();
let nearby = [];
if (location) {
const res = await callApi("list.php", {
lat: location.latitude.toFixed(3),
lng: location.longitude.toFixed(3),
rad: FAVORITES_PICK_RADIUS,
type: "all",
sort: "dist",
});
if (res.data) {
nearby = res.data.stations.map((s) => ({ ...toStation(s), price: s[fuel] ?? null }));
} else if (res.error) {
await showMessage("Tankstellen konnten nicht geladen werden", res.error);
}
}
const saved = readFavorites();
const selected = new Map(saved.map((f) => [f.id, f]));
const savedElsewhere = saved
.filter((f) => !nearby.some((n) => n.id === f.id))
.map((f) => ({ ...f, price: null, dist: location ? distanceKm(location, f) : null }));
const all = [...savedElsewhere, ...nearby];
if (!all.length) {
await showMessage("Keine Tankstellen gefunden", location ? "" : "Standort nicht verfügbar");
return;
}
const table = new UITable();
table.showSeparators = true;
const render = () => {
table.removeAllRows();
const header = new UITableRow();
header.isHeader = true;
header.height = 60;
header.addText(
`Lieblingstankstellen (${selected.size}/${FAVORITES_MAX})`,
`Antippen zum Auswählen · Umkreis ${FAVORITES_PICK_RADIUS} km · Preise ${FUEL[fuel].name}`
);
table.addRow(header);
for (const station of all) {
const isSelected = selected.has(station.id);
const row = new UITableRow();
row.height = 54;
row.dismissOnSelect = false;
const check = row.addText(isSelected ? "✓" : "");
check.widthWeight = 8;
check.titleColor = accent(fuel);
check.titleFont = Font.boldSystemFont(17);
const subtitle = [station.place, station.dist != null ? formatDist(station.dist) : null]
.filter(Boolean)
.join(" · ");
const info = row.addText(station.name, subtitle);
info.widthWeight = 62;
info.subtitleColor = Color.gray();
const price = row.addText(station.price ? priceText(station.price) : "–");
price.widthWeight = 30;
price.rightAligned();
row.onSelect = () => {
if (isSelected) selected.delete(station.id);
else if (selected.size < FAVORITES_MAX) selected.set(station.id, station);
render();
table.reload();
};
table.addRow(row);
}
};
render();
await table.present(false);
// Nur stabile Stammdaten speichern, Preise und Entfernung ändern sich
writeFavorites(
[...selected.values()].map(({ id, name, place, lat, lng }) => ({ id, name, place, lat, lng }))
);
}
async function showMessage(title, message) {
const alert = new Alert();
alert.title = title;
alert.message = message;
alert.addAction("OK");
await alert.present();
}
// ---------- Cache ----------
function readCache() {
try {
if (!fm.fileExists(CACHE_PATH)) return {};
return JSON.parse(fm.readString(CACHE_PATH)) || {};
} catch (e) {
console.error(e);
return {};
}
}
function writeCache(cache) {
try {
fm.writeString(CACHE_PATH, JSON.stringify(cache));
} catch (e) {
console.error(e);
}
}
// ---------- Home-Screen-Widgets ----------
function renderSmall(w, data, params) {
const top = data.stations[0];
w.url = mapsUrl(top);
const head = w.addStack();
head.centerAlignContent();
addPill(head, params.fuel);
head.addSpacer();
addNoonWarnIcon(head, 10);
addStatus(head, data, 10);
w.addSpacer();
addText(w, top.name, Font.boldSystemFont(15), THEME.text);
addText(w, top.place, Font.regularSystemFont(10), THEME.muted);
w.addSpacer(4);
addPrice(w, top.price, 34, accent(params.fuel));
addMeta(w, top, data, 10);
}
function renderMedium(w, data, params) {
const [top, ...rest] = data.stations;
w.url = mapsUrl(top);
const cols = w.addStack();
// Links: günstigste Tankstelle
const left = cols.addStack();
left.layoutVertically();
left.size = new Size(128, 0);
addPill(left, params.fuel);
left.addSpacer();
addText(left, top.name, Font.boldSystemFont(15), THEME.text);
addText(left, top.place, Font.regularSystemFont(10), THEME.muted);
left.addSpacer(4);
addPrice(left, top.price, 30, accent(params.fuel));
addMeta(left, top, data, 10);
cols.addSpacer(10);
// Rechts: Karte mit den nächsten drei
const right = cols.addStack();
right.layoutVertically();
right.backgroundColor = THEME.card;
right.cornerRadius = 14;
right.setPadding(8, 10, 8, 10);
const head = right.addStack();
head.centerAlignContent();
addText(head, data.source === "favorites" ? "Favoriten" : "In der Nähe", Font.semiboldSystemFont(10), THEME.muted);
head.addSpacer();
addNoonWarnIcon(head, 10);
addStatus(head, data, 10);
right.addSpacer(6);
addList(right, data, rest.slice(0, 3), top.price, { compact: true, size: 12, priceSize: 15, gap: 6 });
right.addSpacer();
}
function renderLarge(w, data, params) {
const [top, ...rest] = data.stations;
w.url = mapsUrl(top);
addHeader(w, data, params, 11);
w.addSpacer(10);
addHeroCard(w, top, data, params, { nameSize: 18, priceSize: 40 });
w.addSpacer(14);
addSectionLabel(w, listLabel(data));
w.addSpacer(6);
addList(w, data, rest.slice(0, 4), top.price);
w.addSpacer();
addFooter(w);
}
function renderExtraLarge(w, data, params) {
const [top, ...rest] = data.stations;
w.url = mapsUrl(top);
addHeader(w, data, params, 12);
w.addSpacer(12);
const cols = w.addStack();
const hero = addHeroCard(cols, top, data, params, { nameSize: 24, priceSize: 60, vertical: true });
hero.size = new Size(300, 0);
cols.addSpacer(16);
const list = cols.addStack();
list.layoutVertically();
addSectionLabel(list, listLabel(data));
list.addSpacer(8);
addList(list, data, rest.slice(0, 6), top.price, { size: 14, priceSize: 19 });
list.addSpacer();
w.addSpacer(8);
addFooter(w);
}
function renderError(w, message, params) {
w.addSpacer();
addCentered(w, (row) => addSymbol(row, "fuelpump.fill", 28, accent(params.fuel)));
w.addSpacer(8);
const text = addText(w, message, Font.mediumSystemFont(12), THEME.muted);
text.lineLimit = 3;
text.centerAlignText();
w.addSpacer();
}
// ---------- Sperrbildschirm-Widgets ----------
// Farben setzt hier iOS (Tönung je nach Hintergrund), deshalb ohne textColor.
function renderRectangular(w, data, params) {
const top = data.stations[0];
w.url = mapsUrl(top);
const head = w.addStack();
head.centerAlignContent();
addSymbol(head, "fuelpump.fill", 11);
head.addSpacer(4);
addText(head, `${top.name} · ${FUEL[params.fuel].short}`, Font.semiboldSystemFont(12));
addPrice(w, top.price, 24);
const parts = top.dist != null ? [formatDist(top.dist)] : [];
parts.push(data.stale ? `offline, Stand ${formatTime(data.fetchedAt)}` : formatTime(data.fetchedAt));
if (noonPhase()?.warn) parts.push("↑ 12:00");
addText(w, parts.join(" · "), Font.mediumSystemFont(11));
}
function renderCircular(w, data, params) {
const top = data.stations[0];
const p = priceParts(top.price);
w.addAccessoryWidgetBackground = true;
w.url = mapsUrl(top);
w.addSpacer();
addCentered(w, (row) => addSymbol(row, "fuelpump.fill", 11));
w.addSpacer(1);
addCentered(w, (row) => {
const digits = row.addStack();
digits.topAlignContent();
addText(digits, p.main, Font.boldRoundedSystemFont(16));
addText(digits, String(p.sup), Font.boldRoundedSystemFont(9));
});
addCentered(w, (row) => addText(row, FUEL[params.fuel].short, Font.semiboldRoundedSystemFont(9)));
w.addSpacer();
}
function renderInline(w, data) {
const top = data.stations[0];
w.url = mapsUrl(top);
addSymbol(w, "fuelpump.fill", 12);
addText(w, `${priceText(top.price)} ${top.name}`, Font.body());
}
function renderAccessoryError(w, family, message) {
if (family === "accessoryInline") {
addSymbol(w, "fuelpump.fill", 12);
addText(w, "Keine Preise", Font.body());
return;
}
if (family === "accessoryCircular") {
w.addAccessoryWidgetBackground = true;
w.addSpacer();
addCentered(w, (row) => addSymbol(row, "fuelpump.fill", 18));
w.addSpacer();
return;
}
const head = w.addStack();
head.centerAlignContent();
addSymbol(head, "fuelpump.fill", 11);
head.addSpacer(4);
addText(head, "Benzinpreis", Font.semiboldSystemFont(12));
const text = addText(w, message, Font.systemFont(11));
text.lineLimit = 2;
}
// ---------- Bausteine ----------
function addHeader(parent, data, params, size) {
const head = parent.addStack();
head.centerAlignContent();
addPill(head, params.fuel);
head.addSpacer(6);
const scope = data.source === "favorites" ? "Favoriten" : `${formatNumber(params.radius)} km Umkreis`;
addText(head, scope, Font.mediumSystemFont(size), THEME.muted);
head.addSpacer();
addNoonWarnIcon(head, size);
addStatus(head, data, size);
return head;
}
function addHeroCard(parent, top, data, params, { nameSize, priceSize, vertical = false }) {
const card = parent.addStack();
card.backgroundColor = THEME.card;
card.cornerRadius = 16;
card.setPadding(12, 14, 12, 14);
card.url = mapsUrl(top);
if (vertical) card.layoutVertically();
else card.bottomAlignContent();
const info = card.addStack();
info.layoutVertically();
addText(info, "GÜNSTIGSTE", Font.boldRoundedSystemFont(9), accent(params.fuel));
info.addSpacer(2);
addText(info, top.name, Font.boldSystemFont(nameSize), THEME.text);
addText(info, top.place, Font.regularSystemFont(11), THEME.muted);
info.addSpacer(6);
addMeta(info, top, data, 11, true);
card.addSpacer();
addPrice(card, top.price, priceSize, accent(params.fuel));
return card;
}
function addList(parent, data, stations, cheapest, { gap = 8, ...rowOptions } = {}) {
if (!stations.length) {
const label = data.source === "favorites" ? "Keine weiteren Favoriten geöffnet" : "Keine weiteren offenen Tankstellen";
addText(parent, label, Font.regularSystemFont(11), THEME.muted);
return;
}
stations.forEach((station, i) => {
if (i > 0) parent.addSpacer(gap);
addStationRow(parent, data, station, cheapest, rowOptions);
});
}
function addStationRow(parent, data, station, cheapest, { compact = false, size = 13, priceSize = 17 } = {}) {
const row = parent.addStack();
row.centerAlignContent();
row.url = mapsUrl(station);
if (compact) {
addText(row, station.name, Font.semiboldSystemFont(size), THEME.text);
if (station.dist != null) {
row.addSpacer(4);
addText(row, formatDist(station.dist), Font.regularRoundedSystemFont(size - 2), THEME.muted);
}
} else {
const info = row.addStack();
info.layoutVertically();
addText(info, station.name, Font.semiboldSystemFont(size), THEME.text);
const details = [station.place, station.dist != null ? formatDist(station.dist) : null].filter(Boolean);
addText(info, details.join(" · "), Font.regularSystemFont(size - 3), THEME.muted);
}
row.addSpacer();
// Tankstelle hat nach 12 Uhr erhöht
if (noonInfo(data, station)?.raised) {
addSymbol(row, "exclamationmark.triangle.fill", size - 3, THEME.warn);
row.addSpacer(3);
}
addText(row, deltaText(station.price, cheapest), Font.mediumRoundedSystemFont(size - 3), THEME.muted);
row.addSpacer(6);
addPrice(row, station.price, priceSize, THEME.text);
return row;
}
function addPill(parent, fuel) {
const pill = parent.addStack();
pill.backgroundColor = accentSoft(fuel);
pill.cornerRadius = 6;
pill.setPadding(2, 6, 2, 6);
addText(pill, FUEL[fuel].short, Font.boldRoundedSystemFont(10), accent(fuel));
return pill;
}
// Uhrzeit der Daten; orange mit Warnsymbol bei Cache-Fallback oder Daten von vor 12 Uhr
function addStatus(parent, data, size) {
const status = parent.addStack();
status.centerAlignContent();
const outdated = isOutdated(data);
const color = outdated ? THEME.warn : THEME.muted;
if (outdated) {
addSymbol(status, "exclamationmark.circle.fill", size, color);
status.addSpacer(3);
}
addText(status, formatTime(data.fetchedAt), Font.mediumRoundedSystemFont(size), color);
return status;
}
// Dezentes Symbol neben der Uhrzeit, nur kurz vor der Erhöhungsrunde
function addNoonWarnIcon(parent, size) {
if (!noonPhase()?.warn) return;
addSymbol(parent, "arrow.up.circle.fill", size, THEME.warn);
parent.addSpacer(4);
}
function addMeta(parent, station, data, size, withSince = false) {
const row = parent.addStack();
row.centerAlignContent();
if (station.dist != null) {
addSymbol(row, "location.fill", size - 2, THEME.muted);
row.addSpacer(3);
addText(row, formatDist(station.dist), Font.mediumRoundedSystemFont(size), THEME.muted);
}
const change = priceChange(data, station);
if (change) {
if (station.dist != null) row.addSpacer(8);
addChange(row, change, size, withSince);
}
return row;
}
function addChange(parent, change, size, withSince) {
const down = change.diffCt < 0;
const color = down ? THEME.down : THEME.up;
const row = parent.addStack();
row.centerAlignContent();
addSymbol(row, down ? "arrow.down.right" : "arrow.up.right", size - 1, color);
row.addSpacer(2);
let since = "";
if (withSince) since = change.sinceNoon ? " seit 12 Uhr" : ` seit ${formatTime(change.since)}`;
addText(row, `${formatNumber(Math.abs(change.diffCt))} ct${since}`, Font.semiboldRoundedSystemFont(size), color);
return row;
}
function listLabel(data) {
return data.source === "favorites" ? "Weitere Favoriten" : "Weitere in der Nähe";
}
function addSectionLabel(parent, label) {
return addText(parent, label.toUpperCase(), Font.semiboldSystemFont(10), THEME.muted);
}
function addFooter(parent) {
return addText(parent, "Daten: Tankerkönig / MTS-K", Font.regularSystemFont(8), THEME.muted);
}
// Preis im Tankstellen-Look: 1,79⁹ €
function addPrice(parent, price, size, color) {
const p = priceParts(price);
const row = parent.addStack();
row.bottomAlignContent();
const digits = row.addStack();
digits.topAlignContent();
addText(digits, p.main, Font.heavyRoundedSystemFont(size), color);
addText(digits, String(p.sup), Font.heavyRoundedSystemFont(size * 0.5), color);
row.addSpacer(Math.max(1, size * 0.08));
addText(row, "€", Font.boldRoundedSystemFont(size * 0.55), color);
return row;
}
function addText(parent, text, font, color) {
const t = parent.addText(text);
t.font = font;
if (color) t.textColor = color;
t.lineLimit = 1;
t.minimumScaleFactor = 0.6;
return t;
}
function addSymbol(parent, name, size, color) {
const symbol = SFSymbol.named(name);
if (!symbol) return null;
const image = parent.addImage(symbol.image);
image.imageSize = new Size(size, size);
if (color) image.tintColor = color;
return image;
}
function addCentered(parent, build) {
const row = parent.addStack();
row.addSpacer();
build(row);
row.addSpacer();
return row;
}
// ---------- Helfer ----------
// Integer-Rechnung in Zehntelcent, keine Float-Fehler
function toMilli(price) {
return Math.round(price * 1000);
}
function priceParts(price) {
const milli = toMilli(price);
const main = (Math.floor(milli / 10) / 100).toLocaleString("de-DE", {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
return { main, sup: milli % 10 };
}
function byPrice(a, b) {
return a.price - b.price || (a.dist ?? 0) - (b.dist ?? 0);
}
function priceText(price) {
const p = priceParts(price);
return `${p.main}${SUPERSCRIPT[p.sup]} €`;
}
// Luftlinie in km (Haversine), eine Nachkommastelle
function distanceKm(from, station) {
const toRad = (deg) => (deg * Math.PI) / 180;
const dLat = toRad(station.lat - from.latitude);
const dLng = toRad(station.lng - from.longitude);
const h =
Math.sin(dLat / 2) ** 2 +
Math.cos(toRad(from.latitude)) * Math.cos(toRad(station.lat)) * Math.sin(dLng / 2) ** 2;
return Math.round(2 * 6371 * Math.asin(Math.sqrt(h)) * 10) / 10;
}
function deltaText(price, cheapest) {
const ct = (toMilli(price) - toMilli(cheapest)) / 10;
return ct === 0 ? "±0 ct" : `+${formatNumber(ct)} ct`;
}
// Nur reine GROSS- oder kleinschreibung umwandeln; gemischte Schreibweise bleibt,
// kurze Marken in Großbuchstaben (ARAL, JET, OMV) auf Wunsch auch.
function tidy(str, keepShortCaps = false) {
if (str == null) return "";
str = String(str).trim();
const isMixed = str !== str.toUpperCase() && str !== str.toLowerCase();
if (isMixed) return str;
if (keepShortCaps && str === str.toUpperCase() && str.length <= 4) return str;
return str.toLowerCase().replace(/\p{L}+/gu, (w) => w[0].toUpperCase() + w.slice(1));
}
function mapsUrl(station) {
const dest = `${station.lat},${station.lng}`;
return USE_GOOGLE_MAPS
? `https://www.google.com/maps/dir/?api=1&destination=${dest}&travelmode=driving`
: `https://maps.apple.com/?daddr=${dest}&dirflg=d`;
}
function formatNumber(n) {
return n.toLocaleString("de-DE", { maximumFractionDigits: 1 });
}
function formatDist(km) {
return `${formatNumber(km)} km`;
}
function formatTime(date) {
return date.toLocaleTimeString("de-DE", { hour: "2-digit", minute: "2-digit" });
}
@andreasRedeker

Copy link
Copy Markdown
Author

Das Script hat heute ein Update erhalten:

  • Koordinaten können im Code für einen fixen Standort gesetzt werden (Zeile 18 & 19)
  • Apple Maps ist nun der Standarddienst für die Route zur Tankstelle, im Code kann alternativ Google Maps aktiviert werden (Zeile 13)
  • Fehler behoben, der auftrat wenn die von der API bereitgestellten Tankstelle keinen Preis (null) hatte

@TrafalgaT

Copy link
Copy Markdown

Vielen Dank für das Update !

@Jminter2K

Jminter2K commented Mar 18, 2022 •

Copy link
Copy Markdown

Hi. Bei mir bleibt es ewig auf "Daten werden geladen". MUSS ich die Koordinaten angeben? Oder woran könnte es haken? Danke.

@andreasRedeker

Copy link
Copy Markdown
Author

Hi, die Koordinaten sind optional, standardmäßig werden die anhand deines Standortes ermittelt.
Es könnte sein, dass in deiner Umgebung keine passende Tankstelle gefunden worden ist, versuche mal in Zeile 9 den Radius zu erhöhen (max. 25 km).

@monza258

monza258 commented Jun 1, 2022

Copy link
Copy Markdown

Hi @andreasRedeker,

Tolles Script von dir. Rein optisch hat mich damals dieses Script aus dem Netz angesprochen. Eventuell hast du Lust deins etwas anzupassen da in dem Script welches ich verwende auch der Durchschnittspreis errechnet wird und der Benzinpreis auch besser angezeigt wird. Würde mich freuen. ;-)

let callDataAmount = 40

let fm = FileManager.iCloud();
let p = await args.widgetParameter
let widgetSize = config.widgetFamily

if(p == 'local'){
  fm = FileManager.local();
}

let dir = fm.documentsDirectory()

let historyFolderPath = fm.joinPath(dir, "FuelPriceNearestHistory")
let list = fm.listContents(historyFolderPath)
log("length: " + list.length)
let historyFilePath = fm.joinPath(historyFolderPath, "FuelPriceNearest" + (list.length - 1) + ".json")
let path = fm.joinPath(historyFolderPath, "FuelPriceNearest" + (list.length) + ".json")

let ic = true

let apiKey = 'XXXXXX-XXXXX-XXXX-XXXX-XXXXXXXX' // get API-Key from https://creativecommons.tankerkoenig.de/
let fixedLocation = false // set to true if you want a fixed location
let radius = 5 // radius in km, set it higher if the script throws an error, it's possible that there is no gas station near your location


const apiURL = (location, radius, apiKey) => `https://creativecommons.tankerkoenig.de/json/list.php?lat=${location.latitude.toFixed(3)}&lng=${location.longitude.toFixed(3)}&rad=${radius}&sort=dist&type=all&apikey=${apiKey}`

let station = await loadStation(apiKey, radius, fixedLocation)
log(dir)
let widget = await createWidget(station)
Script.setWidget(widget)
Script.complete()

function map(lat, lng, name) {
  name = name.replace(" ", "%20")
  name = name.replace(" ", "%20")
  name = name.replace(" ", "%20")
  name = name.replace(" ", "%20")
  name = name.replace(" ", "%20")
  var mapURL = "https://maps.apple.com/?t=h&z=12&ll=" + lat + "," + lng + "&q=" + name  
  return mapURL
}

function lineSep(){
  //generate line separator
  const context =new DrawContext()
  let width = 93,h=0.00000000001
  context.size=new Size(width, h)
  context.opaque=false
  context.respectScreenScale=true
  const path = new Path()
  path.move(new Point(18,h))
  path.addLine(new Point(width,h))
  context.addPath(path)
  context.setStrokeColor(Color.blue())
  context.strokePath()
  return context.getImage()
}

async function getFromApi(){
      let location
    
      if (fixedLocation) {
        location = myLocation
      } else {
        location = await Location.current()    
      }
      const data = await new Request(apiURL(location, radius, apiKey)).loadJSON()

      return data
}

function getFromFile(){
  if (fm.fileExists(historyFilePath)){
    data = JSON.parse(fm.readString(historyFilePath));
    return data;
  }
}
  
async function loadStation(apiKey, radius, fixedLocation) {
    try{
      data = await getFromApi();
    }catch {
      data = await getFromFile();
      ic = false
    }
    log(ic)
    log(data)
    return data
}

function formatValue(value) {
    let lastDigit = '⁹'
    let price = value.toString().slice(0, -1)
    return price + lastDigit
}

async function createWidget(data) {
    var attr = data.stations[0]
    
    log(attr.e10)
    
    log("dataLength: " + data.stations.length)

    data.stations.forEach(cheapest)
    
    function cheapest(item, index) {
      if ((item.e10 != null) && (item.e10 < attr.e10)){
        attr = item
      }
    }
    log(attr.e10)
    
    log("address:\n" + attr.street + attr.houseNumber + attr.postCode + attr.place)
    

    const widget = new ListWidget()
    
    widget.url = await map(attr.lat, attr.lng, attr.name)
    log(widget.url)
    
    //   header:
  
  var header_stack = widget.addStack();
  var symbol = SFSymbol.named('car.fill').image;
  var symbol_image = header_stack.addImage(symbol);
    symbol_image.imageSize = new Size(15, 15);
  symbol_image.tintColor = Color.blue()
  header_stack.addSpacer(3);
  var title = header_stack.addText("Sprit Preise");
  title.font = Font.boldRoundedSystemFont(13)
  title.textColor = Color.blue()
  console.log("title:\n" + title.text + "\n")
  
//   line:
  
  let lineImg = lineSep()
  let line = widget.addImage(lineImg)
    line.resizable=false
    line.imageOpacity=1

widget.addSpacer(3)




//   price:

var line2Stack = widget.addStack()
var line2 = line2Stack.addText(formatValue(attr.e10))
    line2.font = Font.boldRoundedSystemFont(36)
    var euroStack = line2Stack.addStack()
    euroStack.layoutVertically()
    euroStack.addSpacer(12)
    var euro = euroStack.addText("€")
    euro.font = Font.boldRoundedSystemFont(24)
    

  if (fm.fileExists(historyFilePath) == false) {
    fm.writeString(historyFilePath, JSON.stringify(data));
  }
  
  
  
  const dataPrev = JSON.parse(fm.readString(historyFilePath));
  let currentPrice = Number(attr.e10)
  var previousPriceAttr = dataPrev.stations[0]  
  
  dataPrev.stations.forEach(prevStation)
    function prevStation(item, index) {
      if ((item.e10 != null) && (String(item.lat + "_" + item.lng) == String(attr.lat + "_" + attr.lng))){
        previousPriceAttr = item
      }
    }
    let previousPrice = previousPriceAttr.e10
    log(previousPrice)
  
  var change = 0
 
  let priceList = new Array()
  var all = 0
  
  var c = 0
    
  list.forEach(myFunction)
  function myFunction(item, index){
    if (index < callDataAmount) {
      let itemPath = fm.joinPath(historyFolderPath, "FuelPriceNearest" + (list.length - index - 1) + ".json")
      const itemData = JSON.parse(fm.readString(itemPath))

      if(itemData != null) {
      
       itemData.stations.forEach(itemStation)
        function itemStation(i, index) {
           if ((i.e10 != null) && (String(i.lat + "_" + i.lng) == String(attr.lat + "_" + attr.lng))){
             priceList[c] = i.e10
             c = c + 1
           }
        }
      }
    }
  }
  
  priceList.forEach(allF)
  

  function allF(item, index) {
      all = all + Number(item)
  }
  
  log("all: " + all)
  
  change = all / (priceList.length)
  
  log("change: " + change)
  
  
  let avrg = String(Math.round((change + Number.EPSILON) * 100) / 100)
  let avrgC = avrg.replace(".","")
  if (avrgC.length < 3) {
    if (avrg.includes("1.")) {
      avrg = avrg + "0"
      if (avrgC.length == 1) {
        avrg = avrg + "0"
      }
    }else if (avrg.includes("0.")) {
      avrg = "0." + avrgC + "0"
    }
  }
  
  log("avrg: " + avrg)
  
  change = Number(avrg)
  
  if (change != 0) {
    if (change == currentPrice) {
      line2.textColor = Color.orange()
      euro.textColor = Color.orange()
    }else if (change > currentPrice) {
      line2.textColor = Color.green()
      euro.textColor = Color.green()
    }else if (change < currentPrice) {
      line2.textColor = Color.red()
      euro.textColor = Color.red()
    }
  }


  
  if (list.length > callDataAmount) {
    let amount = list.length - callDataAmount
    list.forEach(deleteFunc)
    function deleteFunc(item, index) {
      if (index < amount) {
        let itemPath = fm.joinPath(historyFolderPath, "FuelPriceNearest" + (amount - index - 1) + ".json")    
//         if (fm.fileExists(itemPath)) {
//           fm.remove(itemPath)
//         }
      }
    }
    log(list.length)
  }
  
  

  if (currentPrice != previousPrice) {
    fm.writeString(path, JSON.stringify(data))
  }
  
  var line3text = "Super E10"
  if (avrg > 0) {
    line3text = "Super E10 ⌀" + avrg
  }
  
var line3 = widget.addText(line3text)
line3.font = Font.boldRoundedSystemFont(14)
line3.textColor = Color.blue()
widget.addSpacer(0)


let stationStack = widget.addStack()
stationStack.layoutHorizontally()
stationStack.setPadding(0, -4, 0, 0)


let stationOpen = stationStack.addText("|")
stationOpen.font = Font.boldRoundedSystemFont(35)
stationOpen.textColor = Color.red()
if (attr.isOpen == true) {
  stationOpen.textColor = Color.green()
}


let nameStack = stationStack.addStack()
nameStack.layoutVertically()
nameStack.addSpacer(5)

log(attr.brand)

      let stationName = nameStack.addText(attr.brand + " → " + attr.dist + " km")
    stationName.font = Font.boldRoundedSystemFont(10)
      
      let place = nameStack.addText(attr.place)
      place.font = Font.boldRoundedSystemFont(10)
    
    let street = nameStack.addText(attr.street)
      street.font = Font.boldRoundedSystemFont(10)


    return widget
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment