1
0

ledger.lisp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. (in-package :cl-user)
  2. (defpackage chatikbot.plugins.ledger
  3. (:use :cl :chatikbot.common))
  4. (in-package :chatikbot.plugins.ledger)
  5. (eval-when (:compile-toplevel :load-toplevel :execute)
  6. (ql:quickload '(:pta-ledger :legit)))
  7. (defsetting *ledger/default-timezone* -3 "Default timezone for time display. GMT+3")
  8. (defvar *ledger/chat-journals* (make-hash-table))
  9. (defvar *git-repo-locks* (make-hash-table :test #'equal))
  10. (defun git-get-repo-lock (repo)
  11. (let ((key (legit:location repo)))
  12. (setf key
  13. (etypecase key
  14. (string key)
  15. (pathname (namestring key))))
  16. (or (gethash key *git-repo-locks*)
  17. (setf (gethash key *git-repo-locks*)
  18. (bt:make-recursive-lock key)))))
  19. (defun git-get-repo (location remote)
  20. (let ((repo (make-instance 'legit:repository :location location)))
  21. (bt:with-recursive-lock-held ((git-get-repo-lock repo))
  22. (legit:init repo :remote remote :if-does-not-exist :clone))
  23. repo))
  24. (defsetting *git-repos-root* "/tmp/ledger-repos/")
  25. (defun git-get-chat-location (chat-id remote)
  26. (namestring (uiop:ensure-directory-pathname
  27. (merge-pathnames (format nil "~A-~A" chat-id (token-hmac remote))
  28. *git-repos-root*))))
  29. (defun git-read-latest-file (repo path)
  30. (bt:with-recursive-lock-held ((git-get-repo-lock repo))
  31. (legit:fetch repo :branch "master" :remote "origin")
  32. (legit:reset repo :hard t :to "origin/master")
  33. (uiop:read-file-string (merge-pathnames path (legit:location repo)))))
  34. (defun ledger/refresh-git (chat-id remote path)
  35. (let* ((location (git-get-chat-location chat-id remote))
  36. (repo (git-get-repo location remote))
  37. (content (git-read-latest-file repo path))
  38. (journal (pta-ledger:parse-journal content))
  39. (updated (legit:current-age repo)))
  40. (setf (gethash chat-id *ledger/chat-journals*)
  41. (cons journal updated))))
  42. (defun git-append-latest-file (repo path text message)
  43. (bt:with-recursive-lock-held ((git-get-repo-lock repo))
  44. (let ((repo-path (merge-pathnames path (legit:location repo))))
  45. (dotimes (tries 5)
  46. (let ((current (or (ignore-errors (git-read-latest-file repo path)) "")))
  47. (uiop/stream:with-output-file (s repo-path
  48. :if-exists :supersede
  49. :if-does-not-exist :create)
  50. (format s "~A~A" current text)))
  51. (legit:add repo (namestring repo-path))
  52. (legit:commit repo message)
  53. (handler-case
  54. (progn
  55. (legit:push repo)
  56. (return-from git-append-latest-file path))
  57. (legit:git-error ())))
  58. (error "Tried 5 times to push ~A to ~A" path (legit:remote-url repo)))))
  59. (defun ledger/add-git (chat-id remote path text message)
  60. (let* ((location (git-get-chat-location chat-id remote))
  61. (repo (git-get-repo location remote)))
  62. (git-append-latest-file repo path
  63. (format nil "~%~A~%" text)
  64. message)))
  65. (defun ledger/get-hook-url (chat-id)
  66. (get-webhook-url "ledger" chat-id (token-hmac (write-to-string chat-id))))
  67. (defun ledger/format-uri (url)
  68. (let ((uri (quri:uri url)))
  69. (quri:render-uri (quri:make-uri :userinfo (when (quri:uri-userinfo uri) "*:*")
  70. :defaults url))))
  71. (defun ledger/format-time (universal-time)
  72. (when universal-time
  73. (multiple-value-bind (sec min hour day month year dow dst-p tz)
  74. (decode-universal-time universal-time *ledger/default-timezone*)
  75. (declare (ignore dow dst-p tz))
  76. (format nil "~4,'0D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D"
  77. year month day hour min sec))))
  78. (defun ledger/refresh-uri (chat-id uri)
  79. (setf (gethash chat-id *ledger/chat-journals*)
  80. (cons (pta-ledger:parse-journal (http-request uri))
  81. (get-universal-time))))
  82. (defun get-chat-journal-info (chat-id &optional info)
  83. (labels ((process-info (info)
  84. (cond
  85. ((stringp info) (ledger/refresh-uri chat-id info))
  86. ((consp info) (apply #'ledger/refresh-git chat-id info))
  87. (:otherwise nil))))
  88. (let ((journal-info (gethash chat-id *ledger/chat-journals*)))
  89. (if journal-info journal-info
  90. (if info (process-info info)
  91. (with-secret (info (list :ledger chat-id))
  92. (process-info info)))))))
  93. (Defun ledger/handle-info (chat-id)
  94. (with-secret (info (list :ledger chat-id))
  95. (if info
  96. (destructuring-bind (journal . ut)
  97. (get-chat-journal-info chat-id info)
  98. (let ((uri (cond
  99. ((consp info) (car info))
  100. ((stringp info) info))))
  101. (bot-send-message chat-id (format nil "Журнал с ~D записями, из ~A, обновлён ~A.~%Веб-хук: ~A"
  102. (length journal)
  103. (ledger/format-uri uri)
  104. (ledger/format-time ut)
  105. (ledger/get-hook-url chat-id))
  106. :disable-web-preview t)))
  107. (send-response chat-id "Добавь журнал: uri - /ledger <url>; git - /ledger <remote> <path>"))))
  108. (defun ledger/handle-set-info (chat-id info)
  109. (setf (gethash chat-id *ledger/chat-journals*) nil)
  110. (handler-case
  111. (destructuring-bind (journal . ut)
  112. (get-chat-journal-info chat-id info)
  113. (declare (ignore ut))
  114. (secret-set (list :ledger chat-id) info)
  115. (send-response chat-id (format nil "Добавил журнал с ~D записями. Веб-хук для обновления: ~A"
  116. (length journal)
  117. (ledger/get-hook-url chat-id))))
  118. (pta-ledger:journal-failed (e)
  119. (send-response chat-id (format nil "Не смог спарсить: ~A" e)))
  120. (dex:http-request-failed (e)
  121. (send-response chat-id (format nil "Не смог в урл: ~A" (dex:response-body e))))))
  122. (def-message-cmd-handler handler-ledger (:ledger)
  123. (cond
  124. ((<= 1 (length args) 2) (ledger/handle-set-info chat-id args))
  125. (:otherwise (ledger/handle-info chat-id))))
  126. (defmacro with-chat-journal ((chat-id journal updated) &body body)
  127. (let ((info (gensym "info")))
  128. `(let ((,info (get-chat-journal-info ,chat-id)))
  129. (if ,info
  130. (destructuring-bind (,journal . ,updated) ,info
  131. ,@body)
  132. (send-response ,chat-id "Добавь журнал: uri - /ledger <url>; git - /ledger <remote> <path>")))))
  133. (defun ledger/handle-balance (chat-id query)
  134. (with-chat-journal (chat-id journal updated)
  135. (bot-send-message chat-id (format nil "```~%~A~%```Обновлено: ~A"
  136. (pta-ledger:journal-balance journal query)
  137. (ledger/format-time updated))
  138. :parse-mode "markdown")))
  139. (def-message-cmd-handler handler-balance (:balance :bal)
  140. (cond
  141. ((null args) (ledger/handle-balance chat-id "assets"))
  142. (:otherwise (ledger/handle-balance chat-id (spaced args)))))
  143. (defun ledger/handle-journal (chat-id query)
  144. (with-chat-journal (chat-id journal updated)
  145. (let* ((entries (pta-ledger:journal-print journal query))
  146. (len (length entries))
  147. (count (min len 20)))
  148. (bot-send-message chat-id (format nil "```~%~{~A~^ ~%~%~}```Обновлено: ~A"
  149. (subseq entries (- len count) len)
  150. (ledger/format-time updated))
  151. :parse-mode "markdown"))))
  152. (def-message-cmd-handler handler-journal (:journal)
  153. (cond
  154. ((null args) (ledger/handle-journal chat-id "date:thisweek"))
  155. (:otherwise (ledger/handle-journal chat-id (spaced args)))))
  156. (def-webhook-handler ledger/handle-webhook ("ledger")
  157. (when (= 2 (length paths))
  158. (destructuring-bind (chat-id hmac) paths
  159. (let ((true-hmac (token-hmac chat-id)))
  160. (when (string= true-hmac hmac)
  161. (with-secret (info (list :ledger chat-id))
  162. (when info
  163. (let ((chat-id (parse-integer chat-id)))
  164. (log:info "Updating ledger for ~A" chat-id)
  165. (setf (gethash chat-id *ledger/chat-journals*) nil)
  166. (get-chat-journal-info chat-id info)
  167. "OK"))))))))
  168. ;; New entries
  169. (defun format-entry (entry)
  170. (format nil "```~%~A```" (pta-ledger:render entry)))
  171. (defparameter +new-entry-actions+
  172. `(("a" . "➕")
  173. ("e" . "💲")
  174. ("c" . "✖️")))
  175. (defun ledger/new-chat-entry (chat-id entry)
  176. (bot-send-message chat-id (format-entry entry)
  177. :parse-mode "markdown"
  178. :reply-markup (telegram-inline-keyboard-markup
  179. (list (loop for (a . l) in +new-entry-actions+
  180. collect (list :text l
  181. :callback-data
  182. (encode-callback-data
  183. chat-id :ln a 86400)))))))
  184. (defun ledger/format-add-entry-message (from)
  185. (format nil "Ledger add from ~A ~A at ~A"
  186. (aget "first_name" from) (aget "last_name" from)
  187. (ledger/format-time (get-universal-time))))
  188. (defun ledger/process-add-entry (chat-id callback)
  189. (with-secret (info (list :ledger chat-id))
  190. (if info
  191. (cond
  192. ((consp info)
  193. (handler-case (progn
  194. (ledger/add-git
  195. chat-id
  196. (car info) (cadr info)
  197. (agets callback "message" "text")
  198. (ledger/format-add-entry-message (agets callback "from")))
  199. "Добавил!")
  200. (error (e)
  201. (log:error "~A" e)
  202. "Не смог :(")))
  203. (:otherwise "Добавляю только в git журнал :("))
  204. "Добавь git журнал.")))
  205. (def-callback-section-handler cb-handle-ln (:ln)
  206. (case (keyify data)
  207. (:a (telegram-answer-callback-query query-id :text "Добавляю...")
  208. (telegram-send-message chat-id (ledger/process-add-entry
  209. chat-id callback))
  210. (telegram-edit-message-reply-markup nil :chat-id chat-id :message-id message-id))
  211. (:e (telegram-answer-callback-query query-id :text "TBD"))
  212. (:c (telegram-delete-message chat-id message-id))))