1
0

utils.lisp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. (in-package :cl-user)
  2. (defpackage chatikbot.utils
  3. (:use :cl)
  4. (:export :*admins*
  5. :*bot-name*
  6. :*hooks*
  7. :+hour+
  8. :+day+
  9. :*chat-default-timezone*
  10. :run-hooks
  11. :add-hook
  12. :remove-hook
  13. :keyify
  14. :dekeyify
  15. :*settings*
  16. :defsetting
  17. :*backoff-start*
  18. :*backoff-max*
  19. :loop-with-error-backoff
  20. :replace-all
  21. :aget
  22. :agets
  23. :agetter
  24. :preprocess-input
  25. :punctuation-p
  26. :read-from-string-no-punct
  27. :print-with-spaces
  28. :spaced
  29. :text-chunks
  30. :http-request
  31. :xml-request
  32. :get-by-tag
  33. :select-text
  34. :trim-nil
  35. :text-with-cdata
  36. :child-text
  37. :clean-text
  38. :json-request
  39. :plist-hash
  40. :plist-json
  41. :format-ts
  42. :parse-cmd
  43. :parse-float
  44. :smart-f
  45. :format-size
  46. :format-interval
  47. :symbol-append
  48. :get-chat-location
  49. :get-chat-timezone
  50. :same-time-in-chat
  51. :message-id
  52. :from-id
  53. :chat-id
  54. :text
  55. :cmd
  56. :args
  57. :callback
  58. :query-id
  59. :from
  60. :raw-data
  61. :message
  62. :data
  63. :section
  64. :code
  65. :error
  66. :raw-state
  67. :state
  68. :inline-message-id
  69. :source-message
  70. :source-message-id
  71. :source-chat-id
  72. :hook
  73. :headers
  74. :paths))
  75. (in-package #:chatikbot.utils)
  76. (defvar *admins* nil "Admins chat-ids")
  77. (defvar *bot-name* nil "bot name to properly handle text input")
  78. (defvar *hooks* (make-hash-table) "Hooks storage")
  79. (defparameter +hour+ (* 60 60) "Seconds in an hour")
  80. (defparameter +day+ (* 24 60 60) "Seconds in day")
  81. (defun run-hooks (event &rest arguments)
  82. (let ((hooks (gethash event *hooks*)))
  83. (labels ((try-handle (func)
  84. (handler-case
  85. (apply func arguments)
  86. (error (e)
  87. (log:error "Error processing event ~A: ~A" event e)
  88. nil))))
  89. (unless (some #'try-handle hooks)
  90. (log:info "unhandled" event arguments)))))
  91. (defun add-hook (event hook)
  92. (let ((existing (gethash event *hooks*)))
  93. (unless (member hook existing)
  94. (setf (gethash event *hooks*)
  95. (sort (cons hook existing) #'>
  96. :key #'(lambda (h)
  97. (etypecase h
  98. (symbol (get h :prio 0))
  99. (function 0))))))))
  100. (defun remove-hook (event hook)
  101. (setf (gethash event *hooks*)
  102. (remove hook (gethash event *hooks*))))
  103. (defun keyify (key)
  104. (intern (string-upcase (substitute #\- #\_ key)) :keyword))
  105. (defun dekeyify (keyword &optional preserve-dash)
  106. (let ((text (string-downcase (string keyword))))
  107. (if preserve-dash text (substitute #\_ #\- text))))
  108. ;; Settings
  109. (defvar *settings* nil "List of plugin's settings symbols")
  110. (defmacro defsetting (var &optional val doc)
  111. `(progn (defvar ,var ,val ,doc)
  112. (push ',var *settings*)))
  113. (defsetting *chat-default-timezone* -3 "Default timezone for chat users. GMT+3")
  114. (defvar *backoff-start* 1 "Initial back-off")
  115. (defvar *backoff-max* 64 "Maximum back-off delay")
  116. (defun loop-with-error-backoff (func)
  117. (let ((backoff *backoff-start*))
  118. (loop
  119. do
  120. (handler-case
  121. (progn
  122. (funcall func)
  123. (setf backoff *backoff-start*))
  124. (error (e)
  125. (log:error e)
  126. (log:info "Backing off for" backoff)
  127. (sleep backoff)
  128. (setf backoff (min *backoff-max*
  129. (* 2 backoff))))
  130. (usocket:timeout-error (e)
  131. (log:error e)
  132. (log:info "Backing off for" backoff)
  133. (sleep backoff)
  134. (setf backoff (min *backoff-max*
  135. (* 2 backoff))))))))
  136. (defun replace-all (string part replacement &key (test #'char=))
  137. "Returns a new string in which all the occurences of the part
  138. is replaced with replacement."
  139. (with-output-to-string (out)
  140. (loop with part-length = (length part)
  141. for old-pos = 0 then (+ pos part-length)
  142. for pos = (search part string
  143. :start2 old-pos
  144. :test test)
  145. do (write-string string out
  146. :start old-pos
  147. :end (or pos (length string)))
  148. when pos do (write-string replacement out)
  149. while pos)))
  150. (defmacro aget (key alist)
  151. `(cdr (assoc ,key ,alist :test #'equal)))
  152. (defun agets (alist &rest keys)
  153. (reduce #'(lambda (a k) (aget k a)) keys :initial-value alist))
  154. (defun agetter (&rest keys)
  155. (lambda (alist)
  156. (apply 'agets alist keys)))
  157. (defun preprocess-input (text)
  158. (when text
  159. (let* ((text (subseq text (if (equal (char text 0) #\/) 1 0)))
  160. (first-space (position #\Space text))
  161. (first-word (subseq text 0 first-space)))
  162. (if (equal first-word *bot-name*)
  163. (preprocess-input (subseq text (1+ first-space)))
  164. (replace-all text *bot-name* "ты")))))
  165. (defun print-with-spaces (list)
  166. (format nil "~@(~{~a~^ ~}~)" list))
  167. (defun parse-cmd (text)
  168. (let* ((args (split-sequence:split-sequence #\Space (subseq text 1) :remove-empty-subseqs t))
  169. (cmd (subseq (car args) 0 (position #\@ (car args)))))
  170. (values (intern (string-upcase cmd) "KEYWORD") (rest args))))
  171. (defun spaced (list)
  172. (format nil "~{~A~^ ~}" list))
  173. (defparameter +lf-lf+ "
  174. ")
  175. (defparameter +pre-pre+ "```
  176. ")
  177. (defparameter +pre-post+ "```")
  178. (defun text-chunks (elements &key (chunk-size 4096) (text-sep +lf-lf+) (pre-pre +pre-pre+) (pre-post +pre-post+))
  179. (loop for text in elements
  180. with page
  181. when (> (+ (length page) (length text) (length text-sep))
  182. chunk-size)
  183. collect (concatenate 'string pre-pre page pre-post) into pages and do (setf page nil)
  184. do (setf page (if page (concatenate 'string page text-sep text) text))
  185. finally (return (append pages (when page (list (concatenate 'string pre-pre page pre-post)))))))
  186. (defun http-default (url &optional parameters)
  187. (let* ((uri (quri:uri url))
  188. (userinfo (quri:uri-userinfo uri)))
  189. (when parameters
  190. (let ((query (quri:url-encode-params parameters :encoding :utf-8)))
  191. (setf (quri:uri-query uri)
  192. (if (and (quri:uri-query uri)
  193. (string-not-equal (quri:uri-query uri) ""))
  194. (concatenate 'string (quri:uri-query uri) "&" query)
  195. query))))
  196. (when userinfo
  197. (setf (quri:uri-userinfo uri) nil))
  198. (unless (quri:uri-scheme uri)
  199. (setf (quri:uri-scheme uri) "http"))
  200. (values uri userinfo)))
  201. (defun http-request (url &rest args &key method version parameters content headers basic-auth cookie-jar keep-alive use-connection-pool (max-redirects 5) timeout force-binary want-stream ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path user-agent)
  202. (declare (ignore method version content basic-auth cookie-jar keep-alive use-connection-pool max-redirects timeout force-binary want-stream ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path))
  203. (multiple-value-bind (uri userinfo)
  204. (http-default url parameters)
  205. (when userinfo
  206. (push (cons :authorization (concatenate 'string "Basic "
  207. (base64:string-to-base64-string userinfo)))
  208. headers))
  209. (when user-agent
  210. (push (cons :user-agent user-agent) headers)
  211. (remf args :user-agent))
  212. (remf args :parameters)
  213. (remf args :headers)
  214. (apply #'dex:request uri :headers headers args)))
  215. ;; XML processing
  216. (defun xml-request (url &rest args &key method parameters content headers basic-auth cookie-jar keep-alive use-connection-pool timeout ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path user-agent encoding)
  217. (declare (ignore method parameters headers content basic-auth cookie-jar keep-alive use-connection-pool timeout ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path user-agent))
  218. (remf args :encoding)
  219. (multiple-value-bind (raw-body status headers uri)
  220. (apply #'http-request url :force-binary t args)
  221. (let ((encoding
  222. (or
  223. ;; 1. Provided encoding
  224. encoding
  225. ;; 2. Content-type header
  226. (ignore-errors
  227. (let ((ct (gethash "content-type" headers)))
  228. (subseq ct (1+ (position #\= ct)))))
  229. ;; 3. Parse first 1000 bytes
  230. (ignore-errors
  231. (let ((dom (plump:parse (flex:octets-to-string
  232. (subseq raw-body 0 (1+ (position (char-code #\>) raw-body :start 1000)))))))
  233. (or
  234. ;; 3.1 Content-type from http-equiv
  235. (ignore-errors
  236. (let ((ct (loop for meta in (get-by-tag dom "meta")
  237. for http-equiv = (plump:get-attribute meta "http-equiv")
  238. for content = (plump:get-attribute meta "content")
  239. when (equal http-equiv "Content-Type")
  240. return content)))
  241. (subseq ct (1+ (position #\= ct)))))
  242. ;; 3.2 'content' xml node attribute
  243. (ignore-errors (plump:get-attribute (plump:first-child dom) "encoding")))))
  244. ;; 4. Default 'utf-8'
  245. "utf-8")))
  246. (values
  247. (handler-bind ((flex:external-format-encoding-error
  248. (lambda (c) (use-value #\? c))))
  249. (plump:parse
  250. (flex:octets-to-string raw-body :external-format (intern encoding 'keyword))))
  251. status headers uri))))
  252. (defun get-by-tag (node tag)
  253. (nreverse (org.shirakumo.plump.dom::get-elements-by-tag-name node tag)))
  254. (defun select-text (node &optional selector)
  255. (ignore-errors
  256. (when selector (setf node (elt (clss:select selector node) 0)))
  257. (plump:traverse node #'(lambda (n) (setf (plump:text n) ""))
  258. :test #'plump:comment-p)
  259. (plump:text (plump:strip node))))
  260. (defun trim-nil (text)
  261. (when text
  262. (let ((text (string-trim " " text)))
  263. (unless (zerop (length text))
  264. text))))
  265. (defun text-with-cdata (node)
  266. "Compiles all text nodes within the nesting-node into one string."
  267. (with-output-to-string (stream)
  268. (labels ((r (node)
  269. (loop for child across (plump:children node)
  270. do (typecase child
  271. (plump:text-node (write-string (plump:text child) stream))
  272. (plump:cdata (write-string (plump:text child) stream))
  273. (plump:nesting-node (r child))))))
  274. (r node))))
  275. (defun child-text (node tag)
  276. (alexandria:when-let (child (car (get-by-tag node tag)))
  277. (trim-nil (text-with-cdata child))))
  278. (defun clean-text (text)
  279. (when text (trim-nil (plump:text (plump:parse text)))))
  280. ;; JSON processing
  281. (defun json-request (url &rest args &key method parameters content headers basic-auth cookie-jar keep-alive use-connection-pool timeout ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path user-agent (object-as :alist))
  282. (declare (ignore method parameters basic-auth cookie-jar keep-alive use-connection-pool timeout ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path user-agent))
  283. (remf args :object-as)
  284. (when content
  285. (push (cons :content-type "application/json") headers))
  286. (multiple-value-bind (body status headers uri)
  287. (apply #'http-request url args)
  288. (unless (stringp body)
  289. (setf body (babel:octets-to-string body :encoding :utf-8)))
  290. (values (yason:parse body :object-as object-as) status headers uri)))
  291. (defun plist-hash (plist &optional skip-nil (format-key #'identity) &rest hash-table-initargs)
  292. (cond
  293. ((and (consp plist) (keywordp (car plist)))
  294. (let ((table (apply #'make-hash-table hash-table-initargs)))
  295. (do ((tail plist (cddr tail)))
  296. ((not tail))
  297. (let ((key (funcall format-key (car tail)))
  298. (value (cadr tail)))
  299. (when (or value (not skip-nil))
  300. (setf (gethash key table)
  301. (if (listp value)
  302. (apply #'plist-hash value skip-nil format-key hash-table-initargs)
  303. value)))))
  304. table))
  305. ((consp plist)
  306. (loop for item in plist collect (apply #'plist-hash item skip-nil format-key hash-table-initargs)))
  307. (:default plist)))
  308. (defmethod yason:encode ((object (eql 'f)) &optional (stream *standard-output*))
  309. (write-string "false" stream)
  310. object)
  311. (defun plist-json (plist)
  312. (with-output-to-string (stream)
  313. (yason:encode (plist-hash plist t #'dekeyify) stream)))
  314. (defun format-ts (ts)
  315. (local-time:format-timestring nil ts
  316. :format '(:year "-" (:month 2) "-" (:day 2) " "
  317. (:hour 2) ":" (:min 2) ":" (:sec 2))))
  318. (defun parse-float (string)
  319. (etypecase string
  320. (number string)
  321. (string
  322. (let ((*read-eval* nil))
  323. (with-input-from-string (stream string)
  324. (let ((in (read stream nil nil)))
  325. (when (numberp in)
  326. in)))))))
  327. (defun smart-f (arg &optional digits)
  328. (with-output-to-string (s)
  329. (prin1 (cond ((= (round arg) arg) (round arg))
  330. (digits (float (/ (round (* arg (expt 10 digits)))
  331. (expt 10 digits))))
  332. (t arg))
  333. s)))
  334. (defun format-size (bytes)
  335. (cond
  336. ((< bytes 512) (smart-f bytes))
  337. ((< bytes (* 512 1024)) (format nil "~A KiB" (smart-f (/ bytes 1024) 1)))
  338. ((< bytes (* 512 1024 1024)) (format nil "~A MiB" (smart-f (/ bytes 1024 1024) 1)))
  339. ((< bytes (* 512 1024 1024 1024)) (format nil "~A GiB" (smart-f (/ bytes 1024 1024 1024) 1)))
  340. (:otherwise (format nil "~A TiB" (smart-f (/ bytes 1024 1024 1024 1024) 1)))))
  341. (defun format-interval (seconds)
  342. (cond
  343. ((< seconds 60) (format nil "~A sec" seconds))
  344. ((< seconds (* 60 60)) (format nil "~A mins" (round seconds 60)))
  345. ((< seconds (* 60 60 24)) (format nil "~A hours" (round seconds (* 60 60))))
  346. ((< seconds (* 60 60 24 7)) (format nil "~A days" (round seconds (* 60 60 24))))
  347. ((< seconds (* 60 60 24 7 54)) (format nil "~A weeks" (round seconds (* 60 60 24 7))))
  348. (:otherwise (format nil "~A years" (smart-f (/ seconds (* 60 60 24 365.25)) 1)))))
  349. (defun symbol-append (&rest symbols)
  350. (intern (apply #'concatenate 'string
  351. (mapcar #'symbol-name symbols))))
  352. (defun get-chat-location (chat-id)
  353. (let* ((forecast-package (find-package :chatikbot.plugins.forecast))
  354. (chat-locations-sym (when forecast-package
  355. (intern "*CHAT-LOCATIONS*" forecast-package)))
  356. (chat-locations (when (and chat-locations-sym (boundp chat-locations-sym))
  357. (symbol-value chat-locations-sym))))
  358. (when chat-locations (aget chat-id chat-locations))))
  359. (defun get-chat-timezone (chat-id)
  360. (or (let ((chat-loc (get-chat-location chat-id)))
  361. (when chat-loc
  362. (round (- 7.5 (aget "latitude" chat-loc)) 15))) ;; Nautical time
  363. *chat-default-timezone*))
  364. (defun same-time-in-chat (ut chat-id)
  365. (let ((chat-tz (get-chat-timezone chat-id))
  366. (current-tz (nth-value 8 (get-decoded-time))))
  367. (+ ut (* (- chat-tz current-tz) +hour+))))
  368. ;; Fix bug in local-time (following symlinks in /usr/share/zoneinfo/
  369. ;; leads to bad cutoff)
  370. (in-package #:local-time)
  371. (defun reread-timezone-repository (&key (timezone-repository *default-timezone-repository-path*))
  372. (check-type timezone-repository (or pathname string))
  373. (multiple-value-bind (valid? error)
  374. (ignore-errors
  375. (truename timezone-repository)
  376. t)
  377. (unless valid?
  378. (error "REREAD-TIMEZONE-REPOSITORY was called with invalid PROJECT-DIRECTORY (~A). The error is ~A."
  379. timezone-repository error)))
  380. (let* ((root-directory timezone-repository)
  381. (cutoff-position (length (princ-to-string root-directory))))
  382. (flet ((visitor (file)
  383. (handler-case
  384. (let* ((full-name (subseq (princ-to-string file) cutoff-position))
  385. (name (pathname-name file))
  386. (timezone (%realize-timezone (make-timezone :path file :name name))))
  387. (setf (gethash full-name *location-name->timezone*) timezone)
  388. (map nil (lambda (subzone)
  389. (push timezone (gethash (subzone-abbrev subzone)
  390. *abbreviated-subzone-name->timezone-list*)))
  391. (timezone-subzones timezone)))
  392. (invalid-timezone-file () nil))))
  393. (setf *location-name->timezone* (make-hash-table :test 'equal))
  394. (setf *abbreviated-subzone-name->timezone-list* (make-hash-table :test 'equal))
  395. (cl-fad:walk-directory root-directory #'visitor :directories nil :follow-symlinks nil
  396. :test (lambda (file)
  397. (not (find "Etc" (pathname-directory file) :test #'string=))))
  398. (cl-fad:walk-directory (merge-pathnames "Etc/" root-directory) #'visitor :directories nil))))
  399. (let ((zonepath "/usr/share/zoneinfo/"))
  400. (when (directory zonepath)
  401. (local-time:reread-timezone-repository :timezone-repository zonepath)))