1
0

utils.lisp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. (in-package #:chatikbot)
  2. (defvar *bot-name* nil "bot name to properly handle text input")
  3. (defvar *hooks* (make-hash-table) "Hooks storage")
  4. (defun run-hooks (event &rest arguments)
  5. (let ((hooks (gethash event *hooks*)))
  6. (labels ((try-handle (func)
  7. (apply func arguments)))
  8. (unless (some #'try-handle hooks)
  9. (log:info "unhandled" event arguments)))))
  10. (defun add-hook (event hook &optional append)
  11. (let ((existing (gethash event *hooks*)))
  12. (unless (member hook existing)
  13. (setf (gethash event *hooks*)
  14. (if append (append existing (list hook))
  15. (cons hook existing))))))
  16. (defun remove-hook (event hook)
  17. (setf (gethash event *hooks*)
  18. (remove hook (gethash event *hooks*))))
  19. (defun keyify (key)
  20. (intern (string-upcase (substitute #\- #\_ key)) :keyword))
  21. (defun dekeyify (keyword &optional preserve-dash)
  22. (let ((text (string-downcase (string keyword))))
  23. (if preserve-dash text (substitute #\_ #\- text))))
  24. ;; Settings
  25. (defvar *settings* nil "List of plugin's settings symbols")
  26. (defmacro defsetting (var &optional val doc)
  27. `(progn (defvar ,var ,val ,doc)
  28. (push ',var *settings*)))
  29. (defvar *backoff-start* 1 "Initial back-off")
  30. (defvar *backoff-max* 64 "Maximum back-off delay")
  31. (defun loop-with-error-backoff (func)
  32. (let ((backoff *backoff-start*))
  33. (loop
  34. do
  35. (handler-case
  36. (progn
  37. (funcall func)
  38. (setf backoff *backoff-start*))
  39. (error (e)
  40. (log:error e)
  41. (log:info "Backing off for" backoff)
  42. (sleep backoff)
  43. (setf backoff (min *backoff-max*
  44. (* 2 backoff))))
  45. (bordeaux-threads:timeout (e)
  46. (log:error e)
  47. (log:info "Backing off for" backoff)
  48. (sleep backoff)
  49. (setf backoff (min *backoff-max*
  50. (* 2 backoff))))))))
  51. (defun replace-all (string part replacement &key (test #'char=))
  52. "Returns a new string in which all the occurences of the part
  53. is replaced with replacement."
  54. (with-output-to-string (out)
  55. (loop with part-length = (length part)
  56. for old-pos = 0 then (+ pos part-length)
  57. for pos = (search part string
  58. :start2 old-pos
  59. :test test)
  60. do (write-string string out
  61. :start old-pos
  62. :end (or pos (length string)))
  63. when pos do (write-string replacement out)
  64. while pos)))
  65. (defmacro aget (key alist)
  66. `(cdr (assoc ,key ,alist :test #'equal)))
  67. (defun mappend (fn &rest lists)
  68. "Apply fn to each element of lists and append the results."
  69. (apply #'append (apply #'mapcar fn lists)))
  70. (defun random-elt (choices)
  71. "Choose an element from a list at random."
  72. (elt choices (random (length choices))))
  73. (defun flatten (the-list)
  74. "Append together elements (or lists) in the list."
  75. (mappend #'(lambda (x) (if (listp x) (flatten x) (list x))) the-list))
  76. (defun preprocess-input (text)
  77. (when text
  78. (let* ((first-space (position #\Space text))
  79. (first-word (subseq text 0 first-space)))
  80. (if (equal first-word *bot-name*)
  81. (preprocess-input (subseq text (1+ first-space)))
  82. (replace-all text *bot-name* "ты")))))
  83. (defun parse-cmd (text)
  84. (let* ((args (split-sequence:split-sequence #\Space (subseq text 1) :remove-empty-subseqs t))
  85. (cmd (subseq (car args) 0 (position #\@ (car args)))))
  86. (values (intern (string-upcase cmd) "KEYWORD") (rest args))))
  87. (defun http-default (url)
  88. (let ((uri (puri:uri url)))
  89. (puri:render-uri
  90. (if (null (puri:uri-scheme uri))
  91. (puri:uri (format nil "http://~A" url))
  92. uri)
  93. nil)))
  94. ;; XML processing
  95. (defun xml-request (url &key encoding parameters)
  96. (multiple-value-bind (raw-body status headers uri http-stream)
  97. (drakma:http-request (http-default url)
  98. :parameters parameters
  99. :external-format-out :utf-8
  100. :force-binary t
  101. :decode-content t)
  102. (declare (ignore status http-stream))
  103. (let ((encoding
  104. (or
  105. ;; 1. Provided encoding
  106. encoding
  107. ;; 2. Content-type header
  108. (ignore-errors
  109. (let ((ct (aget :content-type headers)))
  110. (subseq ct (1+ (position #\= ct)))))
  111. ;; 3. Parse first 1000 bytes
  112. (ignore-errors
  113. (let ((dom (plump:parse (flex:octets-to-string (subseq raw-body 0 1000)))))
  114. (or
  115. ;; 3.1 Content-type from http-equiv
  116. (ignore-errors
  117. (let ((ct (loop for meta in (get-by-tag dom "meta")
  118. for http-equiv = (plump:get-attribute meta "http-equiv")
  119. for content = (plump:get-attribute meta "content")
  120. when (equal http-equiv "Content-Type")
  121. return content)))
  122. (subseq ct (1+ (position #\= ct)))))
  123. ;; 3.2 'content' xml node attribute
  124. (ignore-errors (plump:get-attribute (plump:first-child dom) "encoding")))))
  125. ;; 4. Default 'utf-8'
  126. "utf-8")))
  127. (values
  128. (handler-bind ((flex:external-format-encoding-error
  129. (lambda (c) (use-value #\? c))))
  130. (plump:parse
  131. (flex:octets-to-string raw-body :external-format (intern encoding 'keyword))))
  132. uri))))
  133. (defun get-by-tag (node tag)
  134. (nreverse (org.shirakumo.plump.dom::get-elements-by-tag-name node tag)))
  135. (defun select-text (selector node)
  136. (ignore-errors
  137. (string-trim '(#\Newline #\Space #\Return) (plump:text (elt (clss:select selector node) 0)))))
  138. ;; JSON processing
  139. (defun json-request (url &key (method :get) parameters (object-as :alist))
  140. (multiple-value-bind (stream status headers uri http-stream)
  141. (drakma:http-request (http-default url) :method method :parameters parameters
  142. :external-format-out :utf-8
  143. :force-binary t :want-stream t :decode-content t)
  144. (declare (ignore status headers))
  145. (unwind-protect
  146. (progn
  147. (setf (flex:flexi-stream-external-format stream) :utf-8)
  148. (values (yason:parse stream :object-as object-as) uri))
  149. (ignore-errors (close http-stream)))))
  150. (defun format-ts (ts)
  151. (local-time:format-timestring nil ts
  152. :format '(:year "-" (:month 2) "-" (:day 2) " "
  153. (:hour 2) ":" (:min 2) ":" (:sec 2))))
  154. (defun smart-f (arg &optional digits)
  155. (with-output-to-string (s)
  156. (prin1 (cond ((= (round arg) arg) (round arg))
  157. (digits (float (/ (round (* arg (expt 10 digits)))
  158. (expt 10 digits))))
  159. (t arg))
  160. s)))
  161. (defun format-size (bytes)
  162. (cond
  163. ((< bytes 512) (smart-f bytes))
  164. ((< bytes (* 512 1024)) (format nil "~A KiB" (smart-f (/ bytes 1024) 1)))
  165. ((< bytes (* 512 1024 1024)) (format nil "~A MiB" (smart-f (/ bytes 1024 1024) 1)))
  166. ((< bytes (* 512 1024 1024 1024)) (format nil "~A GiB" (smart-f (/ bytes 1024 1024 1024) 1)))
  167. (:otherwise (format nil "~A TiB" (smart-f (/ bytes 1024 1024 1024 1024) 1)))))
  168. (defun format-interval (seconds)
  169. (cond
  170. ((< seconds 60) (format nil "~A sec" seconds))
  171. ((< seconds (* 60 60)) (format nil "~A mins" (round seconds 60)))
  172. ((< seconds (* 60 60 24)) (format nil "~A hours" (round seconds (* 60 60))))
  173. ((< seconds (* 60 60 24 7)) (format nil "~A days" (round seconds (* 60 60 24))))
  174. ((< seconds (* 60 60 24 7 54)) (format nil "~A weeks" (round seconds (* 60 60 24 7))))
  175. (:otherwise (format nil "~A years" (smart-f (/ seconds (* 60 60 24 365.25)) 1)))))
  176. (defun google-tts (text &key (lang "en"))
  177. (let ((path #P"google_tts.mp3"))
  178. (with-open-file (s path :direction :output
  179. :element-type '(unsigned-byte 8)
  180. :if-exists :supersede
  181. :if-does-not-exist :create)
  182. (write-sequence
  183. (drakma:http-request
  184. "http://translate.google.com/translate_tts"
  185. :parameters `(("ie" . "UTF-8")
  186. ("client" . "t")
  187. ("tl" . ,lang)
  188. ("q" . ,text))
  189. :user-agent "stagefright/1.2 (Linux;Android 5.0)"
  190. :additional-headers '((:referer . "http://translate.google.com/"))
  191. :external-format-out :utf-8
  192. :force-binary t)
  193. s)
  194. path)))
  195. (defun say-it (lang words)
  196. (cons :voice
  197. (google-tts (print-with-spaces words) :lang lang)))
  198. (defun yit-info ()
  199. (labels ((get-rows (url)
  200. (rest (get-by-tag (plump:get-element-by-id (xml-request url) "apartmentList") "tr")))
  201. (row-data (row)
  202. (mapcar (lambda (e) (string-trim '(#\Newline #\Space) (plump:text e)))
  203. (get-by-tag row "td")))
  204. (format-data (data)
  205. (format nil "~{~A~^ ~}" (mapcar (lambda (n) (nth n data)) '(1 2 3 4 7 6))))
  206. (get-intresting (rows)
  207. (loop for row in rows
  208. for data = (row-data row)
  209. for rooms = (parse-integer (nth 2 data))
  210. for area = (parse-float:parse-float (replace-all (nth 3 data) "," "."))
  211. when (= rooms 3)
  212. when (< 65 area 75)
  213. collect data))
  214. (format-apts (url)
  215. (let ((apts (get-intresting (get-rows url))))
  216. (format nil "~A~%~{~A~^~%~}~%~A/~A" url (mapcar #'format-data apts)
  217. (length (remove "забронировано" apts :test #'equal :key #'(lambda (r) (nth 7 r)) ))
  218. (length apts)))))
  219. (format nil "~{~A~^~%~%~}"
  220. (mapcar #'format-apts
  221. '("http://www.yitspb.ru/yit_spb/catalog/apartments/novoorlovskiy-korpus-1-1-1"
  222. "http://www.yitspb.ru/yit_spb/catalog/apartments/novoorlovskiy-korpus-1-1-2")))))
  223. (defmacro def-message-handler (name (message) &body body)
  224. `(progn
  225. (defun ,name (,message)
  226. (let ((message-id (aget "message_id" ,message))
  227. (from-id (aget "id" (aget "from" ,message)))
  228. (chat-id (aget "id" (aget "chat" ,message)))
  229. (text (aget "text" ,message)))
  230. (declare (ignorable message-id from-id chat-id text))
  231. (handler-case (progn ,@body)
  232. (error (e)
  233. (log:error "~A" e)
  234. (bot-send-message chat-id
  235. (format nil "Ошибочка вышла~@[: ~A~]"
  236. (when (member chat-id *admins*) e)))))))
  237. (add-hook :update-message ',name)))
  238. (defmacro def-message-cmd-handler (name (&rest commands) &body body)
  239. `(def-message-handler ,name (message)
  240. (when (and text (equal #\/ (char text 0)))
  241. (multiple-value-bind (cmd args) (parse-cmd text)
  242. (when (member cmd (list ,@commands))
  243. (log:info cmd message-id chat-id from-id args)
  244. ,@body
  245. t)))))
  246. (defmacro def-message-admin-cmd-handler (name (&rest commands) &body body)
  247. `(def-message-handler ,name (message)
  248. (when (and (member chat-id *admins*)
  249. text (equal #\/ (char text 0)))
  250. (multiple-value-bind (cmd args) (parse-cmd text)
  251. (when (member cmd (list ,@commands))
  252. (log:info cmd message-id chat-id from-id args)
  253. ,@body
  254. t)))))
  255. ;; Schedule
  256. (defmacro defcron (name (&rest schedule) &body body)
  257. (let ((schedule (or schedule '(:minute '* :hour '*))))
  258. `(progn
  259. (defun ,name ()
  260. (handler-case (progn ,@body)
  261. (error (e) (log:error e))))
  262. (add-hook :starting #'(lambda ()
  263. (clon:schedule-function
  264. ',name (clon:make-scheduler
  265. (clon:make-typed-cron-schedule
  266. ,@schedule)
  267. :allow-now-p t)
  268. :name ',name :thread t)
  269. (values))))))
  270. ;; Fix bug in local-time (following symlinks in /usr/share/zoneinfo/
  271. ;; leads to bad cutoff)
  272. (in-package #:local-time)
  273. (defun reread-timezone-repository (&key (timezone-repository *default-timezone-repository-path*))
  274. (check-type timezone-repository (or pathname string))
  275. (multiple-value-bind (valid? error)
  276. (ignore-errors
  277. (truename timezone-repository)
  278. t)
  279. (unless valid?
  280. (error "REREAD-TIMEZONE-REPOSITORY was called with invalid PROJECT-DIRECTORY (~A). The error is ~A."
  281. timezone-repository error)))
  282. (let* ((root-directory timezone-repository)
  283. (cutoff-position (length (princ-to-string root-directory))))
  284. (flet ((visitor (file)
  285. (handler-case
  286. (let* ((full-name (subseq (princ-to-string file) cutoff-position))
  287. (name (pathname-name file))
  288. (timezone (%realize-timezone (make-timezone :path file :name name))))
  289. (setf (gethash full-name *location-name->timezone*) timezone)
  290. (map nil (lambda (subzone)
  291. (push timezone (gethash (subzone-abbrev subzone)
  292. *abbreviated-subzone-name->timezone-list*)))
  293. (timezone-subzones timezone)))
  294. (invalid-timezone-file () nil))))
  295. (setf *location-name->timezone* (make-hash-table :test 'equal))
  296. (setf *abbreviated-subzone-name->timezone-list* (make-hash-table :test 'equal))
  297. (cl-fad:walk-directory root-directory #'visitor :directories nil :follow-symlinks nil
  298. :test (lambda (file)
  299. (not (find "Etc" (pathname-directory file) :test #'string=))))
  300. (cl-fad:walk-directory (merge-pathnames "Etc/" root-directory) #'visitor :directories nil))))
  301. (let ((zonepath "/usr/share/zoneinfo/"))
  302. (when (directory zonepath)
  303. (local-time:reread-timezone-repository :timezone-repository zonepath)))