small change vodafone

Signed-off-by: Benny Samir Hierl <bennysamir@posteo.de>
This commit is contained in:
Benny Samir Hierl 2020-11-11 17:51:48 +01:00
parent 90d108a622
commit 8021750a6a
No known key found for this signature in database
GPG key ID: 69DE3C3C097DB7F7

View file

@ -3,9 +3,11 @@
// icon-color: red; icon-glyph: broadcast-tower; // icon-color: red; icon-glyph: broadcast-tower;
/************** /**************
Version 1.2.3 Version 1.2.4
Changelog: Changelog:
v1.2.4:
- use color.dynamic
v1.2.3: v1.2.3:
- Fix typo (thanks @CuzImStantac) - Fix typo (thanks @CuzImStantac)
v1.2.2: v1.2.2:
@ -46,12 +48,6 @@ const containerList = ['Daten', 'D_EU_DATA', 'C_DIY_Data_National']
const codeList = ['-1', '45500', '40100'] const codeList = ['-1', '45500', '40100']
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
let backColor; //Widget background color
let backColor2; //Widget background color
let textColor; //Widget text color
let fillColor;
let strokeColor;
let widgetInputRAW = args.widgetParameter; let widgetInputRAW = args.widgetParameter;
let widgetInput = null; let widgetInput = null;
@ -59,28 +55,20 @@ let user, pass, number
if (widgetInputRAW !== null) { if (widgetInputRAW !== null) {
[user, pass, number] = widgetInputRAW.toString().split("|"); [user, pass, number] = widgetInputRAW.toString().split("|");
if(!user || !pass || !number) { if (!user || !pass || !number) {
throw new Error("Invalid Widget parameter. Expected format: username|password|phonenumber") throw new Error("Invalid Widget parameter. Expected format: username|password|phonenumber")
} }
if(/^49[\d]{5,}/.test(number) === false) { if (/^49[\d]{5,}/.test(number) === false) {
throw new Error("Invalid phonenumber format. Expected format: 491721234567") throw new Error("Invalid phonenumber format. Expected format: 491721234567")
} }
} }
if (Device.isUsingDarkAppearance()) { const backColor = Color.dynamic(new Color('D32D1F'), new Color('111111'));
backColor = '111111'; const backColor2 = Color.dynamic(new Color('76150C'), new Color('222222'));
backColor2 = '222222'; const textColor = Color.dynamic(new Color('EDEDED'), new Color('EDEDED'));
textColor = 'EDEDED'; const fillColor = Color.dynamic(new Color('EDEDED'), new Color('EDEDED'));
fillColor = 'EDEDED'; const strokeColor = Color.dynamic(new Color('B0B0B0'), new Color('121212'));
strokeColor = '121212';
} else {
backColor = 'D32D1F';
backColor2 = '76150C';
textColor = 'EDEDED';
fillColor = 'EDEDED';
strokeColor = 'B0B0B0';
}
const canvas = new DrawContext(); const canvas = new DrawContext();
const canvSize = 200; const canvSize = 200;
@ -107,8 +95,8 @@ function drawArc(ctr, rad, w, deg) {
bgd = 2 * rad; bgd = 2 * rad;
bgr = new Rect(bgx, bgy, bgd, bgd); bgr = new Rect(bgx, bgy, bgd, bgd);
canvas.setFillColor(new Color(fillColor)); canvas.setFillColor(fillColor);
canvas.setStrokeColor(new Color(strokeColor)); canvas.setStrokeColor(strokeColor);
canvas.setLineWidth(w); canvas.setLineWidth(w);
canvas.strokeEllipse(bgr); canvas.strokeEllipse(bgr);
@ -120,12 +108,12 @@ function drawArc(ctr, rad, w, deg) {
} }
} }
function getTimeRemaining(endtime){ function getTimeRemaining(endtime) {
const total = Date.parse(endtime) - Date.parse(new Date()); const total = Date.parse(endtime) - Date.parse(new Date());
const seconds = Math.floor( (total/1000) % 60 ); const seconds = Math.floor((total / 1000) % 60);
const minutes = Math.floor( (total/1000/60) % 60 ); const minutes = Math.floor((total / 1000 / 60) % 60);
const hours = Math.floor( (total/(1000*60*60)) % 24 ); const hours = Math.floor((total / (1000 * 60 * 60)) % 24);
const days = Math.floor( total/(1000*60*60*24) ); const days = Math.floor(total / (1000 * 60 * 60 * 24));
return { return {
total, total,
@ -154,7 +142,7 @@ async function getSessionCookiesViaNetworkLogin() {
}) })
try { try {
let res = await req.loadJSON() let res = await req.loadJSON()
return { cookies: req.response.cookies, msisdn: res.msisdn} return { cookies: req.response.cookies, msisdn: res.msisdn }
} catch (e) { } catch (e) {
console.log("Login failed! Please check if Wifi is disabled.") console.log("Login failed! Please check if Wifi is disabled.")
throw new Error(`Login failed with HTTP-Status-Code ${req.response.statusCode}`) throw new Error(`Login failed with HTTP-Status-Code ${req.response.statusCode}`)
@ -177,7 +165,7 @@ async function getSessionCookiesViaMeinVodafoneLogin(u, p) {
}) })
try { try {
let res = await req.loadJSON() let res = await req.loadJSON()
return { cookies: req.response.cookies} return { cookies: req.response.cookies }
} catch (e) { } catch (e) {
console.log("Login failed!") console.log("Login failed!")
throw new Error(`Login failed with HTTP-Status-Code ${req.response.statusCode}`) throw new Error(`Login failed with HTTP-Status-Code ${req.response.statusCode}`)
@ -188,7 +176,7 @@ async function getUsage(user, pass, number) {
let cookies, msisdn; let cookies, msisdn;
if (user && pass && number) { if (user && pass && number) {
console.log("Login via MeinVodafone") console.log("Login via MeinVodafone")
let { cookies: c }= await getSessionCookiesViaMeinVodafoneLogin(user, pass); let { cookies: c } = await getSessionCookiesViaMeinVodafoneLogin(user, pass);
cookies = c; cookies = c;
msisdn = number; msisdn = number;
} else { } else {
@ -197,7 +185,7 @@ async function getUsage(user, pass, number) {
cookies = c; cookies = c;
msisdn = m; msisdn = m;
} }
let CookieValues = cookies.map(function(v){ let CookieValues = cookies.map(function (v) {
return v.name + "=" + v.value return v.name + "=" + v.value
}) })
let req; let req;
@ -211,10 +199,10 @@ async function getUsage(user, pass, number) {
try { try {
let res = await req.loadJSON() let res = await req.loadJSON()
console.log("unbilled-usage loaded") console.log("unbilled-usage loaded")
let datenContainer = res['serviceUsageVBO']['usageAccounts'][0]['usageGroup'].find(function(v){ let datenContainer = res['serviceUsageVBO']['usageAccounts'][0]['usageGroup'].find(function (v) {
return containerList.includes(v.container) return containerList.includes(v.container)
}) })
if (datenContainer === undefined) { if (datenContainer === undefined) {
const ErrorMsg = "Can't find usageGroup with supported Container: " + containerList.join(', ') + "."; const ErrorMsg = "Can't find usageGroup with supported Container: " + containerList.join(', ') + ".";
console.log(ErrorMsg) console.log(ErrorMsg)
@ -225,7 +213,7 @@ async function getUsage(user, pass, number) {
console.log("Please check the following list to find the correct container name for your case and adjust the list of container names at the beginnging: " + listOfContainerNamesInResponse.join(", ")) console.log("Please check the following list to find the correct container name for your case and adjust the list of container names at the beginnging: " + listOfContainerNamesInResponse.join(", "))
throw new Error(ErrorMsg) throw new Error(ErrorMsg)
} }
let datenvolumen; let datenvolumen;
if (datenContainer.usage.length == 1) { if (datenContainer.usage.length == 1) {
datenvolumen = datenContainer.usage[0] datenvolumen = datenContainer.usage[0]
@ -234,24 +222,24 @@ async function getUsage(user, pass, number) {
return codeList.includes(v.code) return codeList.includes(v.code)
}) })
} }
if (datenvolumen === undefined) { if (datenvolumen === undefined) {
const ErrorMsg = "Can't find Usage with supported Codes: " + codeList.join(', ') + "."; const ErrorMsg = "Can't find Usage with supported Codes: " + codeList.join(', ') + ".";
console.log(ErrorMsg) console.log(ErrorMsg)
const listOfCodeInResponse = datenContainer.usage.map(function(v) { const listOfCodeInResponse = datenContainer.usage.map(function (v) {
return `Code: "${v.code}" for "${v.description}"`; return `Code: "${v.code}" for "${v.description}"`;
}) })
console.log("Please check the following list to find the correct code for your case and adjust the list of codes at the beginnging: " + listOfCodeInResponse.join(", ")) console.log("Please check the following list to find the correct code for your case and adjust the list of codes at the beginnging: " + listOfCodeInResponse.join(", "))
throw new Error(ErrorMsg) throw new Error(ErrorMsg)
} }
let endDate = datenvolumen.endDate; let endDate = datenvolumen.endDate;
if (endDate == null) { if (endDate == null) {
endDate = res['serviceUsageVBO']['billDetails']['billCycleEndDate'] || null endDate = res['serviceUsageVBO']['billDetails']['billCycleEndDate'] || null
} }
return { return {
total: datenvolumen.total, total: datenvolumen.total,
used: datenvolumen.used, used: datenvolumen.used,
@ -279,7 +267,7 @@ let data;
let lastUpdate let lastUpdate
try { try {
// If cache exists and it's been less than 30 minutes since last request, use cached data. // If cache exists and it's been less than 30 minutes since last request, use cached data.
if (cacheExists&& (today.getTime() - cacheDate.getTime()) < (cacheMinutes * 60 * 1000)) { if (cacheExists && (today.getTime() - cacheDate.getTime()) < (cacheMinutes * 60 * 1000)) {
console.log("Get from Cache") console.log("Get from Cache")
data = JSON.parse(files.readString(cachePath)) data = JSON.parse(files.readString(cachePath))
lastUpdate = cacheDate lastUpdate = cacheDate
@ -289,7 +277,7 @@ try {
console.log("Write Data to Cache") console.log("Write Data to Cache")
try { try {
files.writeString(cachePath, JSON.stringify(data)) files.writeString(cachePath, JSON.stringify(data))
} catch(e) { } catch (e) {
console.log("Creating Cache failed!") console.log("Creating Cache failed!")
console.log(e) console.log(e)
} }
@ -298,7 +286,7 @@ try {
} }
} catch (e) { } catch (e) {
console.error(e) console.error(e)
if (cacheExists) { if (cacheExists) {
console.log("Get from Cache") console.log("Get from Cache")
data = JSON.parse(files.readString(cachePath)) data = JSON.parse(files.readString(cachePath))
lastUpdate = cacheDate lastUpdate = cacheDate
@ -317,36 +305,36 @@ if (data !== undefined) {
const gradient = new LinearGradient() const gradient = new LinearGradient()
gradient.locations = [0, 1] gradient.locations = [0, 1]
gradient.colors = [ gradient.colors = [
new Color(backColor), backColor,
new Color(backColor2) backColor2
] ]
widget.backgroundGradient = gradient widget.backgroundGradient = gradient
let firstLineStack = widget.addStack() let firstLineStack = widget.addStack()
let provider = firstLineStack.addText("Vodafone") let provider = firstLineStack.addText("Vodafone")
provider.font = Font.mediumSystemFont(12) provider.font = Font.mediumSystemFont(12)
provider.textColor = new Color(textColor) provider.textColor = textColor
// Last Update // Last Update
firstLineStack.addSpacer() firstLineStack.addSpacer()
let lastUpdateText = firstLineStack.addDate(lastUpdate) let lastUpdateText = firstLineStack.addDate(lastUpdate)
lastUpdateText.font = Font.mediumSystemFont(8) lastUpdateText.font = Font.mediumSystemFont(8)
lastUpdateText.rightAlignText() lastUpdateText.rightAlignText()
lastUpdateText.applyTimeStyle() lastUpdateText.applyTimeStyle()
lastUpdateText.textColor = Color.lightGray() lastUpdateText.textColor = Color.lightGray()
widget.addSpacer() widget.addSpacer()
let remainingPercentage = (100 / data.total * data.remaining).toFixed(0); let remainingPercentage = (100 / data.total * data.remaining).toFixed(0);
drawArc( drawArc(
new Point(canvSize / 2, canvSize / 2), new Point(canvSize / 2, canvSize / 2),
canvRadius, canvRadius,
canvWidth, canvWidth,
Math.floor(remainingPercentage * 3.6) Math.floor(remainingPercentage * 3.6)
); );
const canvTextRect = new Rect( const canvTextRect = new Rect(
0, 0,
100 - canvTextSize / 2, 100 - canvTextSize / 2,
@ -354,16 +342,16 @@ if (data !== undefined) {
canvTextSize canvTextSize
); );
canvas.setTextAlignedCenter(); canvas.setTextAlignedCenter();
canvas.setTextColor(new Color(textColor)); canvas.setTextColor(textColor);
canvas.setFont(Font.boldSystemFont(canvTextSize)); canvas.setFont(Font.boldSystemFont(canvTextSize));
canvas.drawTextInRect(`${remainingPercentage}%`, canvTextRect); canvas.drawTextInRect(`${remainingPercentage}%`, canvTextRect);
const canvImage = canvas.getImage(); const canvImage = canvas.getImage();
let image = widget.addImage(canvImage); let image = widget.addImage(canvImage);
image.centerAlignImage() image.centerAlignImage()
widget.addSpacer() widget.addSpacer()
// Total Values // Total Values
let totalValues; let totalValues;
if (parseInt(data.total) < 1000) { if (parseInt(data.total) < 1000) {
@ -376,8 +364,8 @@ if (data !== undefined) {
let totalValuesText = widget.addText(totalValues) let totalValuesText = widget.addText(totalValues)
totalValuesText.font = Font.mediumSystemFont(12) totalValuesText.font = Font.mediumSystemFont(12)
totalValuesText.centerAlignText() totalValuesText.centerAlignText()
totalValuesText.textColor = new Color(textColor) totalValuesText.textColor = textColor
// Remaining Days // Remaining Days
if (data.endDate) { if (data.endDate) {
widget.addSpacer(5) widget.addSpacer(5)
@ -385,16 +373,16 @@ if (data !== undefined) {
let remainingDaysText = widget.addText(`${remainingDays} Tage verbleibend`) let remainingDaysText = widget.addText(`${remainingDays} Tage verbleibend`)
remainingDaysText.font = Font.mediumSystemFont(8) remainingDaysText.font = Font.mediumSystemFont(8)
remainingDaysText.centerAlignText() remainingDaysText.centerAlignText()
remainingDaysText.textColor = new Color(textColor) remainingDaysText.textColor = textColor
} }
} else { } else {
let fallbackText = widget.addText("Es ist ein Fehler aufgetreten! Bitte prüfen Sie die Logs direkt in der App.") let fallbackText = widget.addText("Es ist ein Fehler aufgetreten! Bitte prüfen Sie die Logs direkt in der App.")
fallbackText.font = Font.mediumSystemFont(12) fallbackText.font = Font.mediumSystemFont(12)
fallbackText.textColor = new Color(textColor) fallbackText.textColor = textColor
} }
if(!config.runsInWidget) { if (!config.runsInWidget) {
await widget.presentSmall() await widget.presentSmall()
} else { } else {
// Tell the system to show the widget. // Tell the system to show the widget.