fin-lisp.lisp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. ;; Called like: (add-month '202107)
  76. (defun add-month (month-key)
  77. (if (check-month month-key)
  78. (if (not (gethash month-key *records*))
  79. (progn
  80. (setf (gethash month-key *records*)
  81. (make-hash-table :test 'equalp))
  82. month-key))))
  83. (defun add-expense-to-month (expense value month)
  84. (if (gethash month *records*)
  85. (setf (gethash expense (gethash month *records*)) value)
  86. (progn
  87. (print (concatenate 'string "Adding" month))
  88. (if (add-month month)
  89. (setf (gethash expense (gethash month *records*)) value)
  90. (print (concatenate 'string "Failed to add" month))))))
  91. (opts:define-opts
  92. (:name :help
  93. :description "Print help text"
  94. :short #\h
  95. :long "help")
  96. (:name :print-month
  97. :description "Print records for given month. Must conform to either MonthYear or YYYYMM semantics."
  98. :short #\p
  99. :long "print-month"
  100. :arg-parser #'check-month)
  101. (:name :add-expense
  102. :description "Non interactive interface for recording an expense. Expects expense name as an argument, and requires -v|--value and -m|month"
  103. :short #\e
  104. :long "add-expense"
  105. :arg-parser #'identity)
  106. (:name :value
  107. :description "Used with -e|--add-expense. Must be an integer."
  108. :short #\v
  109. :long "value"
  110. :arg-parser #'parse-integer)
  111. (:name :month
  112. :description "Used with -e|--add-expense. Must be a valid month key."
  113. :short #\m
  114. :long "month"
  115. :arg-parser #'check-month)
  116. (:name :interactive-mode
  117. :description "Run in interactive mode"
  118. :short #\i
  119. :long "interactive"))
  120. ;; See: https://github.com/libre-man/unix-opts/blob/master/example/example.lisp
  121. (defmacro when-option ((options opt) &body body)
  122. `(let ((it (getf ,options ,opt)))
  123. (when it
  124. ,@body)))
  125. (defun reload ()
  126. (load "~/Repos/fin-lisp/fin-lisp.lisp"))
  127. (defun parse-api-config (path)
  128. (let ((api-config-hash (yason:parse (uiop:read-file-string path)))
  129. (ret-tuple '())) ; I think this probably can be done in the let binding
  130. (push (gethash "token" api-config-hash) ret-tuple)
  131. (push (gethash "url" api-config-hash) ret-tuple)
  132. ret-tuple))
  133. ;;;;;;;;;;;;;;;;;;;;;;;;
  134. ;;; Encryption stuff ;;;
  135. ;;;;;;;;;;;;;;;;;;;;;;;;
  136. ;;; See: https://www.cliki.net/Ironclad
  137. ;;; Return cipher when provided key
  138. ;;; Currently, this is 'insecure' as we are using a string
  139. ;;; coerced into a byte array as the key, aka a non-random secret.
  140. ;;; Should use twofish
  141. (defun get-cipher (key)
  142. (ironclad:make-cipher
  143. :blowfish
  144. :mode :ecb
  145. :key (ironclad:ascii-string-to-byte-array key)))
  146. (defun encrypt-records (key)
  147. (let* ((cipher (get-cipher key))
  148. (content (ironclad:ascii-string-to-byte-array (with-output-to-string (json)
  149. (yason:encode *records* json)))))
  150. (ironclad:encrypt-in-place cipher content)
  151. (write-to-string (ironclad:octets-to-integer content))))
  152. (defun decrypt-records (key enc-record-string)
  153. (let ((cipher (get-cipher key)))
  154. (let ((content (ironclad:integer-to-octets (parse-integer enc-record-string))))
  155. (ironclad:decrypt-in-place cipher content)
  156. (coerce (mapcar #'code-char (coerce content 'list)) 'string))))
  157. (defun download-records ()
  158. (let* ((api-config (parse-api-config *api-config-path*))
  159. (dl-records (yason:parse (dex:get (concatenate 'string (first api-config) "download")
  160. :headers (list (cons "X-Token" (second api-config)))))))
  161. dl-records))
  162. (defun upload-records (enc-records-string)
  163. (let* ((api-config (parse-api-config *api-config-path*))
  164. (result (dex:post (concatenate 'string (first api-config) "upload")
  165. :headers (list (cons "X-Token" (second api-config))
  166. (cons "Content-Type" "application/json"))
  167. :content (concatenate 'string "{\"content\": \"" enc-records-string "\"}"))))
  168. result))
  169. ;;; Serialization and communicating with the web API
  170. (defun push-records (key)
  171. "Upload records to remote server"
  172. (upload-records (encrypt-records key)))
  173. (defun get-records (key)
  174. "Get records from remote server"
  175. (setf *records* (yason:parse (decrypt-records key (gethash "content" (download-records))))))
  176. ;;; Taken from practical common lisp
  177. (defun prompt-read (prompt)
  178. (format *query-io* "~a: " prompt)
  179. (force-output *query-io*)
  180. (read-line *query-io*))
  181. (defun prompt-for-expense ()
  182. (list
  183. (prompt-read "Enter expense name")
  184. (parse-integer
  185. (prompt-read "Enter expense value"))))
  186. ;;; Given key for *records* hash,
  187. ;;; print expenses/values for month
  188. (defun dump-month (month-key)
  189. (let ((month-hash)
  190. (exp-keys))
  191. (setf month-hash (gethash month-key *records*))
  192. (setf exp-keys (loop for key being the hash-keys of month-hash collect key))
  193. (format t "~C" #\linefeed)
  194. (format t "~a~C" month-key #\linefeed)
  195. (dolist (exp-key exp-keys)
  196. (format t "~a : ~a~C" exp-key (gethash exp-key month-hash) #\linefeed))
  197. (format t "~C" #\linefeed)))
  198. ;;; Given key for *records* hash,
  199. ;;; print expenses/values for month
  200. (defun dump-month-table (month-key)
  201. (let* ((month-hash (gethash month-key *records*))
  202. (exp-keys (loop for key being the hash-keys of month-hash collect key))
  203. (flist))
  204. (dolist (exp-key exp-keys)
  205. (setq flist (append flist (list (list exp-key (gethash exp-key month-hash))))))
  206. (format-table T flist :column-label '("Expense" "Amount"))))
  207. ;;; Dump all records.
  208. (defun dump-records ()
  209. (let ((record-key-list (loop for key being the hash-keys of *records* collect key)))
  210. (dolist (month-key record-key-list) (dump-month month-key))))
  211. (defmacro generic-handler (form error-string)
  212. `(handler-case ,form
  213. (error (e)
  214. (format t "Invalid input: ~a ~%" ,error-string)
  215. (values 0 e))))
  216. ;; Util screen clearer
  217. (defun cls()
  218. (format t "~A[H~@*~A[J" #\escape))
  219. (defun interactive-mode ()
  220. (format t "~%")
  221. (format t "Available options:~%")
  222. (format t "1. Enter expense~%")
  223. (format t "2. Display month~%")
  224. (format t "3. Push records~%")
  225. (format t "4. Get records~%")
  226. (format t "5. Quit~%")
  227. (let
  228. ((answer (prompt-read "Select an option")))
  229. (if (string= answer "1")
  230. (generic-handler
  231. (let ((month-input (prompt-read "Enter month"))
  232. (expense-input (prompt-for-expense)))
  233. (add-expense-to-month (first expense-input)
  234. (second expense-input)
  235. month-input))
  236. "Invalid Input"))
  237. (if (string= answer "2")
  238. (generic-handler
  239. (dump-month-table (prompt-read "Enter month"))
  240. "Invalid month"))
  241. (if (string= answer "3")
  242. (generic-handler
  243. (push-records (prompt-read "Enter encryption key"))
  244. "Serialization error or invalid filename"))
  245. (if (string= answer "4")
  246. (generic-handler
  247. (get-records (prompt-read "Enter decryption key"))
  248. "Deserialization error or invalid filename"))
  249. (if (string= answer "5")
  250. (return-from interactive-mode nil)))
  251. (interactive-mode))
  252. (defun display-help ()
  253. (opts:describe
  254. :prefix "fin-lisp.lisp - Basic expense tracker in lisp"
  255. :usage-of "fin-lisp.lisp"
  256. :args "[FREE-ARGS]")
  257. (quit))
  258. ;; Entry point
  259. (defun main ()
  260. (if (= 1 (length sb-ext:*posix-argv*)) (interactive-mode))
  261. (let ((matches (opts:get-opts)))
  262. ;;(format t "~a ~%" matches)
  263. (when-option (matches :help)
  264. (display-help))
  265. (when-option (matches :print-month)
  266. (let ((key (prompt-read "Enter decryption key"))
  267. (month-key (destructuring-bind (&key print-month) matches
  268. print-month)))
  269. (get-records key)
  270. (dump-month-table month-key)
  271. (quit)))
  272. (when-option (matches :add-expense) ;; This is probably the wrong way to resolve the arguments
  273. (when-option (matches :value)
  274. (when-option (matches :month)
  275. (let ((key (prompt-read "Enter decryption key"))
  276. (name-value-month (destructuring-bind (&key add-expense value month) matches
  277. (list add-expense value month))))
  278. (get-records key)
  279. (if (add-expense-to-month
  280. (first name-value-month)
  281. (second name-value-month)
  282. (third name-value-month))
  283. (push-records key)
  284. (print "Invalid month input"))))))
  285. (when-option (matches :interactive-mode)
  286. (progn
  287. (interactive-mode)
  288. (quit)))))
  289. ;;; Can only be called from the REPL,
  290. ;;; used for importing according to the old schema
  291. (defun import-records (filename)
  292. (let ((old-file-lines
  293. (with-open-file (stream filename)
  294. (loop for line = (read-line stream nil)
  295. while line
  296. collect line)))
  297. (cur-mon)
  298. (cur-exp))
  299. (loop for line in old-file-lines
  300. do (progn
  301. (if (ppcre:scan *old-month-line-regex* line) (setf cur-mon line))
  302. (if (ppcre:scan *old-exp-line-regex* line)
  303. (progn
  304. (setf cur-exp (ppcre:register-groups-bind (first second) (*old-exp-line-regex* line) :sharedp t (list first second)))
  305. (print cur-exp)
  306. (if (gethash cur-mon *records*)
  307. (let ((innerhash (gethash cur-mon *records*)))
  308. (setf (gethash (first cur-exp) innerhash) (second cur-exp))))
  309. (if (not (gethash cur-mon *records*))
  310. (progn
  311. (add-month cur-mon)
  312. (let ((innerhash (gethash cur-mon *records*)))
  313. (setf (gethash (first cur-exp) innerhash) (second cur-exp)))))))))))
  314. (defun reset-records ()
  315. "Used for debugging, just resets the *records* hash to NIL"
  316. (setf *records* (make-hash-table :test 'equal)))