1
0

utils.lisp 14 KB

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