bc100-autofill/acquire_bcnum.js

63 lines
2.4 KiB
JavaScript
Raw Normal View History

"use strict;"
async function getAuthToken() {
let storageData, dec, tok;
storageData = window.sessionStorage.getItem("token");
while (!tok) {
storageData = window.sessionStorage.getItem("token");
dec = JSON.parse(storageData);
if (!!dec && Object.keys(dec).includes("accessToken")) {
2023-11-13 20:25:49 +01:00
let tokInspect = dec.accessToken;
if (tokInspect && tokInspect.startsWith("eyJ")) {
tok = tokInspect;
}
} else {
console.log("No accessToken available. Sleeping...")
await new Promise(res => setTimeout(res, 5000));
}
}
return tok;
}
function correlationId() {
return crypto.randomUUID() + "_" + crypto.randomUUID()
}
async function getBahncardInfo() {
let tok = await getAuthToken();
let req = await fetch("https://www.bahn.de/web/api/kundenkonto/bahncard", {
headers: [
["Accept", "application/json"], ["authorization", "Bearer " + tok], //["X-Correlation-ID", correlationId()]
]
});
if (req.ok) {
const data = await req.json();
console.log(data);
const orders = data.bahnCardBestellungen.filter((order) => {
return order.bahncardTyp === "BC100" && (Date.parse(order.gueltigAb) < Date.now())
});
console.log("BahnCard candidates:", orders);
if (orders[0] !== undefined) {
// Orders are returned in reverse chronological order.
// TODO Ask which one if there are multiple.
// (Maybe inject a <dialog> element here, those have <input type=radio> and dropdowns.)
return orders[0].bcNummer || false;
}
} else {
console.log("Request failed:", req);
return false;
}
}
browser.storage.sync.get("acquireBahncard").then(v => {
if (v.acquireBahncard != false) { // may also be undefined, so no identity check here
getBahncardInfo().then(v => {
if (!!v && v.length == 16) {
const saveData = { "bcnum": v, "acquireBahncard": false }
console.log("Saving", saveData);
browser.storage.sync.set(saveData).then(success => {
if (window !== window.top) {
window.close();
}
});
}
}, f => console.log("Could not acquire BahnCard number.", f))
}
})