From 771abb84830678455de4625ac7f082d8100f0ea0 Mon Sep 17 00:00:00 2001 From: jao Date: Tue, 2 Feb 2021 05:16:17 +0000 Subject: libs -> lib/ --- lib/media/espotify.org | 627 +++++++++++++++++++++++++++++++++++++ lib/media/jao-emms-info-track.el | 212 +++++++++++++ lib/media/jao-emms-lyrics.el | 41 +++ lib/media/jao-emms-random-album.el | 118 +++++++ lib/media/jao-emms.el | 27 ++ lib/media/jao-lyrics.el | 152 +++++++++ lib/media/jao-mpris.el | 139 ++++++++ lib/media/jao-random-album.el | 101 ++++++ lib/media/leoslyrics.py | 84 +++++ lib/media/lyricwiki.rb | 52 +++ 10 files changed, 1553 insertions(+) create mode 100644 lib/media/espotify.org create mode 100644 lib/media/jao-emms-info-track.el create mode 100644 lib/media/jao-emms-lyrics.el create mode 100644 lib/media/jao-emms-random-album.el create mode 100644 lib/media/jao-emms.el create mode 100644 lib/media/jao-lyrics.el create mode 100644 lib/media/jao-mpris.el create mode 100644 lib/media/jao-random-album.el create mode 100755 lib/media/leoslyrics.py create mode 100755 lib/media/lyricwiki.rb (limited to 'lib/media') diff --git a/lib/media/espotify.org b/lib/media/espotify.org new file mode 100644 index 0000000..93338a9 --- /dev/null +++ b/lib/media/espotify.org @@ -0,0 +1,627 @@ +#+title: consulting spotify +#+date: <2021-01-08 04:02> +#+filetags: emacs +#+PROPERTY: header-args :tangle yes :comments no :results silent + +(/Note/: you can tangle this file (e.g., with =C-c C-v t= inside Emacs) +into three elisp libraries, =espotify.el=, =espotify-consult.el, +=espotify-embark=. and =espotify-counsel=) + +We have two kinds of interaction with Spotify: via its HTTP API to +perform operations such as search, and via our local DBUS to talk to +client players running in our computer, such as the official client, +[[https://github.com/Spotifyd/spotifyd][spotifyd]] or [[https://mopidy.com/ext/spotify/][mopidy-spotify]]. Our goal is to obtain via the former a +track or album identifier that we can send then to the latter to play, +with emacs completion mechanisms (consult and friends in this case) +providing the glue between both worlds. + +Let's start with an umbrella customization group: +#+begin_src emacs-lisp + ;;; espotify.el - spotify search and play - -*- lexical-binding: t; -*- + + (defgroup espotify nil + "Access to Spotify API and clients" + :group 'multimedia) +#+end_src + +* Access to Spotify's API: authentication + + I am stealing most of the ideas on how to establish authenticated + connections to the Spotify API and performing queries from + [[https://github.com/Lautaro-Garcia/counsel-spotify][counsel-spotify]], with many simplifications. + + We start defining a couple of end-points: + + #+begin_src emacs-lisp + (defvar espotify-spotify-api-url "https://api.spotify.com/v1") + (defvar espotify-spotify-api-authentication-url + "https://accounts.spotify.com/api/token") + #+end_src + + And we're going to need as well a client id and secret for our + application, which i am again defining as variables since i expect + them to be set in some secure manner instead of via customize: + + #+begin_src emacs-lisp + (defvar espotify-client-id nil "Spotify application client ID.") + (defvar espotify-client-secret nil "Spotify application client secret.") + #+end_src + + To get valid values for them, one just needs to [[https://developer.spotify.com/my-applications][register a Spotify + application]]. From them we can derive a base64-encoded credentials + value: + + #+begin_src emacs-lisp + (defun espotify--basic-auth-credentials () + (let ((credential (concat espotify-client-id ":" espotify-client-secret))) + (concat "Basic " (base64-encode-string credential t)))) + #+end_src + + The return value of the function above is to be used as the + "Authorization" header of our requests to the authorization + end-point, which is going to answer with an authorization token + that we can then use to further requests. Let's define a function to + wrap that operation: + + #+begin_src emacs-lisp + (defun espotify--with-auth-token (callback) + (let ((url-request-method "POST") + (url-request-data "&grant_type=client_credentials") + (url-request-extra-headers + `(("Content-Type" . "application/x-www-form-urlencoded") + ("Authorization" . ,(espotify--basic-auth-credentials))))) + (url-retrieve espotify-spotify-api-authentication-url + (lambda (_status) + (goto-char url-http-end-of-headers) + (funcall callback + (alist-get 'access_token (json-read))))))) + #+end_src + + For instance: + #+begin_src emacs-lisp :load no :tangle no + (espotify--with-auth-token + (lambda (token) (message "Your token is: %s" token))) + #+end_src + + obtains an auth token and prints it as a message. Note that ~body~ + is evaluated asynchronously by ~url-retrieve~, so invocations to + ~espotify-with-auth-token~ evaluate to the request's buffer and are + usually discarded. + +* Search queries using the Spotify API + + We are interested in performing a search for some ~term~, of items + of a given ~types~ (~:track~, ~:album~, ~:artist~, etc.), possibly with an + additional ~filter~. That's specified in a GET request's URL + as constructed by this function: + + #+begin_src emacs-lisp + (defun espotify--make-search-url (term types &optional filter) + (when (null types) + (error "Must supply a non-empty list of types to search for")) + (let ((term (url-encode-url term))) + (format "%s/search?q=%s&type=%s&limit=50" + espotify-spotify-api-url + (if filter (format "%s:%s" filter term) term) + (mapconcat #'symbol-name types ",")))) + #+end_src + + For instance: + + #+begin_src emacs-lisp :load no :tangle no :results replace + (espotify--make-search-url "dream blue turtles" '(album)) + #+end_src + + #+RESULTS: + : https://api.spotify.com/v1/search?q=dream%20blue%20turtles&type=album&limit=50 + + If we have an [[*Access to Spotify's API: authentication][authorisation token]] and a search URL in our hands, + we can use them as in the following helper function, which will + calls the given callback with the results of the query: + + #+begin_src emacs-lisp + (defun espotify--with-query-results (token url callback) + (let ((url-request-extra-headers + `(("Authorization" . ,(concat "Bearer " token))))) + (url-retrieve url + (lambda (_status) + (goto-char url-http-end-of-headers) + (funcall callback + (let ((json-array-type 'list)) + (thread-first + (buffer-substring (point) (point-max)) + (decode-coding-string 'utf-8) + (json-read-from-string)))))))) + #+end_src + + So we can combine this macro with ~espotify--with-auth-token~ in a + single search function that takes a callback that will be applied + to a given query, specified as a triple of term, types and filter: + + #+begin_src emacs-lisp + (defun espotify-get (callback url) + (espotify--with-auth-token + (lambda (token) + (espotify--with-query-results token url callback)))) + + (defun espotify-search (callback term types &optional filter) + (espotify-get callback (espotify--make-search-url term types filter))) + #+end_src + + For instance: + #+begin_src emacs-lisp :load no :tangle no + (defvar espotify-query-result nil) + (espotify-search (lambda (res) (setq espotify-query-result res)) + "dream blue turtles" + '(album artist)) + (sit-for 0) + #+end_src + + #+begin_src emacs-lisp :load no :tangle no :results replace + (mapcar 'car espotify-query-result) + #+end_src + + #+RESULTS: + | albums | artists | + + So Spotify is returning a results entry per type, which in turn, + contains an ~items~ with the list of actual results. So let's + provide an interface for a callback that takes as many lists of + items as types it asks for: + + #+begin_src emacs-lisp + (defun espotify--type-items (res type) + (alist-get 'items (alist-get (intern (format "%ss" type)) res))) + + (defun espotify-search* (callback term types &optional filter) + (let* ((types (if (listp types) types (list types))) + (cb (lambda (res) + (let ((its (mapcar (lambda (tp) + (espotify--type-items res tp)) + types))) + (apply callback its))))) + (espotify-search cb term types filter))) + #+end_src + + For example: + + #+begin_src emacs-lisp :load no :tangle no + (defvar espotify-query-result nil) + (espotify-search* (lambda (al ar) + (message "Found %s albums, %s artists" + (length al) (length ar)) + (setq espotify-query-result (cons al ar))) + "blue turtles" + '(album artist)) + (sit-for 0) + (list (mapcar 'car (car (car espotify-query-result))) + (mapcar 'car (car (cdr espotify-query-result)))) + #+end_src + + #+RESULTS: + | album_type | artists | available_markets | external_urls | href | id | images | name | release_date | release_date_precision | total_tracks | type | uri | + | external_urls | followers | genres | href | id | images | name | popularity | type | uri | | | | + + Another strategy would be to search for several types and pass to + our callback the concatenation of all items: + + #+begin_src emacs-lisp + (defun espotify-search-all (callback term &optional types filter) + (let ((types (or types '(album track artist playlist)))) + (espotify-search* (lambda (&rest items) + (funcall callback (apply 'append items))) + term + types + filter))) + #+end_src + +* Listing user resources in the Spotify API + + It is also possible to obtain lists of items of a given type for the + current user, with a standard URL format: + + #+begin_src emacs-lisp + (defun espotify--make-user-url (type) + (format "%s/me/%ss" espotify-spotify-api-url (symbol-name type))) + #+end_src + + and we can then use ~espotify-get~ to offer access to our playlists, + albums, etc.: + + #+begin_src emacs-lisp + (defun espotify-with-user-resources (callback type) + (espotify-get (lambda (res) (funcall callback (alist-get 'items res))) + (espotify--make-user-url type))) + #+end_src + +* Sending commands to local players + + Once we now the URI we want to play (that ~uri~ entry in our items), + sending it to a local player via DBUS is fairly easy. Let's + define a couple of customizable variables pointing to the service + name and bus: + + #+begin_src emacs-lisp + (defcustom espotify-service-name "mopidy" + "Name of the DBUS service used by the client we talk to. + + The official Spotify client uses `spotify', but one can also use + alternative clients such as mopidy or spotifyd." + :type 'string) + + (defcustom espotify-use-system-bus-p t + "Whether to access the spotify client using the system DBUS.") + #+end_src + + and then using the Emacs DBUS API to send methods to it is a + breeze: + + #+begin_src emacs-lisp + (defun espotify-call-spotify-via-dbus (method &rest args) + "Tell Spotify to execute METHOD with ARGS through DBUS." + (apply #'dbus-call-method `(,(if espotify-use-system-bus-p :system :session) + ,(format "org.mpris.MediaPlayer2.%s" + espotify-service-name) + "/org/mpris/MediaPlayer2" + "org.mpris.MediaPlayer2.Player" + ,method + ,@args))) + + (defun espotify-play-uri (uri) + (espotify-call-spotify-via-dbus "OpenUri" uri)) + #+end_src + +* Search front-end using consult + :PROPERTIES: + :header-args: :tangle espotify-consult.el + :END: + + I am exploring [[https://github.com/minad/consult][consult.el]] (and friends) to replace ivy/counsel, + inspired in part by [[https://protesilaos.com/codelog/2021-01-06-emacs-default-completion/][Protesilaos Stavrou's musings]], and liking a + lot what i see. Up till now, everything i had with counsel is + supported, often in better ways, with one exception: completing + search of spotify albums using [[https://github.com/Lautaro-Garcia/counsel-spotify][counsel-spotify]]. So let's fix that + by defining an asynchronous consult function that does precisely + that! + + The top-level command will have this form: + + #+begin_src emacs-lisp + ;;; espotify-consult.el - consult support - -*- lexical-binding: t; -*- + + (require 'espotify) + (require 'consult) + + (defvar espotify-consult-history nil) + + (defun espotify-consult-by (type &optional filter) + (let ((orderless-matching-styles '(orderless-literal))) + (consult--read (format "Search %ss: " type) + (espotify--search-generator type filter) + :lookup 'espotify--consult-lookup + :category 'espotify-search-item + :history 'espotify-consult-history + :initial consult-async-default-split + :require-match t))) + #+end_src + + where we can write an asynchronous generator of search results + with the helper function: + + #+begin_src emacs-lisp + (defun espotify--search-generator (type filter) + (thread-first (consult--async-sink) + (consult--async-refresh-immediate) + (consult--async-map #'espotify--format-item) + (espotify--async-search type filter) + (consult--async-throttle) + (consult--async-split))) + #+end_src + + The above follows a generic consult pattern, where all functions + are pre-defined for us except ~espotify--async-search~, an + asynchronous dispatcher closure that must generate and handle a + list of candidates, responding to a set of action messages (init, + reset, get, flush, etc.) [fn:1] Here's its definition in our + case: + + #+begin_src emacs-lisp + (defun espotify--async-search (next type filter) + (let ((current "")) + (lambda (action) + (pcase action + ((pred stringp) + (when-let (term (espotify-check-term current action)) + (setq current term) + (espotify-search-all + (lambda (x) + (funcall next 'flush) + (funcall next x)) + current + type + filter))) + (_ (funcall next action)))))) + #+end_src + + We have introduced the convention that we're only launching a search + when the input string ends in "=", to avoid piling on HTTP + requests, and also played a bit with Levenshtein distance, both via + the function =espotify-check-search-term=: + + #+begin_src emacs-lisp :tangle espotify.el + (defvar espotify-search-suffix "=" + "Suffix in the search string launching an actual Web query.") + + (defvar espotify-search-threshold 8 + "Threshold to automatically launch an actual Web query.") + + (defun espotify-check-term (prev new) + (when (not (string-blank-p new)) + (cond ((string-suffix-p espotify-search-suffix new) + (substring new 0 (- (length new) (length espotify-search-suffix)))) + ((>= (string-distance prev new) espotify-search-threshold) new)))) + #+end_src + + In the consult case, a more natural choice for the search suffix is + + #+begin_src emacs-lisp + (setq espotify-search-suffix consult-async-default-split) + #+end_src + + When processing the results, we format them as a displayable + string, while hiding in a property the URI that will allow us to + play the item (and pass the formatter to ~consult-async--map~, in + ~espotify--search-generator~ above): + + #+begin_src emacs-lisp :tangle espotify.el + (defun espotify--additional-info (x) + (mapconcat 'identity + (seq-filter 'identity + `(,(alist-get 'name (alist-get 'album x)) + ,(alist-get 'name (car (alist-get 'artists x))) + ,(alist-get 'display_name (alist-get 'owner x)))) + ", ")) + + (defun espotify--format-item (x) + (propertize (format "%s%s" + (alist-get 'name x) + (if-let ((info (espotify--additional-info x))) + (format " (%s)" info) + "")) + 'espotify-item x)) + + (defun espotify--item (cand) + (get-text-property 0 'espotify-item cand)) + + (defun espotify--uri (cand) + (alist-get 'uri (espotify--item cand))) + #+end_src + + and then we make sure that we access that original string when + consult looks up for it using the ~:lookup~ function, which we can + simply define as: + + #+begin_src emacs-lisp + (require 'seq) + (defun espotify--consult-lookup (_input cands cand) + (seq-find (lambda (x) (string= cand x)) cands)) + #+end_src + + + With that, when we receive the final result from ~consult--read~, + we can play the selected URI right away: + + #+begin_src emacs-lisp :tangle espotify.el + (defun espotify--maybe-play (cand) + (when-let (uri (when cand (espotify--uri cand))) + (espotify-play-uri uri))) + #+end_src + + And here, finally, are our interactive command to search and play + albums using consult: + + #+begin_src emacs-lisp + (defun espotify-consult-album (&optional filter) + (interactive) + (espotify--maybe-play (espotify-consult-by 'album filter))) + #+end_src + + And likewise for playlists, artists and combinations thereof: + + #+begin_src emacs-lisp + (defun espotify-consult-artist (&optional filter) + (interactive) + (espotify--maybe-play (espotify-consult-by 'artist filter))) + + (defun espotify-consult-track (&optional filter) + (interactive) + (espotify--maybe-play (espotify-consult-by 'track filter))) + + (defun espotify-consult-playlist (&optional filter) + (interactive) + (espotify--maybe-play (espotify-consult-by 'playlist filter))) + #+end_src + +* Adding metadata to candidates using Marginalia + :PROPERTIES: + :header-args: :tangle espotify-consult.el + :END: + + Let's add metadata fields to our candidates, so that packages like + [[https://github.com/minad/marginalia][Marginalia]] can offer it to consult or selectrum. + + #+begin_src emacs-lisp + (defun espotify-marginalia-annotate (cand) + (when-let (x (espotify--item cand)) + (marginalia--fields + ((alist-get 'type x "") :face 'marginalia-mode :width 10) + ((if-let (d (alist-get 'duration_ms x)) + (let ((secs (/ d 1000))) + (format "%02d:%02d" (/ secs 60) (mod secs 60))) + "")) + ((if-let (d (alist-get 'total_tracks x)) (format "%s tracks" d) "") + :face 'marginalia-size :width 12) + ((if-let (d (alist-get 'release_date (alist-get 'album x x))) + (format "%s" d) + "") + :face 'marginalia-date :width 10)))) + + (add-to-list 'marginalia-annotators-heavy + '(espotify-search-item . espotify-marginalia-annotate)) + #+end_src + +* Embark actions + :PROPERTIES: + :header-args: :tangle espotify-embark.el + :END: + + In addition to the default action (play the URI in the selected + candidate), we can use embark to define other operations. For + instance, we could print the full item alist in its own buffer, or + always look for an album to play: + + #+begin_src emacs-lisp + (require 'espotify-consult) + (require 'embark) + + (defvar espotify--current-item nil) + + (defun espotify--show-info (name) + "Show low-level info (an alist) about selection." + (interactive "s") + (pop-to-buffer (get-buffer-create "*espotify info*")) + (read-only-mode -1) + (delete-region (point-min) (point-max)) + (insert (propertize name 'face 'bold)) + (newline) + (when espotify--current-item + (insert (pp-to-string espotify--current-item))) + (newline) + (goto-char (point-min)) + (read-only-mode 1)) + + (defun espotify--play-album (ignored) + "Play album associated with selected item." + (interactive "i") + (if-let (album (if (string= "album" + (alist-get 'type espotify--current-item "")) + espotify--current-item + (alist-get 'album espotify--current-item))) + (espotify-play-uri (alist-get 'uri album)) + (error "No album for %s" (alist-get 'nmae espotify--current-item)))) + + (embark-define-keymap espotify-item-keymap + "Actions for Spotify search results" + ("a" espotify--play-album) + ("h" espotify--show-info)) + + (defun espotify--annotate-item (cand) + (setq espotify--current-item (espotify--item cand)) + (cons 'espotify-search-item cand)) + + (add-to-list 'embark-transformer-alist + '(espotify-search-item . espotify--annotate-item)) + + (add-to-list 'embark-keymap-alist + '(espotify-search-item . espotify-item-keymap)) + #+end_src + +* Search fronted using ivy + :PROPERTIES: + :header-args: :tangle espotify-counsel.el + :END: + + #+begin_src emacs-lisp + ;;; counsel-espotify.el - counsel and spotify - -*- lexical-binding: t; -*- + (require 'espotify) + (require 'ivy) + #+end_src + + It is is also not too complicated to provide a counsel collection of + functions. Here, we use =ivy-read= to access the completion + interface, with the flag =dynamic-collection= set. Ivy will wait + until we call =ivy-candidate-updates= with our items. + + #+begin_src emacs-lisp + (defun espotify-counsel--search-by (type filter) + (let ((current-term "")) + (lambda (term) + (when-let (term (espotify-check-term current-term term)) + (espotify-search-all (lambda (its) + (let ((cs (mapcar #'espotify--format-item its))) + (ivy-update-candidates cs))) + (setq current-term term) + type + filter)) + 0))) + #+end_src + + With that, we can define our generic completing read: + + #+begin_src emacs-lisp + + (defun espotify-counsel--play-album (candidate) + "Play album associated with selected item." + (interactive "s") + (let ((item (espotify--item candidate))) + (if-let (album (if (string= "album" (alist-get 'type item "")) + item + (alist-get 'album item))) + (espotify-play-uri (alist-get 'uri album)) + (error "No album for %s" (alist-get 'name item))))) + + (defun espotify-search-by (type filter) + (ivy-read (format "Search %s: " type) + (espotify-counsel--search-by type filter) + :dynamic-collection t + :action `(1 ("a" espotify-counsel--play-album "Play album") + ("p" espotify--maybe-play ,(format "Play %s" type))))) + #+end_src + + and our collection of searching commands: + + #+begin_src emacs-lisp + (defun espotify-counsel-album (&optional filter) + (interactive) + (espotify-search-by 'album filter)) + + (defun espotify-counsel-artist (&optional filter) + (interactive) + (espotify-search-by 'artist filter)) + + (defun espotify-counsel-track (&optional filter) + (interactive) + (espotify-search-by 'track filter)) + + (defun espotify-counsel-playlist (&optional filter) + (interactive) + (espotify-search-by 'playlist filter)) + #+end_src + + Simpler than our initial consult, although it's true that we already + had part of the job done. The nice "split search" that counsult + offers out of the box, though, is much more difficult to get. + +* Postamble + + #+begin_src emacs-lisp + (provide 'espotify) + #+end_src + + #+begin_src emacs-lisp :tangle espotify-consult.el + (provide 'espotify-consult) + #+end_src + + #+begin_src emacs-lisp :tangle espotify-embark.el + (provide 'espotify-embark) + #+end_src + + #+begin_src emacs-lisp :tangle espotify-counsel.el + (provide 'espotify-counsel) + #+end_src + +* Footnotes + +[fn:1] This is an elegant strategy i first learnt about in SICP, many, +many years ago, and i must say that it is very charming to find it +around in the wild! diff --git a/lib/media/jao-emms-info-track.el b/lib/media/jao-emms-info-track.el new file mode 100644 index 0000000..839ef73 --- /dev/null +++ b/lib/media/jao-emms-info-track.el @@ -0,0 +1,212 @@ +;; jao-emms-info-track.el -- utilities to show tracks -*- lexical-binding:t; -*- + +;; Copyright (C) 2009, 2010, 2013, 2017, 2020, 2021 Jose Antonio Ortega Ruiz + +;; Author: Jose Antonio Ortega Ruiz +;; Start date: Sat Jul 04, 2009 13:47 + +;; This file is free software; you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation; either version 3 of the License, or +;; (at your option) any later version. + +;; This file is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see . + +;;; Code: + +(require 'emms) +(require 'emms-tag-editor) +(require 'emms-player-mpd) +(require 'jao-osd) +(require 'jao-emms) +(require 'jao-minibuffer) + +(defgroup jao-emms-faces nil "Faces" + :group 'faces + :group 'jao-emms) + +(defface jao-emms-font-lock-album '((t (:foreground "lightgoldenrod2"))) + "Album name in EMMS track message." + :group 'jao-emms-faces) + +(defface jao-emms-font-lock-track '((t (:bold t))) + "Track number in EMMS track message." + :group 'jao-emms-faces) + +(defface jao-emms-font-lock-title '((t (:foreground "dodgerblue2"))) + "Track title in EMMS track message." + :group 'jao-emms-faces) + +(defface jao-emms-font-lock-artist '((t (:foreground "dodgerblue3"))) + "Artist name in EMMS track message." + :group 'jao-emms-faces) + +(defcustom jao-emms-show-osd-p nil + "Whether to show osd notices on track change" + :group 'jao-emms) + + + +(defun jao-emms-info-track-stream (track) + "Return track info for streams" + (let ((name (emms-track-name track)) + (title (or (emms-track-get track 'title nil) + (car (emms-track-get track 'metadata nil)) + (car (split-string (shell-command-to-string "mpc status") + "\n"))))) + (format "♪ %s (%s)" (or title "") (if title (emms-track-type track) name)))) + +(defsubst jao--put-face (str face) + (put-text-property 0 (length str) 'face face str) + str) + +(defun jao-emms--to-number (x) + (or (and (numberp x) x) + (and (stringp x) + (string-match "\\`\\(:?[0-9]+\\)" x) + (string-to-number (match-string 1 x))))) + +(defun jao-emms--fmt-time (x suffix) + (if x (format "%02d:%02d%s" (/ x 60) (mod x 60) (or suffix "")) "")) + +(defun jao-emms--fmt-song-times (track lapsed pre post) + (if lapsed + (let ((time (when track (emms-track-get track 'info-playing-time)))) + (format "%s%s%s%s" + (or pre "") + (jao-emms--fmt-time lapsed (when time "/")) + (jao-emms--fmt-time time "") + (or post ""))) + "")) + +(defun jao-emms-info-track-file (track &optional lapsed plen titlesep) + "Return a description of the current track." + (let* ((no (jao-emms--to-number (emms-track-get track 'info-tracknumber "0"))) + (time (emms-track-get track 'info-playing-time)) + (year (emms-track-get track 'info-year)) + (year (if year (format " (%s)" year) "")) + (artist (emms-track-get track 'info-artist "")) + (composer (emms-track-get track 'info-composer nil)) + (title (emms-track-get track 'info-title "")) + (album (emms-track-get track 'info-album)) + (last-played (or (emms-track-get track 'last-played) '(0 0 0))) + (play-count (or (emms-track-get track 'play-count) 0)) + (playlength (if plen (format "/%02d" (string-to-number plen)) ""))) + (if (or (not title) (not album)) + (emms-track-simple-description track) + (format "🎵 %s%s%s%s%s%s%s" + (jao--put-face (if (zerop no) "" (format "%02d%s " no playlength)) + 'jao-emms-font-lock-track) + (jao--put-face title + 'jao-emms-font-lock-title) + (or titlesep " ") + (jao-emms--fmt-song-times track lapsed "[" "] ") + (jao--put-face artist 'jao-emms-font-lock-artist) + (jao--put-face (if composer (format " [%s]" composer) "") + 'jao-emms-font-lock-artist) + (jao--put-face (if album + (format " (%s%s)" album year) + (format "%s *") year) + 'jao-emms-font-lock-album))))) + +;;;###autoload +(defun jao-emms-info-track-description (track &optional lapsed plen tsep) + (if (memq (emms-track-type track) '(streamlist url)) + (jao-emms-info-track-stream track) + (jao-emms-info-track-file track lapsed plen tsep))) + +;;;###autoload +(defun jao-emms-toggle-osd () + (interactive) + (setq jao-emms-show-osd-p (not jao-emms-show-osd-p)) + (message "Emms OSD %s" (if jao-emms-show-osd-p "enabled" "disabled"))) + +(defvar jao-emms-show-icon nil) + +(defun jao-emms--with-mpd-track (callback) + (emms-player-mpd-get-status + nil + (lambda (_ st) + (let* ((lapsed (jao-emms--to-number (cdr (assoc "time" st)))) + (plen (cdr (assoc "playlistlength" st))) + (song (jao-emms--to-number (cdr (assoc "song" st)))) + (track (emms-playlist-current-selected-track))) + (when (and track song) + (emms-track-set track 'info-tracknumber (format "%d" (1+ song)))) + (funcall callback track lapsed plen))))) + +;;;###autoload +(defun jao-emms-show-osd () + (interactive) + (jao-emms--with-mpd-track + (lambda (track lapsed play-len) + (let* ((sep "~~~~~") + (s (jao-emms-info-track-description track lapsed play-len sep)) + (s (substring-no-properties s 2)) + (cs (split-string s sep))) + (jao-notify (car cs) (cadr cs) jao-emms-show-icon))))) + +(defun jao-emms-show-osd-hook () + (interactive) + (when jao-emms-show-osd-p (jao-emms-show-osd))) + +(defun jao-emms-install-id3v2 () + (add-to-list 'emms-tag-editor-tagfile-functions + '("mp3" "id3v2" ((info-artist . "-a") + (info-title . "-t") + (info-album . "-A") + (info-tracknumber . "-T") + (info-year . "-y") + (info-genre . "-g") + (info-composer . "--TCOM") + (info-note . "-c"))))) + +(defvar jao-emms-echo-string "") + +(defun jao-emms--echo-string (v) + (setq jao-emms-echo-string v) + (jao-minibuffer-refresh)) + +(defun jao-emms-update-echo-string (&optional existing-track) + (if emms-player-playing-p + (jao-emms--with-mpd-track + (lambda (track lapsed play-len) + (jao-emms--echo-string + (cond ((and emms-player-paused-p existing-track) + (format "(%s/%s)" + (emms-track-get existing-track 'info-tracknumber) + play-len)) + (emms-player-paused-p "") + (t (jao-emms-info-track-description track nil play-len)))))) + (jao-emms--echo-string ""))) + +(defun jao-emms-enable-minibuffer (minibuffer-order) + (jao-minibuffer-add-variable 'jao-emms-echo-string minibuffer-order) + (dolist (h '(emms-track-updated-functions + emms-player-finished-hook + emms-player-stopped-hook + emms-player-started-hook + emms-player-paused-hook)) + (add-hook h #'jao-emms-update-echo-string))) + +;;;###autoload +(defun jao-emms-info-setup (&optional minibuffer show-osd show-echo-line id3) + (setq emms-track-description-function 'jao-emms-info-track-description) + (setq jao-emms-show-osd-p show-osd) + (add-hook 'emms-player-started-hook 'jao-emms-show-osd-hook) + (when minibuffer (jao-emms-enable-minibuffer minibuffer)) + (unless show-echo-line + (eval-after-load 'emms-player-mpd + '(remove-hook 'emms-player-started-hook 'emms-player-mpd-show))) + (when id3 (jao-emms-install-id3v2)) + (ignore-errors (emms-player-mpd-connect))) + + +(provide 'jao-emms-info-track) +;;; jao-emms-info-track.el ends here diff --git a/lib/media/jao-emms-lyrics.el b/lib/media/jao-emms-lyrics.el new file mode 100644 index 0000000..0ea52e0 --- /dev/null +++ b/lib/media/jao-emms-lyrics.el @@ -0,0 +1,41 @@ +;; jao-emms-lyrics.el -- simple show lyrics in emms + +;; Copyright (C) 2009, 2010, 2017, 2019, 2020 Jose Antonio Ortega Ruiz + +;; Author: Jose Antonio Ortega Ruiz +;; Start date: Sat Jul 04, 2009 13:41 + +;; This file is free software; you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation; either version 3 of the License, or +;; (at your option) any later version. + +;; This file is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see . + +;;; Code: + +(require 'emms) +(require 'jao-lyrics) + +;;;###autoload +(defun jao-emms-lyrics-track-data () + (let ((track (or (emms-playlist-current-selected-track) + (error "No playing track")))) + (cons (or (emms-track-get track 'info-artist nil) + (error "No artist")) + (or (emms-track-get track 'info-title nil) + (error "No artist"))))) + +;;;###autoload +(defun jao-emms-show-lyrics (&optional force) + (let ((jao-lyrics-info-function 'jao-emms-lyrics-track-data)) + (jao-show-lyrics force))) + +(provide 'jao-emms-lyrics) +;;; jao-emms-lyrics.el ends here diff --git a/lib/media/jao-emms-random-album.el b/lib/media/jao-emms-random-album.el new file mode 100644 index 0000000..72e056b --- /dev/null +++ b/lib/media/jao-emms-random-album.el @@ -0,0 +1,118 @@ +;; jao-emms-random-album.el -- play random albums in emms + +;; Copyright (C) 2009, 2010, 2017, 2018, 2020 Jose Antonio Ortega Ruiz + +;; Author: Jose Antonio Ortega Ruiz +;; Start date: Sat Jul 04, 2009 13:06 + +;; This file is free software; you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation; either version 3 of the License, or +;; (at your option) any later version. + +;; This file is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see . + + +(require 'emms) +(require 'jao-minibuffer) + +(defvar jao-emms-random-album-p t) +(defvar jao-emms-random-lines nil) +(defvar jao-emms-random-lines-file + (expand-file-name "~/.emacs.d/random-lines")) +(defvar jao-emms-random-album-notify-p t) +(defvar jao-emms-random-album-notify-icon nil) + +(defun jao-emms-random-lines () + (or jao-emms-random-lines + (and (file-exists-p jao-emms-random-lines-file) + (with-current-buffer + (find-file-noselect jao-emms-random-lines-file) + (goto-char (point-min)) + (setq jao-emms-random-lines (read (current-buffer))))) + (dotimes (n (1- (line-number-at-pos (point-max))) + jao-emms-random-lines) + (push (1+ n) jao-emms-random-lines)))) + +(defun jao-emms-random-lines-save () + (with-current-buffer (find-file-noselect jao-emms-random-lines-file) + (delete-region (point-min) (point-max)) + (insert (format "%s\n" jao-emms-random-lines)) + (save-buffer))) + +(defun jao-emms-goto-random-album () + (let* ((pos (random (length (jao-emms-random-lines)))) + (line (nth pos jao-emms-random-lines))) + (setq jao-emms-random-lines (remove line jao-emms-random-lines)) + (jao-emms-random-lines-save) + (goto-line line))) + +(defun jao-emms-next-noerror () + (interactive) + (when emms-player-playing-p + (error "A track is already being played")) + (cond (emms-repeat-track + (emms-start)) + ((condition-case nil + (progn + (emms-playlist-current-select-next) + t) + (error nil)) + (emms-start)) + (t + (if jao-emms-random-album-p + (jao-emms-random-album-next) + (message "No next track in playlist"))))) + + +;; User interface +;;;###autoload +(defun jao-emms-random-album-start () + (interactive) + (setq jao-emms-random-album-p t) + (jao-emms-random-album-next)) + +;;;###autoload +(defun jao-emms-random-album-stop () + (interactive) + (setq jao-emms-random-album-p nil) + (emms-stop)) + +;;;###autoload +(defun jao-emms-random-album-toggle () + (interactive) + (setq jao-emms-random-album-p (not jao-emms-random-album-p)) + (message "Random album %s" + (if jao-emms-random-album-p "enabled" "disabled"))) + +;;;###autoload +(defun jao-emms-random-album-next () + (interactive) + (save-excursion + (ignore-errors (emms-browser-clear-playlist)) + (emms-browse-by-album) + (jao-emms-goto-random-album) + (let ((album (substring-no-properties (thing-at-point 'line) 0 -1))) + (emms-browser-add-tracks-and-play) + (when jao-emms-random-album-notify-p + (jao-notify album "Next album" jao-emms-random-album-notify-icon))) + (emms-browser-bury-buffer) + (jao-minibuffer-refresh))) + +;;;###autoload +(defun jao-emms-random-album-reset () + (interactive) + (setq jao-emms-random-lines nil) + (jao-emms-random-lines-save)) + +(setq emms-player-next-function 'jao-emms-next-noerror) + + +(provide 'jao-emms-random-album) +;;; jao-emms-random-album.el ends here diff --git a/lib/media/jao-emms.el b/lib/media/jao-emms.el new file mode 100644 index 0000000..53b3513 --- /dev/null +++ b/lib/media/jao-emms.el @@ -0,0 +1,27 @@ +;; jao-emms.el -- shared bits + +;; Copyright (C) 2009, 2010 Jose Antonio Ortega Ruiz + +;; Author: Jose Antonio Ortega Ruiz +;; Start date: Sat Jul 04, 2009 13:51 + +;; This file is free software; you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation; either version 3 of the License, or +;; (at your option) any later version. + +;; This file is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see . + +;;; Code: + +(defgroup jao-emms nil "Emms extensions" :group 'emms) + + +(provide 'jao-emms) +;;; jao-emms.el ends here diff --git a/lib/media/jao-lyrics.el b/lib/media/jao-lyrics.el new file mode 100644 index 0000000..dd85da1 --- /dev/null +++ b/lib/media/jao-lyrics.el @@ -0,0 +1,152 @@ +;; jao-lyrics.el -- simple show lyrics using glyrc + +;; Copyright (C) 2009, 2010, 2017, 2019, 2020 Jose Antonio Ortega Ruiz + +;; Author: Jose Antonio Ortega Ruiz +;; Start date: Sat Jul 04, 2009 13:41 + +;; This file is free software; you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation; either version 3 of the License, or +;; (at your option) any later version. + +;; This file is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see . + +;;; Code: + +(defgroup jao-lyrics-faces nil "Faces" + :group 'faces) + +(defface jao-lyrics-font-lock-album '((t (:foreground "lightgoldenrod2"))) + "Album name in lyrics." + :group 'jao-lyrics-faces) + +(defface jao-lyrics-font-lock-title '((t (:foreground "dodgerblue2"))) + "Track title in lyrics." + :group 'jao-lyrics-faces) + +(defface jao-lyrics-font-lock-artist '((t (:foreground "dodgerblue3"))) + "Artist name in lyrics." + :group 'jao-lyrics-faces) + +(defvar jao-lyrics-cache-dir "~/.lyrics") + +(defun jao-lyrics--filename (artist title) + (expand-file-name (format "%s - %s.txt" artist title) + jao-lyrics-cache-dir)) + +(defun jao-lyrics--get-cached (artist title) + (let ((candidate (jao-lyrics--filename artist title))) + (and (file-exists-p candidate) + (with-current-buffer (find-file-noselect candidate) + (prog1 + (buffer-string) + (kill-buffer)))))) + +(defun jao-lyrics--cache (artist title lyrics) + (with-current-buffer + (find-file-noselect (jao-lyrics--filename artist title)) + (delete-region (point-min) (point-max)) + (insert lyrics) + (save-buffer) + (kill-buffer))) + +(make-variable-buffer-local + (defvar jao-lyrics--path nil)) + +(defvar jao-lyrics-mode-map) +(setq jao-lyrics-mode-map + (let ((map (make-keymap))) + (suppress-keymap map) + (define-key map [?q] 'bury-buffer) + (define-key map [?g] 'jao-show-lyrics) + (define-key map [?G] (lambda () (interactive) (jao-show-lyrics t))) + (define-key map [?e] 'jao-edit-lyrics) + map)) + +(defun jao-lyrics-mode () + (interactive) + (kill-all-local-variables) + (use-local-map jao-lyrics-mode-map) + (setq major-mode 'jao-lyrics-mode) + (setq mode-name "lyrics") + (toggle-read-only 1)) + +(defun jao-lyrics-buffer () + (or (get-buffer "*Lyrics*") + (with-current-buffer (get-buffer-create "*Lyrics*") + (jao-lyrics-mode) + (current-buffer)))) + +(defun jao-edit-lyrics () + (interactive) + (unless jao-lyrics--path + (error "No track data available.")) + (find-file-other-window jao-lyrics--path)) + + + +(defun jao-lyrics--clean-download (fn) + (with-current-buffer (find-file-noselect fn) + (goto-char (point-min)) + (when (re-search-forward + "^\\(CreditsWritten by:\\|External linksNominate\\)" nil t) + (beginning-of-line) + (kill-region (point) (point-max))) + (replace-string " " "" nil (point-min) (point-max)) + (replace-string "\\'" "'" nil (point-min) (point-max)) + (save-buffer))) + +(defun jao-lyrics--download (artist title &optional noartist) + (message "Retrieving lyrics...") + (or (executable-find "glyrc") + (error "glyrc not installed")) + (let ((fn (jao-lyrics--filename (or noartist artist) title))) + (shell-command-to-string (format "glyrc lyrics -n 1-8 -Y -a %s -t %s -w %s" + (shell-quote-argument artist) + (shell-quote-argument title) + (shell-quote-argument fn))) + (jao-lyrics--clean-download fn) + (prog1 (jao-lyrics--get-cached artist title) (message nil)))) + +(defvar jao-lyrics-info-function) +(defvar-local jao-lyrics--info-function nil) + +;;;###autoload +(defun jao-show-lyrics (&optional force info-function) + (interactive "P") + (let* ((a/t (funcall (or info-function + jao-lyrics--info-function + jao-lyrics-info-function))) + (artist (car a/t)) + (title (cdr a/t)) + (artist (if force (read-string "Artist: " artist) artist)) + (title (if force (read-string "Title: " title) title)) + (buffer (jao-lyrics-buffer)) + (cached (and (not force) (jao-lyrics--get-cached artist title))) + (cached (and (not (zerop (length cached))) cached)) + (lyrics (or cached + (jao-lyrics--download artist title) + (jao-lyrics--download "" title artist))) + (inhibit-read-only t)) + (with-current-buffer buffer + (when info-function + (setq-local jao-lyrics--info-function info-function)) + (delete-region (point-min) (point-max)) + (insert (format "♪ %s - %s\n\n" + (propertize artist 'face 'jao-lyrics-font-lock-artist) + (propertize title 'face 'jao-lyrics-font-lock-title))) + (when lyrics (insert lyrics)) + (goto-char (point-min)) + (setq jao-lyrics--path (jao-lyrics--filename artist title))) + (pop-to-buffer buffer))) + + +(provide 'jao-lyrics) +;;; jao-lyrics.el ends here diff --git a/lib/media/jao-mpris.el b/lib/media/jao-mpris.el new file mode 100644 index 0000000..ad4b452 --- /dev/null +++ b/lib/media/jao-mpris.el @@ -0,0 +1,139 @@ +;;; jao-mpris.el --- mpris players control -*- lexical-binding: t; -*- + +;; Copyright (C) 2020, 2021 jao + +;; Author: jao +;; Keywords: multimedia + +;; This program is free software; you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see . + +;;; Commentary: + +;; controlling and showing info on mpris players + +;;; Code: + +(require 'dbus) +(require 'jao-minibuffer) +(require 'jao-emms-info-track) + +(defun jao-mpris--playerctl (&rest args) + (shell-command-to-string (format "playerctl %s" + (mapconcat #'shell-quote-argument args " ")))) + +(defmacro jao-playerctl--def (name &rest args) + `(defun ,name () (interactive) (jao-mpris--playerctl ,@args))) + +(jao-playerctl--def jao-mpris-play-pause "play-pause") +(jao-playerctl--def jao-mpris-next "next") +(jao-playerctl--def jao-mpris-previous "previous") + +(defun jao-playerctl--status (&optional sep) + (let* ((sep (or sep " ||| ")) + (fmt (mapconcat 'identity + '("{{status}}" + "{{xesam:trackNumber}}" + "{{title}}" + "{{artist}}" + "{{album}}" + "{{duration(mpris:length)}}") + sep)) + (m (jao-mpris--playerctl "metadata" "--format" fmt))) + (split-string (car (split-string m "\n")) sep))) + +;;;###autoload +(defun jao-mpris-status-times () + (interactive) + (let ((m (jao-mpris--playerctl "metadata" "--format" + (concat "{{duration(position)}}/" + "{{duration(mpris:length)}}")))) + (jao-notify (string-trim m) "Playing"))) + +(defvar jao-mpris--current nil) +(defvar jao-mpris-track-string "") + +(defun jao-mpris--get (k &optional l) + (alist-get k (or l jao-mpris--current))) + +(defun jao-mpris--format (&optional info) + (let* ((artist (jao-mpris--get 'artist info)) + (title (jao-mpris--get 'title info)) + (track (jao-mpris--get 'track info)) + (album (jao-mpris--get 'album info)) + (len (jao-mpris--get 'length info)) + (duration (cond ((stringp len) len) + ((numberp len) (jao-emms--fmt-time (/ len 1e6) ""))))) + (format " %s %s %s%s%s" + (jao--put-face (format "%s" (or track "")) 'jao-emms-font-lock-track) + (jao--put-face title 'jao-emms-font-lock-title) + (jao--put-face artist 'jao-emms-font-lock-artist) + (jao--put-face (if album (format " (%s)" album) "") + 'jao-emms-font-lock-album) + (if duration (format " [%s]" duration) "")))) + +(defun jao-mpris--track (&optional info) + (let ((info (or info (jao-playerctl--status)))) + (if (string= "Playing" (jao-mpris--get 'status info)) + (setq jao-mpris-track-string (jao-mpris--format info)) + (setq jao-mpris-track-string ""))) + (jao-minibuffer-refresh)) + +;;;###autoload +(defun jao-mpris-artist-title () + (when jao-mpris--current + (cons (jao-mpris--get 'artist) (jao-mpris--get 'title)))) + +;;;###autoload +(defun jao-mpris-show-osd () + (interactive) + (when jao-mpris--current + (jao-notify (format "%s: %s" (jao-mpris--get 'status) (jao-mpris--format))))) + +(defun jao-mpris-minibuffer-order (order) + (jao-minibuffer-add-variable 'jao-mpris-track-string order)) + +(defun jao-mpris--handler (iname properties &rest args) + (when properties + (let ((st (caadr (assoc "PlaybackStatus" properties))) + (md (caadr (assoc "Metadata" properties)))) + (cond ((and st (not (string= "Playing" st))) + (setq jao-mpris-track-string "") + (setq jao-mpris--current + (cons (cons 'status st) + (assq-delete-all 'status jao-mpris--current))) + (jao-minibuffer-refresh) + (message "Music %s" st)) + (md (let ((tno (caadr (assoc "xesam:trackNumber" md))) + (tlt (caadr (assoc "xesam:title" md))) + (art (caaadr (assoc "xesam:artist" md))) + (alb (caadr (assoc "xesam:album" md))) + (len (caadr (assoc "mpris:length" md)))) + (setq jao-mpris--current + `((track . ,tno) (title . ,tlt) + (artist . ,art) (album . ,alb) + (length . ,len) (status . ,st))) + (jao-mpris--track jao-mpris--current))))))) + +;;;###autoload +(defun jao-mpris-minibuffer-register (name &optional bus) + (dbus-register-signal (or bus :session) + name + "/org/mpris/MediaPlayer2" + "org.freedesktop.DBus.Properties" + "PropertiesChanged" + 'jao-mpris--handler)) + + +(provide 'jao-mpris) +;;; jao-mpris.el ends here diff --git a/lib/media/jao-random-album.el b/lib/media/jao-random-album.el new file mode 100644 index 0000000..7158417 --- /dev/null +++ b/lib/media/jao-random-album.el @@ -0,0 +1,101 @@ +;; jao-random-album.el -- play random albums + +;; Copyright (C) 2009, 2010, 2017, 2018, 2019 Jose Antonio Ortega Ruiz + +;; Author: Jose Antonio Ortega Ruiz +;; Start date: Sat Jul 04, 2009 13:06 + +;; This file is free software; you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation; either version 3 of the License, or +;; (at your option) any later version. + +;; This file is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see . + +(require 'jao-notify) + +(defvar jao-random-album-p t) +(defvar jao-random-lines nil) +(defvar jao-random-lines-file (expand-file-name "~/.emacs.d/random-lines")) +(defvar jao-random-album-notify-p t) +(defvar jao-random-album-notify-icon nil) +(defvar jao-random-album-skip-lines 2) + +(defun jao-random-lines () + (or jao-random-lines + (and (file-exists-p jao-random-lines-file) + (with-current-buffer + (find-file-noselect jao-random-lines-file) + (goto-char (point-min)) + (setq jao-random-lines (read (current-buffer))))) + (dotimes (n (1- (line-number-at-pos (point-max))) + jao-random-lines) + (when (> n jao-random-album-skip-lines) + (push (1+ n) jao-random-lines))))) + +(defun jao-random-lines-save () + (with-current-buffer (find-file-noselect jao-random-lines-file) + (delete-region (point-min) (point-max)) + (insert (format "%s\n" jao-random-lines)) + (save-buffer))) + +(defun jao-goto-random-album () + (let* ((pos (random (length (jao-random-lines)))) + (line (nth pos jao-random-lines))) + (setq jao-random-lines (remove line jao-random-lines)) + (jao-random-lines-save) + (goto-line line))) + + +;; User interface +(defvar jao-random-album-buffer) +(defvar jao-random-album-add-tracks-and-play) +(defvar jao-random-album-stop) + +(defun jao-random-album-start () + (interactive) + (setq jao-random-album-p t) + (jao-random-album-next)) + +(defun jao-random-album-stop () + (interactive) + (setq jao-random-album-p nil) + (funcall jao-random-album-stop)) + +(defun jao-random-album-toggle () + (interactive) + (setq jao-random-album-p (not jao-random-album-p)) + (message "Random album %s" + (if jao-random-album-p "enabled" "disabled"))) + +(defun jao-random-album-next () + (interactive) + (with-current-buffer (get-buffer (funcall jao-random-album-buffer)) + (save-excursion + (jao-goto-random-album) + (let ((album (string-trim + (substring-no-properties (thing-at-point 'line) 0 -1)))) + (funcall jao-random-album-add-tracks-and-play) + (when jao-random-album-notify-p + (jao-notify album "Next album" jao-random-album-notify-icon)))))) + +(defun jao-random-album-reset () + (interactive) + (setq jao-random-lines nil) + (jao-random-lines-save)) + +(defun jao-random-album-setup (album-buffer add-and-play stop &optional icon) + (setq jao-random-album-buffer album-buffer + jao-random-album-add-tracks-and-play add-and-play + jao-random-album-stop stop + jao-random-album-notify-icon icon)) + + +(provide 'jao-random-album) +;;; jao-random-album.el ends here diff --git a/lib/media/leoslyrics.py b/lib/media/leoslyrics.py new file mode 100755 index 0000000..5e4f8c8 --- /dev/null +++ b/lib/media/leoslyrics.py @@ -0,0 +1,84 @@ +#!/usr/bin/python +# +# (c) 2004-2008 The Music Player Daemon Project +# http://www.musicpd.org/ +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# + +# +# Load lyrics from leoslyrics.com +# + +from sys import argv, exit +from urllib import urlencode, urlopen +from xml.sax import make_parser, SAXException +from xml.sax.handler import ContentHandler + +class SearchContentHandler(ContentHandler): + def __init__(self): + self.code = None + self.hid = None + + def startElement(self, name, attrs): + if name == 'response': + self.code = int(attrs['code']) + elif name == 'result': + if self.hid is None or attrs['exactMatch'] == 'true': + self.hid = attrs['hid'] + +def search(artist, title): + query = urlencode({'auth': 'ncmpc', + 'artist': artist, + 'songtitle': title}) + url = "http://api.leoslyrics.com/api_search.php?" + query + f = urlopen(url) + handler = SearchContentHandler() + parser = make_parser() + parser.setContentHandler(handler) + parser.parse(f) + return handler.hid + +class LyricsContentHandler(ContentHandler): + def __init__(self): + self.code = None + self.is_text = False + self.text = None + + def startElement(self, name, attrs): + if name == 'text': + self.text = '' + self.is_text = True + else: + self.is_text = False + + def characters(self, chars): + if self.is_text: + self.text += chars + +def lyrics(hid): + query = urlencode({'auth': 'ncmpc', + 'hid': hid}) + url = "http://api.leoslyrics.com/api_lyrics.php?" + query + f = urlopen(url) + handler = LyricsContentHandler() + parser = make_parser() + parser.setContentHandler(handler) + parser.parse(f) + return handler.text + +hid = search(argv[1], argv[2]) +if hid is None: + exit(2) +print lyrics(hid).encode('utf-8') diff --git a/lib/media/lyricwiki.rb b/lib/media/lyricwiki.rb new file mode 100755 index 0000000..f163fa4 --- /dev/null +++ b/lib/media/lyricwiki.rb @@ -0,0 +1,52 @@ +#!/usr/bin/env ruby +# +# (c) 2004-2008 The Music Player Daemon Project +# http://www.musicpd.org/ +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# + +# +# Load lyrics from lyrics.wikia.com, formerly lyricwiki.org +# + +require 'uri' +require 'net/http' +require 'cgi' + +url = "http://lyrics.wikia.com/api.php?action=lyrics&fmt=xml&func=getSong" + \ + "&artist=#{URI.escape(ARGV[0])}&song=#{URI.escape(ARGV[1])}" +response = Net::HTTP.get(URI.parse(url)) + +if not response =~ /\s*(.*?)\s*<\/url>/im + $stderr.puts "No URL in response!" + exit(1) +end + +url = $1 +exit(69) if url =~ /action=edit$/ + +response = Net::HTTP.get(URI.parse(url)) +if not response =~ /
\s*(.*?)\s*