1
0

utils.lisp 17 KB

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