utils.lisp 13 KB

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