utils.lisp 19 KB

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