]> kaliko git repositories - python-musicpd.git/blob - doc/source/use.rst
Some documentation refactoring, improvements
[python-musicpd.git] / doc / source / use.rst
1 .. SPDX-FileCopyrightText: 2018-2023  kaliko <kaliko@azylum.org>
2 .. SPDX-License-Identifier: LGPL-3.0-or-later
3
4 Using the client library
5 =========================
6
7 Introduction
8 ------------
9
10 The client library can be used as follows:
11
12 .. code-block:: python
13
14     client = musicpd.MPDClient()       # create client object
15     client.connect()                   # use MPD_HOST/MPD_PORT if set else
16                                        #   test ${XDG_RUNTIME_DIR}/mpd/socket for existence
17                                        #   fallback to localhost:6600
18                                        # connect support host/port argument as well
19     print(client.mpd_version)          # print the MPD protocol version
20     client.setvol('42')                # sets the volume
21     client.disconnect()                # disconnect from the server
22
23 The MPD command protocol exchanges line-based text records. The client emits a
24 command with optional arguments. In the example above the client sends a
25 `setvol` command with the string argument `42`.
26
27 MPD commands are exposed as :py:class:`musicpd.MPDClient` methods. Methods
28 **arguments are python strings**. Some commands are composed of more than one word
29 (ie "**tagtypes [disable|enable|all]**"), for these use a `snake case`_ style to
30 access the method. Then **"tagtypes enable"** command is called with
31 **"tagtypes_enable"**.
32
33 Remember MPD protocol is text based, then all MPD command arguments are UTF-8
34 strings. In the example above, an integer can be used as argument for the
35 `setvol` command, but it is then evaluated as a string when the command is
36 written to the socket. To avoid confusion use regular string instead of relying
37 on object string representation.
38
39 :py:class:`musicpd.MPDClient` methods returns different kinds of objects depending on the command. Could be :py:obj:`None`, a single object as a :py:obj:`str` or a :py:obj:`dict`, a list of :py:obj:`dict`.
40
41 For more about the protocol and MPD commands see the `MPD protocol
42 documentation`_.
43
44 For a list of currently supported commands in this python module see
45 :ref:`commands`.
46
47 .. _environment_variables:
48
49 Environment variables
50 ---------------------
51
52 :py:class:`musicpd.MPDClient` honors the following environment variables:
53
54 .. envvar:: MPD_HOST
55
56    MPD host (:abbr:`FQDN (fully qualified domain name)`, IP, socket path or abstract socket) and password.
57
58     | To define a **password** set :envvar:`MPD_HOST` to "*password@host*" (password only "*password@*")
59     | For **abstract socket** use "@" as prefix : "*@socket*" and then with a password  "*pass@@socket*"
60     | Regular **unix socket** are set with an absolute path: "*/run/mpd/socket*"
61
62 .. envvar:: MPD_PORT
63
64    MPD port, relevant for TCP socket only
65
66 .. envvar:: MPD_TIMEOUT
67
68    socket timeout when connecting to MPD and waiting for MPD’s response (in seconds)
69
70 .. envvar:: XDG_RUNTIME_DIR
71
72    path to look for potential socket
73
74 .. _default_settings:
75
76 Default settings
77 ----------------
78
79 Default host:
80  * use :envvar:`MPD_HOST` environment variable if set, extract password if present,
81  * else looks for an existing file in :envvar:`${XDG_RUNTIME_DIR:-/run/}/mpd/socket`
82  * else set host to ``localhost``
83
84 Default port:
85  * use :envvar:`MPD_PORT` environment variable is set
86  * else use ``6600``
87
88 Default timeout:
89  * use :envvar:`MPD_TIMEOUT` is set
90  * else use :py:obj:`musicpd.CONNECTION_TIMEOUT`
91
92 Context manager
93 ---------------
94
95 Calling MPDClient in a context manager :py:obj:`musicpd.MPDClient.connect` is
96 transparently called with :ref:`default setting<default_settings>` (use
97 :ref:`environment variables<environment_variables>` to override defaults).
98 Leaving the context manager :py:obj:`musicpd.MPDClient.disconnect` is called.
99
100 .. code-block:: python
101
102     import os
103     os.environ['MPD_HOST'] = 'mpdhost'
104     with MPDClient() as c:
105         c.status()
106         c.next()
107
108 Command lists
109 -------------
110
111 Command lists are also supported using `command_list_ok_begin()` and
112 `command_list_end()` :
113
114 .. code-block:: python
115
116     client.command_list_ok_begin()       # start a command list
117     client.update()                      # insert the update command into the list
118     client.status()                      # insert the status command into the list
119     results = client.command_list_end()  # results will be a list with the results
120
121 Ranges
122 ------
123
124 Some commands (e.g. delete) allow specifying a range in the form `"START:END"` (cf. `MPD protocol documentation`_ for more details).
125
126 Possible ranges are: `"START:END"`, `"START:"` and `":"` :
127
128 Instead of giving the plain string as `"START:END"`, you **can** provide a :py:obj:`tuple` as `(START,END)`. The module is then ensuring the format is correct and raises an :py:obj:`musicpd.CommandError` exception otherwise. Empty start or end can be specified as en empty string ``''`` or :py:obj:`None`.
129
130 .. code-block:: python
131
132     # An intelligent clear
133     # clears played track in the queue, currentsong included
134     pos = client.currentsong().get('pos', 0)
135     # the range object accepts str, no need to convert to int
136     client.delete((0, pos))
137     # missing end interpreted as highest value possible, pay attention still need a tuple.
138     client.delete((pos,))  # purge queue from current to the end
139
140 A notable case is the *rangeid* command allowing an empty range specified
141 as a single colon as argument (i.e. sending just ``":"``):
142
143 .. code-block:: python
144
145     # sending "rangeid :" to clear the range, play everything
146     client.rangeid(())  # send an empty tuple
147
148 Empty start in range (i.e. ":END") are not possible and will raise a CommandError.
149
150 Remember the of the tuple is optional, range can still be specified as single string ``"START:END"``.
151
152 Iterators
153 ----------
154
155 Commands may also return iterators instead of lists if `iterate` is set to
156 `True`:
157
158 .. code-block:: python
159
160     client.iterate = True
161     for song in client.playlistinfo():
162         print song['file']
163
164 Idle prefixed commands
165 ----------------------
166
167 Each command have a *send\_<CMD>* and a *fetch\_<CMD>* variant, which allows to
168 send a MPD command and then fetch the result later (non-blocking call).
169 This is useful for the idle command:
170
171 .. code-block:: python
172
173     >>> client.send_idle()
174     # do something else or use function like select()
175     # http://docs.python.org/howto/sockets.html#non-blocking-sockets
176     # ex. select([client], [], [])
177     >>> events = client.fetch_idle()
178
179     # more complex use for example, with glib/gobject:
180     >>> def callback(source, condition):
181     >>>    changes = client.fetch_idle()
182     >>>    print changes
183     >>>    return False  # removes the IO watcher
184
185     >>> client.send_idle()
186     >>> gobject.io_add_watch(client, gobject.IO_IN, callback)
187     >>> gobject.MainLoop().run()
188
189 See also use of :ref:`socket timeout<socket_timeout>` with idle command.
190
191 Fetching binary content (cover art)
192 -----------------------------------
193
194 Fetching album covers is possible with albumart, here is an example:
195
196 .. code-block:: python
197
198     >>> cli = musicpd.MPDClient()
199     >>> cli.connect()
200     >>> track = "Steve Reich/1978-Music for 18 Musicians"
201     >>> aart = cli.albumart(track, 0)
202     >>> received = int(aart.get('binary'))
203     >>> size = int(aart.get('size'))
204     >>> with open('/tmp/cover', 'wb') as cover:
205     >>>     # aart = {'size': 42, 'binary': 2051, data: bytes(...)}
206     >>>     cover.write(aart.get('data'))
207     >>>     while received < size:
208     >>>         aart = cli.albumart(track, received)
209     >>>         cover.write(aart.get('data'))
210     >>>         received += int(aart.get('binary'))
211     >>>     if received != size:
212     >>>         print('something went wrong', file=sys.stderr)
213     >>> cli.disconnect()
214
215 A `CommandError` is raised if the album does not expose a cover.
216
217 You can also use `readpicture` command to fetch embedded picture:
218
219 .. code-block:: python
220
221     >>> cli = musicpd.MPDClient()
222     >>> cli.connect()
223     >>> track = 'muse/Amon Tobin/2011-ISAM/01-Amon Tobin - Journeyman.mp3'
224     >>> rpict = cli.readpicture(track, 0)
225     >>> if not rpict:
226     >>>     print('No embedded picture found', file=sys.stderr)
227     >>>     sys.exit(1)
228     >>> size = int(rpict['size'])
229     >>> done = int(rpict['binary'])
230     >>> with open('/tmp/cover', 'wb') as cover:
231     >>>     cover.write(rpict['data'])
232     >>>     while size > done:
233     >>>         rpict = cli.readpicture(track, done)
234     >>>         done += int(rpict['binary'])
235     >>>         print(f'writing {rpict["binary"]}, done {100*done/size:03.0f}%')
236     >>>         cover.write(rpict['data'])
237     >>> cli.disconnect()
238
239 Refer to `MPD protocol documentation`_ for the meaning of `binary`, `size` and `data`.
240
241 .. _socket_timeout:
242
243 Socket timeout
244 --------------
245
246 .. note::
247   When the timeout is reached it raises a :py:obj:`socket.timeout` exception. An :py:obj:`OSError` subclass.
248
249 A timeout is used for the initial MPD connection (``connect`` command), then
250 the socket is put in blocking mode with no timeout. Its value is set in
251 :py:obj:`musicpd.CONNECTION_TIMEOUT` at module level and
252 :py:obj:`musicpd.MPDClient.mpd_timeout` in MPDClient instances . However it
253 is possible to set socket timeout for all command setting
254 :py:obj:`musicpd.MPDClient.socket_timeout` attribute to a value in second.
255
256 Having ``socket_timeout`` enabled can help to detect "half-open connection".
257 For instance loosing connectivity without the server explicitly closing the
258 connection (switching network interface ethernet/wifi, router down, etc…).
259
260 **Nota bene**: with ``socket_timeout`` enabled each command sent to MPD might
261 timeout. A couple of seconds should be enough for commands to complete except
262 for the special case of ``idle`` command which by definition *“ waits until
263 there is a noteworthy change in one or more of MPD’s subsystems.”* (cf. `MPD
264 protocol documentation`_).
265
266 Here is a solution to use ``idle`` command with ``socket_timeout``:
267
268 .. code-block:: python
269
270     import musicpd
271     import select
272     import socket
273
274     cli = musicpd.MPDClient()
275     try:
276         cli.socket_timeout = 10  # seconds
277         select_timeout = 5 # second
278         cli.connect()
279         while True:
280             cli.send_idle()  # use send_ API to avoid blocking on read
281             _read, _, _ = select.select([cli], [], [], select_timeout)
282             if _read:  # tries to read response
283                 ret = cli.fetch_idle()
284                 print(', '.join(ret))  # Do something
285             else: # cancels idle
286                 cli.noidle()
287     except socket.timeout as err:
288         print(f'{err} (timeout {cli.socket_timeout})')
289     except (OSError, musicpd.MPDError) as err:
290         print(f'{err!r}')
291         if cli._sock is not None:
292             cli.disconnect()
293     except KeyboardInterrupt:
294         pass
295
296 Some explanations:
297
298   * First launch a non blocking ``idle`` command. This call do not wait for a
299     response to avoid socket timeout waiting for an MPD event.
300   * ``select`` waits for something to read on the socket (the idle response
301     in this case), returns after ``select_timeout`` seconds anyway.
302   * In case there is something to read read it using ``fetch_idle``
303   * Nothing to read, cancel idle with ``noidle``
304
305 All three commands in the while loop (send_idle, fetch_idle, noidle) are not
306 triggering a socket timeout unless the connection is actually lost (actually it
307 could also be that MPD took too much time to answer, but MPD taking more than a
308 couple of seconds for these commands should never occur).
309
310
311 .. _MPD protocol documentation: http://www.musicpd.org/doc/protocol/
312 .. _snake case: https://en.wikipedia.org/wiki/Snake_case
313 .. vim: spell spelllang=en