Advertisement
Tiwas_

Untitled

Apr 22nd, 2025
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 22.79 KB | None | 0 0
  1. Task: Gemini_helligdag
  2.  
  3. <Get and set variables>
  4. A1: If [ 1 eq 1 ]
  5.  
  6. A2: Flash [
  7. Text: Updating holidays...
  8. Continue Task Immediately: On
  9. Dismiss On Click: On ]
  10.  
  11. A3: JavaScriptlet [
  12. Code: var year
  13. year = new Date().getFullYear()
  14. Auto Exit: On
  15. Timeout (Seconds): 45 ]
  16.  
  17. A4: Multiple Variables Set [
  18. Names: %next_year=%year+1
  19. %api_base_url=https://webapi.no/api/v1/holidays/
  20. Values Splitter: =
  21. Do Maths: On
  22. Max Rounding Digits: 3
  23. Structure Output (JSON, etc): On ]
  24.  
  25. A5: AutoTools Json Read [
  26. Configuration: Simple Mode: true
  27. Json: %api_base_url%year
  28. Json Root Variable: json_holidays
  29. Separator: ,
  30. Timeout (Seconds): 60
  31. Structure Output (JSON, etc): On
  32. Continue Task After Error:On ]
  33.  
  34. A6: AutoTools Json Read [
  35. Configuration: Simple Mode: true
  36. Json: %api_base_url%next_year
  37. Json Root Variable: json_holidays_next_year
  38. Separator: ,
  39. Timeout (Seconds): 60
  40. Structure Output (JSON, etc): On
  41. Continue Task After Error:On ]
  42.  
  43. A7: If [ %err Set ]
  44.  
  45. A8: Flash [
  46. Text: Error getting dates: %errmsg
  47. Continue Task Immediately: On
  48. Dismiss On Click: On ]
  49.  
  50. A9: Stop [
  51. With Error: On ]
  52.  
  53. A10: End If
  54.  
  55. A11: JavaScriptlet [
  56. Code: /*
  57. * Tasker JavaScriptlet for å behandle (parse, slå sammen, sortere)
  58. * helligdags-JSON hentet via Tasker HTTP Request.
  59. * Forventer at Tasker-variablene %holidays_current og %holidays_next
  60. * inneholder JSON-strenger fra API-et.
  61. */
  62.  
  63. //flash("Starter behandling av helligdager...");
  64.  
  65. let jsonStringCurrent = local('json_holidays');
  66. let jsonStringNext = local('json_holidays_next_year');
  67. let holidays_sorted = []; // For å lagre det ferdige resultatet
  68. let errorMsg = '';
  69.  
  70. // Sjekk om vi faktisk fikk data fra Tasker
  71. if (!jsonStringCurrent || !jsonStringNext) {
  72. errorMsg = "Mangler data fra Tasker (%holidays_current eller %holidays_next er tom).";
  73. flash(errorMsg);
  74. setLocal('holidays_error', errorMsg);
  75. setLocal('holidays_sorted_json', ''); // Tøm resultat
  76. } else {
  77. try {
  78. // 1. Parse JSON-strengene
  79. let dataCurrent = JSON.parse(jsonStringCurrent);
  80. let dataNext = JSON.parse(jsonStringNext);
  81. //flash("JSON parset for begge år.");
  82.  
  83. // 2. Hent ut selve listene (data-arrayene) - bruk || [] for sikkerhet
  84. let arrayCurrent = (dataCurrent && dataCurrent.data) ? dataCurrent.data : [];
  85. let arrayNext = (dataNext && dataNext.data) ? dataNext.data : [];
  86.  
  87. if (!Array.isArray(arrayCurrent) || !Array.isArray(arrayNext)) {
  88. throw new Error("'.data' feltet var ikke en array i en av responsene.");
  89. }
  90. //flash(`Antall før sammenslåing: År 1=${arrayCurrent.length}, År 2=${arrayNext.length}`);
  91.  
  92. // 3. Slå sammen listene
  93. let allHolidays = [...arrayCurrent, ...arrayNext];
  94. //flash(`Totalt antall etter sammenslåing: ${allHolidays.length}`);
  95.  
  96. // 4. Sorter listen etter dato
  97. allHolidays.sort((a, b) => {
  98. // Sikrer at vi har gyldige objekter og datoer før sammenligning
  99. if (a && a.date && b && b.date) {
  100. return a.date.localeCompare(b.date);
  101. } else {
  102. // Hvis data er ugyldig, ikke endre rekkefølgen relativt til hverandre
  103. return 0;
  104. }
  105. });
  106. //flash("Helligdager sortert.");
  107.  
  108. // ---- VIS ET PAR ELEMENTER FOR Å BEKREFTE ----
  109. if (allHolidays.length > 0) {
  110. let firstHoliday = allHolidays[0];
  111. let lastHoliday = allHolidays[allHolidays.length - 1];
  112.  
  113. // Vis første og siste (kun dato YYYY-MM-DD)
  114. //flash(`Første: ${firstHoliday.date.substring(0, 10)} - ${firstHoliday.description}`);
  115. //flash(`Siste: ${lastHoliday.date.substring(0, 10)} - ${lastHoliday.description}`);
  116.  
  117. // Ekstra: Finn en fra neste år for å bekrefte at begge er med
  118. //let nextYearStart = (new Date().getFullYear() + 1).toString(); // Finner neste år som streng
  119. //let holidayInNextYear = allHolidays.find(h => h.date.startsWith(nextYearStart));
  120. //if (holidayInNextYear) {
  121. //flash(`Eksempel neste år: ${holidayInNextYear.date.substring(0, 10)} - ${holidayInNextYear.description}`);
  122. //}
  123.  
  124. } else {
  125. flash("Ingen helligdager funnet etter behandling.");
  126. }
  127.  
  128. // Lagre HELE den sorterte listen som JSON i en Tasker-variabel for evt. senere bruk
  129. holidays_sorted = allHolidays; // Lagre den faktiske arrayen
  130. setLocal('holidays_sorted_json', JSON.stringify(holidays_sorted));
  131. setLocal('holidays_error', ''); // Ingen feil
  132. //flash("Behandling ferdig. Resultat lagret i %holidays_sorted_json.");
  133.  
  134. } catch (error) {
  135. errorMsg = `Feil under behandling: ${error.message || error}`;
  136. flash(errorMsg);
  137. setLocal('holidays_error', errorMsg);
  138. setLocal('holidays_sorted_json', ''); // Tøm resultat
  139. }
  140. }
  141. Auto Exit: On
  142. Timeout (Seconds): 45 ]
  143.  
  144. A12: JavaScriptlet [
  145. Code: /*
  146. * Tasker JavaScriptlet to:
  147. * 1. Read the Tasker variable %num_days to determine the time period.
  148. * 2. Filter a sorted list of holidays (%holidays_sorted_json).
  149. * 3. Format the result as a single comma-separated string with abbreviated weekday:
  150. * "DD.MM.YYYY (Mon): Description, ..." and save in %upcoming_holidays_formatted.
  151. * 4. Create a Tasker array (%upcoming_holidays_dates) with just the dates (DD.MM.YYYY).
  152. * 5. Create a Tasker array (%upcoming_holidays_daynames) with just the abbreviated day names (Mon, Tue, etc.).
  153. * 6. Create a Tasker array (%upcoming_holidays_colors) with RGB color codes ("255,0,0" for weekend, "0,255,0" for weekday).
  154. * 7. If input data (%holidays_sorted_json) is missing/invalid, or an error occurs,
  155. * set %upcoming_holidays_formatted to "No data. Please refresh!",
  156. * and the new array variables are set to empty.
  157. *
  158. * Version with DD.MM.YYYY date format, abbreviated weekday, reads %num_days, special error output,
  159. * and creates separate arrays for dates, day names, and colors.
  160. * Only flashes on error.
  161. */
  162.  
  163. // Define Tasker variable names (these strings MUST match your Tasker variables)
  164. let outputVariableName = 'upcoming_holidays_formatted';
  165. let datesArrayVariableName = 'upcoming_holidays_dates'; // Name for date array
  166. let dayNamesArrayVariableName = 'upcoming_holidays_daynames'; // Name for day name array
  167. let colorsArrayVariableName = 'upcoming_holidays_colors'; // NEW: Name for color array
  168. let errorVariableName = 'filter_format_error';
  169. let errorOutputString = 'No data. Please refresh!'; // Default error text for output
  170.  
  171. // Define colors
  172. const colorRed = "255,0,0"; // RGB for weekend (Saturday/Sunday)
  173. const colorGreen = "0,255,0"; // RGB for weekday (Monday-Friday)
  174. const colorError = ""; // Value for color array on date error
  175.  
  176. // Reset variables before starting
  177. setLocal(outputVariableName, '');
  178. setLocal(datesArrayVariableName, '');
  179. setLocal(dayNamesArrayVariableName, '');
  180. setLocal(colorsArrayVariableName, ''); // NEW: Reset color array
  181. setLocal(errorVariableName, '');
  182.  
  183. // Get input data
  184. let sortedJson = local('holidays_sorted_json'); // Reads Tasker variable %holidays_sorted_json
  185. let processingError = ''; // Internal JS variable for error messages
  186.  
  187. if (!sortedJson) {
  188. // --- Handling missing input ---
  189. processingError = "Error: Could not find sorted list in %holidays_sorted_json.";
  190. setLocal(errorVariableName, processingError);
  191. setLocal(outputVariableName, errorOutputString);
  192. // Ensure array variables are also empty on error
  193. setLocal(datesArrayVariableName, '');
  194. setLocal(dayNamesArrayVariableName, '');
  195. setLocal(colorsArrayVariableName, ''); // NEW: Reset color array on error
  196. flash(processingError); // Flash the specific error cause
  197. } else {
  198. // --- Try processing data ---
  199. try {
  200. // Parse the JSON string
  201. let sortedHolidays = JSON.parse(sortedJson);
  202.  
  203. if (!Array.isArray(sortedHolidays)) {
  204. throw new Error("The content of %holidays_sorted_json is not a valid list (array).");
  205. }
  206.  
  207. // Define the time frame
  208. let today = new Date();
  209. today.setHours(0, 0, 0, 0);
  210.  
  211. // Read and interpret %num_days
  212. let numDaysString = local('num_days'); // Reads Tasker variable %num_days
  213. let numberOfDays = parseInt(numDaysString, 10);
  214. // Show all if %num_days is not a positive number or is 'n/a'
  215. let showAllUpcoming = isNaN(numberOfDays) || numberOfDays <= 0 || numDaysString === 'n/a';
  216.  
  217. // Filter the list based on %num_days
  218. let upcomingHolidays = sortedHolidays.filter(holiday => {
  219. if (!holiday || !holiday.date) return false;
  220. try {
  221. // Ensure date is valid and in the future (or today)
  222. let holidayDate = new Date(holiday.date);
  223. if (isNaN(holidayDate.getTime())) return false; // Invalid date format
  224. if (holidayDate < today) return false; // Always exclude past dates
  225.  
  226. // Decide whether to include based on %num_days
  227. if (showAllUpcoming) return true; // Show all future dates
  228.  
  229. // Otherwise, check specific period
  230. let specificFutureDate = new Date();
  231. specificFutureDate.setDate(today.getDate() + numberOfDays);
  232. specificFutureDate.setHours(0, 0, 0, 0);
  233. return holidayDate < specificFutureDate; // Include if within the next numberOfDays
  234. } catch (dateError) {
  235. // Error parsing date string inside filter
  236. return false;
  237. }
  238. });
  239.  
  240. // Prepare arrays to hold the separate data
  241. let formattedStringsArray = []; // For the main output string "DD.MM.YYYY (Day): Desc"
  242. let datesOnlyArray = []; // For the dates array "%upcoming_holidays_dates"
  243. let dayNamesOnlyArray = []; // For the day names array "%upcoming_holidays_daynames"
  244. let colorsRgbArray = []; // NEW: Array for colors "%upcoming_holidays_colors"
  245. const englishDaysShort = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; // English day abbreviations
  246.  
  247. // Iterate through the filtered holidays to format AND collect data for arrays
  248. upcomingHolidays.forEach(holiday => {
  249. let isoDatePart = holiday.date.substring(0, 10); // Expect YYYY-MM-DD format
  250. let dateParts = isoDatePart.split('-');
  251. let formattedDate = "Invalid date";
  252. let weekdayShort = "";
  253. let actualDayName = "";
  254. let rgbColor = colorError; // NEW: Start with error color
  255.  
  256. if (dateParts.length === 3) {
  257. // Format as DD.MM.YYYY
  258. formattedDate = `${dateParts[2]}.${dateParts[1]}.${dateParts[0]}`;
  259. try {
  260. // Use the full ISO string (or at least YYYY-MM-DD) for a correct Date object to get the day of the week
  261. let dateObject = new Date(holiday.date); // Re-parse to safely get Date object properties
  262. if (!isNaN(dateObject.getTime())) {
  263. let dayIndex = dateObject.getDay(); // 0=Sunday, 1=Monday, ..., 6=Saturday
  264. actualDayName = englishDaysShort[dayIndex]; // Get the English day name
  265. weekdayShort = `(${actualDayName})`; // Format for the main string "(Day)"
  266.  
  267. // NEW: Determine color based on day of the week
  268. if (dayIndex === 0 || dayIndex === 6) { // Sunday or Saturday
  269. rgbColor = colorRed;
  270. } else { // Monday to Friday
  271. rgbColor = colorGreen;
  272. }
  273. } else {
  274. // Handle case where the date string was filterable but Date object creation failed here
  275. actualDayName = "Invalid";
  276. weekdayShort = "(Invalid)";
  277. formattedDate = "Invalid date"; // Correct if Date object became invalid
  278. rgbColor = colorError; // Set error color
  279. }
  280. } catch (dateParseError) {
  281. // Error during Date object creation or method calls
  282. actualDayName = "Error";
  283. weekdayShort = "(Error)";
  284. formattedDate = "Date error"; // Indicate error in the date part
  285. rgbColor = colorError; // Set error color
  286. }
  287. } else {
  288. // If the initial date format was wrong (not YYYY-MM-DD...)
  289. formattedDate = "Bad format"; // Or keep "Invalid date"
  290. actualDayName = "";
  291. weekdayShort = "";
  292. rgbColor = colorError;
  293. }
  294.  
  295. let descriptionPart = holiday.description || "No description";
  296. // Combine parts for the main formatted string array element
  297. let finalFormattedStringPart = `${formattedDate} ${weekdayShort}: ${descriptionPart}`;
  298.  
  299. // Add to the respective JavaScript arrays
  300. formattedStringsArray.push(finalFormattedStringPart);
  301. datesOnlyArray.push(formattedDate); // Add only the date string
  302. dayNamesOnlyArray.push(actualDayName); // Add only the day name (without parentheses)
  303. colorsRgbArray.push(rgbColor); // NEW: Add the RGB color string
  304. });
  305.  
  306. // Join the main string array with commas
  307. let finalFormattedString = formattedStringsArray.join(', ');
  308.  
  309. // Save the final formatted string to the Tasker variable %upcoming_holidays_formatted
  310. setLocal(outputVariableName, finalFormattedString);
  311.  
  312. // Save the new arrays as comma-separated strings for Tasker
  313. // NOTE: Tasker will usually interpret a comma-separated string as an array
  314. // if the variable name ends with (). Use %var(), e.g., %upcoming_holidays_dates() in Tasker actions.
  315. setLocal(datesArrayVariableName, datesOnlyArray.join('=-=')); // Sets %upcoming_holidays_dates
  316. setLocal(dayNamesArrayVariableName, dayNamesOnlyArray.join('=-=')); // Sets %upcoming_holidays_daynames
  317. setLocal(colorsArrayVariableName, colorsRgbArray.join('=-=')); // NEW: Sets %upcoming_holidays_colors
  318.  
  319. setLocal(errorVariableName, ''); // Clear any previous error message if successful
  320.  
  321. } catch (error) {
  322. // --- Handling errors during processing ---
  323. processingError = `Error during filtering/formatting: ${error.message || error}`;
  324. setLocal(errorVariableName, processingError); // Set the error variable %filter_format_error
  325. setLocal(outputVariableName, errorOutputString); // Set the main output to the defined error string
  326. // Ensure array variables are also empty on processing error
  327. setLocal(datesArrayVariableName, '');
  328. setLocal(dayNamesArrayVariableName, '');
  329. setLocal(colorsArrayVariableName, ''); // NEW: Reset color array on error
  330. flash(`ERROR: ${processingError}`); // Flash the detailed error
  331. }
  332. }
  333. // No flash on success here
  334. Auto Exit: On
  335. Timeout (Seconds): 45 ]
  336.  
  337. A13: Variable Split [
  338. Name: %upcoming_holidays_dates
  339. Splitter: =-= ]
  340.  
  341. A14: Variable Split [
  342. Name: %upcoming_holidays_daynames
  343. Splitter: =-= ]
  344.  
  345. A15: Variable Split [
  346. Name: %upcoming_holidays_colors
  347. Splitter: =-= ]
  348.  
  349. A16: End If
  350.  
  351. A17: Arrays Merge [
  352. Names: %upcoming_holidays_dates
  353. %upcoming_holidays_daynames
  354. %upcoming_holidays_colors
  355. Merge Type: Format
  356. Format: {
  357. "children": [
  358. {
  359. "color": "%upcoming_holidays_colors",
  360. "text": "%upcoming_holidays_dates %upcoming_holidays_daynames",
  361. "type": "Text"
  362. }
  363. ],
  364. "horizontalAlignment": "Center",
  365. "verticalAlignment": "Center",
  366. "fillMaxSize": true,
  367. "type": "Column",
  368. "useMaterialYouColors": false
  369. }
  370. Output: %holidays ]
  371.  
  372. A18: Widget v2 [
  373. Widget Name: Helligdager
  374. Layout: Custom
  375. Custom Layout: {
  376. "children": [
  377. {
  378. "align": "Center",
  379. "bold": true,
  380. "text": "Norwegian Holidays",
  381. "textSize": "20",
  382. "size": {
  383. "fillMaxWidth": true
  384. },
  385. "type": "Text"
  386. },
  387. {
  388. "scrolling": true,
  389. "children": [
  390. {
  391. "variableName": "%holidays()",
  392. "padding": 10,
  393. "type": "Placeholder",
  394. "visibility": "Visible"
  395. }
  396. ],
  397. "size": "fill",
  398. "type": "Column",
  399. "visibility": "Visible"
  400. }
  401. ],
  402. "horizontalAlignment": "Center",
  403. "verticalAlignment": "Top",
  404. "backgroundColor": "Grey",
  405. "cornerRadius": 10,
  406. "fillMaxSize": true,
  407. "task": "Gemini_helligdag",
  408. "type": "Column",
  409. "useMaterialYouColors": false,
  410. "visibility": "Visible"
  411. }
  412. Material You Colors: On
  413. Ask To Add If Not Present: On ]
  414.  
  415. A19: [X] Variable Search Replace [
  416. Variable: %upcoming_holidays_formatted
  417. Search: ,\s?
  418. Replace Matches: On
  419. Replace With: \\n ]
  420.  
  421. A20: [X] Widget v2 [
  422. Widget Name: Helligdager
  423. Layout: Custom
  424. Custom Layout: {
  425. "children": [
  426. {
  427. "children": [
  428. {
  429. "bold": true,
  430. "text": "Norwegian Holidays",
  431. "textSize": "20",
  432. "type": "Text"
  433. },
  434. {
  435. "scrolling": true,
  436. "children": [
  437. {
  438. "variableName": "%holidays() ",
  439. "padding": 10,
  440. "type": "Placeholder",
  441. "visibility": "Visible"
  442. }
  443. ],
  444. "size": "fill",
  445. "type": "Column",
  446. "visibility": "Visible"
  447. },
  448. {
  449. "scrolling": true,
  450. "children": [
  451. {
  452. "text": "%upcoming_holidays_formatted",
  453. "textSize": "18",
  454. "size": "fill",
  455. "type": "Text",
  456. "visibility": "Visible"
  457. }
  458. ],
  459. "size": "fill",
  460. "type": "Column",
  461. "visibility": "Gone"
  462. }
  463. ],
  464. "type": "Row"
  465. }
  466. ],
  467. "horizontalAlignment": "Center",
  468. "verticalAlignment": "Top",
  469. "backgroundColor": "onError",
  470. "cornerRadius": 10,
  471. "fillMaxSize": true,
  472. "type": "Column",
  473. "useMaterialYouColors": false,
  474. "visibility": "Visible"
  475. }
  476. Material You Colors: On
  477. Ask To Add If Not Present: On ]
  478.  
  479.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement