utils.lisp 19 KB

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