music.lisp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. (in-package :cl-user)
  2. (defpackage chatikbot.plugins.music
  3. (:use :cl :chatikbot.common :alexandria))
  4. (in-package :chatikbot.plugins.music)
  5. (defvar *cookies* (cl-cookie:make-cookie-jar))
  6. (defvar *deluge-api* "http://localhost:8112/json")
  7. (defvar *deluge-password* "chads")
  8. (defvar *deluge-request-id* 1)
  9. (defvar *chad-music-stats-url* "http://localhost:5000/api/stats"))
  10. (defvar *chad-music-rescan-url* "http://localhost:5000/api/rescan"))
  11. (defun jojo-request (url &rest args &key method parameters content headers basic-auth cookie-jar keep-alive use-connection-pool timeout ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path user-agent (as :plist))
  12. (declare (ignore method parameters basic-auth cookie-jar keep-alive use-connection-pool timeout ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path user-agent))
  13. (remf args :as)
  14. (when content
  15. (push (cons :content-type "application/json") headers))
  16. (remf args :headers)
  17. (multiple-value-bind (body status headers uri)
  18. (handler-bind
  19. ((sb-int:broken-pipe #'(lambda (c) (declare (ignorable c))
  20. (invoke-restart (find-restart 'dexador:retry-request)))))
  21. (apply #'http-request url :headers headers args))
  22. (unless (stringp body)
  23. (setf body (trivial-utf-8:utf-8-bytes-to-string body)))
  24. (values (jojo:parse body :as as) status headers uri)))
  25. (defun deluge-request (method &optional params is-auth)
  26. (let* ((content (trivial-utf-8:string-to-utf-8-bytes
  27. (jojo:to-json `(:|id| ,(incf *deluge-request-id*)
  28. :|method| ,method
  29. :|params| ,params))))
  30. (response (jojo-request *deluge-api* :method :post
  31. :content content
  32. :cookie-jar *cookies*))
  33. (error-message (getf (getf response :|error|) :|message|)))
  34. (if error-message
  35. (if (and (null is-auth)
  36. (equal error-message "Not authenticated"))
  37. (progn
  38. (deluge-auth)
  39. (deluge-request method params t)) ;; Retry original request
  40. (error error-message))
  41. (getf response :|result|))))
  42. (defun deluge-auth ()
  43. (deluge-request "auth.login" (list *deluge-password*) t))
  44. (defun infohash-magnet (info-hash)
  45. (concatenate 'string "magnet:?xt=urn:btih:" info-hash))
  46. (defun deluge-add-info-hash (info-hashes)
  47. (unless (listp info-hashes)
  48. (setf info-hashes (list info-hashes)))
  49. (let ((torrents (loop for ih in info-hashes
  50. collect (list :|path| (infohash-magnet ih)
  51. :|options| '(:|add_paused| :true)))))
  52. (deluge-request "web.add_torrents" (list torrents))))
  53. (defun deluge-get-torrents ()
  54. (deluge-request "core.get_session_state"))
  55. (defun deluge-get-torrent-status (info-hash fields)
  56. (deluge-request "core.get_torrent_status" (list info-hash fields)))
  57. (defun deluge-get-torrents-status (filter fields)
  58. (deluge-request "core.get_torrents_status" (list filter fields)))
  59. (defun deluge-remove-torrent (ih &optional from-disk)
  60. (deluge-request "core.remove_torrent" (list ih from-disk)))
  61. (defparameter +deluge-default-status-fields+ '("name" "state" "save_path" "files" "file_priorities" "total_size" "total_wanted" "total_done" "num_files"))
  62. (defun raw-pathname (pathspec)
  63. (values (cl-ppcre:regex-replace-all "\\[" pathspec "\\\\[")))
  64. (defun deluge-get-torrent-files (info-hash)
  65. (let* ((status (deluge-request "core.get_torrent_status" (list info-hash +deluge-default-status-fields+)))
  66. (save-path (getf status :|save_path|)))
  67. (loop for file in (getf status :|files|)
  68. for prio in (getf status :|file_priorities|)
  69. do (setf (getf file :|prio|) prio
  70. (getf file :|path|) (pathname (raw-pathname (format nil "~A/~A" save-path (getf file :|path|)))))
  71. collect file)))
  72. (defun deluge-add-torrent-magnet (uri &optional options)
  73. (deluge-request "core.add_torrent_magnet" (list uri options)))
  74. (defun get-non-skipped (files)
  75. (remove 0 files :key (lambda (f) (getf f :|prio|))))
  76. (defun get-files-folders (files)
  77. (delete-duplicates (mapcar (lambda (f) (uiop:pathname-directory-pathname (getf f :|path|))) files)))
  78. (defparameter +media-exts+ '("mp3" "flac" "ac3"))
  79. (defun media-p (path)
  80. (let* ((ext (subseq path (1+ (or (position #\. path :from-end t) (1- (length path)))))))
  81. (member (string-downcase ext) +media-exts+ :test #'equal)))
  82. (defun get-torrent-info (status)
  83. (labels ((f (field)
  84. (getf status field)))
  85. (let ((wanted-dirs (loop for file in (f :|files|)
  86. for prio in (f :|file_priorities|)
  87. for path = (getf file :|path|)
  88. when (media-p path)
  89. unless (= prio 0)
  90. collect (subseq path 0 (1+ (position #\/ path :from-end t))))))
  91. (list
  92. :name (f :|name|)
  93. :state (keyify (f :|state|))
  94. :save-path (f :|save_path|)
  95. :total-size (f :|total_size|)
  96. :total-wanted (f :|total_wanted|)
  97. :total-done (f :|total_done|)
  98. :num-files (f :|num_files|)
  99. :wanted-files (length wanted-dirs)
  100. :media-dirs (remove-duplicates wanted-dirs :test #'equal)))))
  101. (defun get-import-notify (info action)
  102. (labels ((f (fl) (getf info fl)))
  103. (format nil "[[🎶]] ~a *~a*, ~a альбомов с ~a треками. Весит ~a" action
  104. (f :name) (length (f :media-dirs)) (f :wanted-files) (format-size (f :total-wanted)))))
  105. (defun get-root-paths (info)
  106. (let ((roots (delete-duplicates (loop for dir in (getf info :media-dirs)
  107. collect (subseq dir 0 (1+ (position #\/ dir))))
  108. :test #'equal))
  109. (save (getf info :save-path)))
  110. (mapcar #'(lambda (r) (concatenate 'string save "/" r)) roots)))
  111. (defvar *beet-bin* '("sudo" "-u" "uploader" "/home/uploader/.local/bin/beet"))
  112. (defun beets-import-cmd (paths)
  113. (append *beet-bin*
  114. (list "import" "--move" "--quiet")
  115. paths))
  116. (defun run-import (paths &optional dry)
  117. (let ((cmd (beets-import-cmd paths)))
  118. (if dry (format t "Running ~{~a~^ ~}" cmd)
  119. (uiop:run-program cmd))))
  120. (defun deluge-get-seeding-torrents ()
  121. (loop for (torrent state) on (deluge-get-torrents-status '(:|state| "Seeding") '("name")) by #'cddr
  122. collect (cons (string torrent) (getf state :|name|))))
  123. (defun deluge-pause-torrents (&rest torrents)
  124. (deluge-request "core.pause_torrent" (list torrents)))
  125. (defun deluge-delete-skipped (torrent &optional dry)
  126. (let* ((status (deluge-request "core.get_torrent_status" (list torrent +deluge-default-status-fields+)))
  127. (save-path (getf status :|save_path|)))
  128. (loop for file in (getf status :|files|)
  129. for prio in (getf status :|file_priorities|)
  130. for path = (pathname (raw-pathname (format nil "~A/~A" save-path (getf file :|path|))))
  131. when (zerop prio)
  132. when (probe-file path)
  133. do (if dry (format t "Deleting '~A'~%" path)
  134. (uiop:delete-file-if-exists path)))))
  135. (defun send-admins (msg &optional dry)
  136. (if dry (format t "~a~%" msg)
  137. (loop for *chat-id* in (lists-get :music-admins)
  138. do (bot-send-message msg :parse-mode "markdown"))))
  139. (defun process-downloaded (ih &optional dry)
  140. (let* ((status (deluge-get-torrent-status ih +deluge-default-status-fields+))
  141. (info (get-torrent-info status))
  142. (notify (get-import-notify info "Добавляем"))
  143. (paths (get-root-paths info)))
  144. (send-admins notify dry)
  145. (deluge-pause-torrents ih)
  146. (deluge-delete-skipped ih dry)
  147. (run-import paths dry)
  148. (json-request *chad-music-rescan-url* :method :post)
  149. (if dry (format t "Removing torrent ~a" ih)
  150. (deluge-remove-torrent ih))))
  151. (defun process-imports ()
  152. (loop
  153. (loop for (ih . name) in (deluge-get-seeding-torrents)
  154. do (handler-case (process-downloaded ih)
  155. (error (c) (log:error "Error processing torrent" name c))))
  156. (sleep 1)))
  157. (defvar *watcher* nil "Importer thread ")
  158. (defvar *lock* (bordeaux-threads:make-recursive-lock "Music watch"))
  159. (defun ensure-watcher ()
  160. (bt:with-recursive-lock-held (*lock*)
  161. (if (lists-get :music-watch)
  162. (unless *watcher*
  163. (setf *watcher* (bt:make-thread 'process-imports :name "music watch")))
  164. (when *watcher*
  165. (bt:destroy-thread *watcher*)
  166. (setf *watcher* nil))))
  167. (values))
  168. (defun handle-set-watch (enable)
  169. (lists-set-entry :music-watch *chat-id* enable)
  170. (ensure-watcher)
  171. (bot-send-message (if enable "[🎶] Импортим музло" "[🎶] Пусть мешки парятся")))
  172. (defun handle-status ()
  173. (let* ((db-stats (when *chad-music-stats-url*
  174. (json-request *chad-music-stats-url*)))
  175. (stats (loop
  176. for (torrent status) on (deluge-get-torrents-status nil '("state" "name" "total_wanted")) by #'cddr
  177. for state = (getf status :|state|)
  178. when (equal state "Downloading") counting t into down
  179. when (equal state "Seeding") counting t into seed
  180. summing (getf status :|total_wanted|) into size
  181. finally (return (list :down down :seed seed :size size)))))
  182. (bot-send-message (format nil "[[🎶]] Осталось скачать ~a, заимпортить ~a торрентов, общий объём ~a.~%Сейчас в базе ~a исполнителей с ~a альбомами и ~a треками, общей длительностью ~a"
  183. (getf stats :down) (getf stats :seed) (format-size (getf stats :size))
  184. (agets db-stats "artists")
  185. (agets db-stats "albums")
  186. (agets db-stats "tracks")
  187. (agets db-stats "duration"))
  188. :parse-mode "markdown")))
  189. (defparameter +magnet-regex+ (ppcre:create-scanner "magnet:\\?\\S+"))
  190. (defun handle-add-torrent (magnet)
  191. (let* ((ih (deluge-add-torrent-magnet magnet))
  192. (status (deluge-get-torrent-status ih +deluge-default-status-fields+))
  193. (info (get-torrent-info status))
  194. (notify (get-import-notify info "Качаем")))
  195. (bot-send-message notify)))
  196. (def-message-cmd-handler handle-cmd-music (:music)
  197. (with-chat-in-list :music-admins
  198. (let ((arg (car *args*)))
  199. (cond
  200. ((and (= 1 (length *args*)) (member (string-downcase arg) '("on" "off") :test 'equal))
  201. (handle-set-watch (equal "on" arg)))
  202. ((ppcre:scan-to-strings +magnet-regex+ arg)
  203. (handle-add-torrent (ppcre:scan-to-strings +magnet-regex+ arg)))
  204. (:otherwise (handle-status))))))
  205. (add-hook :starting #'ensure-watcher)