1
0

utils.lisp 10 KB

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