utils.lisp 18 KB

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