utils.lisp 12 KB

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