fin-lisp.lisp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. ;;;(ql:quickload "cl-store")
  2. (ql:quickload "yason")
  3. (ql:quickload "cl-ppcre")
  4. (ql:quickload "unix-opts")
  5. (ql:quickload "ironclad")
  6. (ql:quickload "dexador")
  7. ;;; Features
  8. ;;; - Import records from old .txt format
  9. ;;; - Removed as I'll never use it again
  10. ;;; - Added in again to retest some things
  11. ;;; - Interactive prompt to manage expenses
  12. ;;; - Generic expense handling
  13. ;;; - Encryption/decryption of old records
  14. ;;; - Upload/download support like perl version
  15. ;;; TODO
  16. ;;; - Non interactive CLI Interface
  17. ;;;; Reimplementation of my bills tracker in Lisp
  18. ;;; All records exist in this data structure
  19. ;;; nil on start and loaded in from file
  20. ;;; *records* represents as hash of months,
  21. ;;; where the key is the month stamp, eg 20210701
  22. ;;; and the value is the monthly expenses hash
  23. (defvar *records* (make-hash-table :test 'equalp))
  24. (defvar *api-config-path* "./auth.json")
  25. (defvar *api-url* NIL)
  26. (defvar *api-key* NIL)
  27. ;;; Used for input checking (mostly)
  28. (defvar *old-month-line-regex* (ppcre:create-scanner "^([A-Z][a-z]{1,})[0-9]{4}$"))
  29. (defvar *old-exp-line-regex* (ppcre:create-scanner "^([A-Z].*)\ -\ \\\$([0-9]{1,4}) - PAID"))
  30. (defvar *new-month-line-regex* (ppcre:create-scanner "20[0-9]{4}"))
  31. ;;; Taken from: https://gist.github.com/WetHat/a49e6f2140b401a190d45d31e052af8f
  32. ;;; Used for pretty printing output
  33. (defconstant +CELL-FORMATS+ '(:left "~vA"
  34. :center "~v:@<~A~>"
  35. :right "~v@A"))
  36. (defun format-table (stream data &key (column-label (loop for i from 1 to (length (car data))
  37. collect (format nil "COL~D" i)))
  38. (column-align (loop for i from 1 to (length (car data))
  39. collect :left)))
  40. (let* ((col-count (length column-label))
  41. (strtable (cons column-label ; table header
  42. (loop for row in data ; table body with all cells as strings
  43. collect (loop for cell in row
  44. collect (if (stringp cell)
  45. cell
  46. ;else
  47. (format nil "~A" cell))))))
  48. (col-widths (loop with widths = (make-array col-count :initial-element 0)
  49. for row in strtable
  50. do (loop for cell in row
  51. for i from 0
  52. do (setf (aref widths i)
  53. (max (aref widths i) (length cell))))
  54. finally (return widths))))
  55. ;------------------------------------------------------------------------------------
  56. ; splice in the header separator
  57. (setq strtable
  58. (nconc (list (car strtable) ; table header
  59. (loop for align in column-align ; generate separator
  60. for width across col-widths
  61. collect (case align
  62. (:left (format nil ":~v@{~A~:*~}"
  63. (1- width) "-"))
  64. (:right (format nil "~v@{~A~:*~}:"
  65. (1- width) "-"))
  66. (:center (format nil ":~v@{~A~:*~}:"
  67. (- width 2) "-")))))
  68. (cdr strtable))) ; table body
  69. ;------------------------------------------------------------------------------------
  70. ; Generate the formatted table
  71. (let ((row-fmt (format nil "| ~{~A~^ | ~} |~~%" ; compile the row format
  72. (loop for align in column-align
  73. collect (getf +CELL-FORMATS+ align))))
  74. (widths (loop for w across col-widths collect w)))
  75. ; write each line to the given stream
  76. (dolist (row strtable)
  77. (apply #'format stream row-fmt (mapcan #'list widths row))))))
  78. ;;; Used by "print-month" arg to validate
  79. ;;; the user provided a valid key
  80. (defun check-month (month-key)
  81. (if (stringp month-key) month-key
  82. (return-from check-month NIL))
  83. (if (ppcre:scan *old-month-line-regex* month-key) month-key
  84. (if (ppcre:scan *new-month-line-regex* month-key) month-key
  85. (return-from check-month NIL))))
  86. (opts:define-opts
  87. (:name :help
  88. :description "Print help text"
  89. :short #\h
  90. :long "help")
  91. (:name :print-month
  92. :description "Print records for given month. Must conform to either MonthYear or YYYYMM semantics."
  93. :short #\p
  94. :long "print-month"
  95. :arg-parser #'check-month)
  96. (:name :interactive-mode
  97. :description "Run in interactive mode"
  98. :short #\i
  99. :long "interactive"))
  100. ;; See: https://github.com/libre-man/unix-opts/blob/master/example/example.lisp
  101. (defmacro when-option ((options opt) &body body)
  102. `(let ((it (getf ,options ,opt)))
  103. (when it
  104. ,@body)))
  105. (defun reload ()
  106. (load "~/Repos/fin-lisp/fin-lisp.lisp"))
  107. (defun parse-api-config (path)
  108. (let ((api-config-hash (yason:parse (uiop:read-file-string path)))
  109. (ret-tuple '())) ; I think this probably can be done in the let binding
  110. (push (gethash "token" api-config-hash) ret-tuple)
  111. (push (gethash "url" api-config-hash) ret-tuple)
  112. ret-tuple))
  113. ;;;;;;;;;;;;;;;;;;;;;;;;
  114. ;;; Encryption stuff ;;;
  115. ;;;;;;;;;;;;;;;;;;;;;;;;
  116. ;;; See: https://www.cliki.net/Ironclad
  117. ;;; Return cipher when provided key
  118. ;;; Currently, this is 'insecure' as we are using a string
  119. ;;; coerced into a byte array as the key, aka a non-random secret.
  120. ;;; Should use twofish
  121. (defun get-cipher (key)
  122. (ironclad:make-cipher
  123. :blowfish
  124. :mode :ecb
  125. :key (ironclad:ascii-string-to-byte-array key)))
  126. (defun encrypt-records (key)
  127. (let* ((cipher (get-cipher key))
  128. (content (ironclad:ascii-string-to-byte-array (with-output-to-string (json)
  129. (yason:encode *records* json)))))
  130. (ironclad:encrypt-in-place cipher content)
  131. (write-to-string (ironclad:octets-to-integer content))))
  132. (defun decrypt-records (key enc-record-string)
  133. (let ((cipher (get-cipher key)))
  134. (let ((content (ironclad:integer-to-octets (parse-integer enc-record-string))))
  135. (ironclad:decrypt-in-place cipher content)
  136. (coerce (mapcar #'code-char (coerce content 'list)) 'string))))
  137. (defun download-records ()
  138. (let* ((api-config (parse-api-config *api-config-path*))
  139. (dl-records (yason:parse (dex:get (concatenate 'string (first api-config) "download")
  140. :headers (list (cons "X-Token" (second api-config)))))))
  141. dl-records))
  142. (defun upload-records (enc-records-string)
  143. (let* ((api-config (parse-api-config *api-config-path*))
  144. (result (dex:post (concatenate 'string (first api-config) "upload")
  145. :headers (list (cons "X-Token" (second api-config))
  146. (cons "Content-Type" "application/json"))
  147. :content (concatenate 'string "{\"content\": \"" enc-records-string "\"}"))))
  148. result))
  149. ;;; Serialization and communicating with the web API
  150. (defun push-records (key)
  151. "Upload records to remote server"
  152. (upload-records (encrypt-records key)))
  153. (defun get-records (key)
  154. "Get records from remote server"
  155. (setf *records* (yason:parse (decrypt-records key (gethash "content" (download-records))))))
  156. ;; Called like: (add-month '202107)
  157. (defun add-month (month-key)
  158. (if (check-month month-key)
  159. (setf (gethash month-key *records*) (make-hash-table :test 'equalp))
  160. (return-from add-month NIL)))
  161. ;;; Taken from practical common lisp
  162. (defun prompt-read (prompt)
  163. (format *query-io* "~a: " prompt)
  164. (force-output *query-io*)
  165. (read-line *query-io*))
  166. (defun prompt-for-expense ()
  167. (list
  168. (prompt-read "Enter expense name")
  169. (parse-integer
  170. (prompt-read "Enter expense value"))))
  171. (defun add-expense-to-month (month)
  172. (if (gethash month *records*)
  173. (let ((innerhash (gethash month *records*))
  174. (exp-l (prompt-for-expense)))
  175. (setf (gethash (first exp-l) innerhash) (second exp-l)))
  176. (add-expense-to-month (add-month month))))
  177. ;;; Given key for *records* hash,
  178. ;;; print expenses/values for month
  179. (defun dump-month (month-key)
  180. (let ((month-hash)
  181. (exp-keys))
  182. (setf month-hash (gethash month-key *records*))
  183. (setf exp-keys (loop for key being the hash-keys of month-hash collect key))
  184. (format t "~C" #\linefeed)
  185. (format t "~a~C" month-key #\linefeed)
  186. (dolist (exp-key exp-keys)
  187. (format t "~a : ~a~C" exp-key (gethash exp-key month-hash) #\linefeed))
  188. (format t "~C" #\linefeed)))
  189. ;;; Given key for *records* hash,
  190. ;;; print expenses/values for month
  191. (defun dump-month-table (month-key)
  192. (let* ((month-hash (gethash month-key *records*))
  193. (exp-keys (loop for key being the hash-keys of month-hash collect key))
  194. (flist))
  195. (dolist (exp-key exp-keys)
  196. (setq flist (append flist (list (list exp-key (gethash exp-key month-hash))))))
  197. (format-table T flist :column-label '("Expense" "Amount"))))
  198. ;;; Dump all records.
  199. (defun dump-records ()
  200. (let ((record-key-list (loop for key being the hash-keys of *records* collect key)))
  201. (dolist (month-key record-key-list) (dump-month month-key))))
  202. (defmacro generic-handler (form error-string)
  203. `(handler-case ,form
  204. (error (e)
  205. (format t "Invalid input: ~a ~%" ,error-string)
  206. (values 0 e))))
  207. ;; Util screen clearer
  208. (defun cls()
  209. (format t "~A[H~@*~A[J" #\escape))
  210. (defun interactive-mode ()
  211. (format t "~%")
  212. (format t "Available options:~%")
  213. (format t "1. Enter expense~%")
  214. (format t "2. Display month~%")
  215. (format t "3. Push records~%")
  216. (format t "4. Get records~%")
  217. (format t "5. Quit~%")
  218. (let
  219. ((answer (prompt-read "Select an option")))
  220. (if (string= answer "1")
  221. (generic-handler
  222. (add-expense-to-month (prompt-read "Enter month"))
  223. "Invalid Input"))
  224. (if (string= answer "2")
  225. (generic-handler
  226. (dump-month-table (prompt-read "Enter month"))
  227. "Invalid month"))
  228. (if (string= answer "3")
  229. (generic-handler
  230. (push-records (prompt-read "Enter encryption key"))
  231. "Serialization error or invalid filename"))
  232. (if (string= answer "4")
  233. (generic-handler
  234. (get-records (prompt-read "Enter decryption key"))
  235. "Deserialization error or invalid filename"))
  236. (if (string= answer "5")
  237. (return-from interactive-mode nil)))
  238. (interactive-mode))
  239. (defun display-help ()
  240. (format t "foo ~%")
  241. (opts:describe
  242. :prefix "fin-lisp.lisp - Basic expense tracker in lisp"
  243. :usage-of "fin-lisp.lisp"
  244. :args "[FREE-ARGS]")
  245. (quit))
  246. ;; Entry point
  247. (defun main ()
  248. (if (= 1 (length sb-ext:*posix-argv*)) (interactive-mode))
  249. (let ((matches (opts:get-opts)))
  250. (format t "~a ~%" matches)
  251. (when-option (matches :help)
  252. (display-help))
  253. (when-option (matches :print-month)
  254. (let ((key (prompt-read "Enter decryption key: "))
  255. (month-key (destructuring-bind (&key print-month) matches
  256. print-month)))
  257. (get-records key)
  258. (dump-month-table month-key)))
  259. (when-option (matches :interactive-mode)
  260. (progn
  261. (interactive-mode)
  262. (quit)))))
  263. ;;; Can only be called from the REPL,
  264. ;;; used for importing according to the old schema
  265. (defun import-records (filename)
  266. (let ((old-file-lines
  267. (with-open-file (stream filename)
  268. (loop for line = (read-line stream nil)
  269. while line
  270. collect line)))
  271. (cur-mon)
  272. (cur-exp))
  273. (loop for line in old-file-lines
  274. do (progn
  275. (if (ppcre:scan *old-month-line-regex* line) (setf cur-mon line))
  276. (if (ppcre:scan *old-exp-line-regex* line)
  277. (progn
  278. (setf cur-exp (ppcre:register-groups-bind (first second) (*old-exp-line-regex* line) :sharedp t (list first second)))
  279. (print cur-exp)
  280. (if (gethash cur-mon *records*)
  281. (let ((innerhash (gethash cur-mon *records*)))
  282. (setf (gethash (first cur-exp) innerhash) (second cur-exp))))
  283. (if (not (gethash cur-mon *records*))
  284. (progn
  285. (add-month cur-mon)
  286. (let ((innerhash (gethash cur-mon *records*)))
  287. (setf (gethash (first cur-exp) innerhash) (second cur-exp)))))))))))
  288. (defun reset-records ()
  289. "Used for debugging, just resets the *records* hash to NIL"
  290. (setf *records* (make-hash-table :test 'equal)))