utils.lisp 16 KB

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