├── doc ├── _static │ └── .gitkeep ├── commands_header.txt ├── topics │ ├── logging.rst │ ├── advanced.rst │ ├── porting.rst │ ├── getting-started.rst │ └── commands.rst ├── index.rst ├── generate_command_reference.py ├── changes.rst ├── Makefile └── conf.py ├── .envrc ├── MANIFEST.in ├── .github ├── dependabot.yml └── workflows │ ├── test.yml │ └── update-flake-lock.yml ├── examples ├── logger.py ├── helloworld.py ├── multitags.py ├── randomqueue.py ├── summary.txt ├── coverart.py ├── locking.py ├── twisted_example.py ├── stats.py ├── asyncio_example.py ├── stickers.py └── errorhandling.py ├── tox.ini ├── .mergify.yml ├── .gitignore ├── INSTALL.rst ├── Makefile ├── mpd ├── __init__.py ├── twisted.py ├── asyncio.py └── base.py ├── flake.nix ├── flake.lock ├── pyproject.toml ├── README.rst ├── LICENSE.txt └── GPL.txt /doc/_static/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.envrc: -------------------------------------------------------------------------------- 1 | use flake 2 | 3 | export PYTHONPATH=$(realpath .):$PYTHONPATH 4 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.txt 2 | include *.rst 3 | recursive-include doc *.rst 4 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | directory: "/" 5 | schedule: 6 | interval: "weekly" 7 | -------------------------------------------------------------------------------- /examples/logger.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import mpd 3 | 4 | logging.basicConfig(level=logging.DEBUG) 5 | client = mpd.MPDClient() 6 | client.connect("localhost", 6600) 7 | client.find("any", "house") 8 | -------------------------------------------------------------------------------- /doc/commands_header.txt: -------------------------------------------------------------------------------- 1 | ======== 2 | Commands 3 | ======== 4 | .. note:: 5 | 6 | Each command have a *send_* and a *fetch_* variant, which allows to send a 7 | MPD command and then fetch the result later. See :ref:`getting-started` for 8 | examples and more information. 9 | -------------------------------------------------------------------------------- /examples/helloworld.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import mpd 3 | 4 | client = mpd.MPDClient() 5 | client.connect("localhost", 6600) 6 | 7 | for entry in client.lsinfo("/"): 8 | print("%s" % entry) 9 | for key, value in client.status().items(): 10 | print("%s: %s" % (key, value)) 11 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py310,py311,py312,py313,py314,pypy3 3 | 4 | [testenv] 5 | deps = coverage 6 | Twisted 7 | commands = coverage erase 8 | coverage run -m unittest mpd.tests 9 | coverage report 10 | coverage html -d coverage_html/{envname} 11 | -------------------------------------------------------------------------------- /.mergify.yml: -------------------------------------------------------------------------------- 1 | queue_rules: 2 | - name: default 3 | queue_conditions: 4 | - base=master 5 | - label~=merge-queue|dependencies 6 | merge_conditions: [] 7 | merge_method: rebase 8 | 9 | pull_request_rules: 10 | - name: refactored queue action rule 11 | conditions: [] 12 | actions: 13 | queue: 14 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: "Test" 2 | on: 3 | pull_request: 4 | push: 5 | branches: 6 | - main 7 | - staging 8 | - trying 9 | jobs: 10 | tests: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v5 14 | - uses: cachix/install-nix-action@v31 15 | - name: run tests 16 | run: 17 | nix develop -c tox -p auto 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # Packages 4 | *.egg 5 | *.egg-info 6 | /.eggs/ 7 | /dist/ 8 | /build/ 9 | /eggs/ 10 | /parts/ 11 | /bin/ 12 | /var/ 13 | /sdist/ 14 | /develop-eggs/ 15 | /lib/ 16 | /lib64/ 17 | /include/ 18 | /local/ 19 | /.installed.cfg 20 | 21 | # Installer logs 22 | /pip-selfcheck.json 23 | /pip-log.txt 24 | 25 | # Unit test / coverage reports 26 | /.coverage 27 | /.tox 28 | /nosetests.xml 29 | /coverage_html/ 30 | 31 | # Sphinx docs 32 | /doc/_build 33 | -------------------------------------------------------------------------------- /doc/topics/logging.rst: -------------------------------------------------------------------------------- 1 | Logging 2 | ------- 3 | 4 | By default messages are sent to the logger named ``mpd``:: 5 | 6 | >>> import logging, mpd 7 | >>> logging.basicConfig(level=logging.DEBUG) 8 | >>> client = mpd.MPDClient() 9 | >>> client.connect("localhost", 6600) 10 | INFO:mpd:Calling MPD connect('localhost', 6600, timeout=None) 11 | >>> client.find('any', 'dubstep') 12 | DEBUG:mpd:Calling MPD find('any', 'dubstep') 13 | 14 | For more information about logging configuration, see 15 | http://docs.python.org/2/howto/logging.html 16 | -------------------------------------------------------------------------------- /examples/multitags.py: -------------------------------------------------------------------------------- 1 | # Multi tag files 2 | # 3 | # Some tag formats (such as ID3v2 and VorbisComment) support defining the same tag multiple times, mostly for when a song has multiple artists. MPD supports this, and sends each occurrence of a tag to the client. 4 | # 5 | # When python-mpd encounters the same tag more than once on the same song, it uses a list instead of a string. 6 | # Function to get a string only song object. 7 | 8 | 9 | def collapse_tags(song): 10 | for tag, value in song.iteritems(): 11 | if isinstance(value, list): 12 | song[tag] = ", ".join(set(value)) 13 | -------------------------------------------------------------------------------- /.github/workflows/update-flake-lock.yml: -------------------------------------------------------------------------------- 1 | name: update-flake-lock 2 | on: 3 | workflow_dispatch: # allows manual triggering 4 | schedule: 5 | - cron: '5 10 8 * *' # Run once a month 6 | 7 | jobs: 8 | lockfile: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Checkout repository 12 | uses: actions/checkout@v5 13 | - name: Install Nix 14 | uses: cachix/install-nix-action@v31 15 | - name: Update flake.lock 16 | uses: DeterminateSystems/update-flake-lock@v27 17 | with: 18 | pr-body: | 19 | Automated changes by the update-flake-lock 20 | ``` 21 | {{ env.GIT_COMMIT_MESSAGE }} 22 | ``` 23 | bors merge 24 | -------------------------------------------------------------------------------- /examples/randomqueue.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # IMPORTS 5 | from mpd import MPDClient, CommandError 6 | from random import choice 7 | from socket import error as SocketError 8 | from sys import exit 9 | 10 | 11 | ## SETTINGS 12 | ## 13 | HOST = "localhost" 14 | PORT = "6600" 15 | PASSWORD = False 16 | ### 17 | 18 | 19 | client = MPDClient() 20 | 21 | try: 22 | client.connect(host=HOST, port=PORT) 23 | except SocketError: 24 | exit(1) 25 | 26 | if PASSWORD: 27 | try: 28 | client.password(PASSWORD) 29 | except CommandError: 30 | exit(1) 31 | 32 | client.add(choice(client.list("file"))) 33 | client.disconnect() 34 | 35 | # VIM MODLINE 36 | # vim: ai ts=4 sw=4 sts=4 expandtab 37 | -------------------------------------------------------------------------------- /INSTALL.rst: -------------------------------------------------------------------------------- 1 | PyPI: 2 | ~~~~~ 3 | 4 | :: 5 | 6 | $ pip install python-mpd2 7 | 8 | Debian 9 | ~~~~~~ 10 | 11 | Drop this line in */etc/apt/sources.list.d/python-mpd2.list*:: 12 | 13 | deb http://deb.kaliko.me/debian/ testing main 14 | deb-src http://deb.kaliko.me/debian/ testing main 15 | 16 | Import the gpg key as root:: 17 | 18 | $ wget -O - http://sima.azylum.org/sima.gpg | apt-key add - 19 | 20 | Key fingerprint:: 21 | 22 | 2255 310A D1A2 48A0 7B59 7638 065F E539 32DC 551D 23 | 24 | Controls with *apt-key finger*. 25 | 26 | Then simply update/install *python-mpd2* or *python3-mpd2* with apt or 27 | aptitude: 28 | 29 | Arch Linux 30 | ~~~~~~~~~~ 31 | 32 | Install `python-mpd2 `__ 33 | from AUR. 34 | 35 | Gentoo Linux 36 | ~~~~~~~~~~~~ 37 | 38 | Replaces the original python-mpd beginning with version 0.4.2:: 39 | 40 | $ emerge -av python-mpd 41 | 42 | FreeBSD 43 | ~~~~~~~ 44 | 45 | Install *py-mpd2*:: 46 | 47 | $ pkg_add -r py-mpd2 48 | 49 | Packages for other distributions are welcome! 50 | -------------------------------------------------------------------------------- /examples/summary.txt: -------------------------------------------------------------------------------- 1 | :Python scripts examples 2 | 3 | Here follows some scripts using python-mpd to connect and play with your MPD server. 4 | 5 | MPD server used in the script is localhost:6600, please adapt to your own configuration changing the proper var in the script header. 6 | Examples 7 | 8 | Print out general stats: ExampleStats 9 | Random queue: ExampleRandomQueue 10 | Handling errors: ExampleErrorhandling 11 | Deal with mutli-tag files. Some sound files may define the same tag multiple times, here is a function to deal with it in your client: ExampleMultiTags 12 | idle command (python-mpd > 0.3 & mpd > 0.14) ExampleIdle 13 | Manipulate and query stickers: ExampleStickers 14 | 15 | 16 | ExampleErrorhandling demo of handling errors in long-running client 17 | 2010-11-29 18 | ExampleIdle Using idle command 2010-12-14 19 | ExampleMultiTags How to deal with multi tag file 2009-09-15 20 | ExampleRandomQueue Queue song at random 2009-09-24 21 | ExampleStats Get general information of your MPD server 2009-09-12 22 | ExampleStickers A command-line client for manipulating and querying stickers 23 | 2010-12-18 24 | Examples Some example scripts to show how to play with python-mpd 2010-12-18 25 | 26 | The asyncio_example.py shows how MPD can be used with the asyncio idioms; it 27 | requires at least Python 3.5 to run. 28 | -------------------------------------------------------------------------------- /examples/coverart.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # IMPORTS 5 | from mpd import MPDClient, CommandError, FailureResponseCode 6 | from socket import error as SocketError 7 | from sys import exit 8 | from PIL import Image 9 | from io import BytesIO 10 | 11 | ## SETTINGS 12 | ## 13 | HOST = "localhost" 14 | PORT = "6600" 15 | PASSWORD = False 16 | SONG = "" 17 | ### 18 | 19 | client = MPDClient() 20 | 21 | try: 22 | client.connect(host=HOST, port=PORT) 23 | except SocketError: 24 | exit(1) 25 | 26 | if PASSWORD: 27 | try: 28 | client.password(PASSWORD) 29 | except CommandError: 30 | exit(1) 31 | 32 | try: 33 | missing_cover_art = client.albumart("does/not/exist") 34 | except CommandError as error: 35 | # Asking for media that does not exist or media that has no 36 | # albumart should raise: 37 | # mpd.base.CommandError: [50@0] {albumart} No file exists 38 | if error.errno is not FailureResponseCode.NO_EXIST: 39 | raise error 40 | 41 | try: 42 | cover_art = client.readpicture(SONG) 43 | except CommandError: 44 | exit(1) 45 | 46 | if "binary" not in cover_art: 47 | # The song exists but has no embedded cover art 48 | print("No embedded art found!") 49 | exit(1) 50 | 51 | if "type" in cover_art: 52 | print("Cover art of type " + cover_art["type"]) 53 | 54 | with Image.open(BytesIO(cover_art["binary"])) as img: 55 | img.show() 56 | 57 | client.disconnect() 58 | 59 | # VIM MODLINE 60 | # vim: ai ts=4 sw=4 sts=4 expandtab 61 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | PYTHON ?= python3.13 2 | REMOTE = git@github.com:Mic92/python-mpd2 3 | VERSION = $(shell $(PYTHON) -c "import mpd; print('.'.join(map(str,mpd.VERSION)))") 4 | 5 | release: 6 | test "$(shell git symbolic-ref --short HEAD)" = "main" || (echo "not on main branch"; exit 1) 7 | git pull --rebase origin main 8 | $(PYTHON) -m build 9 | $(PYTHON) -m twine check dist/python_mpd2-$(VERSION).tar.gz dist/python_mpd2-$(VERSION)-py3-none-any.whl 10 | git tag "v$(VERSION)" 11 | git push --tags git@github.com:Mic92/python-mpd2 "v$(VERSION)" 12 | $(PYTHON) -m twine upload --repository python-mpd2 dist/python_mpd2-$(VERSION).tar.gz dist/python_mpd2-$(VERSION)-py3-none-any.whl 13 | clean: 14 | rm -rf dist build *.egg-info 15 | 16 | bump-version: 17 | @if [ -z "$(NEW_VERSION)" ]; then \ 18 | echo "Usage: make bump-version NEW_VERSION=x.y.z"; \ 19 | exit 1; \ 20 | fi 21 | @echo "Bumping version to $(NEW_VERSION)..." 22 | @# Convert x.y.z to (x, y, z) for mpd/base.py 23 | @VERSION_TUPLE=$$(echo "$(NEW_VERSION)" | sed 's/\./,\ /g'); \ 24 | sed -i.bak "s/^VERSION = (.*/VERSION = ($$VERSION_TUPLE)/" mpd/base.py && rm mpd/base.py.bak 25 | @# Update version in pyproject.toml 26 | @sed -i.bak 's/^version = .*/version = "$(NEW_VERSION)"/' pyproject.toml && rm pyproject.toml.bak 27 | @echo "Version bumped to $(NEW_VERSION)" 28 | @# Commit the version bump 29 | @git add mpd/base.py pyproject.toml 30 | @git commit -m "Bump version to $(NEW_VERSION)" 31 | @echo "Committed version bump to $(NEW_VERSION)" 32 | 33 | .PHONY: test release clean bump-version 34 | -------------------------------------------------------------------------------- /examples/locking.py: -------------------------------------------------------------------------------- 1 | from threading import Lock, Thread 2 | from random import choice 3 | from mpd import MPDClient 4 | 5 | 6 | class LockableMPDClient(MPDClient): 7 | def __init__(self): 8 | super(LockableMPDClient, self).__init__() 9 | self._lock = Lock() 10 | 11 | def acquire(self): 12 | self._lock.acquire() 13 | 14 | def release(self): 15 | self._lock.release() 16 | 17 | def __enter__(self): 18 | self.acquire() 19 | 20 | def __exit__(self, type, value, traceback): 21 | self.release() 22 | 23 | 24 | client = LockableMPDClient() 25 | client.connect("localhost", 6600) 26 | # now whenever you need thread-safe access 27 | # use the 'with' statement like this: 28 | with client: # acquire lock 29 | status = client.status() 30 | # if you leave the block, the lock is released 31 | # it is recommend to leave it soon, 32 | # otherwise your other threads will blocked. 33 | 34 | 35 | # Let's test if it works .... 36 | def fetch_playlist(): 37 | for i in range(10): 38 | if choice([0, 1]) == 0: 39 | with client: 40 | song = client.currentsong() 41 | assert isinstance(song, dict) 42 | else: 43 | with client: 44 | playlist = client.playlist() 45 | assert isinstance(playlist, list) 46 | 47 | 48 | threads = [] 49 | for i in range(5): 50 | t = Thread(target=fetch_playlist) 51 | threads.append(t) 52 | t.start() 53 | for t in threads: 54 | t.join() 55 | 56 | print("Done...") 57 | -------------------------------------------------------------------------------- /doc/topics/advanced.rst: -------------------------------------------------------------------------------- 1 | Future Compatible 2 | ----------------- 3 | 4 | New commands or special handling of commands can be easily implemented. Use 5 | ``add_command()`` or ``remove_command()`` to modify the commands of the 6 | *MPDClient* class and all its instances.:: 7 | 8 | def fetch_cover(client): 9 | """"Take a MPDClient instance as its arguments and return mimetype and image""" 10 | # this command may come in the future. 11 | pass 12 | 13 | client.add_command("get_cover", fetch_cover) 14 | # you can then use: 15 | client.get_cover() 16 | 17 | # remove the command, because it doesn't exist already. 18 | client.remove_command("get_cover") 19 | 20 | 21 | Thread-Safety 22 | ------------- 23 | 24 | Currently ``MPDClient`` is **NOT** thread-safe. As it use a socket internally, 25 | only one thread can send or receive at the time. 26 | 27 | But ``MPDClient`` can be easily extended to be thread-safe using `locks 28 | `__. Take a look at 29 | ``examples/locking.py`` for further informations. 30 | 31 | 32 | Unicode Handling 33 | ---------------- 34 | 35 | To quote the `mpd protocol documentation 36 | `_: 37 | 38 | > All data between the client and the server is encoded in UTF-8. 39 | 40 | With Python 3: 41 | ~~~~~~~~~~~~~~ 42 | 43 | In Python 3, Unicode string is the default string type. So just pass these 44 | strings as arguments for MPD commands and *python-mpd2* will also return such 45 | Unicode string. 46 | -------------------------------------------------------------------------------- /doc/topics/porting.rst: -------------------------------------------------------------------------------- 1 | ============= 2 | Porting guide 3 | ============= 4 | 5 | Until the versions 0.4.x, `python-mpd2`_ was a drop-in replacement for application 6 | which were using the original `python-mpd`_. That is, you could just replace the 7 | package's content of the latter one by the former one, and *things should just 8 | work*. 9 | 10 | However, starting from version 0.5, `python-mpd2`_ provides enhanced features 11 | which are *NOT* backward compatibles with the original `python-mpd`_ package. 12 | This goal of this document is to explains the differences the releases and if it 13 | makes sense, how to migrate from one version to another. 14 | 15 | 16 | Stickers API 17 | ============ 18 | 19 | When fetching stickers, `python-mpd2`_ used to return mostly the raw results MPD 20 | was providing:: 21 | 22 | >>> client.sticker_get('song', 'foo.mp3', 'my-sticker') 23 | 'my-sticker=some value' 24 | >>> client.sticker_list('song', 'foo.mp3') 25 | ['my-sticker=some value', 'foo=bar'] 26 | 27 | Starting from version 0.5, `python-mpd2`_ provides a higher-level representation 28 | of the stickers' content:: 29 | 30 | >>> client.sticker_get('song', 'foo.mp3', 'my-sticker') 31 | 'some value' 32 | >>> client.sticker_list('song', 'foo.mp3') 33 | {'my-sticker': 'some value', 'foo': 'bar'} 34 | 35 | This removes the burden from the application to do the interpretation of the 36 | stickers' content by itself. 37 | 38 | .. versionadded:: 0.5 39 | 40 | 41 | .. _python-mpd: http://jatreuman.indefero.net/p/python-mpd/ 42 | .. _python-mpd2: https://github.com/Mic92/python-mpd2/ 43 | 44 | .. vim:ft=rst 45 | -------------------------------------------------------------------------------- /examples/twisted_example.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | from mpd import MPDProtocol 3 | from twisted.internet import protocol 4 | from twisted.internet import reactor 5 | 6 | 7 | class MPDApp(object): 8 | # Example application which deals with MPD 9 | 10 | def __init__(self, protocol): 11 | self.protocol = protocol 12 | 13 | def __call__(self, result): 14 | # idle result callback 15 | print("Subsystems: {}".format(list(result))) 16 | 17 | def status_success(result): 18 | # status query success 19 | print("Status success: {}".format(result)) 20 | 21 | def status_error(result): 22 | # status query failure 23 | print("Status error: {}".format(result)) 24 | 25 | # query player status 26 | self.protocol.status().addCallback(status_success).addErrback(status_error) 27 | 28 | 29 | class MPDClientFactory(protocol.ClientFactory): 30 | protocol = MPDProtocol 31 | 32 | def buildProtocol(self, addr): 33 | print("Create MPD protocol") 34 | protocol = self.protocol() 35 | protocol.factory = self 36 | protocol.idle_result = MPDApp(protocol) 37 | return protocol 38 | 39 | def clientConnectionFailed(self, connector, reason): 40 | print("Connection failed - goodbye!: {}".format(reason)) 41 | reactor.stop() 42 | 43 | def clientConnectionLost(self, connector, reason): 44 | print("Connection lost - goodbye!: {}".format(reason)) 45 | if reactor.running: 46 | reactor.stop() 47 | 48 | 49 | if __name__ == "__main__": 50 | factory = MPDClientFactory() 51 | reactor.connectTCP("localhost", 6600, factory) 52 | reactor.run() 53 | -------------------------------------------------------------------------------- /examples/stats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # IMPORTS 5 | import sys 6 | import pprint 7 | 8 | from mpd import MPDClient, CommandError 9 | from socket import error as SocketError 10 | 11 | HOST = "localhost" 12 | PORT = "6600" 13 | PASSWORD = False 14 | ## 15 | CON_ID = {"host": HOST, "port": PORT} 16 | ## 17 | 18 | 19 | ## Some functions 20 | def mpdConnect(client, con_id): 21 | """ 22 | Simple wrapper to connect MPD. 23 | """ 24 | try: 25 | client.connect(**con_id) 26 | except SocketError: 27 | return False 28 | return True 29 | 30 | 31 | def mpdAuth(client, secret): 32 | """ 33 | Authenticate 34 | """ 35 | try: 36 | client.password(secret) 37 | except CommandError: 38 | return False 39 | return True 40 | 41 | 42 | ## 43 | 44 | 45 | def main(): 46 | ## MPD object instance 47 | client = MPDClient() 48 | if mpdConnect(client, CON_ID): 49 | print("Got connected!") 50 | else: 51 | print("fail to connect MPD server.") 52 | sys.exit(1) 53 | 54 | # Auth if password is set non False 55 | if PASSWORD: 56 | if mpdAuth(client, PASSWORD): 57 | print("Pass auth!") 58 | else: 59 | print("Error trying to pass auth.") 60 | client.disconnect() 61 | sys.exit(2) 62 | 63 | ## Fancy output 64 | pp = pprint.PrettyPrinter(indent=4) 65 | 66 | ## Print out MPD stats & disconnect 67 | print("\nCurrent MPD state:") 68 | pp.pprint(client.status()) 69 | 70 | print("\nMusic Library stats:") 71 | pp.pprint(client.stats()) 72 | 73 | client.disconnect() 74 | sys.exit(0) 75 | 76 | 77 | # Script starts here 78 | if __name__ == "__main__": 79 | main() 80 | -------------------------------------------------------------------------------- /mpd/__init__.py: -------------------------------------------------------------------------------- 1 | # python-mpd2: Python MPD client library 2 | # 3 | # Copyright (C) 2008-2010 J. Alexander Treuman 4 | # Copyright (C) 2012 J. Thalheim 5 | # Copyright (C) 2016 Robert Niederreiter 6 | # 7 | # python-mpd2 is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU Lesser General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # python-mpd2 is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU Lesser General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU Lesser General Public License 18 | # along with python-mpd2. If not, see . 19 | 20 | from mpd.base import CommandError as CommandError 21 | from mpd.base import CommandListError as CommandListError 22 | from mpd.base import ConnectionError as ConnectionError 23 | from mpd.base import FailureResponseCode as FailureResponseCode 24 | from mpd.base import IteratingError as IteratingError 25 | from mpd.base import MPDClient as MPDClient 26 | from mpd.base import MPDError as MPDError 27 | from mpd.base import PendingCommandError as PendingCommandError 28 | from mpd.base import ProtocolError as ProtocolError 29 | from mpd.base import VERSION as VERSION 30 | 31 | try: 32 | from mpd.twisted import MPDProtocol 33 | except ImportError: 34 | 35 | class MPDProtocolDummy: 36 | def __init__(self) -> None: 37 | raise Exception("No twisted module found") 38 | 39 | MPDProtocol = MPDProtocolDummy # type: ignore 40 | -------------------------------------------------------------------------------- /examples/asyncio_example.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | 3 | from mpd.asyncio import MPDClient 4 | 5 | 6 | async def main(): 7 | print("Create MPD client") 8 | client = MPDClient() 9 | 10 | # Not necessary, but should not cause any trouble either 11 | client.disconnect() 12 | 13 | try: 14 | await client.connect("localhost", 6600) 15 | except Exception as e: 16 | print("Connection failed:", e) 17 | return 18 | 19 | print("Connected to MPD version", client.mpd_version) 20 | 21 | try: 22 | status = await client.status() 23 | except Exception as e: 24 | print("Status error:", e) 25 | return 26 | else: 27 | print("Status success:", status) 28 | 29 | print(list(await client.commands())) 30 | 31 | import time 32 | 33 | start = time.time() 34 | for x in await client.listall(): 35 | print("sync:", x) 36 | print("Time to first sync:", time.time() - start) 37 | break 38 | 39 | start = time.time() 40 | async for x in client.listall(): 41 | print("async:", x) 42 | print("Time to first async:", time.time() - start) 43 | break 44 | 45 | try: 46 | await client.addid() 47 | except Exception as e: 48 | print("An erroneous command, as expected, raised:", e) 49 | 50 | try: 51 | async for x in client.plchangesposid(): 52 | print("Why does this work?") 53 | except Exception as e: 54 | print("An erroneous asynchronously looped command, as expected, raised:", e) 55 | 56 | i = 0 57 | async for subsystem in client.idle(): 58 | print("Idle change in", subsystem) 59 | i += 1 60 | if i > 5: 61 | print("Enough changes, quitting") 62 | break 63 | 64 | 65 | if __name__ == "__main__": 66 | asyncio.run(main()) 67 | -------------------------------------------------------------------------------- /flake.nix: -------------------------------------------------------------------------------- 1 | { 2 | description = "Development environment for this project"; 3 | 4 | inputs = { 5 | nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; 6 | flake-parts.url = "github:hercules-ci/flake-parts"; 7 | flake-parts.inputs.nixpkgs-lib.follows = "nixpkgs"; 8 | treefmt-nix.url = "github:numtide/treefmt-nix"; 9 | treefmt-nix.inputs.nixpkgs.follows = "nixpkgs"; 10 | }; 11 | 12 | outputs = 13 | inputs@{ flake-parts, treefmt-nix, ... }: 14 | flake-parts.lib.mkFlake { inherit inputs; } { 15 | imports = [ 16 | treefmt-nix.flakeModule 17 | ]; 18 | systems = [ 19 | "aarch64-linux" 20 | "x86_64-linux" 21 | "aarch64-darwin" 22 | "x86_64-darwin" 23 | ]; 24 | perSystem = 25 | { pkgs, config, ... }: 26 | { 27 | treefmt = { 28 | projectRootFile = "flake.nix"; 29 | programs = { 30 | ruff.format = true; 31 | ruff.check = true; 32 | mypy.enable = true; 33 | mypy.directories = { 34 | "." = { 35 | modules = [ "mpd" ]; 36 | }; 37 | }; 38 | }; 39 | }; 40 | 41 | devShells.default = pkgs.mkShell { 42 | packages = with pkgs; [ 43 | bashInteractive 44 | python310 45 | python311 46 | python312 47 | (python313.withPackages (ps: [ 48 | ps.setuptools 49 | ps.tox 50 | ps.wheel 51 | ps.build 52 | ])) 53 | python314 54 | pypy3 55 | twine 56 | mypy 57 | ruff 58 | config.treefmt.build.wrapper 59 | ]; 60 | }; 61 | }; 62 | }; 63 | } 64 | -------------------------------------------------------------------------------- /doc/index.rst: -------------------------------------------------------------------------------- 1 | python-mpd2 Documentation 2 | ========================= 3 | 4 | *python-mpd2* is a Python library which provides a client interface for 5 | the `Music Player Daemon `__. 6 | 7 | Difference with python-mpd 8 | -------------------------- 9 | 10 | python-mpd2 is a fork of `python-mpd`_. While 0.4.x was backwards compatible 11 | with python-mpd, starting with 0.5 provides enhanced features which are *NOT* 12 | backward compatibles with the original `python-mpd`_ package. See 13 | :doc:`Porting ` for more information. 14 | 15 | The following features were added: 16 | 17 | - Python 3 support (but you need at least Python 2.7 or 3.4) 18 | - asyncio/twisted support 19 | - support for the client-to-client protocol 20 | - support for new commands from MPD v0.17 (seekcur, prio, prioid, 21 | config, searchadd, searchaddpl) and MPD v0.18 (readcomments, toggleoutput) 22 | - remove deprecated commands (volume) 23 | - explicitly declared MPD commands (which is handy when using for 24 | example `IPython `__) 25 | - a test suite 26 | - API documentation to add new commands (see :doc:`Future Compatible `) 27 | - support for Unicode strings in all commands (optionally in python2, 28 | default in python3 - see :doc:`Unicode Handling `) 29 | - configurable timeouts 30 | - support for :doc:`logging ` 31 | - improved support for sticker 32 | - improved support for ranges 33 | 34 | 35 | Getting Started 36 | =============== 37 | 38 | A quick guide for getting started python-mpd2: 39 | 40 | * :doc:`Getting Started ` 41 | 42 | .. _python-mpd: https://pypi.python.org/pypi/python-mpd/ 43 | 44 | Command Reference 45 | ================= 46 | 47 | A complete list of all available commands: 48 | 49 | * :doc:`Commands ` 50 | 51 | Changelog 52 | ========= 53 | 54 | * :doc:`Change log ` 55 | -------------------------------------------------------------------------------- /flake.lock: -------------------------------------------------------------------------------- 1 | { 2 | "nodes": { 3 | "flake-parts": { 4 | "inputs": { 5 | "nixpkgs-lib": [ 6 | "nixpkgs" 7 | ] 8 | }, 9 | "locked": { 10 | "lastModified": 1756770412, 11 | "narHash": "sha256-+uWLQZccFHwqpGqr2Yt5VsW/PbeJVTn9Dk6SHWhNRPw=", 12 | "owner": "hercules-ci", 13 | "repo": "flake-parts", 14 | "rev": "4524271976b625a4a605beefd893f270620fd751", 15 | "type": "github" 16 | }, 17 | "original": { 18 | "owner": "hercules-ci", 19 | "repo": "flake-parts", 20 | "type": "github" 21 | } 22 | }, 23 | "nixpkgs": { 24 | "locked": { 25 | "lastModified": 1757068644, 26 | "narHash": "sha256-NOrUtIhTkIIumj1E/Rsv1J37Yi3xGStISEo8tZm3KW4=", 27 | "owner": "NixOS", 28 | "repo": "nixpkgs", 29 | "rev": "8eb28adfa3dc4de28e792e3bf49fcf9007ca8ac9", 30 | "type": "github" 31 | }, 32 | "original": { 33 | "owner": "NixOS", 34 | "ref": "nixos-unstable", 35 | "repo": "nixpkgs", 36 | "type": "github" 37 | } 38 | }, 39 | "root": { 40 | "inputs": { 41 | "flake-parts": "flake-parts", 42 | "nixpkgs": "nixpkgs", 43 | "treefmt-nix": "treefmt-nix" 44 | } 45 | }, 46 | "treefmt-nix": { 47 | "inputs": { 48 | "nixpkgs": [ 49 | "nixpkgs" 50 | ] 51 | }, 52 | "locked": { 53 | "lastModified": 1758728421, 54 | "narHash": "sha256-ySNJ008muQAds2JemiyrWYbwbG+V7S5wg3ZVKGHSFu8=", 55 | "owner": "numtide", 56 | "repo": "treefmt-nix", 57 | "rev": "5eda4ee8121f97b218f7cc73f5172098d458f1d1", 58 | "type": "github" 59 | }, 60 | "original": { 61 | "owner": "numtide", 62 | "repo": "treefmt-nix", 63 | "type": "github" 64 | } 65 | } 66 | }, 67 | "root": "root", 68 | "version": 7 69 | } 70 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=61.0"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "python-mpd2" 7 | version = "3.1.2" 8 | description = "A Python MPD client library" 9 | readme = "README.rst" 10 | authors = [ 11 | {name = "Joerg Thalheim", email = "joerg@thalheim.io"}, 12 | ] 13 | maintainers = [ 14 | {name = "Joerg Thalheim", email = "joerg@thalheim.io"}, 15 | ] 16 | license = {text = "GNU Lesser General Public License v3 (LGPLv3)"} 17 | keywords = ["mpd"] 18 | classifiers = [ 19 | "Development Status :: 5 - Production/Stable", 20 | "Intended Audience :: Developers", 21 | "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)", 22 | "Natural Language :: English", 23 | "Operating System :: OS Independent", 24 | "Programming Language :: Python", 25 | "Programming Language :: Python :: 3", 26 | "Topic :: Software Development :: Libraries :: Python Modules", 27 | ] 28 | requires-python = ">=3.10" 29 | dependencies = [] 30 | 31 | [project.optional-dependencies] 32 | twisted = ["Twisted"] 33 | test = [ 34 | "tox", 35 | "Twisted", 36 | ] 37 | 38 | [project.urls] 39 | Homepage = "https://github.com/Mic92/python-mpd2" 40 | Repository = "https://github.com/Mic92/python-mpd2" 41 | Issues = "https://github.com/Mic92/python-mpd2/issues" 42 | 43 | [tool.setuptools] 44 | packages = ["mpd"] 45 | zip-safe = true 46 | 47 | 48 | [tool.setuptools.package-data] 49 | "*" = ["py.typed"] 50 | 51 | 52 | [tool.mypy] 53 | python_version = "3.10" 54 | pretty = true 55 | warn_redundant_casts = true 56 | disallow_untyped_calls = true 57 | disallow_untyped_defs = true 58 | no_implicit_optional = true 59 | 60 | [[tool.mypy.overrides]] 61 | module = "setuptools.*" 62 | ignore_missing_imports = true 63 | 64 | [[tool.mypy.overrides]] 65 | module = "twisted.*" 66 | ignore_missing_imports = true 67 | 68 | [[tool.mypy.overrides]] 69 | module = "mpd.tests.*" 70 | disable_error_code = ["attr-defined", "union-attr"] 71 | 72 | [tool.ruff] 73 | target-version = "py310" 74 | line-length = 88 75 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | python-mpd2 2 | =========== 3 | 4 | .. image:: https://travis-ci.org/Mic92/python-mpd2.png?branch=master 5 | :target: http://travis-ci.org/Mic92/python-mpd2 6 | :alt: Build Status 7 | 8 | *python-mpd2* is a Python library which provides a client interface for 9 | the `Music Player Daemon `__. 10 | 11 | 12 | Getting the latest source code 13 | ------------------------------ 14 | 15 | If you would like to use the latest source code, you can grab a 16 | copy of the development version from Git by running the command:: 17 | 18 | $ git clone https://github.com/Mic92/python-mpd2.git 19 | 20 | 21 | Getting the latest release 22 | -------------------------- 23 | 24 | The latest stable release of *python-mpd2* can be found on 25 | `PyPI `__ 26 | 27 | 28 | PyPI: 29 | ~~~~~ 30 | 31 | :: 32 | 33 | $ pip install python-mpd2 34 | 35 | 36 | Installation in Linux/BSD distributions 37 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 38 | 39 | Until Linux distributions adapt this package, here are some ready to use 40 | packages to test your applications: 41 | 42 | See `INSTALL.rst `__ 43 | 44 | 45 | Installing from source 46 | ---------------------- 47 | 48 | To install *python-mpd2* from source, simply run the command:: 49 | 50 | $ python setup.py install 51 | 52 | You can use the *--help* switch to *setup.py* for a complete list of commands 53 | and their options. See the `Installing Python Modules `__ document for more details. 54 | 55 | 56 | Documentation 57 | ------------- 58 | 59 | `Documentation `__ 60 | 61 | `Getting Started `__ 62 | 63 | `Command Reference `__ 64 | 65 | `Examples `__ 66 | 67 | 68 | Testing 69 | ------- 70 | 71 | Just run:: 72 | 73 | $ python setup.py test 74 | 75 | This will install `Tox `__. Tox will take care of 76 | testing against all the supported Python versions (at least available) on our 77 | computer, with the required dependencies 78 | 79 | If you have nix, you can also use the provided `default.nix` to bring all supported 80 | python versions in scope using `nix-shell`. In that case run `tox` directly instead 81 | of using `setup.py`:: 82 | 83 | $ nix-shell --command 'tox' 84 | 85 | 86 | Building Documentation 87 | ---------------------- 88 | 89 | Install Sphinx:: 90 | 91 | $ pip install Sphinx 92 | 93 | Change to the source directory and run:: 94 | 95 | $ python ./setup.py build_sphinx 96 | 97 | The command reference is generated from the official mpd protocol documentation. 98 | In order to update it, install python-lxml and run the following command:: 99 | 100 | $ python ./doc/generate_command_reference.py > ./doc/topics/commands.rst 101 | 102 | 103 | .. _python-mpd: https://pypi.python.org/pypi/python-mpd/ 104 | -------------------------------------------------------------------------------- /doc/topics/getting-started.rst: -------------------------------------------------------------------------------- 1 | .. _getting-started: 2 | 3 | Using the client library 4 | ------------------------ 5 | 6 | The client library can be used as follows:: 7 | 8 | >>> from mpd import MPDClient 9 | >>> client = MPDClient() # create client object 10 | >>> client.timeout = 10 # network timeout in seconds (floats allowed), default: None 11 | >>> client.idletimeout = None # timeout for fetching the result of the idle command is handled seperately, default: None 12 | >>> client.connect("localhost", 6600) # connect to localhost:6600 13 | >>> print(client.mpd_version) # print the MPD version 14 | >>> print(client.find("any", "house")) # print result of the command "find any house" 15 | >>> client.close() # send the close command 16 | >>> client.disconnect() # disconnect from the server 17 | 18 | A list of supported commands, their arguments (as MPD currently understands 19 | them), and the functions used to parse their responses can be found in 20 | :doc:`Commands `. See the `MPD protocol documentation 21 | `__ for more details. 22 | 23 | Command lists are also supported using *command\_list\_ok\_begin()* and 24 | *command\_list\_end()*:: 25 | 26 | >>> client.command_list_ok_begin() # start a command list 27 | >>> client.update() # insert the update command into the list 28 | >>> client.status() # insert the status command into the list 29 | >>> results = client.command_list_end() # results will be a list with the results 30 | 31 | Commands may also return iterators instead of lists if *iterate* is set 32 | to *True*:: 33 | 34 | client.iterate = True 35 | for song in client.playlistinfo(): 36 | print song["file"] 37 | 38 | Each command have a *send\_* and a *fetch\_* variant, which allows to send a MPD 39 | command and then fetch the result later. This is useful for the idle command:: 40 | 41 | >>> client.send_idle() 42 | # do something else or use function like select(): http://docs.python.org/howto/sockets.html#non-blocking-sockets 43 | # ex. select([client], [], []) or with gobject: http://jatreuman.indefero.net/p/python-mpd/page/ExampleIdle/ 44 | >>> events = client.fetch_idle() 45 | 46 | Some more complex usage examples can be found 47 | `here `_ 48 | 49 | Some commands support integer ranges as argument. This is done in python-mpd2 50 | by using two element tuple:: 51 | 52 | # move the first three songs 53 | # after the last in the playlist 54 | >>> client.status() 55 | ['file: song1.mp3', 56 | 'file: song2.mp3', 57 | 'file: song3.mp3', 58 | 'file: song4.mp3'] 59 | >>> client.move((0,3), 1) 60 | >>> client.status() 61 | ['file: song4.mp3' 62 | 'file: song1.mp3', 63 | 'file: song2.mp3', 64 | 'file: song3.mp3',] 65 | 66 | Second element can be omitted. MPD will assumes the biggest possible number then (don't forget the comma!):: 67 | NOTE: mpd versions between 0.16.8 and 0.17.3 contains a bug, so omitting doesn't work. 68 | 69 | >>> client.delete((1,)) # delete all songs, but the first. 70 | -------------------------------------------------------------------------------- /examples/stickers.py: -------------------------------------------------------------------------------- 1 | # Descriptio, file=sys.stderrn 2 | # 3 | # Using this client, one can manipulate and query stickers. The script is essentially a raw interface to the MPD protocol's sticker command, and is used in exactly the same way. 4 | # Examples 5 | 6 | ## set sticker "foo" to "bar" on "dir/song.mp3" 7 | # sticker.py set dir/song.mp3 foo bar 8 | # 9 | ## get sticker "foo" on "dir/song.mp3" 10 | # sticker.py get dir/song.mp3 foo 11 | # 12 | ## list all stickers on "dir/song.mp3" 13 | # sticker.py list dir/song.mp3 14 | # 15 | ## find all files with sticker "foo" in "dir" 16 | # sticker.py find dir foo 17 | # 18 | ## find all files with sticker "foo" 19 | # sticker.py find / foo 20 | # 21 | ## delete sticker "foo" from "dir/song.mp3" 22 | # sticker.py delete dir/song.mp3 foo 23 | # 24 | # sticker.py 25 | 26 | #! /usr/bin/env python 27 | 28 | from optparse import OptionParser 29 | from socket import error as SocketError 30 | from sys import stderr 31 | 32 | from mpd import MPDClient, MPDError 33 | 34 | # Edit these 35 | HOST = "localhost" 36 | PORT = 6600 37 | PASS = None 38 | 39 | 40 | ACTIONS = ("get", "set", "delete", "list", "find") 41 | 42 | 43 | def main(action, uri, name, value): 44 | client = MPDClient() 45 | client.connect(HOST, PORT) 46 | if PASS: 47 | client.password(PASS) 48 | 49 | if action == "get": 50 | print(client.sticker_get("song", uri, name)) 51 | if action == "set": 52 | client.sticker_set("song", uri, name, value) 53 | if action == "delete": 54 | client.sticker_delete("song", uri, name) 55 | if action == "list": 56 | stickers = client.sticker_list("song", uri) 57 | for sticker in stickers: 58 | print(sticker) 59 | if action == "find": 60 | matches = client.sticker_find("song", uri, name) 61 | for match in matches: 62 | if "file" in match: 63 | print(match["file"]) 64 | 65 | 66 | if __name__ == "__main__": 67 | parser = OptionParser( 68 | usage="%prog action args", 69 | version="0.1", 70 | description="Manipulate and query MPD song stickers.", 71 | ) 72 | options, args = parser.parse_args() 73 | 74 | if len(args) < 1: 75 | parser.error("no action specified, must be one of: %s" % " ".join(ACTIONS)) 76 | action = args.pop(0) 77 | 78 | if action not in ACTIONS: 79 | parser.error("action must be one of: %s" % " ".join(ACTIONS)) 80 | 81 | if len(args) < 1: 82 | parser.error("no URI specified") 83 | uri = args.pop(0) 84 | 85 | if action in ("get", "set", "delete", "find"): 86 | if len(args) < 1: 87 | parser.error("no name specified") 88 | name = args.pop(0) 89 | else: 90 | name = None 91 | 92 | if action == "set": 93 | if len(args) < 1: 94 | parser.error("no value specified") 95 | value = args.pop(0) 96 | else: 97 | value = None 98 | 99 | try: 100 | main(action, uri, name, value) 101 | except SocketError as e: 102 | print( 103 | "%s: error with connection to MPD: %s" % (parser.get_prog_name(), e[1]), 104 | file=stderr, 105 | ) 106 | except MPDError as e: 107 | print( 108 | "%s: error executing action: %s" % (parser.get_prog_name(), e), file=stderr 109 | ) 110 | 111 | 112 | # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: 113 | -------------------------------------------------------------------------------- /doc/generate_command_reference.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import re 4 | import sys 5 | import os.path 6 | from textwrap import TextWrapper 7 | import urllib.request 8 | 9 | try: 10 | from lxml import etree 11 | except ImportError: 12 | sys.stderr.write("Please install lxml to run this script.") 13 | sys.exit(1) 14 | 15 | DEPRECATED_COMMANDS = [] 16 | SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__)) 17 | 18 | 19 | def get_text(elements, itemize=False): 20 | paragraphs = [] 21 | highlight_elements = ["varname", "parameter"] 22 | strip_elements = [ 23 | "returnvalue", 24 | "command", 25 | "link", 26 | "footnote", 27 | "simpara", 28 | "footnoteref", 29 | "function", 30 | ] + highlight_elements 31 | for element in elements: 32 | # put "Since MPD version..." in parenthese 33 | etree.strip_tags(element, "application") 34 | for e in element.xpath("footnote/simpara"): 35 | e.text = "(" + e.text.strip() + ")" 36 | 37 | for e in element.xpath("|".join(highlight_elements)): 38 | e.text = "*" + e.text.strip() + "*" 39 | etree.strip_tags(element, *strip_elements) 40 | if itemize: 41 | initial_indent = " * " 42 | subsequent_indent = " " 43 | else: 44 | initial_indent = " " 45 | subsequent_indent = " " 46 | wrapper = TextWrapper( 47 | subsequent_indent=subsequent_indent, initial_indent=initial_indent 48 | ) 49 | text = element.text.replace("\n", " ").strip() 50 | text = re.subn(r"\s+", " ", text)[0] 51 | paragraphs.append(wrapper.fill(text)) 52 | return "\n\n".join(paragraphs) 53 | 54 | 55 | def main(url): 56 | header_file = os.path.join(SCRIPT_PATH, "commands_header.txt") 57 | with open(header_file, "r") as f: 58 | print(f.read()) 59 | 60 | r = urllib.request.urlopen(url) 61 | tree = etree.parse(r) 62 | chapter = tree.xpath('/book/chapter[@id="command_reference"]')[0] 63 | for section in chapter.xpath("section"): 64 | title = section.xpath("title")[0].text 65 | print(title) 66 | print(len(title) * "-") 67 | 68 | print(get_text(section.xpath("para"))) 69 | print("") 70 | 71 | for entry in section.xpath("variablelist/varlistentry"): 72 | cmd = entry.xpath("term/cmdsynopsis/command")[0].text 73 | if cmd in DEPRECATED_COMMANDS: 74 | continue 75 | subcommand = "" 76 | args = "" 77 | begin_optional = False 78 | first_argument = True 79 | 80 | for arg in entry.xpath("term/cmdsynopsis/arg"): 81 | choice = arg.attrib.get("choice", None) 82 | if choice == "opt" and not begin_optional: 83 | begin_optional = True 84 | args += "[" 85 | if args != "" and args != "[": 86 | args += ", " 87 | replaceables = arg.xpath("replaceable") 88 | if len(replaceables) > 0: 89 | for replaceable in replaceables: 90 | args += replaceable.text.lower() 91 | elif first_argument: 92 | subcommand = arg.text 93 | else: 94 | args += '"{}"'.format(arg.text) 95 | first_argument = False 96 | if begin_optional: 97 | args += "]" 98 | if subcommand != "": 99 | cmd += "_" + subcommand 100 | print(".. function:: MPDClient." + cmd + "(" + args + ")") 101 | description = get_text(entry.xpath("listitem/para")) 102 | description = re.sub(r":$", r"::", description, flags=re.MULTILINE) 103 | 104 | print("\n") 105 | print(description) 106 | print("\n") 107 | 108 | for screen in entry.xpath("listitem/screen | listitem/programlisting"): 109 | for line in screen.text.split("\n"): 110 | print(" " + line) 111 | for item in entry.xpath("listitem/itemizedlist/listitem"): 112 | print(get_text(item.xpath("para"), itemize=True)) 113 | print("\n") 114 | 115 | 116 | if __name__ == "__main__": 117 | url = "https://raw.githubusercontent.com/MusicPlayerDaemon/MPD/master/doc/protocol.xml" 118 | if len(sys.argv) > 1: 119 | url += "?id=release-" + sys.argv[1] 120 | main(url) 121 | -------------------------------------------------------------------------------- /examples/errorhandling.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # 3 | # Introduction 4 | # 5 | # A python program that continuously polls for song info. Demonstrates how and where to handle errors 6 | # Details 7 | # 8 | 9 | from mpd import MPDClient, MPDError, CommandError 10 | import sys 11 | 12 | 13 | class PollerError(Exception): 14 | """Fatal error in poller.""" 15 | 16 | 17 | class MPDPoller(object): 18 | def __init__(self, host="localhost", port="6600", password=None): 19 | self._host = host 20 | self._port = port 21 | self._password = password 22 | self._client = MPDClient() 23 | 24 | def connect(self): 25 | try: 26 | self._client.connect(self._host, self._port) 27 | # Catch socket errors 28 | except IOError as err: 29 | errno, strerror = err 30 | raise PollerError("Could not connect to '%s': %s" % (self._host, strerror)) 31 | 32 | # Catch all other possible errors 33 | # ConnectionError and ProtocolError are always fatal. Others may not 34 | # be, but we don't know how to handle them here, so treat them as if 35 | # they are instead of ignoring them. 36 | except MPDError as e: 37 | raise PollerError("Could not connect to '%s': %s" % (self._host, e)) 38 | 39 | if self._password: 40 | try: 41 | self._client.password(self._password) 42 | 43 | # Catch errors with the password command (e.g., wrong password) 44 | except CommandError as e: 45 | # On CommandErrors we have access to the parsed error response 46 | # split into errno, offset, command and msg. 47 | raise PollerError( 48 | "Could not connect to '%s': " 49 | "password commmand failed: [%d] %s" % (self._host, e.errno, e.msg) 50 | ) 51 | 52 | # Catch all other possible errors 53 | except (MPDError, IOError) as e: 54 | raise PollerError( 55 | "Could not connect to '%s': " 56 | "error with password command: %s" % (self._host, e) 57 | ) 58 | 59 | def disconnect(self): 60 | # Try to tell MPD we're closing the connection first 61 | try: 62 | self._client.close() 63 | 64 | # If that fails, don't worry, just ignore it and disconnect 65 | except (MPDError, IOError): 66 | pass 67 | 68 | try: 69 | self._client.disconnect() 70 | 71 | # Disconnecting failed, so use a new client object instead 72 | # This should never happen. If it does, something is seriously broken, 73 | # and the client object shouldn't be trusted to be re-used. 74 | except (MPDError, IOError): 75 | self._client = MPDClient() 76 | 77 | def poll(self): 78 | try: 79 | song = self._client.currentsong() 80 | 81 | # Couldn't get the current song, so try reconnecting and retrying 82 | except (MPDError, IOError): 83 | # No error handling required here 84 | # Our disconnect function catches all exceptions, and therefore 85 | # should never raise any. 86 | self.disconnect() 87 | 88 | try: 89 | self.connect() 90 | 91 | # Reconnecting failed 92 | except PollerError as e: 93 | raise PollerError("Reconnecting failed: %s" % e) 94 | 95 | try: 96 | song = self._client.currentsong() 97 | 98 | # Failed again, just give up 99 | except (MPDError, IOError) as e: 100 | raise PollerError("Couldn't retrieve current song: %s" % e) 101 | 102 | # Hurray! We got the current song without any errors! 103 | print(song) 104 | 105 | 106 | def main(): 107 | from time import sleep 108 | 109 | poller = MPDPoller() 110 | poller.connect() 111 | 112 | while True: 113 | poller.poll() 114 | sleep(3) 115 | 116 | 117 | if __name__ == "__main__": 118 | import sys 119 | 120 | try: 121 | main() 122 | 123 | # Catch fatal poller errors 124 | except PollerError as e: 125 | print("Fatal poller error: %s" % e, file=sys.stderr) 126 | sys.exit(1) 127 | 128 | # Catch all other non-exit errors 129 | except Exception as e: 130 | print("Unexpected exception: %s" % e, file=sys.stderr) 131 | sys.exit(1) 132 | 133 | # Catch the remaining exit errors 134 | except Exception: 135 | sys.exit(0) 136 | 137 | 138 | # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: 139 | -------------------------------------------------------------------------------- /doc/changes.rst: -------------------------------------------------------------------------------- 1 | python-mpd2 Changes List 2 | ======================== 3 | 4 | Changes in v3.1.1 5 | ----------------- 6 | 7 | * Propagate exception to all pending commands by @2franix in https://github.com/Mic92/python-mpd2/pull/221 8 | * Fix test for python 3.12 by @Mic92 in https://github.com/Mic92/python-mpd2/pull/222 9 | 10 | 11 | Changes in v3.1.0 12 | ----------------- 13 | 14 | * fixed multiple use of "group" in list command by @SoongNoonien in https://github.com/Mic92/python-mpd2/pull/187 15 | * fix unmount command not working by @burrocargado in https://github.com/Mic92/python-mpd2/pull/188 16 | * added binarylimit command by @SoongNoonien in https://github.com/Mic92/python-mpd2/pull/191 17 | * Implement abstract socket support by @aurieh in https://github.com/Mic92/python-mpd2/pull/193 18 | * missing import / wrong variable by @mk-81 in https://github.com/Mic92/python-mpd2/pull/196 19 | * also test python3.12 by @Mic92 in https://github.com/Mic92/python-mpd2/pull/200 20 | * asyncio: fix race condition in command queue by @yakshaver2000 in https://github.com/Mic92/python-mpd2/pull/199 21 | 22 | Changes in v3.0.5 23 | ----------------- 24 | 25 | * python 3.10 compatibility 26 | * fixes for using idle in async 27 | * use python's internal mock library instead of external mock 28 | * expose connection status in async (connected property) 29 | 30 | Changes in v3.0.4 31 | ----------------- 32 | 33 | * exposes failure responses in CommandError exceptions 34 | 35 | Changes in v3.0.3 36 | ----------------- 37 | 38 | * asyncio: tolerate early disconnects 39 | 40 | Changes in v3.0.2 41 | ----------------- 42 | 43 | * asyncio: fix disconnect happen before connect 44 | * asyncio: better protection against request cancellation 45 | * asyncio: idle iterator raises error when connection closed 46 | 47 | 48 | Changes in v3.0.1 49 | ----------------- 50 | 51 | * 3.0.0 accidentially introduced typing annotation that were not meant to be published yet. 52 | 53 | 54 | Changes in v3.0.0 55 | ----------------- 56 | 57 | * Breaking changes: albumart now returns dictionary :code:`{"size": "...", 58 | "binary": b"..."}` instead of just a string 59 | * add readpicture command 60 | * add partition, newpartition and delpartition commands 61 | * add moveoutput command 62 | * removed deprecated `send_` and `fetch_` commands. Use the asyncio or twisted API instead for asynchronous mpd commands. 63 | 64 | Changes in v2.0.0 65 | ----------------- 66 | 67 | * Minimum python version was increased to python3.6, python2.7 support was dropped 68 | * asyncio: fix parsing delimiters 69 | * add support for albumart command 70 | 71 | Changes in v1.1.0 72 | ----------------- 73 | 74 | * Fix list command to work with grouping. Always returns list of dictionaries now. 75 | Make sure to adopt your code since this is an API change. 76 | * fix compatibility with python3.9 77 | * fix connecting to unix socket in asyncio version 78 | * close asyncio transports on disconnect 79 | * create TCP socket with TCP_NODELAY for better responsiveness 80 | 81 | 82 | Changes in v1.0.0 83 | ----------------- 84 | 85 | * Add support for twisted 86 | * Add support for asyncio 87 | * Use @property and @property.setter for MPDClient.timeout 88 | * Deprecate send_* and fetch_* variants of MPD commands: Consider using asyncio/twisted instead 89 | * Port argument is optional when connecting via unix sockets. 90 | * python-mpd will now raise mpd.ConnectionError instead of socket.error, when connection is lost 91 | * Add command outputvolume for forked-daapd 92 | 93 | 94 | Changes in v0.5.5 95 | ----------------- 96 | 97 | * fix sended newlines on windows systems 98 | * include tests in source distribution 99 | 100 | 101 | Changes in v0.5.4 102 | ----------------- 103 | 104 | * support for listfiles, rangeid, addtagid, cleartagid, mount, umount, 105 | listmounts, listneighbors 106 | 107 | 108 | Changes in v0.5.3 109 | ----------------- 110 | 111 | * noidle command does returns pending changes now 112 | 113 | 114 | Changes in v0.5.2 115 | ----------------- 116 | 117 | * add support for readcomments and toggleoutput 118 | 119 | 120 | Changes in v0.5.1 121 | ----------------- 122 | 123 | * add support for ranges 124 | 125 | 126 | Changes in 0.5.0 127 | ---------------- 128 | 129 | * improved support for sticker 130 | 131 | 132 | Changes in 0.4.6 133 | ---------------- 134 | 135 | * enforce utf8 for encoding/decoding in python3 136 | 137 | 138 | Changes in 0.4.5 139 | ---------------- 140 | 141 | * support for logging 142 | 143 | 144 | Changes in 0.4.4 145 | ---------------- 146 | 147 | * fix cleanup after broken connection 148 | * deprecate timeout parameter added in v0.4.2 149 | * add timeout and idletimeout property 150 | 151 | 152 | Changes in 0.4.3 153 | ---------------- 154 | 155 | * add searchadd and searchaddpl command 156 | * fix commands without a callback function 157 | * transform MPDClient to new style class 158 | 159 | 160 | Changes in 0.4.2 161 | ---------------- 162 | 163 | * backward compatible unicode handling 164 | * added optional socket timeout parameter 165 | 166 | 167 | Changes in 0.4.1 168 | ---------------- 169 | 170 | * prio and prioid was spelled wrong 171 | * added config command 172 | * remove deprecated volume command 173 | 174 | 175 | Changes in 0.4.0 176 | ---------------- 177 | 178 | * python3 support (python2.6 is minimum python version required) 179 | * support for the upcoming client-to-client protocol 180 | * added new commands of mpd (seekcur, prior, priorid) 181 | * methods are explicit declared now, so they are shown in ipython 182 | * added unit tests 183 | * documented API to add new commands (see Future Compatible) 184 | 185 | 186 | Changes in 0.3.0 187 | ---------------- 188 | 189 | * added replay_gain_mode and replay_gain_status commands 190 | * added mixrampdb and mixrampdelay commands 191 | * added findadd and rescan commands 192 | * added decoders command 193 | * changed license to LGPL 194 | * added sticker commands 195 | * correctly handle errors in command lists (fixes a longstanding bug) 196 | * raise IteratingError instead of breaking horribly when called wrong 197 | * added fileno() to export socket FD (for polling with select et al.) 198 | * asynchronous API (use send_ to queue, fetch_ to retrieve) 199 | * support for connecting to unix domain sockets 200 | * added consume and single commands 201 | * added idle and noidle commands 202 | * added listplaylists command 203 | 204 | 205 | Changes in 0.2.1 206 | ---------------- 207 | 208 | * connect() no longer broken on Windows 209 | 210 | 211 | Changes in 0.2.0 212 | ---------------- 213 | 214 | * support for IPv6 and multi-homed hostnames 215 | * connect() will fail if already connected 216 | * commands may now raise ConnectionError 217 | * addid and update may now return None 218 | -------------------------------------------------------------------------------- /doc/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python-mpd2.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python-mpd2.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/python-mpd2" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python-mpd2" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /doc/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # python-mpd2 documentation build configuration file, created by 4 | # sphinx-quickstart on Thu Apr 4 09:22:21 2013. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys 15 | import os 16 | 17 | # If extensions (or modules to document with autodoc) are in another directory, 18 | # add these directories to sys.path here. If the directory is relative to the 19 | # documentation root, use os.path.abspath to make it absolute, like shown here. 20 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 21 | import mpd 22 | 23 | # -- General configuration ----------------------------------------------------- 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | # needs_sphinx = '1.0' 27 | 28 | # Add any Sphinx extension module names here, as strings. They can be extensions 29 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 30 | extensions = ["sphinx.ext.viewcode"] 31 | 32 | # Add any paths that contain templates here, relative to this directory. 33 | templates_path = ["_templates"] 34 | 35 | # The suffix of source filenames. 36 | source_suffix = ".rst" 37 | 38 | # The encoding of source files. 39 | # source_encoding = 'utf-8-sig' 40 | 41 | # The master toctree document. 42 | master_doc = "index" 43 | 44 | # General information about the project. 45 | project = "python-mpd2" 46 | copyright = "2013, Jörg Thalheim" 47 | 48 | # The version info for the project you're documenting, acts as replacement for 49 | # |version| and |release|, also used in various other places throughout the 50 | # built documents. 51 | # 52 | # The short X.Y version. 53 | version = ".".join(map(str, mpd.VERSION)) 54 | # The full version, including alpha/beta/rc tags. 55 | release = version 56 | 57 | # The language for content autogenerated by Sphinx. Refer to documentation 58 | # for a list of supported languages. 59 | # language = None 60 | 61 | # There are two options for replacing |today|: either, you set today to some 62 | # non-false value, then it is used: 63 | # today = '' 64 | # Else, today_fmt is used as the format for a strftime call. 65 | # today_fmt = '%B %d, %Y' 66 | 67 | # List of patterns, relative to source directory, that match files and 68 | # directories to ignore when looking for source files. 69 | exclude_patterns = ["_build"] 70 | 71 | # The reST default role (used for this markup: `text`) to use for all documents. 72 | # default_role = None 73 | 74 | # If true, '()' will be appended to :func: etc. cross-reference text. 75 | # add_function_parentheses = True 76 | 77 | # If true, the current module name will be prepended to all description 78 | # unit titles (such as .. function::). 79 | # add_module_names = True 80 | 81 | # If true, sectionauthor and moduleauthor directives will be shown in the 82 | # output. They are ignored by default. 83 | # show_authors = False 84 | 85 | # The name of the Pygments (syntax highlighting) style to use. 86 | pygments_style = "sphinx" 87 | 88 | # A list of ignored prefixes for module index sorting. 89 | # modindex_common_prefix = [] 90 | 91 | # If true, keep warnings as "system message" paragraphs in the built documents. 92 | # keep_warnings = False 93 | 94 | 95 | # -- Options for HTML output --------------------------------------------------- 96 | 97 | # The theme to use for HTML and HTML Help pages. See the documentation for 98 | # a list of builtin themes. 99 | html_theme = "default" 100 | 101 | # Theme options are theme-specific and customize the look and feel of a theme 102 | # further. For a list of options available for each theme, see the 103 | # documentation. 104 | # html_theme_options = {} 105 | 106 | # Add any paths that contain custom themes here, relative to this directory. 107 | # html_theme_path = [] 108 | 109 | # The name for this set of Sphinx documents. If None, it defaults to 110 | # " v documentation". 111 | # html_title = None 112 | 113 | # A shorter title for the navigation bar. Default is the same as html_title. 114 | # html_short_title = None 115 | 116 | # The name of an image file (relative to this directory) to place at the top 117 | # of the sidebar. 118 | # html_logo = None 119 | 120 | # The name of an image file (within the static path) to use as favicon of the 121 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 122 | # pixels large. 123 | # html_favicon = None 124 | 125 | # Add any paths that contain custom static files (such as style sheets) here, 126 | # relative to this directory. They are copied after the builtin static files, 127 | # so a file named "default.css" will overwrite the builtin "default.css". 128 | html_static_path = ["_static"] 129 | 130 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 131 | # using the given strftime format. 132 | # html_last_updated_fmt = '%b %d, %Y' 133 | 134 | # If true, SmartyPants will be used to convert quotes and dashes to 135 | # typographically correct entities. 136 | # html_use_smartypants = True 137 | 138 | # Custom sidebar templates, maps document names to template names. 139 | # html_sidebars = {} 140 | 141 | # Additional templates that should be rendered to pages, maps page names to 142 | # template names. 143 | # html_additional_pages = {} 144 | 145 | # If false, no module index is generated. 146 | # html_domain_indices = True 147 | 148 | # If false, no index is generated. 149 | # html_use_index = True 150 | 151 | # If true, the index is split into individual pages for each letter. 152 | # html_split_index = False 153 | 154 | # If true, links to the reST sources are added to the pages. 155 | # html_show_sourcelink = True 156 | 157 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 158 | # html_show_sphinx = True 159 | 160 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 161 | # html_show_copyright = True 162 | 163 | # If true, an OpenSearch description file will be output, and all pages will 164 | # contain a tag referring to it. The value of this option must be the 165 | # base URL from which the finished HTML is served. 166 | # html_use_opensearch = '' 167 | 168 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 169 | # html_file_suffix = None 170 | 171 | # Output file base name for HTML help builder. 172 | htmlhelp_basename = "python-mpd2doc" 173 | 174 | 175 | # -- Options for LaTeX output -------------------------------------------------- 176 | 177 | latex_elements = { 178 | # The paper size ('letterpaper' or 'a4paper'). 179 | #'papersize': 'letterpaper', 180 | # The font size ('10pt', '11pt' or '12pt'). 181 | #'pointsize': '10pt', 182 | # Additional stuff for the LaTeX preamble. 183 | #'preamble': '', 184 | } 185 | 186 | # Grouping the document tree into LaTeX files. List of tuples 187 | # (source start file, target name, title, author, documentclass [howto/manual]). 188 | latex_documents = [ 189 | ( 190 | "index", 191 | "python-mpd2.tex", 192 | "python-mpd2 Documentation", 193 | "Jörg Thalheim", 194 | "manual", 195 | ), 196 | ] 197 | 198 | # The name of an image file (relative to this directory) to place at the top of 199 | # the title page. 200 | # latex_logo = None 201 | 202 | # For "manual" documents, if this is true, then toplevel headings are parts, 203 | # not chapters. 204 | # latex_use_parts = False 205 | 206 | # If true, show page references after internal links. 207 | # latex_show_pagerefs = False 208 | 209 | # If true, show URL addresses after external links. 210 | # latex_show_urls = False 211 | 212 | # Documents to append as an appendix to all manuals. 213 | # latex_appendices = [] 214 | 215 | # If false, no module index is generated. 216 | # latex_domain_indices = True 217 | 218 | 219 | # -- Options for manual page output -------------------------------------------- 220 | 221 | # One entry per manual page. List of tuples 222 | # (source start file, name, description, authors, manual section). 223 | man_pages = [ 224 | ("index", "python-mpd2", "python-mpd2 Documentation", ["Jörg Thalheim"], 1) 225 | ] 226 | 227 | # If true, show URL addresses after external links. 228 | # man_show_urls = False 229 | 230 | 231 | # -- Options for Texinfo output ------------------------------------------------ 232 | 233 | # Grouping the document tree into Texinfo files. List of tuples 234 | # (source start file, target name, title, author, 235 | # dir menu entry, description, category) 236 | texinfo_documents = [ 237 | ( 238 | "index", 239 | "python-mpd2", 240 | "python-mpd2 Documentation", 241 | "Jörg Thalheim", 242 | "python-mpd2", 243 | "One line description of project.", 244 | "Miscellaneous", 245 | ), 246 | ] 247 | 248 | # Documents to append as an appendix to all manuals. 249 | # texinfo_appendices = [] 250 | 251 | # If false, no module index is generated. 252 | # texinfo_domain_indices = True 253 | 254 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 255 | # texinfo_show_urls = 'footnote' 256 | 257 | # If true, do not generate a @detailmenu in the "Top" node's menu. 258 | # texinfo_no_detailmenu = False 259 | -------------------------------------------------------------------------------- /mpd/twisted.py: -------------------------------------------------------------------------------- 1 | # python-mpd2: Python MPD client library 2 | # 3 | # Copyright (C) 2008-2010 J. Alexander Treuman 4 | # Copyright (C) 2010 Jasper St. Pierre 5 | # Copyright (C) 2010-2011 Oliver Mader 6 | # Copyright (C) 2016 Robert Niederreiter 7 | # 8 | # python-mpd2 is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU Lesser General Public License as published by 10 | # the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # python-mpd2 is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU Lesser General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU Lesser General Public License 19 | # along with python-mpd2. If not, see . 20 | # 21 | # THIS MODULE IS EXPERIMENTAL. AS SOON AS IT IS CONSIDERED STABLE THIS NOTE 22 | # WILL BE REMOVED. PLEASE REPORT INCONSISTENCIES, BUGS AND IMPROVEMENTS AT 23 | # https://github.com/Mic92/python-mpd2/issues 24 | 25 | from __future__ import absolute_import, unicode_literals 26 | 27 | import threading 28 | import types 29 | from typing import Any, Callable, List, Optional, Protocol, Union, cast 30 | 31 | from twisted.internet import defer 32 | from twisted.protocols import basic 33 | 34 | from mpd.base import ( 35 | ERROR_PREFIX, 36 | HELLO_PREFIX, 37 | NEXT, 38 | SUCCESS, 39 | CommandError, 40 | CommandListError, 41 | MPDClientBase, 42 | escape, 43 | logger, 44 | mpd_command_provider, 45 | mpd_commands, 46 | ) 47 | 48 | 49 | def lock(func: Callable) -> Callable: 50 | def wrapped(self: Any, *args: Any, **kwargs: Any) -> Any: 51 | with self._lock: 52 | return func(self, *args, **kwargs) 53 | 54 | return wrapped 55 | 56 | 57 | class FunctionWithCallable(Protocol): 58 | callback: Callable 59 | 60 | def __call__(self, *args: Any, **kwargs: Any) -> Any: 61 | pass 62 | 63 | 64 | def _create_command( 65 | wrapper: Callable[[Any, str, Any, FunctionWithCallable], Any], 66 | name: str, 67 | callback: Callable, 68 | ) -> Callable: 69 | def mpd_command(self: Any, *args: Any) -> Any: 70 | def func(lines: List[str]) -> Any: 71 | return callback(self, lines) 72 | 73 | bound_callback = cast(FunctionWithCallable, func) 74 | bound_callback.callback = callback 75 | return wrapper(self, name, args, bound_callback) 76 | 77 | return mpd_command 78 | 79 | 80 | @mpd_command_provider 81 | class MPDProtocol(basic.LineReceiver, MPDClientBase): 82 | delimiter = b"\n" 83 | 84 | def __init__( 85 | self, default_idle: bool = True, idle_result: Optional[Callable] = None 86 | ) -> None: 87 | super(MPDProtocol, self).__init__() 88 | # flag whether client should idle by default 89 | self._default_idle = default_idle 90 | self.idle_result = idle_result 91 | self._reset() 92 | self._lock = threading.RLock() 93 | 94 | def _reset(self) -> None: 95 | super(MPDProtocol, self)._reset() 96 | self.mpd_version = None 97 | self._in_command_list = False 98 | self._command_list_results: List[List[defer.Deferred]] = [] 99 | self._rcvd_lines: List[str] = [] 100 | self._state: List[List[defer.Deferred]] = [] 101 | self._idle = False 102 | 103 | @classmethod 104 | def add_command(cls: Any, name: str, callback: Callable) -> None: 105 | # ignore commands which are implemented on class directly 106 | if getattr(cls, name, None) is not None: 107 | return 108 | # create command and hook it on class 109 | func = _create_command(cls._execute, name, callback) 110 | escaped_name = name.replace(" ", "_") 111 | setattr(cls, escaped_name, func) 112 | 113 | @lock 114 | def lineReceived(self, line: bytes) -> None: 115 | line_str = line.decode("utf-8") 116 | command_list = self._state and isinstance(self._state[0], list) 117 | state_list = self._state[0] if command_list else self._state 118 | if line_str.startswith(HELLO_PREFIX): 119 | self.mpd_version = line_str[len(HELLO_PREFIX) :].strip() 120 | # default state idle, enter idle 121 | if self._default_idle: 122 | self.idle().addCallback(self._dispatch_idle_result) 123 | elif line_str.startswith(ERROR_PREFIX): 124 | error = line_str[len(ERROR_PREFIX) :].strip() 125 | if command_list: 126 | state_list[0].errback(CommandError(error)) 127 | for state in state_list[1:-1]: 128 | state.errback(CommandListError("An earlier command failed.")) 129 | state_list[-1].errback(CommandListError(error)) 130 | del self._state[0] 131 | del self._command_list_results[0] 132 | else: 133 | state_list.pop(0).errback(CommandError(error)) 134 | self._continue_idle() 135 | elif line_str == SUCCESS or (command_list and line_str == NEXT): 136 | state_list.pop(0).callback(self._rcvd_lines[:]) 137 | self._rcvd_lines = [] 138 | if command_list and line_str == SUCCESS: 139 | del self._state[0] 140 | self._continue_idle() 141 | else: 142 | self._rcvd_lines.append(line_str) 143 | 144 | def _lookup_callback( 145 | self, parser: Union[None, Callable, FunctionWithCallable] 146 | ) -> Optional[Callable]: 147 | if hasattr(parser, "callback") and parser is not None: 148 | return parser.callback 149 | return parser 150 | 151 | @lock 152 | def _execute( 153 | self, command: str, args: List[str] = [], parser: Optional[Callable] = None 154 | ) -> defer.Deferred: 155 | # close or kill command in command list not allowed 156 | if self._in_command_list and self._lookup_callback(parser) is self.NOOP: 157 | msg = "{} not allowed in command list".format(command) 158 | raise CommandListError(msg) 159 | # default state idle and currently in idle state, trigger noidle 160 | if self._default_idle and self._idle and command != "idle": 161 | self.noidle().addCallback(self._dispatch_noidle_result) 162 | # write command to MPD 163 | self._write_command(command, args) 164 | # create command related deferred 165 | deferred = defer.Deferred() 166 | # extend pending result queue 167 | state = self._state[-1] if self._in_command_list else self._state 168 | state.append(deferred) 169 | # NOOP is for close and kill commands 170 | if self._lookup_callback(parser) is not self.NOOP: 171 | # attach command related result parser 172 | deferred.addCallback(parser) 173 | # command list, attach handler for collecting command list results 174 | if self._in_command_list: 175 | deferred.addCallback(self._parse_command_list_item) 176 | return deferred 177 | 178 | def _create_command(self, command: str, args: List[str] = []) -> bytes: 179 | # XXX: this function should be generalized in future. There exists 180 | # almost identical code in ``MPDClient._write_command``, with the 181 | # difference that it's using ``encode_str`` for text arguments. 182 | parts = [command] 183 | for arg in args: 184 | if type(arg) is tuple: 185 | if len(arg) == 0: 186 | parts.append('":"') 187 | elif len(arg) == 1: 188 | parts.append('"{}:"'.format(int(arg[0]))) 189 | else: 190 | parts.append('"{}:{}"'.format(int(arg[0]), int(arg[1]))) 191 | else: 192 | parts.append('"{}"'.format(escape(arg))) 193 | return " ".join(parts).encode("utf-8") 194 | 195 | def _write_command(self, command: str, args: List[str] = []) -> None: 196 | self.sendLine(self._create_command(command, args)) 197 | 198 | def _parse_command_list_item(self, result: Any) -> Any: 199 | if isinstance(result, types.GeneratorType): 200 | result = list(result) 201 | self._command_list_results[0].append(result) 202 | return result 203 | 204 | def _parse_command_list_end(self, lines: List[str]) -> Any: 205 | return self._command_list_results.pop(0) 206 | 207 | @mpd_commands(*MPDClientBase._parse_nothing.mpd_commands) 208 | def _parse_nothing(self, lines: List[str]) -> None: 209 | return None 210 | 211 | def _continue_idle(self) -> None: 212 | if self._default_idle and not self._idle and not self._state: 213 | self.idle().addCallback(self._dispatch_idle_result) 214 | 215 | def _do_dispatch(self, result: Any) -> None: 216 | if self.idle_result: 217 | self.idle_result(result) 218 | else: 219 | res = list(result) 220 | msg = "MPDProtocol: no idle callback defined: {}".format(res) 221 | logger.warning(msg) 222 | 223 | def _dispatch_noidle_result(self, result: Any) -> None: 224 | self._do_dispatch(result) 225 | 226 | def _dispatch_idle_result(self, result: Any) -> None: 227 | self._idle = False 228 | self._do_dispatch(result) 229 | self._continue_idle() 230 | 231 | def idle(self) -> defer.Deferred: 232 | if self._idle: 233 | raise CommandError("Already in idle state") 234 | self._idle = True 235 | return self._execute("idle", [], self._parse_list) 236 | 237 | def noidle(self) -> defer.Deferred: 238 | if not self._idle: 239 | raise CommandError("Not in idle state") 240 | # delete first pending deferred, idle returns nothing when 241 | # noidle gets called 242 | self._state.pop(0) 243 | self._idle = False 244 | return self._execute("noidle", [], self._parse_list) 245 | 246 | def command_list_ok_begin(self) -> None: 247 | if self._in_command_list: 248 | raise CommandListError("Already in command list") 249 | if self._default_idle and self._idle: 250 | self.noidle().addCallback(self._dispatch_noidle_result) 251 | self._write_command("command_list_ok_begin") 252 | self._in_command_list = True 253 | self._command_list_results.append([]) 254 | self._state.append([]) 255 | 256 | def command_list_end(self) -> defer.Deferred: 257 | if not self._in_command_list: 258 | raise CommandListError("Not in command list") 259 | self._write_command("command_list_end") 260 | deferred = defer.Deferred() 261 | deferred.addCallback(self._parse_command_list_end) 262 | self._state[-1].append(deferred) 263 | self._in_command_list = False 264 | return deferred 265 | 266 | 267 | # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: 268 | -------------------------------------------------------------------------------- /mpd/asyncio.py: -------------------------------------------------------------------------------- 1 | """Asynchronous access to MPD using the asyncio methods of Python 3. 2 | 3 | Interaction happens over the mpd.asyncio.MPDClient class, whose connect and 4 | command methods are coroutines. 5 | 6 | Some commands (eg. listall) additionally support the asynchronous iteration 7 | (aiter, `async for`) interface; using it allows the library user to obtain 8 | items of result as soon as they arrive. 9 | 10 | The .idle() method works differently here: It is an asynchronous iterator that 11 | produces a list of changed subsystems whenever a new one is available. The 12 | MPDClient object automatically switches in and out of idle mode depending on 13 | which subsystems there is currently interest in. 14 | 15 | Command lists are currently not supported. 16 | 17 | 18 | This module requires Python 3.5.2 or later to run. 19 | """ 20 | 21 | import asyncio 22 | import warnings 23 | from functools import partial 24 | from typing import ( 25 | Any, 26 | AsyncIterator, 27 | Callable, 28 | Iterable, 29 | List, 30 | Optional, 31 | Set, 32 | Tuple, 33 | Union, 34 | Dict, 35 | cast, 36 | ) 37 | 38 | from mpd.base import ( 39 | ERROR_PREFIX, 40 | SUCCESS, 41 | CommandError, 42 | CommandListError, 43 | ConnectionError, 44 | CallableWithCommands, 45 | ) 46 | from mpd.base import MPDClient as SyncMPDClient 47 | from mpd.base import MPDClientBase, ProtocolError, mpd_command_provider 48 | 49 | 50 | class BaseCommandResult(asyncio.Future): 51 | """A future that carries its command/args/callback with it for the 52 | convenience of passing it around to the command queue.""" 53 | 54 | def __init__(self, command: str, args: List[str], callback: Callable) -> None: 55 | super().__init__() 56 | self._command = command 57 | self._args = args 58 | self._callback = callback 59 | 60 | def _feed_line(self, line: Optional[str]) -> None: # FIXME just inline? 61 | raise NotImplementedError 62 | 63 | def _feed_error(self, error: Exception) -> None: 64 | raise NotImplementedError 65 | 66 | async def _feed_from(self, mpdclient: "MPDClient") -> None: 67 | while True: 68 | line = await mpdclient._read_line() 69 | self._feed_line(line) 70 | if line is None: 71 | return 72 | 73 | 74 | class CommandResult(BaseCommandResult): 75 | def __init__(self, *args: Any, **kwargs: Any) -> None: 76 | super().__init__(*args, **kwargs) 77 | self.__spooled_lines: List[str] = [] 78 | 79 | def _feed_line(self, line: Optional[str]) -> None: # FIXME just inline? 80 | """Put the given line into the callback machinery, and set the result on a None line.""" 81 | if line is None: 82 | if self.cancelled(): 83 | # Data was still pulled out of the connection, but the original 84 | # requester has cancelled the request -- no need to filter the 85 | # data through the preprocessing callback 86 | pass 87 | else: 88 | self.set_result(self._callback(self.__spooled_lines)) 89 | else: 90 | self.__spooled_lines.append(line) 91 | 92 | def _feed_error(self, error: Exception) -> None: 93 | if not self.done(): 94 | self.set_exception(error) 95 | else: 96 | # These do occur (especially during the test suite run) when a 97 | # disconnect was already initialized, but the run task being 98 | # cancelled has not ever yielded at all and thus still needs to run 99 | # through to its first await point (which is then in a situation 100 | # where properties it'd like to access are already cleaned up, 101 | # resulting in an AttributeError) 102 | # 103 | # Rather than quenching them here, they are made visible (so that 104 | # other kinds of double errors raise visibly, even though none are 105 | # known right now); instead, the run loop yields initially with a 106 | # sleep(0) that ensures it can be cancelled properly at any time. 107 | raise error 108 | 109 | 110 | class BinaryCommandResult(asyncio.Future): 111 | # Unlike the regular commands that defer to any callback that may be 112 | # defined for them, this uses the predefined _read_binary mechanism of the 113 | # mpdclient 114 | async def _feed_from(self, mpdclient: "MPDClient") -> None: 115 | # Data must be pulled out no matter whether will later be ignored or not 116 | binary = await mpdclient._read_binary() 117 | if self.cancelled(): 118 | pass 119 | else: 120 | self.set_result(binary) 121 | 122 | def _feed_error(self, error: Exception) -> None: 123 | return CommandResult._feed_error(cast(CommandResult, self), error) 124 | 125 | 126 | class CommandResultIterable(BaseCommandResult): 127 | """Variant of CommandResult where the underlying callback is an 128 | asynchronous` generator, and can thus interpret lines as they come along. 129 | 130 | The result can be used with the aiter interface (`async for`). If it is 131 | still used as a future instead, it eventually results in a list. 132 | 133 | Commands used with this CommandResult must use their passed lines not like 134 | an iterable (as in the synchronous implementation), but as a asyncio.Queue. 135 | Furthermore, they must check whether the queue elements are exceptions, and 136 | raise them. 137 | """ 138 | 139 | def __init__(self, *args: Any, **kwargs: Any) -> None: 140 | super().__init__(*args, **kwargs) 141 | self.__spooled_lines: asyncio.Queue[Union[str, None, Exception]] = ( 142 | asyncio.Queue() 143 | ) 144 | 145 | def _feed_line(self, line: Union[str, None]) -> None: 146 | self.__spooled_lines.put_nowait(line) 147 | 148 | def _feed_error(self, error: Exception) -> None: 149 | self.__spooled_lines.put_nowait(error) 150 | 151 | def __await__(self) -> Any: 152 | asyncio.Task(self.__feed_future()) 153 | return super().__await__() 154 | 155 | __iter__ = __await__ # for 'yield from' style invocation 156 | 157 | async def __feed_future(self) -> None: 158 | result = [] 159 | try: 160 | async for r in self: 161 | result.append(r) 162 | except Exception as e: 163 | self.set_exception(e) 164 | else: 165 | if not self.cancelled(): 166 | self.set_result(result) 167 | 168 | def __aiter__(self) -> "Any": 169 | if self.done(): 170 | raise RuntimeError("Command result is already being consumed") 171 | return self._callback(self.__spooled_lines).__aiter__() 172 | 173 | 174 | @mpd_command_provider 175 | class MPDClient(MPDClientBase): 176 | __run_task = None # doubles as indicator for being connected 177 | 178 | #: Indicator of whether there is a pending idle command that was not terminated yet. 179 | # When in doubt; this is True, thus erring at the side of caution (because 180 | # a "noidle" being sent while racing against an incoming idle notification 181 | # does no harm) 182 | __in_idle = False 183 | 184 | #: Indicator that the last attempted idle failed. 185 | # 186 | # When set, IMMEDIATE_COMMAND_TIMEOUT is ignored in favor of waiting until 187 | # *something* else happens, and only then retried. 188 | # 189 | # Note that the only known condition in which this happens is when between 190 | # start of the connection and the presentation of credentials, more than 191 | # IMMEDIATE_COMMAND_TIMEOUT passes. 192 | __idle_failed = False 193 | 194 | #: Seconds after a command's completion to send idle. Setting this too high 195 | # causes "blind spots" in the client's view of the server, setting it too 196 | # low sends needless idle/noidle after commands in quick succession. 197 | IMMEDIATE_COMMAND_TIMEOUT = 0.1 198 | 199 | #: FIFO list of processors that may consume the read stream one after the 200 | # other 201 | # 202 | # As we don't have any other form of backpressure in the sending side 203 | # (which is not expected to be limited), its limit of COMMAND_QUEUE_LENGTH 204 | # serves as a limit against commands queuing up indefinitely. (It's not 205 | # *directly* throttling output, but as the convention is to put the 206 | # processor on the queue and then send the command, and commands are of 207 | # limited size, this is practically creating backpressure.) 208 | __command_queue: Optional[ 209 | "asyncio.Queue[Union[BaseCommandResult, BinaryCommandResult]]" 210 | ] = None 211 | 212 | #: Construction size of __command_queue. The default limit is high enough 213 | # that a client can easily send off all existing commands simultaneously 214 | # without needlessly blocking the TCP flow, but small enough that 215 | # freespinning tasks create warnings. 216 | COMMAND_QUEUE_LENGTH = 128 217 | 218 | #: Callbacks registered by any current callers of `idle()`. 219 | # 220 | # The first argument lists the changes that the caller is interested in 221 | # (and all current listeners' union is used to populate the `idle` 222 | # command's arguments), the latter is an actual callback that will be 223 | # passed either a set of changes or an exception. 224 | __idle_consumers: Optional[ 225 | List[ 226 | Tuple[ 227 | Union[List[str], Tuple[str]], 228 | Callable[[Union[List[str], Exception]], None], 229 | ] 230 | ] 231 | ] = None 232 | 233 | def __init__(self, *args: Any, **kwargs: Any) -> None: 234 | super().__init__(*args, **kwargs) 235 | self.__rfile: Optional[asyncio.StreamReader] = None 236 | self.__wfile: Optional[asyncio.StreamWriter] = None 237 | 238 | async def connect( 239 | self, 240 | host: str, 241 | port: int = 6600, 242 | loop: Optional[asyncio.AbstractEventLoop] = None, 243 | ) -> None: 244 | if loop is not None: 245 | warnings.warn( 246 | "loop passed into MPDClient.connect is ignored, this will become an error", 247 | DeprecationWarning, 248 | ) 249 | if host.startswith("@"): 250 | host = "\0" + host[1:] 251 | if host.startswith("\0") or "/" in host: 252 | r, w = await asyncio.open_unix_connection(host) 253 | else: 254 | r, w = await asyncio.open_connection(host, port) 255 | self.__rfile, self.__wfile = r, w 256 | 257 | self.__command_queue = asyncio.Queue(maxsize=self.COMMAND_QUEUE_LENGTH) 258 | self.__idle_consumers = [] 259 | 260 | try: 261 | helloline = await asyncio.wait_for(self.__readline(), timeout=5) 262 | except asyncio.TimeoutError: 263 | self.disconnect() 264 | raise ConnectionError("No response from server while reading MPD hello") 265 | # FIXME should be reusable w/o reaching in 266 | SyncMPDClient._hello(cast(SyncMPDClient, self), helloline) 267 | 268 | self.__run_task = asyncio.Task(self.__run()) 269 | 270 | @property 271 | def connected(self) -> bool: 272 | return self.__run_task is not None 273 | 274 | def disconnect(self) -> None: 275 | if ( 276 | self.__run_task is not None 277 | ): # is None eg. when connection fails in .connect() 278 | self.__run_task.cancel() 279 | if self.__wfile is not None: 280 | self.__wfile.close() 281 | self.__rfile = self.__wfile = None 282 | self.__run_task = None 283 | self.__command_queue = None 284 | if self.__idle_consumers is not None: 285 | # copying the list as each raising callback will remove itself from __idle_consumers 286 | for subsystems, callback in list(self.__idle_consumers): 287 | callback(ConnectionError()) 288 | self.__idle_consumers = None 289 | 290 | def _get_idle_interests(self) -> Optional[Set[str]]: 291 | """Accumulate a set of interests from the current __idle_consumers. 292 | Returns the union of their subscribed subjects, [] if at least one of 293 | them is the empty catch-all set, or None if there are no interests at 294 | all.""" 295 | 296 | if not self.__idle_consumers: 297 | return None 298 | if any(len(s) == 0 for (s, c) in self.__idle_consumers): 299 | return set() 300 | return set.union(*(set(s) for (s, c) in self.__idle_consumers)) 301 | 302 | def _end_idle(self) -> None: 303 | """If the main task is currently idling, make it leave idle and process 304 | the next command (if one is present) or just restart idle""" 305 | 306 | if self.__in_idle: 307 | self.__write("noidle\n") 308 | self.__in_idle = False 309 | 310 | async def __run(self) -> None: 311 | # See CommandResult._feed_error documentation 312 | await asyncio.sleep(0) 313 | 314 | try: 315 | while True: 316 | try: 317 | if self.__command_queue is None: 318 | raise ConnectionError("Disconnected while waiting for command") 319 | result = await asyncio.wait_for( 320 | self.__command_queue.get(), 321 | timeout=self.IMMEDIATE_COMMAND_TIMEOUT, 322 | ) 323 | except asyncio.TimeoutError: 324 | # The cancellation of the __command_queue.get() that happens 325 | # in this case is intended, and is just what asyncio.Queue 326 | # suggests for "get with timeout". 327 | 328 | if ( 329 | self.__command_queue is not None 330 | and not self.__command_queue.empty() 331 | ): 332 | # A __command_queue.put() has happened after the 333 | # asyncio.wait_for() timeout but before execution of 334 | # this coroutine resumed. Looping around again will 335 | # fetch the new entry from the queue. 336 | continue 337 | 338 | if self.__idle_failed: 339 | # We could try for a more elaborate path where we now 340 | # await the command queue indefinitely, but as we're 341 | # already in an error case, this whole situation only 342 | # persists until the error is processed somewhere else, 343 | # so ticking once per idle timeout is OK to keep things 344 | # simple. 345 | continue 346 | 347 | subsystems = self._get_idle_interests() 348 | if subsystems is None: 349 | # The presumably most quiet subsystem -- in this case, 350 | # idle is only used to keep the connection alive. 351 | subsystems = set(["database"]) 352 | 353 | # Careful: There can't be any await points between the 354 | # except and here, or the sequence between the idle and the 355 | # command processor might be wrong. 356 | result = CommandResult("idle", subsystems, self._parse_list) 357 | result.add_done_callback(self.__idle_result) 358 | self.__in_idle = True 359 | self._write_command(result._command, result._args) 360 | 361 | # A new command was issued, so there's a chance that whatever 362 | # made idle fail is now fixed. 363 | self.__idle_failed = False 364 | 365 | try: 366 | await result._feed_from(self) 367 | except CommandError as e: 368 | result._feed_error(e) 369 | # This kind of error we can tolerate without breaking up 370 | # the connection; any other would fly out, be reported 371 | # through the result and terminate the connection 372 | 373 | except Exception as e: 374 | # Pass exception to any pending task to terminate them. Otherwise they will hang 375 | # indefinitely as we are about to disconnect. 376 | try: 377 | while ( 378 | self.__command_queue is not None 379 | and not self.__command_queue.empty() 380 | ): 381 | pending_result = self.__command_queue.get_nowait() 382 | pending_result._feed_error(e) 383 | except asyncio.QueueEmpty: 384 | # As per documentation, the queue raises this type of exception when get_nowait() 385 | # is called and the queue is empty. It actually rather block on the get_nowait() call 386 | # but let's leave the except just in case. 387 | pass 388 | 389 | # Prevent the destruction of the pending task in the shutdown 390 | # function -- it's just shutting down by itself. 391 | self.__run_task = None 392 | self.disconnect() 393 | 394 | if result is not None: 395 | # The last command has failed: Forward that result. 396 | # 397 | # (In idle, that's fine too -- everyone watching see a 398 | # nonspecific event). 399 | result._feed_error(e) 400 | return 401 | else: 402 | raise 403 | # Typically this is a bug in mpd.asyncio. 404 | 405 | def __idle_result(self, result: BaseCommandResult) -> None: 406 | try: 407 | idle_changes = result.result() 408 | except CommandError: 409 | # Don't retry until something changed 410 | self.__idle_failed = True 411 | 412 | # Not raising this any further: The callbacks are notified that 413 | # "something is up" (which is all their API gives), and whichever 414 | # command is issued to act on it will hopefully run into the same 415 | # condition. 416 | # 417 | # This does swallow the exact error cause. 418 | 419 | idle_changes = set() 420 | if self.__idle_consumers is not None: 421 | for subsystems, _ in self.__idle_consumers: 422 | idle_changes = idle_changes.union(subsystems) 423 | 424 | # make generator accessible multiple times 425 | idle_changes = list(idle_changes) 426 | 427 | if self.__idle_consumers is not None: 428 | for subsystems, callback in self.__idle_consumers: 429 | if not subsystems or any(s in subsystems for s in idle_changes): 430 | callback(idle_changes) 431 | 432 | # helper methods 433 | 434 | async def __readline(self) -> str: 435 | """Wrapper around .__rfile.readline that handles encoding""" 436 | if self.__rfile is None: 437 | raise ConnectionError("Can not read from a disconnected client") 438 | data = await self.__rfile.readline() 439 | try: 440 | return data.decode("utf8") 441 | except UnicodeDecodeError: 442 | self.disconnect() 443 | raise ProtocolError("Invalid UTF8 received") 444 | 445 | async def _read_chunk(self, length: int) -> bytes: 446 | if self.__rfile is None: 447 | raise ConnectionError("Can not read from a disconnected client") 448 | try: 449 | return await self.__rfile.readexactly(length) 450 | except asyncio.IncompleteReadError: 451 | raise ConnectionError("Connection lost while reading binary") 452 | 453 | def __write(self, text: str) -> None: 454 | """Wrapper around .__wfile.write that handles encoding.""" 455 | if self.__wfile is None: 456 | raise ConnectionError("Can not write to a disconnected client") 457 | self.__wfile.write(text.encode("utf8")) 458 | 459 | # copied and subtly modifiedstuff from base 460 | 461 | # This is just a wrapper for the below. 462 | def _write_line(self, text: str) -> None: 463 | self.__write(text + "\n") 464 | 465 | def _write_command(self, command: str, args: List[Any]) -> None: 466 | # FIXME This code should be shareable. 467 | SyncMPDClient._write_command(cast(SyncMPDClient, self), command, args) 468 | 469 | async def _read_line(self) -> Optional[str]: 470 | line = await self.__readline() 471 | if not line.endswith("\n"): 472 | raise ConnectionError("Connection lost while reading line") 473 | line = line.rstrip("\n") 474 | if line.startswith(ERROR_PREFIX): 475 | error = line[len(ERROR_PREFIX) :].strip() 476 | raise CommandError(error) 477 | if line == SUCCESS: 478 | return None 479 | return line 480 | 481 | async def _parse_objects_direct( # type: ignore 482 | self, 483 | lines: "asyncio.Queue[str]", 484 | delimiters: List[str] = [], 485 | lookup_delimiter: bool = False, 486 | ) -> AsyncIterator[Dict[str, str]]: 487 | obj: Dict[str, Any] = {} 488 | while True: 489 | line = await lines.get() 490 | if isinstance(line, BaseException): 491 | raise line 492 | if line is None: 493 | break 494 | key, value = self._parse_pair(line, separator=": ") 495 | key = key.lower() 496 | if lookup_delimiter and not delimiters: 497 | delimiters = [key] 498 | if obj: 499 | if key in delimiters: 500 | yield obj 501 | obj = {} 502 | elif key in obj: 503 | if not isinstance(obj[key], list): 504 | obj[key] = [obj[key], value] 505 | else: 506 | obj[key].append(value) 507 | continue 508 | obj[key] = value 509 | if obj: 510 | yield obj 511 | 512 | async def _execute_binary( 513 | self, command: str, args: Iterable[Any] 514 | ) -> Dict[str, Union[str, bytes]]: 515 | # Fun fact: By fetching data in lockstep, this is a bit less efficient 516 | # than it could be (which would be "after having received the first 517 | # chunk, guess that the other chunks are of equal size and request at 518 | # several multiples concurrently, ensuring the TCP connection can stay 519 | # full), but at the other hand it leaves the command queue empty so 520 | # that more time critical commands can be executed right away 521 | 522 | data = None 523 | args = list(args) 524 | assert len(args) == 1 525 | args.append(0) 526 | final_metadata = None 527 | if self.__command_queue is None: 528 | raise ConnectionError("Can not send command to disconnected client") 529 | while True: 530 | partial_result = BinaryCommandResult() 531 | await self.__command_queue.put(partial_result) 532 | self._end_idle() 533 | self._write_command(command, args) 534 | metadata = await partial_result 535 | chunk = metadata.pop("binary", None) 536 | 537 | if final_metadata is None: 538 | data = chunk 539 | final_metadata = metadata 540 | if not data: 541 | break 542 | try: 543 | size = int(final_metadata["size"]) 544 | except KeyError: 545 | size = len(chunk) 546 | except ValueError: 547 | raise CommandError("Size data unsuitable for binary transfer") 548 | else: 549 | if metadata != final_metadata: 550 | raise CommandError( 551 | "Metadata of binary data changed during transfer" 552 | ) 553 | if chunk is None: 554 | raise CommandError("Binary field vanished changed during transfer") 555 | data += chunk 556 | args[-1] = len(data) 557 | if len(data) > size: 558 | breakpoint() 559 | raise CommandListError("Binary data announced size exceeded") 560 | elif len(data) == size: 561 | break 562 | 563 | if data is not None: 564 | final_metadata["binary"] = data 565 | 566 | final_metadata.pop("size", None) 567 | 568 | return final_metadata 569 | 570 | # omits _read_chunk checking because the async version already 571 | # raises; otherwise it's just awaits sprinkled in 572 | async def _read_binary(self) -> Dict[str, Union[str, bytes]]: 573 | obj = {} 574 | 575 | while True: 576 | line = await self._read_line() 577 | if line is None: 578 | break 579 | 580 | value: Union[str, bytes] 581 | key, value = self._parse_pair(line, ": ") 582 | 583 | if key == "binary": 584 | chunk_size = int(value) 585 | value = await self._read_chunk(chunk_size) 586 | if self.__rfile is None: 587 | raise ConnectionError("Can not read from a disconnected client") 588 | 589 | if await self.__rfile.readexactly(1) != b"\n": 590 | # newline after binary content 591 | self.disconnect() 592 | raise ConnectionError("Connection lost while reading line") 593 | 594 | obj[key] = value 595 | return obj 596 | 597 | # command provider interface 598 | @classmethod 599 | def add_command(cls: Any, name: str, callback: CallableWithCommands) -> None: 600 | if callback.mpd_commands_binary: 601 | 602 | async def async_func(self: Any, *args: Any) -> BaseCommandResult: 603 | result = await self._execute_binary(name, args) 604 | 605 | # With binary, the callback is applied to the final result 606 | # rather than to the iterator over the lines (cf. 607 | # MPDClient._execute_binary) 608 | return callback(self, result) 609 | 610 | escaped_name = name.replace(" ", "_") 611 | async_func.__name__ = escaped_name 612 | setattr(cls, escaped_name, async_func) 613 | else: 614 | command_class = ( 615 | CommandResultIterable if callback.mpd_commands_direct else CommandResult 616 | ) 617 | if hasattr(cls, name): 618 | # Idle and noidle are explicitly implemented, skipping them. 619 | return 620 | 621 | def sync_func(self: Any, *args: Any) -> BaseCommandResult: 622 | result = command_class(name, args, partial(callback, self)) 623 | if self.__run_task is None: 624 | raise ConnectionError("Can not send command to disconnected client") 625 | 626 | try: 627 | self.__command_queue.put_nowait(result) 628 | except asyncio.QueueFull as e: 629 | e.args = ( 630 | "Command queue overflowing; this indicates the" 631 | " application sending commands in an uncontrolled" 632 | " fashion without awaiting them, and typically" 633 | " indicates a memory leak.", 634 | ) 635 | # While we *could* indicate to the queued result that it has 636 | # yet to send its request, that'd practically create a queue of 637 | # awaited items in the user application that's growing 638 | # unlimitedly, eliminating any chance of timely responses. 639 | # Furthermore, the author sees no practical use case that's not 640 | # violating MPD's guidance of "Do not manage a client-side copy 641 | # of MPD's database". If a use case *does* come up, any change 642 | # would need to maintain the property of providing backpressure 643 | # information. That would require an API change. 644 | raise 645 | 646 | self._end_idle() 647 | # Careful: There can't be any await points between the queue 648 | # appending and the write 649 | try: 650 | self._write_command(result._command, result._args) 651 | except BaseException as e: 652 | self.disconnect() 653 | result.set_exception(e) 654 | return result 655 | 656 | escaped_name = name.replace(" ", "_") 657 | sync_func.__name__ = escaped_name 658 | setattr(cls, escaped_name, sync_func) 659 | 660 | # commands that just work differently 661 | async def idle( 662 | self, subsystems: Union[List[str], Tuple[str]] = [] 663 | ) -> AsyncIterator[Union[List[str], Exception]]: 664 | if self.__idle_consumers is None: 665 | raise ConnectionError("Can not start idle on a disconnected client") 666 | 667 | interests_before = self._get_idle_interests() 668 | # A queue accepting either a list of things that changed in a single 669 | # idle cycle, or an exception to be raised 670 | changes: asyncio.Queue[Union[List[str], Exception]] = asyncio.Queue() 671 | try: 672 | entry = (subsystems, changes.put_nowait) 673 | self.__idle_consumers.append(entry) 674 | if self._get_idle_interests != interests_before: 675 | # Technically this does not enter idle *immediately* but rather 676 | # only after any commands after IMMEDIATE_COMMAND_TIMEOUT; 677 | # practically that should be a good thing. 678 | self._end_idle() 679 | while True: 680 | item = await changes.get() 681 | if isinstance(item, Exception): 682 | raise item 683 | yield item 684 | finally: 685 | if self.__idle_consumers is not None: 686 | self.__idle_consumers.remove(entry) 687 | 688 | def noidle(self) -> None: 689 | raise AttributeError("noidle is not supported / required in mpd.asyncio") 690 | -------------------------------------------------------------------------------- /doc/topics/commands.rst: -------------------------------------------------------------------------------- 1 | ======== 2 | Commands 3 | ======== 4 | .. note:: 5 | 6 | Each command have a *send_* and a *fetch_* variant, which allows to send a 7 | MPD command and then fetch the result later. See :ref:`getting-started` for 8 | examples and more information. 9 | 10 | Querying 11 | --------- 12 | 13 | 14 | .. function:: MPDClient.clearerror() 15 | 16 | 17 | Clears the current error message in status (this is also 18 | accomplished by any command that starts playback). 19 | 20 | 21 | .. function:: MPDClient.currentsong() 22 | 23 | 24 | Returns the song info of the current song (same song that is 25 | identified in status). 26 | 27 | 28 | .. function:: MPDClient.idle([subsystems]) 29 | 30 | 31 | (Introduced with MPD 0.14) Waits until there is a noteworthy 32 | change in one or more of MPD's subsystems. As soon as there is 33 | one, it lists all changed systems in a line in the format changed:: 34 | SUBSYSTEM, where SUBSYSTEM is one of the following:: 35 | 36 | While a client is waiting for idle results, the server disables 37 | timeouts, allowing a client to wait for events as long as mpd 38 | runs. The idle command can be canceled by sending the command 39 | noidle (no other commands are allowed). MPD will then leave idle 40 | mode and print results immediately; might be empty at this time. 41 | 42 | If the optional *SUBSYSTEMS* argument is used, MPD will only send 43 | notifications when something changed in one of the specified 44 | subsytems. 45 | 46 | 47 | * database: the song database has been modified after update. 48 | 49 | 50 | * update: a database update has started or finished. If the 51 | database was modified during the update, the database event is 52 | also emitted. 53 | 54 | 55 | * stored_playlist: a stored playlist has been modified, renamed, 56 | created or deleted 57 | 58 | 59 | * playlist: the current playlist has been modified 60 | 61 | 62 | * player: the player has been started, stopped or seeked 63 | 64 | 65 | * mixer: the volume has been changed 66 | 67 | 68 | * output: an audio output has been enabled or disabled 69 | 70 | 71 | * options: options like 72 | 73 | 74 | * partition: a partition was added, removed or changed 75 | 76 | 77 | * sticker: the sticker database has been modified. 78 | 79 | 80 | * subscription: a client has subscribed or unsubscribed to a 81 | channel 82 | 83 | 84 | * message: a message was received on a channel this client is 85 | subscribed to; this event is only emitted when the queue is 86 | empty 87 | 88 | 89 | .. function:: MPDClient.status() 90 | 91 | 92 | Returns the current status of the player and the volume level. 93 | 94 | 95 | * *partition*: the name of the current partition 96 | 97 | 98 | * *volume*: 0-100 99 | 100 | 101 | * *repeat*: 0 or 1 102 | 103 | 104 | * *random*: 0 or 1 105 | 106 | 107 | * *single*: (Introduced with MPD 0.15) 0 or 1 108 | 109 | 110 | * *consume*: 0 or 1 111 | 112 | 113 | * *playlist*: 31-bit unsigned integer, the playlist version number 114 | 115 | 116 | * *playlistlength*: integer, the length of the playlist 117 | 118 | 119 | * *state*: play, stop, or pause 120 | 121 | 122 | * *song*: playlist song number of the current song stopped on or 123 | playing 124 | 125 | 126 | * *songid*: playlist songid of the current song stopped on or 127 | playing 128 | 129 | 130 | * *nextsong*: playlist song number of the next song to be played 131 | 132 | 133 | * *nextsongid*: playlist songid of the next song to be played 134 | 135 | 136 | * *time*: total time elapsed (of current playing/paused song) 137 | 138 | 139 | * *elapsed*: (Introduced with MPD 0.16) Total time elapsed within 140 | the current song, but with higher resolution. 141 | 142 | 143 | * *duration*: (Introduced with MPD 0.20) Duration of the current 144 | song in seconds. 145 | 146 | 147 | * *bitrate*: instantaneous bitrate in kbps 148 | 149 | 150 | * *xfade*: crossfade in seconds 151 | 152 | 153 | * *mixrampdb*: mixramp threshold in dB 154 | 155 | 156 | * *mixrampdelay*: mixrampdelay in seconds 157 | 158 | 159 | * *audio*: sampleRate:bits:channels 160 | 161 | 162 | * *updating_db*: job id 163 | 164 | 165 | * *error*: if there is an error, returns message here 166 | 167 | 168 | .. function:: MPDClient.stats() 169 | 170 | 171 | Displays statistics. 172 | 173 | 174 | * *artists*: number of artists 175 | 176 | 177 | * *albums*: number of albums 178 | 179 | 180 | * *songs*: number of songs 181 | 182 | 183 | * *uptime*: daemon uptime in seconds 184 | 185 | 186 | * *db_playtime*: sum of all song times in the db 187 | 188 | 189 | * *db_update*: last db update in UNIX time 190 | 191 | 192 | * *playtime*: time length of music played 193 | 194 | 195 | Playback options 196 | ---------------- 197 | 198 | 199 | .. function:: MPDClient.consume(state) 200 | 201 | 202 | Sets consume state to *STATE*, *STATE* should be 0 or 1. When 203 | consume is activated, each song played is removed from playlist. 204 | 205 | 206 | .. function:: MPDClient.crossfade(seconds) 207 | 208 | 209 | Sets crossfading between songs. 210 | 211 | 212 | .. function:: MPDClient.mixrampdb(decibels) 213 | 214 | 215 | Sets the threshold at which songs will be overlapped. Like 216 | crossfading but doesn't fade the track volume, just overlaps. The 217 | songs need to have MixRamp tags added by an external tool. 0dB is 218 | the normalized maximum volume so use negative values, I prefer 219 | -17dB. In the absence of mixramp tags crossfading will be used. 220 | See http://sourceforge.net/projects/mixramp 221 | 222 | 223 | .. function:: MPDClient.mixrampdelay(seconds) 224 | 225 | 226 | Additional time subtracted from the overlap calculated by 227 | mixrampdb. A value of "nan" disables MixRamp overlapping and falls 228 | back to crossfading. 229 | 230 | 231 | .. function:: MPDClient.random(state) 232 | 233 | 234 | Sets random state to *STATE*, *STATE* should be 0 or 1. 235 | 236 | 237 | .. function:: MPDClient.repeat(state) 238 | 239 | 240 | Sets repeat state to *STATE*, *STATE* should be 0 or 1. 241 | 242 | 243 | .. function:: MPDClient.setvol(vol) 244 | 245 | 246 | Sets volume to *VOL*, the range of volume is 0-100. 247 | 248 | .. function:: MPDClient.volume(vol_change) 249 | 250 | Changes volume by amount *VOL_CHANGE*, the range is -100 to +100. 251 | A negative value decreases volume, positive value increases volume. 252 | 253 | 254 | .. function:: MPDClient.single(state) 255 | 256 | 257 | Sets single state to *STATE*, *STATE* should be 0 or 1. When 258 | single is activated, playback is stopped after current song, or 259 | song is repeated if the 'repeat' mode is enabled. 260 | 261 | 262 | .. function:: MPDClient.replay_gain_mode(mode) 263 | 264 | 265 | Sets the replay gain mode. One of *off*, *track*, *album*, *auto* 266 | (added in MPD 0.16) . 267 | 268 | Changing the mode during playback may take several seconds, 269 | because the new settings does not affect the buffered data. 270 | 271 | This command triggers the options idle event. 272 | 273 | 274 | .. function:: MPDClient.replay_gain_status() 275 | 276 | 277 | Returns replay gain options. Currently, only the variable 278 | *replay_gain_mode* is returned. 279 | 280 | 281 | Controlling playback 282 | -------------------- 283 | 284 | 285 | .. function:: MPDClient.next() 286 | 287 | 288 | Plays next song in the playlist. 289 | 290 | 291 | .. function:: MPDClient.pause(pause) 292 | 293 | 294 | Toggles pause/resumes playing, *PAUSE* is 0 or 1. 295 | 296 | 297 | .. function:: MPDClient.play(songpos) 298 | 299 | 300 | Begins playing the playlist at song number *SONGPOS*. 301 | 302 | 303 | .. function:: MPDClient.playid(songid) 304 | 305 | 306 | Begins playing the playlist at song *SONGID*. 307 | 308 | 309 | .. function:: MPDClient.previous() 310 | 311 | 312 | Plays previous song in the playlist. 313 | 314 | 315 | .. function:: MPDClient.seek(songpos, time) 316 | 317 | 318 | Seeks to the position *TIME* (in seconds; fractions allowed) of 319 | entry *SONGPOS* in the playlist. 320 | 321 | 322 | .. function:: MPDClient.seekid(songid, time) 323 | 324 | 325 | Seeks to the position *TIME* (in seconds; fractions allowed) of 326 | song *SONGID*. 327 | 328 | 329 | .. function:: MPDClient.seekcur(time) 330 | 331 | 332 | Seeks to the position *TIME* (in seconds; fractions allowed) 333 | within the current song. If prefixed by '+' or '-', then the time 334 | is relative to the current playing position. 335 | 336 | 337 | .. function:: MPDClient.stop() 338 | 339 | 340 | Stops playing. 341 | 342 | 343 | The current playlist 344 | -------------------- 345 | 346 | 347 | .. function:: MPDClient.add(uri) 348 | 349 | 350 | Adds the file *URI* to the playlist (directories add recursively). 351 | *URI* can also be a single file. 352 | 353 | 354 | .. function:: MPDClient.addid(uri, position) 355 | 356 | 357 | Adds a song to the playlist (non-recursive) and returns the song 358 | id. 359 | 360 | *URI* is always a single file or URL. For example:: 361 | 362 | 363 | 364 | addid "foo.mp3" 365 | Id: 999 366 | OK 367 | 368 | .. function:: MPDClient.clear() 369 | 370 | 371 | Clears the current playlist. 372 | 373 | 374 | .. function:: MPDClient.delete(index_or_range) 375 | 376 | 377 | Deletes a song, or a range of songs, from the playlist based on the song's 378 | position in the playlist. 379 | 380 | A range can be specified by passing a tuple. 381 | 382 | 383 | .. function:: MPDClient.deleteid(songid) 384 | 385 | 386 | Deletes the song *SONGID* from the playlist 387 | 388 | 389 | .. function:: MPDClient.move(to) 390 | 391 | 392 | Moves the song at *FROM* or range of songs at *START:END* to *TO* 393 | in the playlist. (Ranges are supported since MPD 0.15) 394 | 395 | 396 | .. function:: MPDClient.moveid(from, to) 397 | 398 | 399 | Moves the song with *FROM* (songid) to *TO* (playlist index) in 400 | the playlist. If *TO* is negative, it is relative to the current 401 | song in the playlist (if there is one). 402 | 403 | 404 | .. function:: MPDClient.playlist() 405 | 406 | 407 | Displays the current playlist. 408 | 409 | 410 | .. function:: MPDClient.playlistfind(tag, needle) 411 | 412 | 413 | Finds songs in the current playlist with strict matching. 414 | 415 | 416 | .. function:: MPDClient.playlistid(songid) 417 | 418 | 419 | Returns a list of songs in the playlist. *SONGID* is optional and 420 | specifies a single song to display info for. 421 | 422 | 423 | .. function:: MPDClient.playlistinfo() 424 | 425 | 426 | Returns a list of all songs in the playlist, or if the optional 427 | argument is given, displays information only for the song 428 | *SONGPOS* or the range of songs *START:END* 429 | 430 | 431 | .. function:: MPDClient.playlistsearch(tag, needle) 432 | 433 | 434 | Returns case-insensitive search results for partial matches in the 435 | current playlist. 436 | 437 | 438 | .. function:: MPDClient.plchanges(version, start:end) 439 | 440 | 441 | Returns changed songs currently in the playlist since *VERSION*. 442 | Start and end positions may be given to limit the output to 443 | changes in the given range. 444 | 445 | To detect songs that were deleted at the end of the playlist, use 446 | playlistlength returned by status command. 447 | 448 | 449 | .. function:: MPDClient.plchangesposid(version, start:end) 450 | 451 | 452 | Returns changed songs currently in the playlist since *VERSION*. 453 | This function only returns the position and the id of the changed 454 | song, not the complete metadata. This is more bandwidth efficient. 455 | 456 | To detect songs that were deleted at the end of the playlist, use 457 | playlistlength returned by status command. 458 | 459 | 460 | .. function:: MPDClient.prio(priority, start:end) 461 | 462 | 463 | Set the priority of the specified songs. A higher priority means 464 | that it will be played first when "random" mode is enabled. 465 | 466 | A priority is an integer between 0 and 255. The default priority 467 | of new songs is 0. 468 | 469 | 470 | .. function:: MPDClient.prioid(priority, id) 471 | 472 | 473 | Same as prio, but address the songs with their id. 474 | 475 | 476 | .. function:: MPDClient.rangeid(id, start:end) 477 | 478 | 479 | (Since MPD 0.19) Specifies the portion of the song that shall be 480 | played. *START* and *END* are offsets in seconds (fractional 481 | seconds allowed); both are optional. Omitting both (i.e. sending 482 | just ":") means "remove the range, play everything". A song that 483 | is currently playing cannot be manipulated this way. 484 | 485 | 486 | .. function:: MPDClient.shuffle(start:end) 487 | 488 | 489 | Shuffles the current playlist. *START:END* is optional and 490 | specifies a range of songs. 491 | 492 | 493 | .. function:: MPDClient.swap(song1, song2) 494 | 495 | 496 | Swaps the positions of *SONG1* and *SONG2*. 497 | 498 | 499 | .. function:: MPDClient.swapid(song1, song2) 500 | 501 | 502 | Swaps the positions of *SONG1* and *SONG2* (both song ids). 503 | 504 | 505 | .. function:: MPDClient.addtagid(songid, tag, value) 506 | 507 | 508 | Adds a tag to the specified song. Editing song tags is only 509 | possible for remote songs. This change is volatile: it may be 510 | overwritten by tags received from the server, and the data is gone 511 | when the song gets removed from the queue. 512 | 513 | 514 | .. function:: MPDClient.cleartagid(songid[, tag]) 515 | 516 | 517 | Removes tags from the specified song. If *TAG* is not specified, 518 | then all tag values will be removed. Editing song tags is only 519 | possible for remote songs. 520 | 521 | 522 | Stored playlists 523 | ---------------- 524 | Playlists are stored inside the configured playlist directory. 525 | They are addressed with their file name (without the directory and 526 | without the 527 | 528 | Some of the commands described in this section can be used to run 529 | playlist plugins instead of the hard-coded simple 530 | 531 | .. function:: MPDClient.listplaylist(name) 532 | 533 | 534 | Returns a list of the songs in the playlist. Playlist plugins are supported. 535 | 536 | 537 | .. function:: MPDClient.listplaylistinfo(name) 538 | 539 | 540 | Returns a list of the songs with metadata in the playlist. Playlist plugins 541 | are supported. 542 | 543 | 544 | .. function:: MPDClient.listplaylists() 545 | 546 | 547 | Returns a list of the playlist in the playlist directory. 548 | 549 | After each playlist name the server sends its last modification 550 | time as attribute "Last-Modified" in ISO 8601 format. To avoid 551 | problems due to clock differences between clients and the server, 552 | clients should not compare this value with their local clock. 553 | 554 | 555 | .. function:: MPDClient.load(name[, start:end]) 556 | 557 | 558 | Loads the playlist into the current queue. Playlist plugins are 559 | supported. A range may be specified to load only a part of the 560 | playlist. 561 | 562 | 563 | .. function:: MPDClient.playlistadd(name, uri) 564 | 565 | 566 | Adds *URI* to the playlist 567 | 568 | 569 | 570 | 571 | .. function:: MPDClient.playlistclear(name) 572 | 573 | 574 | Clears the playlist 575 | 576 | 577 | .. function:: MPDClient.playlistdelete(name, songpos) 578 | 579 | 580 | Deletes *SONGPOS* from the playlist 581 | 582 | 583 | .. function:: MPDClient.playlistmove(name, from, to) 584 | 585 | 586 | Moves the song at position *FROM* in the playlist 587 | 588 | 589 | .. function:: MPDClient.rename(name, new_name) 590 | 591 | 592 | Renames the playlist 593 | 594 | 595 | .. function:: MPDClient.rm(name) 596 | 597 | 598 | Removes the playlist 599 | 600 | 601 | .. function:: MPDClient.save(name) 602 | 603 | 604 | Saves the current playlist to 605 | 606 | 607 | The music database 608 | ------------------ 609 | 610 | .. function:: MPDClient.albumart(uri) 611 | 612 | 613 | Returns the album art image for the given song. 614 | 615 | *URI* is always a single file or URL. 616 | 617 | The returned value is a dictionary containing the album art image in its 618 | ``'binary'`` entry. If the given URI is invalid, or the song does not have 619 | an album cover art file that MPD recognizes, a CommandError is thrown. 620 | .. function:: MPDClient.count(tag, needle[, ..., "group", grouptype]) 621 | 622 | 623 | Returns the counts of the number of songs and their total playtime in 624 | the db matching *TAG* exactly. 625 | 626 | The *group* keyword may be used to group the results by a tag. The 627 | following prints per-artist counts:: 628 | 629 | 630 | count group artist 631 | .. function:: MPDClient.find(type, what[, ..., startend]) 632 | 633 | 634 | Returns songs in the db that are exactly *WHAT*. *TYPE* can be any 635 | tag supported by MPD, or one of the special parameters:: 636 | 637 | *WHAT* is what to find. 638 | 639 | *window* can be used to query only a portion of the real response. 640 | The parameter is two zero-based record numbers; a start number and 641 | an end number. 642 | 643 | 644 | * *any* checks all tag values 645 | 646 | 647 | * *file* checks the full path (relative to the music directory) 648 | 649 | 650 | * *base* restricts the search to songs in the given directory 651 | (also relative to the music directory) 652 | 653 | 654 | * *modified-since* compares the file's time stamp with the given 655 | value (ISO 8601 or UNIX time stamp) 656 | 657 | 658 | .. function:: MPDClient.findadd(type, what[, ...]) 659 | 660 | 661 | Returns songs in the db that are exactly *WHAT* and adds them to 662 | current playlist. Parameters have the same meaning as for find. 663 | 664 | 665 | .. function:: MPDClient.list(type[, filtertype, filterwhat, ..., "group", grouptype, ...]) 666 | 667 | 668 | Returns a list of unique tag values of the specified type. 669 | *TYPE* can be any tag supported by MPD or *file*. 670 | 671 | Additional arguments may specify a filter like the one in the find 672 | command. 673 | 674 | The *group* keyword may be used (repeatedly) to group the results 675 | by one or more tags. The following example lists all album names, 676 | grouped by their respective (album) artist:: 677 | 678 | 679 | list album group albumartist 680 | .. function:: MPDClient.listall(uri) 681 | 682 | 683 | Returns a lists of all songs and directories in *URI*. 684 | 685 | Do not use this command. Do not manage a client-side copy of MPD's 686 | database. That is fragile and adds huge overhead. It will break 687 | with large databases. Instead, query MPD whenever you need 688 | something. 689 | 690 | 691 | .. function:: MPDClient.listallinfo(uri) 692 | 693 | Returns a lists of all songs and directories with their metadata 694 | info in *URI*. 695 | 696 | Same as listall, except it also returns metadata info in the same 697 | format as lsinfo. 698 | 699 | Do not use this command. Do not manage a client-side copy of MPD's 700 | database. That is fragile and adds huge overhead. It will break 701 | with large databases. Instead, query MPD whenever you need 702 | something. 703 | 704 | 705 | .. function:: MPDClient.listfiles(uri) 706 | 707 | 708 | Returns a list of the contents of the directory *URI*, including files 709 | are not recognized by MPD. *URI* can be a path relative to the music 710 | directory or an URI understood by one of the storage plugins. The 711 | response contains at least one line for each directory entry with 712 | the prefix "file: " or "directory: ", and may be followed by file 713 | attributes such as "Last-Modified" and "size". 714 | 715 | For example, "smb://SERVER" returns a list of all shares on the 716 | given SMB/CIFS server; "nfs://servername/path" obtains a directory 717 | listing from the NFS server. 718 | 719 | 720 | .. function:: MPDClient.lsinfo(uri) 721 | 722 | 723 | Returns a list of the contents of the directory *URI*. 724 | 725 | When listing the root directory, this currently returns the list 726 | of stored playlists. This behavior is deprecated; use 727 | "listplaylists" instead. 728 | 729 | This command may be used to list metadata of remote files (e.g. 730 | URI beginning with "http://" or "smb://"). 731 | 732 | Clients that are connected via UNIX domain socket may use this 733 | command to read the tags of an arbitrary local file (URI is an 734 | absolute path). 735 | 736 | 737 | .. function:: MPDClient.readcomments(uri) 738 | 739 | 740 | Returns "comments" (i.e. key-value pairs) from the file specified by 741 | "URI". This "URI" can be a path relative to the music directory or 742 | an absolute path. 743 | 744 | This command may be used to list metadata of remote files (e.g. 745 | URI beginning with "http://" or "smb://"). 746 | 747 | The response consists of lines in the form "KEY: VALUE". Comments 748 | with suspicious characters (e.g. newlines) are ignored silently. 749 | 750 | The meaning of these depends on the codec, and not all decoder 751 | plugins support it. For example, on Ogg files, this lists the 752 | Vorbis comments. 753 | 754 | 755 | .. function:: MPDClient.readpicture(uri) 756 | 757 | 758 | Returns the embedded cover image for the given song. 759 | 760 | *URI* is always a single file or URL. 761 | 762 | The returned value is a dictionary containing the embedded cover image in its 763 | ``'binary'`` entry, and potentially the picture's MIME type in its ``'type'`` entry. 764 | If the given URI is invalid, a CommandError is thrown. If the given song URI exists, 765 | but the song does not have an embedded cover image that MPD recognizes, an empty 766 | dictionary is returned. 767 | 768 | 769 | .. function:: MPDClient.search(type, what[, ..., startend]) 770 | 771 | 772 | Returns results of a search for any song that contains *WHAT*. 773 | Parameters have the same meaning as for find, except that search 774 | is not case sensitive. 775 | 776 | 777 | .. function:: MPDClient.searchadd(type, what[, ...]) 778 | 779 | 780 | Searches for any song that contains *WHAT* in tag *TYPE* and adds 781 | them to current playlist. 782 | 783 | Parameters have the same meaning as for find, except that search 784 | is not case sensitive. 785 | 786 | 787 | .. function:: MPDClient.searchaddpl(name, type, what[, ...]) 788 | 789 | 790 | Searches for any song that contains *WHAT* in tag *TYPE* and adds 791 | them to the playlist named *NAME*. 792 | 793 | If a playlist by that name doesn't exist it is created. 794 | 795 | Parameters have the same meaning as for find, except that search 796 | is not case sensitive. 797 | 798 | 799 | .. function:: MPDClient.update([uri]) 800 | 801 | 802 | Updates the music database: find new files, remove deleted files, 803 | update modified files. 804 | 805 | *URI* is a particular directory or song/file to update. If you do 806 | not specify it, everything is updated. 807 | 808 | Prints "updating_db: JOBID" where *JOBID* is a positive number 809 | identifying the update job. You can read the current job id in the 810 | status response. 811 | 812 | 813 | .. function:: MPDClient.rescan([uri]) 814 | 815 | 816 | Same as update, but also rescans unmodified files. 817 | 818 | 819 | Mounts and neighbors 820 | -------------------- 821 | A "storage" provides access to files in a directory tree. The most 822 | basic storage plugin is the "local" storage plugin which accesses 823 | the local file system, and there are plugins to access NFS and SMB 824 | servers. 825 | 826 | Multiple storages can be "mounted" together, similar to the mount 827 | command on many operating systems, but without cooperation from 828 | the kernel. No superuser privileges are necessary, because this 829 | mapping exists only inside the MPD process 830 | 831 | .. function:: MPDClient.mount(path, uri) 832 | 833 | 834 | Mount the specified remote storage URI at the given path. Example:: 835 | 836 | 837 | mount foo nfs://192.168.1.4/export/mp3 838 | .. function:: MPDClient.unmount(path) 839 | 840 | 841 | Unmounts the specified path. Example:: 842 | 843 | 844 | unmount foo 845 | .. function:: MPDClient.listmounts() 846 | 847 | 848 | Returns a list of all mounts. By default, this contains just the 849 | configured *music_directory*. Example:: 850 | 851 | 852 | listmounts 853 | mount: 854 | storage: /home/foo/music 855 | mount: foo 856 | storage: nfs://192.168.1.4/export/mp3 857 | OK 858 | 859 | .. function:: MPDClient.listneighbors() 860 | 861 | 862 | Returns a list of "neighbors" (e.g. accessible file servers on the 863 | local net). Items on that list may be used with the mount command. 864 | Example:: 865 | 866 | 867 | listneighbors 868 | neighbor: smb://FOO 869 | name: FOO (Samba 4.1.11-Debian) 870 | OK 871 | 872 | Stickers 873 | -------- 874 | "Stickers" are pieces of information attached to existing MPD 875 | objects (e.g. song files, directories, albums). Clients can create 876 | arbitrary name/value pairs. MPD itself does not assume any special 877 | meaning in them. 878 | 879 | The goal is to allow clients to share additional (possibly 880 | dynamic) information about songs, which is neither stored on the 881 | client (not available to other clients), nor stored in the song 882 | files (MPD has no write access). 883 | 884 | Client developers should create a standard for common sticker 885 | names, to ensure interoperability. 886 | 887 | Objects which may have stickers are addressed by their object type 888 | ("song" for song objects) and their URI (the path within the 889 | database for songs). 890 | 891 | .. function:: MPDClient.sticker_get(type, uri, name) 892 | 893 | 894 | Reads and returns a sticker value for the specified object. 895 | 896 | 897 | .. function:: MPDClient.sticker_set(type, uri, name, value) 898 | 899 | 900 | Adds a sticker value to the specified object. If a sticker item 901 | with that name already exists, it is replaced. 902 | 903 | 904 | .. function:: MPDClient.sticker_delete(type, uri[, name]) 905 | 906 | 907 | Deletes a sticker value from the specified object. If you do not 908 | specify a sticker name, all sticker values are deleted. 909 | 910 | 911 | .. function:: MPDClient.sticker_list(type, uri) 912 | 913 | 914 | Lists the stickers for the specified object. 915 | 916 | 917 | .. function:: MPDClient.sticker_find(type, uri, name) 918 | 919 | 920 | Searches the sticker database for stickers with the specified 921 | name, below the specified directory (URI). For each matching song, 922 | it prints the URI and that one sticker's value. 923 | 924 | 925 | .. function:: MPDClient.sticker_find(type, uri, name, "=", value) 926 | 927 | 928 | Returns the results of a search for stickers with the given value. 929 | 930 | Other supported operators are: "<", ">" 931 | 932 | 933 | Connection settings 934 | ------------------- 935 | 936 | 937 | .. function:: MPDClient.close() 938 | 939 | 940 | Closes the connection to MPD. MPD will try to send the remaining 941 | output buffer before it actually closes the connection, but that 942 | cannot be guaranteed. This command will not generate a response. 943 | 944 | 945 | .. function:: MPDClient.kill() 946 | 947 | 948 | Kills MPD. 949 | 950 | 951 | .. function:: MPDClient.password(password) 952 | 953 | 954 | This is used for authentication with the server. *PASSWORD* is 955 | simply the plaintext password. 956 | 957 | 958 | .. function:: MPDClient.ping() 959 | 960 | 961 | Does nothing but return "OK". 962 | 963 | 964 | Partition commands 965 | ------------------ 966 | 967 | These commands allow a client to inspect and manage 968 | "partitions". A partition is one frontend of a multi-player 969 | MPD process: it has separate queue, player and outputs. A 970 | client is assigned to one partition at a time. 971 | 972 | 973 | .. function:: MPDClient.partition(name) 974 | Switch the client to a different partition. 975 | 976 | 977 | .. function:: MPDClient.listpartitions() 978 | Return a list of partitions. 979 | 980 | 981 | .. function:: MPDClient.newpartition(name) 982 | Create a new partition. 983 | 984 | 985 | .. function:: MPDClient.delpartition(name) 986 | Delete a partition. The partition must be empty (no connected 987 | clients and no outputs). 988 | 989 | 990 | .. function:: MPDClient.moveoutput(output_name) 991 | Move an output to the current partition. 992 | 993 | 994 | Audio output devices 995 | -------------------- 996 | 997 | 998 | .. function:: MPDClient.disableoutput(id) 999 | 1000 | 1001 | Turns an output off. 1002 | 1003 | 1004 | .. function:: MPDClient.enableoutput(id) 1005 | 1006 | 1007 | Turns an output on. 1008 | 1009 | 1010 | .. function:: MPDClient.toggleoutput(id) 1011 | 1012 | 1013 | Turns an output on or off, depending on the current state. 1014 | 1015 | 1016 | .. function:: MPDClient.outputs() 1017 | 1018 | 1019 | Returns information about all outputs:: 1020 | 1021 | 1022 | 1023 | outputid: 0 1024 | outputname: My ALSA Device 1025 | outputenabled: 0 1026 | OK 1027 | 1028 | * *outputid*: ID of the output. May change between executions 1029 | 1030 | 1031 | * *outputname*: Name of the output. It can be any. 1032 | 1033 | 1034 | * *outputenabled*: Status of the output. 0 if disabled, 1 if 1035 | enabled. 1036 | 1037 | 1038 | Reflection 1039 | ---------- 1040 | 1041 | 1042 | .. function:: MPDClient.config() 1043 | 1044 | 1045 | Returns a dump of all configuration values that may be interesting 1046 | for the client. This command is only permitted to "local" clients 1047 | (connected via UNIX domain socket). 1048 | 1049 | The following response attributes are available:: 1050 | 1051 | 1052 | .. function:: MPDClient.commands() 1053 | 1054 | 1055 | Returns which commands the current user has access to. 1056 | 1057 | 1058 | .. function:: MPDClient.notcommands() 1059 | 1060 | 1061 | Returns which commands the current user does not have access to. 1062 | 1063 | 1064 | .. function:: MPDClient.tagtypes() 1065 | 1066 | 1067 | Returns a list of available song metadata. 1068 | 1069 | 1070 | .. function:: MPDClient.urlhandlers() 1071 | 1072 | 1073 | Returns a list of available URL handlers. 1074 | 1075 | 1076 | .. function:: MPDClient.decoders() 1077 | 1078 | 1079 | Returns a list of decoder plugins, followed by their supported 1080 | suffixes and MIME types. Example response:: 1081 | 1082 | 1083 | plugin: mad 1084 | suffix: mp3 1085 | suffix: mp2 1086 | mime_type: audio/mpeg 1087 | plugin: mpcdec 1088 | suffix: mpc 1089 | Client to client 1090 | ---------------- 1091 | Clients can communicate with each others over "channels". A 1092 | channel is created by a client subscribing to it. More than one 1093 | client can be subscribed to a channel at a time; all of them will 1094 | receive the messages which get sent to it. 1095 | 1096 | Each time a client subscribes or unsubscribes, the global idle 1097 | event *subscription* is generated. In conjunction with the 1098 | channels command, this may be used to auto-detect clients 1099 | providing additional services. 1100 | 1101 | New messages are indicated by the *message* idle event. 1102 | 1103 | .. function:: MPDClient.subscribe(name) 1104 | 1105 | 1106 | Subscribe to a channel. The channel is created if it does not 1107 | exist already. The name may consist of alphanumeric ASCII 1108 | characters plus underscore, dash, dot and colon. 1109 | 1110 | 1111 | .. function:: MPDClient.unsubscribe(name) 1112 | 1113 | 1114 | Unsubscribe from a channel. 1115 | 1116 | 1117 | .. function:: MPDClient.channels() 1118 | 1119 | 1120 | Obtains and returns a list of all channels. The response is a list of 1121 | "channel:" lines. 1122 | 1123 | 1124 | .. function:: MPDClient.readmessages() 1125 | 1126 | 1127 | Reads messages for this client. The response is a list of 1128 | "channel:" and "message:" lines. 1129 | 1130 | 1131 | .. function:: MPDClient.sendmessage(channel, text) 1132 | 1133 | 1134 | Send a message to the specified channel. 1135 | 1136 | 1137 | -------------------------------------------------------------------------------- /mpd/base.py: -------------------------------------------------------------------------------- 1 | # python-mpd2: Python MPD client library 2 | # 3 | # Copyright (C) 2008-2010 J. Alexander Treuman 4 | # Copyright (C) 2012 J. Thalheim 5 | # Copyright (C) 2016 Robert Niederreiter 6 | # 7 | # python-mpd2 is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU Lesser General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # python-mpd2 is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU Lesser General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU Lesser General Public License 18 | # along with python-mpd2. If not, see . 19 | 20 | import logging 21 | import re 22 | import socket 23 | import sys 24 | import warnings 25 | from enum import Enum 26 | from logging import NullHandler 27 | from typing import ( 28 | IO, 29 | Any, 30 | Callable, 31 | Dict, 32 | Iterator, 33 | List, 34 | Optional, 35 | Tuple, 36 | Iterable, 37 | Type, 38 | Union, 39 | ) 40 | 41 | VERSION = (3, 1, 2) 42 | HELLO_PREFIX = "OK MPD " 43 | ERROR_PREFIX = "ACK " 44 | ERROR_PATTERN = re.compile( 45 | r"\[(?P\d+)@(?P\d+)\]\s+{(?P\w+)}\s+(?P.*)" 46 | ) 47 | SUCCESS = "OK" 48 | NEXT = "list_OK" 49 | 50 | logger = logging.getLogger(__name__) 51 | logger.addHandler(NullHandler()) 52 | 53 | 54 | def escape(text: str) -> str: 55 | return text.replace("\\", "\\\\").replace('"', '\\"') 56 | 57 | 58 | # MPD Protocol errors as found in CommandError exceptions 59 | # https://github.com/MusicPlayerDaemon/MPD/blob/master/src/protocol/Ack.hxx 60 | class FailureResponseCode(Enum): 61 | NOT_LIST = 1 62 | ARG = 2 63 | PASSWORD = 3 64 | PERMISSION = 4 65 | UNKNOWN = 5 66 | 67 | NO_EXIST = 50 68 | PLAYLIST_MAX = 51 69 | SYSTEM = 52 70 | PLAYLIST_LOAD = 53 71 | UPDATE_ALREADY = 54 72 | PLAYER_SYNC = 55 73 | EXIST = 56 74 | 75 | 76 | class MPDError(Exception): 77 | pass 78 | 79 | 80 | class ConnectionError(MPDError): 81 | pass 82 | 83 | 84 | class ProtocolError(MPDError): 85 | pass 86 | 87 | 88 | class CommandError(MPDError): 89 | def __init__(self, error: str) -> None: 90 | self.errno = None 91 | self.offset = None 92 | self.command = None 93 | self.msg = None 94 | 95 | match = ERROR_PATTERN.match(error) 96 | if match: 97 | self.errno = FailureResponseCode(int(match.group("errno"))) 98 | self.offset = int(match.group("offset")) 99 | self.command = match.group("command") 100 | self.msg = match.group("msg") 101 | 102 | 103 | class CommandListError(MPDError): 104 | pass 105 | 106 | 107 | class PendingCommandError(MPDError): 108 | pass 109 | 110 | 111 | class IteratingError(MPDError): 112 | pass 113 | 114 | 115 | class CallableWithCommands: 116 | mpd_commands: Tuple[str, ...] = () 117 | mpd_commands_direct: bool = False 118 | mpd_commands_binary: bool = False 119 | 120 | def __call__(self, *args: Any) -> Any: 121 | pass 122 | 123 | 124 | class mpd_commands: 125 | """Decorator for registering MPD commands with it's corresponding result 126 | callback. 127 | """ 128 | 129 | def __init__(self, *commands: str, **kwargs: bool) -> None: 130 | self.commands = commands 131 | self.is_direct = kwargs.pop("is_direct", False) 132 | self.is_binary = kwargs.pop("is_binary", False) 133 | if kwargs: 134 | raise AttributeError( 135 | "mpd_commands() got unexpected keyword arguments %s" % ",".join(kwargs) 136 | ) 137 | 138 | def __call__(self, ob: Any) -> CallableWithCommands: 139 | ob.mpd_commands = self.commands 140 | ob.mpd_commands_direct = self.is_direct 141 | ob.mpd_commands_binary = self.is_binary 142 | return ob 143 | 144 | 145 | class Noop(object): 146 | """An instance of this class represents a MPD command callback which 147 | does nothing. 148 | """ 149 | 150 | mpd_commands = None 151 | 152 | 153 | class MPDClientBase: 154 | """Abstract MPD client. 155 | 156 | This class defines a general client contract, provides MPD protocol parsers 157 | and defines all available MPD commands and it's corresponding result 158 | parsing callbacks. There might be the need of overriding some callbacks on 159 | subclasses. 160 | """ 161 | 162 | def __init__(self, use_unicode: Optional[bool] = None) -> None: 163 | self.iterate = False 164 | if use_unicode is not None: 165 | warnings.warn( 166 | "use_unicode parameter to ``MPDClientBase`` constructor is deprecated", 167 | DeprecationWarning, 168 | stacklevel=2, 169 | ) 170 | self._reset() 171 | 172 | @property 173 | def use_unicode(self) -> bool: 174 | warnings.warn( 175 | "``use_unicode`` is deprecated: python-mpd 2.x always uses Unicode", 176 | DeprecationWarning, 177 | stacklevel=2, 178 | ) 179 | return True 180 | 181 | @classmethod 182 | def add_command(cls, name: str, callback: Any) -> None: 183 | raise NotImplementedError( 184 | "Abstract ``MPDClientBase`` does not implement ``add_command``" 185 | ) 186 | 187 | def noidle(self) -> None: 188 | raise NotImplementedError( 189 | "Abstract ``MPDClientBase`` does not implement ``noidle``" 190 | ) 191 | 192 | def command_list_ok_begin(self) -> None: 193 | raise NotImplementedError( 194 | "Abstract ``MPDClientBase`` does not implement ``command_list_ok_begin``" 195 | ) 196 | 197 | def command_list_end(self) -> None: 198 | raise NotImplementedError( 199 | "Abstract ``MPDClientBase`` does not implement ``command_list_end``" 200 | ) 201 | 202 | def _reset(self) -> None: 203 | self.mpd_version: Optional[str] = None 204 | self._command_list: Optional[list[Any]] = None 205 | 206 | def _parse_pair(self, line: str, separator: str = ": ") -> List[str]: 207 | pair = line.split(separator, 1) 208 | if len(pair) < 2: 209 | raise ProtocolError("Could not parse pair: '{}'".format(line)) 210 | return pair 211 | 212 | def _parse_pairs( 213 | self, lines: Iterable[str], separator: str = ": " 214 | ) -> Iterator[List[str]]: 215 | for line in lines: 216 | yield self._parse_pair(line, separator) 217 | 218 | def _parse_objects( 219 | self, 220 | lines: Iterable[str], 221 | delimiters: List[str] = [], 222 | lookup_delimiter: bool = False, 223 | ) -> Iterator[Dict[str, str]]: 224 | obj: Dict[str, Any] = {} 225 | for key, value in self._parse_pairs(lines): 226 | key = key.lower() 227 | if lookup_delimiter and key not in delimiters: 228 | delimiters = delimiters + [key] 229 | if obj: 230 | if key in delimiters: 231 | if lookup_delimiter: 232 | if key in obj: 233 | yield obj 234 | obj = obj.copy() 235 | while delimiters[-1] != key: 236 | obj.pop(delimiters[-1], None) 237 | delimiters.pop() 238 | else: 239 | yield obj 240 | obj = {} 241 | elif key in obj: 242 | if not isinstance(obj[key], list): 243 | obj[key] = [obj[key], value] 244 | else: 245 | obj[key].append(value) 246 | continue 247 | obj[key] = value 248 | if obj: 249 | yield obj 250 | 251 | # Use this instead of _parse_objects whenever the result is returned 252 | # immediately in a command implementation 253 | _parse_objects_direct = _parse_objects 254 | 255 | def _parse_raw_stickers(self, lines: Iterable[str]) -> Iterator[Tuple[str, str]]: 256 | for _, sticker in self._parse_pairs(lines): 257 | value = sticker.split("=", 1) 258 | if len(value) != 2: 259 | raise ProtocolError("Could not parse sticker: {}".format(repr(sticker))) 260 | yield value[0], value[1] 261 | 262 | NOOP = mpd_commands("close", "kill")(Noop()) 263 | 264 | @mpd_commands("plchangesposid", is_direct=True) 265 | def _parse_changes(self, lines: List[str]) -> Iterator[Dict[str, str]]: 266 | return self._parse_objects_direct(lines, ["cpos"]) 267 | 268 | @mpd_commands("listall", "listallinfo", "listfiles", "lsinfo", is_direct=True) 269 | def _parse_database(self, lines: List[str]) -> Iterator[Dict[str, str]]: 270 | return self._parse_objects_direct(lines, ["file", "directory", "playlist"]) 271 | 272 | @mpd_commands("idle") 273 | def _parse_idle(self, lines: List[str]) -> Iterator[str]: 274 | return self._parse_list(lines) 275 | 276 | @mpd_commands("addid", "replay_gain_status", "rescan", "update") 277 | def _parse_item(self, lines: List[str]) -> Optional[str]: 278 | pairs = list(self._parse_pairs(lines)) 279 | if len(pairs) != 1: 280 | return None 281 | return pairs[0][1] 282 | 283 | @mpd_commands( 284 | "channels", "commands", "listplaylist", "notcommands", "tagtypes", "urlhandlers" 285 | ) 286 | def _parse_list(self, lines: List[str]) -> Iterator[str]: 287 | seen = None 288 | for key, value in self._parse_pairs(lines): 289 | if key != seen: 290 | if seen is not None: 291 | raise ProtocolError("Expected key '{}', got '{}'".format(seen, key)) 292 | seen = key 293 | yield value 294 | 295 | @mpd_commands("list", is_direct=True) 296 | def _parse_list_groups(self, lines: List[str]) -> Iterator[Dict[str, str]]: 297 | return self._parse_objects_direct(lines, lookup_delimiter=True) 298 | 299 | @mpd_commands("readmessages", is_direct=True) 300 | def _parse_messages(self, lines: List[str]) -> Iterator[Dict[str, str]]: 301 | return self._parse_objects_direct(lines, ["channel"]) 302 | 303 | @mpd_commands("listmounts", is_direct=True) 304 | def _parse_mounts(self, lines: List[str]) -> Iterator[Dict[str, str]]: 305 | return self._parse_objects_direct(lines, ["mount"]) 306 | 307 | @mpd_commands("listneighbors", is_direct=True) 308 | def _parse_neighbors(self, lines: List[str]) -> Iterator[Dict[str, str]]: 309 | return self._parse_objects_direct(lines, ["neighbor"]) 310 | 311 | @mpd_commands("listpartitions", is_direct=True) 312 | def _parse_partitions(self, lines: List[str]) -> Iterator[Dict[str, str]]: 313 | return self._parse_objects_direct(lines, ["partition"]) 314 | 315 | @mpd_commands( 316 | "add", 317 | "addtagid", 318 | "binarylimit", 319 | "clear", 320 | "clearerror", 321 | "cleartagid", 322 | "consume", 323 | "crossfade", 324 | "delete", 325 | "deleteid", 326 | "delpartition", 327 | "disableoutput", 328 | "enableoutput", 329 | "findadd", 330 | "load", 331 | "mixrampdb", 332 | "mixrampdelay", 333 | "mount", 334 | "move", 335 | "moveid", 336 | "moveoutput", 337 | "newpartition", 338 | "next", 339 | "outputvolume", 340 | "partition", 341 | "password", 342 | "pause", 343 | "ping", 344 | "play", 345 | "playid", 346 | "playlistadd", 347 | "playlistclear", 348 | "playlistdelete", 349 | "playlistmove", 350 | "previous", 351 | "prio", 352 | "prioid", 353 | "random", 354 | "rangeid", 355 | "rename", 356 | "repeat", 357 | "replay_gain_mode", 358 | "rm", 359 | "save", 360 | "searchadd", 361 | "searchaddpl", 362 | "seek", 363 | "seekcur", 364 | "seekid", 365 | "sendmessage", 366 | "setvol", 367 | "shuffle", 368 | "single", 369 | "sticker delete", 370 | "sticker set", 371 | "stop", 372 | "subscribe", 373 | "swap", 374 | "swapid", 375 | "toggleoutput", 376 | "unmount", 377 | "unsubscribe", 378 | "volume", 379 | ) 380 | def _parse_nothing(self, lines: List[str]) -> None: 381 | for line in lines: 382 | raise ProtocolError( 383 | "Got unexpected return value: '{}'".format(", ".join(lines)) 384 | ) 385 | 386 | @mpd_commands("config", "count", "currentsong", "readcomments", "stats", "status") 387 | def _parse_object(self, lines: List[str]) -> Dict[str, str]: 388 | try: 389 | return next(self._parse_objects(lines)) 390 | except StopIteration: 391 | return {} 392 | 393 | @mpd_commands("outputs", is_direct=True) 394 | def _parse_outputs(self, lines: List[str]) -> Iterator[Dict[str, str]]: 395 | return self._parse_objects_direct(lines, ["outputid"]) 396 | 397 | @mpd_commands("playlist") 398 | def _parse_playlist(self, lines: List[str]) -> Iterator[str]: 399 | for key, value in self._parse_pairs(lines, ":"): 400 | yield value 401 | 402 | @mpd_commands("listplaylists", is_direct=True) 403 | def _parse_playlists(self, lines: List[str]) -> Iterator[Dict[str, str]]: 404 | return self._parse_objects_direct(lines, ["playlist"]) 405 | 406 | @mpd_commands("decoders", is_direct=True) 407 | def _parse_plugins(self, lines: List[str]) -> Iterator[Dict[str, str]]: 408 | return self._parse_objects_direct(lines, ["plugin"]) 409 | 410 | @mpd_commands( 411 | "find", 412 | "listplaylistinfo", 413 | "playlistfind", 414 | "playlistid", 415 | "playlistinfo", 416 | "playlistsearch", 417 | "plchanges", 418 | "search", 419 | "sticker find", 420 | is_direct=True, 421 | ) 422 | def _parse_songs(self, lines: List[str]) -> Iterator[Dict[str, str]]: 423 | return self._parse_objects_direct(lines, ["file"]) 424 | 425 | @mpd_commands("sticker get") 426 | def _parse_sticker(self, lines: List[str]) -> str: 427 | key, value = list(self._parse_raw_stickers(lines))[0] 428 | return value 429 | 430 | @mpd_commands("sticker list") 431 | def _parse_stickers(self, lines: List[str]) -> Dict[str, str]: 432 | return dict(self._parse_raw_stickers(lines)) 433 | 434 | @mpd_commands("albumart", "readpicture", is_binary=True) 435 | def _parse_plain_binary(self, structure: Any) -> Any: 436 | return structure 437 | 438 | 439 | def mpd_command_provider(cls: Type[MPDClientBase]) -> Type[MPDClientBase]: 440 | """Decorator hooking up registered MPD commands to concrete client 441 | implementation. 442 | 443 | A class using this decorator must inherit from ``MPDClientBase`` and 444 | implement it's ``add_command`` function. 445 | """ 446 | 447 | def collect( 448 | cls: Any, callbacks: Dict[str, Tuple[Any, Any]] = {} 449 | ) -> Dict[str, Tuple[Any, Any]]: 450 | """Collect MPD command callbacks from given class. 451 | 452 | Searches class __dict__ on given class and all it's bases for functions 453 | which have been decorated with @mpd_commands and returns a dict 454 | containing callback name as keys and 455 | (callback, callback implementing class) tuples as values. 456 | """ 457 | for name, ob in cls.__dict__.items(): 458 | if hasattr(ob, "mpd_commands") and name not in callbacks: 459 | callbacks[name] = (ob, cls) 460 | for base in cls.__bases__: 461 | callbacks = collect(base, callbacks) 462 | return callbacks 463 | 464 | for name, value in collect(cls).items(): 465 | callback, from_ = value 466 | for command in callback.mpd_commands: 467 | cls.add_command(command, callback) 468 | return cls 469 | 470 | 471 | def _create_callback( 472 | self: Any, function: Callable[[Any, Any], Any], wrap_result: bool 473 | ) -> Optional[Callable[[], Any]]: 474 | """Create MPD command related response callback.""" 475 | if not callable(function): 476 | return None 477 | 478 | def command_callback() -> Any: 479 | # command result callback expects response from MPD as iterable lines, 480 | # thus read available lines from socket 481 | res = function(self, self._read_lines()) 482 | # wrap result in iterator helper if desired 483 | if wrap_result: 484 | res = self._wrap_iterator(res) 485 | return res 486 | 487 | return command_callback 488 | 489 | 490 | def _create_command( 491 | wrapper: Callable, name: str, return_value: Any, wrap_result: bool 492 | ) -> Callable: 493 | """Create MPD command related function.""" 494 | 495 | def mpd_command(self: Any, *args: Any) -> Any: 496 | callback = _create_callback(self, return_value, wrap_result) 497 | return wrapper(self, name, args, callback) 498 | 499 | return mpd_command 500 | 501 | 502 | class _NotConnected: 503 | def __getattr__(self, attr: str) -> Callable: 504 | return self._dummy 505 | 506 | def _dummy(*args: Any) -> None: 507 | raise ConnectionError("Not connected") 508 | 509 | 510 | @mpd_command_provider 511 | class MPDClient(MPDClientBase): 512 | idletimeout = None 513 | _timeout = None 514 | _wrap_iterator_parsers = [ 515 | MPDClientBase._parse_list, 516 | MPDClientBase._parse_list_groups, 517 | MPDClientBase._parse_playlist, 518 | MPDClientBase._parse_changes, 519 | MPDClientBase._parse_songs, 520 | MPDClientBase._parse_mounts, 521 | MPDClientBase._parse_neighbors, 522 | MPDClientBase._parse_partitions, 523 | MPDClientBase._parse_playlists, 524 | MPDClientBase._parse_database, 525 | MPDClientBase._parse_messages, 526 | MPDClientBase._parse_outputs, 527 | MPDClientBase._parse_plugins, 528 | ] 529 | 530 | def __init__(self, use_unicode: Optional[bool] = None) -> None: 531 | if use_unicode is not None: 532 | warnings.warn( 533 | "use_unicode parameter to ``MPDClient`` constructor is deprecated", 534 | DeprecationWarning, 535 | stacklevel=2, 536 | ) 537 | super().__init__() 538 | 539 | def _reset(self) -> None: 540 | super()._reset() 541 | self._iterating = False 542 | self._sock: Optional[socket.socket] = None 543 | self._rbfile: Union[IO[bytes], _NotConnected] = _NotConnected() 544 | self._wfile: Union[IO[str], _NotConnected] = _NotConnected() 545 | 546 | def _execute(self, command: str, args: List[Any], retval: Any) -> Any: 547 | if self._iterating: 548 | raise IteratingError("Cannot execute '{}' while iterating".format(command)) 549 | if self._command_list is not None: 550 | if not callable(retval): 551 | raise CommandListError( 552 | "'{}' not allowed in command list".format(command) 553 | ) 554 | self._write_command(command, args) 555 | self._command_list.append(retval) 556 | else: 557 | self._write_command(command, args) 558 | if callable(retval): 559 | return retval() 560 | return retval 561 | 562 | def _write_line(self, line: str) -> None: 563 | try: 564 | if self._wfile is _NotConnected: 565 | raise ConnectionError("Not connected") 566 | self._wfile.write("{}\n".format(line)) 567 | self._wfile.flush() 568 | except socket.error: 569 | error_message = "Connection to server was reset" 570 | logger.info(error_message) 571 | self._reset() 572 | e = ConnectionError(error_message) 573 | raise e.with_traceback(sys.exc_info()[2]) 574 | 575 | def _write_command(self, command: str, args: List[Any] = []) -> None: 576 | parts = [command] 577 | for arg in args: 578 | if type(arg) is tuple: 579 | if len(arg) == 0: 580 | parts.append('":"') 581 | elif len(arg) == 1: 582 | parts.append('"{}:"'.format(int(arg[0]))) 583 | else: 584 | parts.append('"{}:{}"'.format(int(arg[0]), int(arg[1]))) 585 | else: 586 | parts.append('"{}"'.format(escape(str(arg)))) 587 | # Minimize logging cost if the logging is not activated. 588 | if logger.isEnabledFor(logging.DEBUG): 589 | if command == "password": 590 | logger.debug("Calling MPD password(******)") 591 | else: 592 | logger.debug("Calling MPD %s%r", command, args) 593 | cmd = " ".join(parts) 594 | self._write_line(cmd) 595 | 596 | def _read_line(self) -> Optional[str]: 597 | line = self._rbfile.readline().decode("utf-8") 598 | if not line.endswith("\n"): 599 | self.disconnect() 600 | raise ConnectionError("Connection lost while reading line") 601 | line = line.rstrip("\n") 602 | if line.startswith(ERROR_PREFIX): 603 | error = line[len(ERROR_PREFIX) :].strip() 604 | raise CommandError(error) 605 | if self._command_list is not None: 606 | if line == NEXT: 607 | return None 608 | if line == SUCCESS: 609 | raise ProtocolError("Got unexpected '{}'".format(SUCCESS)) 610 | elif line == SUCCESS: 611 | return None 612 | return line 613 | 614 | def _read_lines(self) -> Iterator[str]: 615 | line = self._read_line() 616 | while line is not None: 617 | yield line 618 | line = self._read_line() 619 | 620 | def _read_chunk(self, amount: int) -> bytes: 621 | chunk = bytearray() 622 | while amount > 0: 623 | result = self._rbfile.read(amount) 624 | if len(result) == 0: 625 | break 626 | chunk.extend(result) 627 | amount -= len(result) 628 | return bytes(chunk) 629 | 630 | def _read_binary(self) -> Dict[str, Union[str, bytes]]: 631 | """From the data stream, read Unicode lines until one says "binary: 632 | \\n"; at that point, read binary data of the given length. 633 | 634 | This behaves like _parse_objects (with empty set of delimiters; even 635 | returning only a single result), but rather than feeding from a lines 636 | iterable (which would be preprocessed too far), it reads directly off 637 | the stream.""" 638 | 639 | obj = {} 640 | 641 | while True: 642 | line = self._read_line() 643 | if line is None: 644 | break 645 | 646 | value: Union[str, bytes] 647 | key, value = self._parse_pair(line, ": ") 648 | 649 | if key == "binary": 650 | chunk_size = int(value) 651 | value = self._read_chunk(chunk_size) 652 | 653 | if len(value) != chunk_size: 654 | self.disconnect() 655 | raise ConnectionError( 656 | "Connection lost while reading binary data: " 657 | "expected %d bytes, got %d" % (chunk_size, len(value)) 658 | ) 659 | 660 | if self._rbfile.read(1) != b"\n": 661 | # newline after binary content 662 | self.disconnect() 663 | raise ConnectionError("Connection lost while reading line") 664 | 665 | obj[key] = value 666 | return obj 667 | 668 | def _execute_binary( 669 | self, command: str, args: List[Any] 670 | ) -> Dict[str, Union[str, bytes]]: 671 | """Execute a command repeatedly with an additional offset argument, 672 | keeping all the identical returned dictionary items and concatenating 673 | the binary chunks following the binary item into one of exactly size. 674 | 675 | This differs from _execute in that rather than passing the lines to the 676 | callback which'd then call on something like _parse_objects, it builds 677 | a parsed object on its own (as a prerequisite to the chunk driving 678 | process) and then joins together the chunks into a single big response.""" 679 | if self._iterating or self._command_list is not None: 680 | raise IteratingError( 681 | "Cannot execute '{}' with command lists".format(command) 682 | ) 683 | data = None 684 | args = list(args) 685 | assert len(args) == 1 686 | args.append(0) 687 | final_metadata = None 688 | while True: 689 | self._write_command(command, args) 690 | metadata = self._read_binary() 691 | chunk = metadata.pop("binary", None) 692 | 693 | if final_metadata is None: 694 | data = chunk 695 | final_metadata = metadata 696 | if not data: 697 | break 698 | try: 699 | size = int(final_metadata["size"]) 700 | except KeyError: 701 | if chunk is None: 702 | raise CommandError( 703 | "Binary field vanished changed during transfer" 704 | ) 705 | size = len(chunk) 706 | except ValueError: 707 | raise CommandError("Size data unsuitable for binary transfer") 708 | else: 709 | if metadata != final_metadata: 710 | raise CommandError( 711 | "Metadata of binary data changed during transfer" 712 | ) 713 | if chunk is None: 714 | raise CommandError("Binary field vanished changed during transfer") 715 | data += chunk 716 | args[-1] = len(data) 717 | if len(data) > size: 718 | raise CommandListError("Binary data announced size exceeded") 719 | elif len(data) == size: 720 | break 721 | 722 | if data is not None: 723 | final_metadata["binary"] = data 724 | 725 | final_metadata.pop("size", None) 726 | 727 | return final_metadata 728 | 729 | def _read_command_list(self) -> Iterator[Dict[str, str]]: 730 | try: 731 | if self._command_list is None: 732 | raise CommandListError("Not in command list") 733 | for retval in self._command_list: 734 | yield retval() 735 | finally: 736 | self._command_list = None 737 | self._parse_nothing(self._read_lines()) 738 | 739 | def _iterator_wrapper( 740 | self, iterator: Iterator[Dict[str, str]] 741 | ) -> Iterator[Dict[str, str]]: 742 | try: 743 | for item in iterator: 744 | yield item 745 | finally: 746 | self._iterating = False 747 | 748 | def _wrap_iterator( 749 | self, iterator: Iterator[Dict[str, str]] 750 | ) -> Iterator[Union[Dict[str, str], List[Dict[str, str]]]]: 751 | if not self.iterate: 752 | return list(iterator) 753 | self._iterating = True 754 | return self._iterator_wrapper(iterator) 755 | 756 | def _hello(self, line: str) -> None: 757 | if not line.endswith("\n"): 758 | self.disconnect() 759 | raise ConnectionError("Connection lost while reading MPD hello") 760 | line = line.rstrip("\n") 761 | if not line.startswith(HELLO_PREFIX): 762 | raise ProtocolError("Got invalid MPD hello: '{}'".format(line)) 763 | self.mpd_version = line[len(HELLO_PREFIX) :].strip() 764 | 765 | def _connect_unix(self, path: str) -> socket.socket: 766 | if not hasattr(socket, "AF_UNIX"): 767 | raise ConnectionError("Unix domain sockets not supported on this platform") 768 | sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) 769 | sock.settimeout(self.timeout) 770 | sock.connect(path) 771 | return sock 772 | 773 | def _connect_tcp(self, host: str, port: int) -> socket.socket: 774 | err = None 775 | for res in socket.getaddrinfo( 776 | host, 777 | port, 778 | socket.AF_UNSPEC, 779 | socket.SOCK_STREAM, 780 | socket.IPPROTO_TCP, 781 | socket.AI_ADDRCONFIG, 782 | ): 783 | af, socktype, proto, canonname, sa = res 784 | sock = None 785 | try: 786 | sock = socket.socket(af, socktype, proto) 787 | sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) 788 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) 789 | sock.settimeout(self.timeout) 790 | sock.connect(sa) 791 | return sock 792 | except socket.error as e: 793 | err = e 794 | if sock is not None: 795 | sock.close() 796 | if err is not None: 797 | raise err 798 | else: 799 | raise ConnectionError("getaddrinfo returns an empty list") 800 | 801 | @mpd_commands("idle") 802 | def _parse_idle( 803 | self, lines: List[str] 804 | ) -> Iterator[Union[Dict[str, str], List[Dict[str, str]]]]: 805 | if self._sock is not None: 806 | self._sock.settimeout(self.idletimeout) 807 | ret = self._wrap_iterator(self._parse_list(lines)) 808 | if self._sock is not None: 809 | self._sock.settimeout(self._timeout) 810 | return ret 811 | 812 | @property 813 | def timeout(self) -> Optional[float]: 814 | return self._timeout 815 | 816 | @timeout.setter 817 | def timeout(self, timeout: Optional[float]) -> None: 818 | self._timeout = timeout 819 | if self._sock is not None: 820 | self._sock.settimeout(timeout) 821 | 822 | def connect( 823 | self, host: str, port: Optional[int] = None, timeout: Optional[float] = None 824 | ) -> None: 825 | logger.info("Calling MPD connect(%r, %r, timeout=%r)", host, port, timeout) 826 | if self._sock is not None: 827 | raise ConnectionError("Already connected") 828 | if timeout is not None: 829 | warnings.warn( 830 | "The timeout parameter in connect() is deprecated! " 831 | "Use MPDClient.timeout = yourtimeout instead.", 832 | DeprecationWarning, 833 | ) 834 | self.timeout = timeout 835 | if host.startswith("@"): 836 | host = "\0" + host[1:] 837 | if host.startswith(("/", "\0")): 838 | self._sock = self._connect_unix(host) 839 | else: 840 | if port is None: 841 | raise ValueError( 842 | "port argument must be specified when connecting via tcp" 843 | ) 844 | self._sock = self._connect_tcp(host, port) 845 | 846 | # - Force UTF-8 encoding, since this is dependant from the LC_CTYPE 847 | # locale. 848 | # - by setting newline explicit, we force to send '\n' also on 849 | # windows 850 | self._rbfile = self._sock.makefile("rb", newline="\n") 851 | self._wfile = self._sock.makefile("w", encoding="utf-8", newline="\n") 852 | 853 | try: 854 | helloline = self._rbfile.readline().decode("utf-8") 855 | self._hello(helloline) 856 | except Exception: 857 | self.disconnect() 858 | raise 859 | 860 | def disconnect(self) -> None: 861 | logger.info("Calling MPD disconnect()") 862 | if self._rbfile is not None and not isinstance(self._rbfile, _NotConnected): 863 | self._rbfile.close() 864 | if self._wfile is not None and not isinstance(self._wfile, _NotConnected): 865 | self._wfile.close() 866 | if self._sock is not None: 867 | self._sock.close() 868 | self._reset() 869 | 870 | def fileno(self) -> int: 871 | if self._sock is None: 872 | raise ConnectionError("Not connected") 873 | return self._sock.fileno() 874 | 875 | def command_list_ok_begin(self) -> None: 876 | if self._command_list is not None: 877 | raise CommandListError("Already in command list") 878 | if self._iterating: 879 | raise IteratingError("Cannot begin command list while iterating") 880 | self._write_command("command_list_ok_begin") 881 | self._command_list = [] 882 | 883 | def command_list_end(self) -> Any: 884 | if self._command_list is None: 885 | raise CommandListError("Not in command list") 886 | if self._iterating: 887 | raise IteratingError("Already iterating over a command list") 888 | self._write_command("command_list_end") 889 | return self._wrap_iterator(self._read_command_list()) 890 | 891 | @classmethod 892 | def add_command(cls, name: str, callback: Any) -> None: 893 | wrap_result = callback in cls._wrap_iterator_parsers 894 | if callback.mpd_commands_binary: 895 | 896 | def method(self, *args): 897 | return callback(self, cls._execute_binary(self, name, args)) 898 | else: 899 | method = _create_command(cls._execute, name, callback, wrap_result) 900 | # create new mpd commands as function: 901 | escaped_name = name.replace(" ", "_") 902 | setattr(cls, escaped_name, method) 903 | 904 | @classmethod 905 | def remove_command(cls, name: str) -> None: 906 | if not hasattr(cls, name): 907 | raise ValueError("Can't remove not existent '{}' command".format(name)) 908 | name = name.replace(" ", "_") 909 | delattr(cls, str(name)) 910 | 911 | 912 | # vim: set expandtab shiftwidth=4 softtabstop=4 textwidth=79: 913 | -------------------------------------------------------------------------------- /GPL.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------