ledger.lisp 11 KB

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