Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Task: Gemini_helligdag
- A1: Flash [
- Text: Updating holidays...
- Continue Task Immediately: On
- Dismiss On Click: On ]
- A2: JavaScriptlet [
- Code: var year
- year = new Date().getFullYear()
- Auto Exit: On
- Timeout (Seconds): 45 ]
- A3: Multiple Variables Set [
- Names: %next_year=%year+1
- %api_base_url=https://webapi.no/api/v1/holidays/
- Values Splitter: =
- Do Maths: On
- Max Rounding Digits: 3
- Structure Output (JSON, etc): On ]
- A4: AutoTools Json Read [
- Configuration: Simple Mode: true
- Json: %api_base_url%year
- Json Root Variable: json_holidays
- Separator: ,
- Timeout (Seconds): 60
- Structure Output (JSON, etc): On
- Continue Task After Error:On ]
- A5: AutoTools Json Read [
- Configuration: Simple Mode: true
- Json: %api_base_url%next_year
- Json Root Variable: json_holidays_next_year
- Separator: ,
- Timeout (Seconds): 60
- Structure Output (JSON, etc): On
- Continue Task After Error:On ]
- A6: If [ %err Set ]
- A7: Flash [
- Text: Error getting dates: %errmsg
- Continue Task Immediately: On
- Dismiss On Click: On ]
- A8: Stop [
- With Error: On ]
- A9: End If
- A10: JavaScriptlet [
- Code: /*
- * Tasker JavaScriptlet for å behandle (parse, slå sammen, sortere)
- * helligdags-JSON hentet via Tasker HTTP Request.
- * Forventer at Tasker-variablene %holidays_current og %holidays_next
- * inneholder JSON-strenger fra API-et.
- */
- //flash("Starter behandling av helligdager...");
- let jsonStringCurrent = local('json_holidays');
- let jsonStringNext = local('json_holidays_next_year');
- let holidays_sorted = []; // For å lagre det ferdige resultatet
- let errorMsg = '';
- // Sjekk om vi faktisk fikk data fra Tasker
- if (!jsonStringCurrent || !jsonStringNext) {
- errorMsg = "Mangler data fra Tasker (%holidays_current eller %holidays_next er tom).";
- flash(errorMsg);
- setLocal('holidays_error', errorMsg);
- setLocal('holidays_sorted_json', ''); // Tøm resultat
- } else {
- try {
- // 1. Parse JSON-strengene
- let dataCurrent = JSON.parse(jsonStringCurrent);
- let dataNext = JSON.parse(jsonStringNext);
- //flash("JSON parset for begge år.");
- // 2. Hent ut selve listene (data-arrayene) - bruk || [] for sikkerhet
- let arrayCurrent = (dataCurrent && dataCurrent.data) ? dataCurrent.data : [];
- let arrayNext = (dataNext && dataNext.data) ? dataNext.data : [];
- if (!Array.isArray(arrayCurrent) || !Array.isArray(arrayNext)) {
- throw new Error("'.data' feltet var ikke en array i en av responsene.");
- }
- //flash(`Antall før sammenslåing: År 1=${arrayCurrent.length}, År 2=${arrayNext.length}`);
- // 3. Slå sammen listene
- let allHolidays = [...arrayCurrent, ...arrayNext];
- //flash(`Totalt antall etter sammenslåing: ${allHolidays.length}`);
- // 4. Sorter listen etter dato
- allHolidays.sort((a, b) => {
- // Sikrer at vi har gyldige objekter og datoer før sammenligning
- if (a && a.date && b && b.date) {
- return a.date.localeCompare(b.date);
- } else {
- // Hvis data er ugyldig, ikke endre rekkefølgen relativt til hverandre
- return 0;
- }
- });
- //flash("Helligdager sortert.");
- // ---- VIS ET PAR ELEMENTER FOR Å BEKREFTE ----
- if (allHolidays.length > 0) {
- let firstHoliday = allHolidays[0];
- let lastHoliday = allHolidays[allHolidays.length - 1];
- // Vis første og siste (kun dato YYYY-MM-DD)
- //flash(`Første: ${firstHoliday.date.substring(0, 10)} - ${firstHoliday.description}`);
- //flash(`Siste: ${lastHoliday.date.substring(0, 10)} - ${lastHoliday.description}`);
- // Ekstra: Finn en fra neste år for å bekrefte at begge er med
- //let nextYearStart = (new Date().getFullYear() + 1).toString(); // Finner neste år som streng
- //let holidayInNextYear = allHolidays.find(h => h.date.startsWith(nextYearStart));
- //if (holidayInNextYear) {
- //flash(`Eksempel neste år: ${holidayInNextYear.date.substring(0, 10)} - ${holidayInNextYear.description}`);
- //}
- } else {
- flash("Ingen helligdager funnet etter behandling.");
- }
- // Lagre HELE den sorterte listen som JSON i en Tasker-variabel for evt. senere bruk
- holidays_sorted = allHolidays; // Lagre den faktiske arrayen
- setLocal('holidays_sorted_json', JSON.stringify(holidays_sorted));
- setLocal('holidays_error', ''); // Ingen feil
- //flash("Behandling ferdig. Resultat lagret i %holidays_sorted_json.");
- } catch (error) {
- errorMsg = `Feil under behandling: ${error.message || error}`;
- flash(errorMsg);
- setLocal('holidays_error', errorMsg);
- setLocal('holidays_sorted_json', ''); // Tøm resultat
- }
- }
- Auto Exit: On
- Timeout (Seconds): 45 ]
- A11: JavaScriptlet [
- Code: /*
- * Tasker JavaScriptlet to:
- * 1. Read the Tasker variable %num_days to determine the time period.
- * 2. Filter a sorted list of holidays (%holidays_sorted_json).
- * 3. Format the result as a single comma-separated string with abbreviated weekday:
- * "DD.MM.YYYY (Mon): Description, ..." and save in %upcoming_holidays_formatted.
- * 4. Create a Tasker array (%upcoming_holidays_dates) with just the dates (DD.MM.YYYY).
- * 5. Create a Tasker array (%upcoming_holidays_daynames) with just the abbreviated day names (Mon, Tue, etc.).
- * 6. Create a Tasker array (%upcoming_holidays_colors) with RGB color codes ("255,0,0" for weekend, "0,255,0" for weekday).
- * 7. If input data (%holidays_sorted_json) is missing/invalid, or an error occurs,
- * set %upcoming_holidays_formatted to "No data. Please refresh!",
- * and the new array variables are set to empty.
- *
- * Version with DD.MM.YYYY date format, abbreviated weekday, reads %num_days, special error output,
- * and creates separate arrays for dates, day names, and colors.
- * Only flashes on error.
- */
- // Define Tasker variable names (these strings MUST match your Tasker variables)
- let outputVariableName = 'upcoming_holidays_formatted';
- let datesArrayVariableName = 'upcoming_holidays_dates'; // Name for date array
- let dayNamesArrayVariableName = 'upcoming_holidays_daynames'; // Name for day name array
- let colorsArrayVariableName = 'upcoming_holidays_colors'; // NEW: Name for color array
- let errorVariableName = 'filter_format_error';
- let errorOutputString = 'No data. Please refresh!'; // Default error text for output
- // Define colors
- const colorRed = "255,0,0"; // RGB for weekend (Saturday/Sunday)
- const colorGreen = "0,255,0"; // RGB for weekday (Monday-Friday)
- const colorError = ""; // Value for color array on date error
- // Reset variables before starting
- setLocal(outputVariableName, '');
- setLocal(datesArrayVariableName, '');
- setLocal(dayNamesArrayVariableName, '');
- setLocal(colorsArrayVariableName, ''); // NEW: Reset color array
- setLocal(errorVariableName, '');
- // Get input data
- let sortedJson = local('holidays_sorted_json'); // Reads Tasker variable %holidays_sorted_json
- let processingError = ''; // Internal JS variable for error messages
- if (!sortedJson) {
- // --- Handling missing input ---
- processingError = "Error: Could not find sorted list in %holidays_sorted_json.";
- setLocal(errorVariableName, processingError);
- setLocal(outputVariableName, errorOutputString);
- // Ensure array variables are also empty on error
- setLocal(datesArrayVariableName, '');
- setLocal(dayNamesArrayVariableName, '');
- setLocal(colorsArrayVariableName, ''); // NEW: Reset color array on error
- flash(processingError); // Flash the specific error cause
- } else {
- // --- Try processing data ---
- try {
- // Parse the JSON string
- let sortedHolidays = JSON.parse(sortedJson);
- if (!Array.isArray(sortedHolidays)) {
- throw new Error("The content of %holidays_sorted_json is not a valid list (array).");
- }
- // Define the time frame
- let today = new Date();
- today.setHours(0, 0, 0, 0);
- // Read and interpret %num_days
- let numDaysString = local('num_days'); // Reads Tasker variable %num_days
- let numberOfDays = parseInt(numDaysString, 10);
- // Show all if %num_days is not a positive number or is 'n/a'
- let showAllUpcoming = isNaN(numberOfDays) || numberOfDays <= 0 || numDaysString === 'n/a';
- // Filter the list based on %num_days
- let upcomingHolidays = sortedHolidays.filter(holiday => {
- if (!holiday || !holiday.date) return false;
- try {
- // Ensure date is valid and in the future (or today)
- let holidayDate = new Date(holiday.date);
- if (isNaN(holidayDate.getTime())) return false; // Invalid date format
- if (holidayDate < today) return false; // Always exclude past dates
- // Decide whether to include based on %num_days
- if (showAllUpcoming) return true; // Show all future dates
- // Otherwise, check specific period
- let specificFutureDate = new Date();
- specificFutureDate.setDate(today.getDate() + numberOfDays);
- specificFutureDate.setHours(0, 0, 0, 0);
- return holidayDate < specificFutureDate; // Include if within the next numberOfDays
- } catch (dateError) {
- // Error parsing date string inside filter
- return false;
- }
- });
- // Prepare arrays to hold the separate data
- let formattedStringsArray = []; // For the main output string "DD.MM.YYYY (Day): Desc"
- let datesOnlyArray = []; // For the dates array "%upcoming_holidays_dates"
- let dayNamesOnlyArray = []; // For the day names array "%upcoming_holidays_daynames"
- let colorsRgbArray = []; // NEW: Array for colors "%upcoming_holidays_colors"
- const englishDaysShort = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; // English day abbreviations
- // Iterate through the filtered holidays to format AND collect data for arrays
- upcomingHolidays.forEach(holiday => {
- let isoDatePart = holiday.date.substring(0, 10); // Expect YYYY-MM-DD format
- let dateParts = isoDatePart.split('-');
- let formattedDate = "Invalid date";
- let weekdayShort = "";
- let actualDayName = "";
- let rgbColor = colorError; // NEW: Start with error color
- if (dateParts.length === 3) {
- // Format as DD.MM.YYYY
- formattedDate = `${dateParts[2]}.${dateParts[1]}.${dateParts[0]}`;
- try {
- // Use the full ISO string (or at least YYYY-MM-DD) for a correct Date object to get the day of the week
- let dateObject = new Date(holiday.date); // Re-parse to safely get Date object properties
- if (!isNaN(dateObject.getTime())) {
- let dayIndex = dateObject.getDay(); // 0=Sunday, 1=Monday, ..., 6=Saturday
- actualDayName = englishDaysShort[dayIndex]; // Get the English day name
- weekdayShort = `(${actualDayName})`; // Format for the main string "(Day)"
- // NEW: Determine color based on day of the week
- if (dayIndex === 0 || dayIndex === 6) { // Sunday or Saturday
- rgbColor = colorRed;
- } else { // Monday to Friday
- rgbColor = colorGreen;
- }
- } else {
- // Handle case where the date string was filterable but Date object creation failed here
- actualDayName = "Invalid";
- weekdayShort = "(Invalid)";
- formattedDate = "Invalid date"; // Correct if Date object became invalid
- rgbColor = colorError; // Set error color
- }
- } catch (dateParseError) {
- // Error during Date object creation or method calls
- actualDayName = "Error";
- weekdayShort = "(Error)";
- formattedDate = "Date error"; // Indicate error in the date part
- rgbColor = colorError; // Set error color
- }
- } else {
- // If the initial date format was wrong (not YYYY-MM-DD...)
- formattedDate = "Bad format"; // Or keep "Invalid date"
- actualDayName = "";
- weekdayShort = "";
- rgbColor = colorError;
- }
- let descriptionPart = holiday.description || "No description";
- // Combine parts for the main formatted string array element
- let finalFormattedStringPart = `${formattedDate} ${weekdayShort}: ${descriptionPart}`;
- // Add to the respective JavaScript arrays
- formattedStringsArray.push(finalFormattedStringPart);
- datesOnlyArray.push(formattedDate); // Add only the date string
- dayNamesOnlyArray.push(actualDayName); // Add only the day name (without parentheses)
- colorsRgbArray.push(rgbColor); // NEW: Add the RGB color string
- });
- // Join the main string array with commas
- let finalFormattedString = formattedStringsArray.join(', ');
- // Save the final formatted string to the Tasker variable %upcoming_holidays_formatted
- setLocal(outputVariableName, finalFormattedString);
- // Save the new arrays as comma-separated strings for Tasker
- // NOTE: Tasker will usually interpret a comma-separated string as an array
- // if the variable name ends with (). Use %var(), e.g., %upcoming_holidays_dates() in Tasker actions.
- setLocal(datesArrayVariableName, datesOnlyArray.join(',')); // Sets %upcoming_holidays_dates
- setLocal(dayNamesArrayVariableName, dayNamesOnlyArray.join(',')); // Sets %upcoming_holidays_daynames
- setLocal(colorsArrayVariableName, colorsRgbArray.join(',')); // NEW: Sets %upcoming_holidays_colors
- setLocal(errorVariableName, ''); // Clear any previous error message if successful
- } catch (error) {
- // --- Handling errors during processing ---
- processingError = `Error during filtering/formatting: ${error.message || error}`;
- setLocal(errorVariableName, processingError); // Set the error variable %filter_format_error
- setLocal(outputVariableName, errorOutputString); // Set the main output to the defined error string
- // Ensure array variables are also empty on processing error
- setLocal(datesArrayVariableName, '');
- setLocal(dayNamesArrayVariableName, '');
- setLocal(colorsArrayVariableName, ''); // NEW: Reset color array on error
- flash(`ERROR: ${processingError}`); // Flash the detailed error
- }
- }
- // No flash on success here
- Auto Exit: On
- Timeout (Seconds): 45 ]
- A12: Arrays Merge [
- Names: %upcoming_holidays_dates, %upcoming_holidays_daynames,
- %upcoming_holidays_colors
- Merge Type: Format
- Format: {
- "children": [
- {
- "color": "%upcoming_holidays_colors",
- "text": "test",
- "type": "Text"
- }
- ],
- "horizontalAlignment": "Center",
- "verticalAlignment": "Center",
- "fillMaxSize": true,
- "type": "Column",
- "useMaterialYouColors": false
- }
- Output: %holidays ]
- A13: Widget v2 [
- Widget Name: Helligdager
- Layout: Custom
- Custom Layout: {
- "children": [
- {
- "children": [
- {
- "bold": true,
- "text": "Norwegian Holidays",
- "textSize": "20",
- "type": "Text"
- },
- {
- "scrolling": true,
- "children": [
- {
- "variableName": "%holidays() ",
- "padding": 10,
- "type": "Placeholder",
- "visibility": "Visible"
- }
- ],
- "size": "fill",
- "type": "Column",
- "visibility": "Visible"
- }
- ],
- "type": "Column"
- }
- ],
- "horizontalAlignment": "Center",
- "verticalAlignment": "Top",
- "backgroundColor": "onError",
- "cornerRadius": 10,
- "fillMaxSize": true,
- "type": "Column",
- "useMaterialYouColors": false,
- "visibility": "Visible"
- }
- Material You Colors: On
- Ask To Add If Not Present: On ]
- A14: Variable Search Replace [
- Variable: %upcoming_holidays_formatted
- Search: ,\s?
- Replace Matches: On
- Replace With: \\n ]
- A15: [X] Widget v2 [
- Widget Name: Helligdager
- Layout: Custom
- Custom Layout: {
- "children": [
- {
- "children": [
- {
- "bold": true,
- "text": "Norwegian Holidays",
- "textSize": "20",
- "type": "Text"
- },
- {
- "scrolling": true,
- "children": [
- {
- "variableName": "%holidays() ",
- "padding": 10,
- "type": "Placeholder",
- "visibility": "Visible"
- }
- ],
- "size": "fill",
- "type": "Column",
- "visibility": "Visible"
- },
- {
- "scrolling": true,
- "children": [
- {
- "text": "%upcoming_holidays_formatted",
- "textSize": "18",
- "size": "fill",
- "type": "Text",
- "visibility": "Visible"
- }
- ],
- "size": "fill",
- "type": "Column",
- "visibility": "Gone"
- }
- ],
- "type": "Row"
- }
- ],
- "horizontalAlignment": "Center",
- "verticalAlignment": "Top",
- "backgroundColor": "onError",
- "cornerRadius": 10,
- "fillMaxSize": true,
- "type": "Column",
- "useMaterialYouColors": false,
- "visibility": "Visible"
- }
- Material You Colors: On
- Ask To Add If Not Present: On ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement