1
0

gsheets.lisp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. (in-package :cl-user)
  2. (defpackage chatikbot.plugins.gsheets
  3. (:use :cl :chatikbot.common))
  4. (in-package :chatikbot.plugins.gsheets)
  5. (defsetting *gsheets-client-id* nil "google oauth2 client id")
  6. (defsetting *gsheets-client-secret* nil "client secret")
  7. (defparameter +google-oauth-endpoint+ "https://accounts.google.com/o/oauth2/v2/auth" "Google OAuth2.0 endpoint")
  8. (defparameter +google-token-endpoint+ "https://www.googleapis.com/oauth2/v4/token" "Google OAuth2 token endpoint")
  9. (defparameter +gsheets-scope+ "https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/spreadsheets" "Google Sheets API scopes to find edit sheets")
  10. (defparameter +gsheets-base-uri+ "https://sheets.googleapis.com/v4/")
  11. (defparameter +gdrive-base-uri+ "https://www.googleapis.com/drive/v3/")
  12. (defun update-alist-settings (symbol key value)
  13. (set-setting symbol
  14. (cons (cons key value)
  15. (remove key (symbol-value symbol) :key #'car))))
  16. (defvar *gsheets-from-tokens* nil "ALIST of (token-id . (access_token . refresh_token))")
  17. (defun gsheets-get-tokens (token-id)
  18. (let ((tokens (aget token-id *gsheets-from-tokens*)))
  19. (values (car tokens) (cdr tokens))))
  20. (defun gsheets-set-tokens (token-id access-token &optional refresh-token)
  21. (update-alist-settings '*gsheets-from-tokens* token-id (cons access-token refresh-token)))
  22. (defun gsheets-get-authorization-url (state)
  23. (quri:render-uri
  24. (quri:merge-uris
  25. (quri:make-uri :query (quri:url-encode-params
  26. `(("response_type" . "code")
  27. ("client_id" . ,*gsheets-client-id*)
  28. ("redirect_uri" . ,(get-oauth-url))
  29. ("scope" . ,+gsheets-scope+)
  30. ("state" . ,(encode-oauth-state :gsheets state))
  31. ("access_type" . "offline")
  32. ("prompt" . "consent"))))
  33. (quri:uri +google-oauth-endpoint+))))
  34. (defun gsheets-refresh-access-token (token-id)
  35. (multiple-value-bind (old-access-token refresh-token) (gsheets-get-tokens token-id)
  36. (declare (ignore old-access-token))
  37. (when refresh-token
  38. (let* ((resp (json-request +google-token-endpoint+ :method :post
  39. :content (list
  40. (cons "refresh_token" refresh-token)
  41. (cons "client_id" *gsheets-client-id*)
  42. (cons "client_secret" *gsheets-client-secret*)
  43. (cons "grant_type" "refresh_token"))))
  44. (access-token (aget "access_token" resp)))
  45. (log:info resp)
  46. (when access-token
  47. (gsheets-set-tokens token-id access-token refresh-token)
  48. access-token)))))
  49. (def-oauth-section-handler gsheets-oauth-handler (:gsheets)
  50. (if code
  51. (progn
  52. (log:info code state)
  53. (let* ((resp (json-request +google-token-endpoint+ :method :post
  54. :content (list
  55. (cons "code" code)
  56. (cons "client_id" *gsheets-client-id*)
  57. (cons "client_secret" *gsheets-client-secret*)
  58. (cons "redirect_uri" (get-oauth-url))
  59. (cons "grant_type" "authorization_code"))))
  60. (access-token (aget "access_token" resp))
  61. (refresh-token (aget "refresh_token" resp))
  62. (token-id (parse-integer state)))
  63. (log:info token-id access-token refresh-token resp)
  64. (if access-token
  65. (progn
  66. (gsheets-set-tokens token-id access-token refresh-token)
  67. (hunchentoot:redirect "/oauth/success"))
  68. (hunchentoot:redirect "/oauth/fail"))))
  69. (progn
  70. (log:info error)
  71. (hunchentoot:redirect "/oauth/fail"))))
  72. (defun %gsheets-send-auth (chat-id token-id)
  73. (bot-send-message chat-id "Нет токена"
  74. :reply-markup (telegram-inline-keyboard-markup
  75. (list (list (list :text "Авторизоваться!"
  76. :url (gsheets-get-authorization-url token-id)))))))
  77. (defun google-api-call (token-id path base-url &key (method :get) parameters hash-body is-retry)
  78. (alexandria:when-let (access-token (gsheets-get-tokens token-id))
  79. (let* ((content (when hash-body
  80. (with-output-to-string (stream)
  81. (yason:encode hash-body stream))))
  82. (response (json-request
  83. (quri:render-uri (quri:merge-uris (quri:make-uri :path path) (quri:uri base-url)))
  84. :method method :parameters parameters :content content
  85. :headers (list (cons "Authorization" (format nil "Bearer ~A" access-token)))))
  86. (err (aget "error" response)))
  87. (if (and err (equal 401 (aget "code" err)) (not is-retry) (gsheets-refresh-access-token token-id))
  88. ;; Retry in case of auth error and successful token refresh
  89. (google-api-call token-id path base-url :method method :parameters parameters :hash-body hash-body :is-retry t)
  90. response))))
  91. (defun gsheets-find-files (token-id &optional next-page-token)
  92. (google-api-call token-id "files" +gdrive-base-uri+
  93. :parameters `(("pageSize" . "10")
  94. ("q" . "mimeType='application/vnd.google-apps.spreadsheet'")
  95. ("pageToken" . ,next-page-token))))
  96. (defun gsheets-file-watch (token-id file-id webhook &key token expiration payload params)
  97. (google-api-call token-id
  98. (format nil "files/~A/watch" file-id) +gdrive-base-uri+
  99. :method :post
  100. :hash-body
  101. (alexandria:plist-hash-table
  102. (append
  103. (list "kind" "api#channel"
  104. "id" (princ-to-string (uuid:make-v4-uuid))
  105. "type" "web_hook"
  106. "address" (get-webhook-url webhook))
  107. (when token (list "token" token))
  108. (when expiration (list "expiration" expiration))
  109. (when payload (list "payload" "true"))
  110. (when params (list "params" params))))))
  111. (defun gsheets-get-sheet (token-id sheet-id &key fields ranges include-grid-data)
  112. (google-api-call token-id
  113. (format nil "spreadsheets/~A" sheet-id) +gsheets-base-uri+
  114. :parameters (append
  115. (when fields (list (cons "fields" fields)))
  116. (when ranges (list (cons "ranges" ranges)))
  117. (when include-grid-data (list (cons "includeGridData" include-grid-data))))))
  118. (defun gsheets-get-sheet-values (token-id sheet-id ranges &key fields major-dimension)
  119. (google-api-call token-id
  120. (format nil "spreadsheets/~A/values:batchGet" sheet-id) +gsheets-base-uri+
  121. :parameters (append
  122. (loop for range in (if (listp ranges) ranges (list ranges))
  123. collect (cons "ranges" range))
  124. (when fields (list (cons "fields" fields)))
  125. (when major-dimension (list (cons "majorDimension" major-dimension))))))
  126. (defun gsheets-put-sheet-values (token-id sheet-id range-values &key raw major-dimension)
  127. (google-api-call token-id
  128. (format nil "spreadsheets/~A/values:batchUpdate" sheet-id) +gsheets-base-uri+
  129. :method :post
  130. :hash-body
  131. (alexandria:plist-hash-table
  132. (list "valueInputOption" (if raw "RAW" "USER_ENTERED")
  133. "data" (loop for (range . values) in range-values
  134. collect (alexandria:plist-hash-table
  135. (append
  136. (list "range" range
  137. "values" values)
  138. (when major-dimension
  139. (list "majorDimension" major-dimension)))))))))
  140. (defvar *gsheets-chat-sheets* nil "ALIST of (chat-id . sheet-id)")
  141. (defvar *gsheets-chat-sheet-sessions* nil "ALIST of (chat-id . (files . next)) for sheet selection")
  142. (defun %gsheets-files-markup-update-session (chat-id token-id &optional next-page-token)
  143. (let* ((resp (gsheets-find-files token-id next-page-token))
  144. (files (aget "files" resp))
  145. (next-page (aget "nextPageToken" resp)))
  146. (when resp
  147. (update-alist-settings '*gsheets-chat-sheet-sessions* chat-id (cons files next-page))
  148. (telegram-inline-keyboard-markup
  149. (append
  150. (loop
  151. for file in files
  152. for index from 0
  153. collect (list (list :text (format nil "📑 ~A" (aget "name" file))
  154. :callback-data (encode-callback-data
  155. chat-id :gs (format nil "s-~A" index)))))
  156. (list (list (list :text (if next-page "➡ Вперед" "🔁 Сначала")
  157. :callback-data (encode-callback-data chat-id :gs "n-1")))))))))
  158. (defun %gsheets-get-file-title-update-session (chat-id token-id sheet-id)
  159. (when sheet-id
  160. (let* ((sheet (gsheets-get-sheet token-id sheet-id :fields "properties.title"))
  161. (title (aget "title" (aget "properties" sheet))))
  162. (when title
  163. (update-alist-settings '*gsheets-chat-sheets* chat-id sheet-id)
  164. title))))
  165. (def-message-cmd-handler sheets-handler (:sheets :sheet)
  166. (cond
  167. (*args*
  168. ;; Set active sheet
  169. (let* ((uri (quri:uri (car *args*)))
  170. (scheme (quri:uri-scheme uri))
  171. (path (quri:uri-path uri))
  172. (sheet-id (cond
  173. ((and (equal scheme "https")
  174. (equal (subseq path 0 (min 16 (length path))) "/spreadsheets/d/"))
  175. (subseq path 16 (position #\/ path :start 16)))
  176. ((null scheme) path)))
  177. (title (%gsheets-get-file-title-update-session *chat-id* *from-id* sheet-id)))
  178. (bot-send-message (if title
  179. (format nil "Выбран 📑 ~A" title)
  180. "Нет такого документа (или доступа)"))))
  181. (:otherwise
  182. ;; Show list of available files
  183. (let ((files-markup (%gsheets-files-markup-update-session *chat-id* *from-id*)))
  184. (if files-markup
  185. (bot-send-message "Выбери документ:" :reply-markup files-markup)
  186. (%gsheets-send-auth *chat-id* *from-id*))))))
  187. (def-message-cmd-handler sheet-read-handler (:sheet-read)
  188. (let ((sheet-id (aget *chat-id* *gsheets-chat-sheets*)))
  189. (if sheet-id
  190. (let* ((range (car *args*))
  191. (resp (gsheets-get-sheet-values *from-id* sheet-id range))
  192. (values (aget "values" resp)))
  193. (bot-send-message (format nil "```~%~{~{~A~^ ~}~^~%~}```" values)
  194. :parse-mode "markdown"))
  195. (bot-send-message "Выбери документ сначала: /sheets"))))
  196. (def-message-cmd-handler sheet-write-handler (:sheet-write)
  197. (let ((sheet-id (aget *chat-id* *gsheets-chat-sheets*)))
  198. (if sheet-id
  199. (let* ((range (car *args*))
  200. (values (list (cdr *args*)))
  201. (resp (gsheets-put-sheet-values *from-id* sheet-id (list (cons range values)))))
  202. (bot-send-message (format nil "Записал в ~A" (aget "updatedRange" resp))))
  203. (bot-send-message "Выбери документ сначала: /sheets"))))
  204. (def-callback-section-handler cb-handle-gss (:gs)
  205. (destructuring-bind (type id) (split-sequence:split-sequence #\- *data* :count 2)
  206. (case (intern (string-upcase type) "KEYWORD")
  207. (:s (let* ((file (elt (car (aget *source-chat-id* *gsheets-chat-sheet-sessions*)) (parse-integer id)))
  208. (title (%gsheets-get-file-title-update-session *source-chat-id* *from-id* (aget "id" file))))
  209. (telegram-edit-message-text
  210. (if title (format nil "Выбран 📑 ~A" title) "Чот лажа")
  211. :chat-id *source-chat-id* :message-id *source-message-id*)
  212. (update-alist-settings '*gsheets-chat-sheet-sessions* *source-chat-id* nil)))
  213. (:n (let* ((token-next (cdr (aget *source-chat-id* *gsheets-chat-sheet-sessions*)))
  214. (files-markup (%gsheets-files-markup-update-session *source-chat-id* *from-id* token-next)))
  215. (if files-markup
  216. (telegram-edit-message-reply-markup files-markup :chat-id *source-chat-id* :message-id *source-message-id*)
  217. (telegram-edit-message-text "Чот лажа" :chat-id *source-chat-id* :message-id *source-message-id*)))))))