Applescript(7)

Recientemente escribí un par de entradas (una, otra) de la solución que me he hecho usando AppleScript (pese a que no he dado mayores detalles de ésta) en un aspecto del manejo de mis pendientes. El script y sus pormenores decidí mejor dejarlos para esta entrada en la serie dedicada a este lenguaje de scripting.

use scripting additions

use theParser : script "Parsing"
use theTyper : script "Types"
use theConstants : script "Constants"
use TheFormatter : script "Formatting"

set theList to "Endeavours"
tell (current date) to tell it + (32 - (its day)) * days to ¬
	set lastDayOfThisMonth to (it - (its day) * days)'s day
set theDate to current date
set day of theDate to lastDayOfThisMonth
set time of theDate to 23 * hours + 59 * minutes

set theCosts to ""
set newLine to theConstants's NEW_LINE
set theWidth to 20
set theTotal to 0
set theRate to 20


if theList is not false then
	
	tell application "Reminders"
		
		activate
		
		set theReminders to every reminder whose completed is false and ¬
			(name of container is theList) and (due date < theDate)
		repeat with everyReminder in theReminders
			set theActivity to name of everyReminder
			set theNotes to body of everyReminder
			
			set theAmount to 0
			set theCurrency to ""
			
			if theNotes is not missing value then
				set theTokens to theParser's getTokens((body of everyReminder) as string, space)
				if not theTyper's isEmpty(theTokens) then
					set theAmount to the first item of theTokens
					if length of theTokens is greater than 1 then
						set theCurrency to the second item of theTokens
						if theCurrency is in theConstants's CURRENCIES then
							if length of theActivity is greater than theWidth then
								set theLine to text 1 thru theWidth of theActivity & "..." & ¬
									TheFormatter's Repeating(tab, 2)
							else
								set theLine to theActivity & TheFormatter's Repeating(tab, 6)
							end if
							set theLine to theLine & theAmount & space & theCurrency & newLine
							set theCosts to theCosts & theLine
							if theCurrency is "USD" then
								set theTotal to theTotal + ((text 2 thru (the end of theAmount) of theAmount) as number) * theRate
							else
								set theTotal to theTotal + (text 2 thru (the end of theAmount) of theAmount) as number
								
							end if
						end if
					end if
				end if
			end if
		end repeat
		
		set theCosts to theCosts & TheFormatter's Repeating(newLine, 2) & ¬
			"Total: $" & theTotal & " MXN"
		
		display dialog theCosts
		
	end tell
end if

tell application "Reminders" to if it is running then quit

Independientemente del aprendizaje en el scripting sobre la aplicación Reminders, el desarrollo del script me llevó a aprender y observar varias cosas. Aquí las enumero y describo colocando entre paréntesis el número o rango de líneas acorde a la numeración que presenta el widget que muestra el código.

  1. (1) Un error extraño apareció durante el desarrollo. Un mensaje de error desconociendo la palabra dialog. Según averigüe1, se debia a que en su versión 2, AppleScript ya no inlcuye por defecto cierta funcionalidad, entre ellas display dialog. El error se corrigió incluyendo explícitamente las Scripting additions.
  2. (3-6) Según la documentación sobre AppleScript, la creación de bibliotecas no es muy diferente a crear cualquier script, pero hay algunos puntos obscuros en esto. ALgunas cosas que logré aclarar es el que la ruta donde deben estar las bibliotecas es ~/Library/Script Libraries y se cargan mediante la instrucción

    use alias : script "nombre-sin-extensión"
  3. (8) La lista de pendientes a usar se establece.
  4. (9-13) La determinación del fin de mes (día y hora) mediante algo de artimética de fechas.
  5. (15-19) Variables de trabajo.
  6. (28-29) Lista filtrada de recordatorios de la lista de recordatosio seleccionada (punto 3).
  7. (31-32) Para cada elemento en la lista de pendientes, se obtiene su título y notas.
  8. (37-61) Para cada nota se separan sus elementos (tokens) a fin de identificar números y claves de moneda. Se espera que el primer y segundo token en el campo de notas sean la cantidad monetaria y moneda que describe la cantidad a pagar o gastar para dicho recordatorio. Aquellos recordatorios que tengas notas así, son agregados y el costo asociado acumulado.
  9. (64-65) Terminados de procesar todos los recordartorios, se imprimen (con lo que AppleScript permite) la lista de pendientes que implican un gasto y su total en pesos.
  10. (72) Se cierra la aplicación Reminders.

Bien, ahora algunas observaciones interesantes

  • La instrucción activate de la linea 26 puede omitirse pero el script tarda tres veces más en correr. Y lo mismo pasa si dicha instrucción se moviera antes de la línea 67. Es decir, si la aplicación no está activa el script corre pero la prioridad de atención (o la velocidad de respuesta) se reduce significativamente.
  • La verdad es confusa y pobre la documentación sobre la creación de bibliotecas en AppleScript. Uno debe consultar varias fuentes y hacer varias pruebas para entender como funciona el asunto e ir conociendo los errores cuando algo está mal.

Pese a todo lo anterior, AppleScript es una buena herramienta que vale conocer,

Referencias

  1. «Expected end of line but found identifier«, stackoverflow.com, web forum, Asked: 2017.06.16; answered: 2018.09.09. URL: https://stackoverflow.com/questions/44587459/expected-end-of-line-but-found-identifier.

Siguiente

Deja un comentario

Este sitio utiliza Akismet para reducir el spam. Conoce cómo se procesan los datos de tus comentarios.