Skip to content

Instantly share code, notes, and snippets.

@marckohlbrugge
Last active June 4, 2024 09:12
Show Gist options
  • Save marckohlbrugge/3fbf4fd2a179ee21a61ee1eaf0ccce02 to your computer and use it in GitHub Desktop.
Save marckohlbrugge/3fbf4fd2a179ee21a61ee1eaf0ccce02 to your computer and use it in GitHub Desktop.
// Replace with your API key from https://wip.co/my/api_keys
const API_KEY = "wip_sk_FOOBAR";
const API_URL = `https://api.wip.co/v1/users/me.json?api_key=${API_KEY}`;
// Function to fetch data from the API
async function fetchStreakData() {
if (API_KEY === "wip_sk_FOOBAR") {
let alert = new Alert();
alert.title = "API Key Missing";
alert.message = "Please replace the placeholder API key with your actual API key.";
alert.addAction("OK");
await alert.present();
return null;
}
let request = new Request(API_URL);
let response = await request.loadJSON();
return response;
}
// Function to calculate hours left until midnight in a given time zone
function hoursLeftUntilMidnight(timeZone) {
let now = new Date();
let nowInUserTimeZone = new Date(now.toLocaleString("en-US", { timeZone: timeZone }));
let midnight = new Date(nowInUserTimeZone);
midnight.setHours(24, 0, 0, 0); // Set to midnight
let hoursLeft = (midnight - nowInUserTimeZone) / (1000 * 60 * 60); // Convert milliseconds to hours
return hoursLeft.toFixed(0);
}
// Function to create a widget displaying the streak info
async function createWidget() {
let data = await fetchStreakData();
if (!data) {
let widget = new ListWidget();
let errorText = widget.addText("API Key Missing");
errorText.font = Font.boldSystemFont(16);
errorText.textColor = Color.red();
errorText.centerAlignText();
return widget;
}
let streakText;
let widget = new ListWidget();
streakText = widget.addText(`${data.streak} 🔥`);
streakText.font = Font.boldSystemFont(30);
streakText.textColor = Color.black();
streakText.centerAlignText()
widget.addSpacer(8)
let statusText;
if (data.streaking) {
statusText = widget.addText("Streaking");
widget.backgroundColor = new Color("#f9db00"); // Yellow
} else {
let hoursLeft = hoursLeftUntilMidnight(data.time_zone);
statusText = widget.addText(`${hoursLeft} hours left...`);
widget.backgroundColor = new Color("#F44336"); // Red
}
statusText.textColor = Color.black();
statusText.font = Font.boldSystemFont(16)
statusText.centerAlignText()
return widget;
}
// Main
let widget = await createWidget();
if (config.runsInWidget) {
Script.setWidget(widget);
} else {
widget.presentSmall();
}
Script.complete();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment