1
0

utils.lisp 19 KB

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