Advertisement
Tiwas_

Widget 1

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