fin-lisp.lisp 12 KB

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