1
0

utils.lisp 14 KB

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