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