fin-lisp.lisp 11 KB

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