utils.lisp 18 KB

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