diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 000000000..0f5481f0c --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,31 @@ +### Problem + +(Describe your problem, feature request, or discussion topic here. If you're reporting a bug, please fill out this and the "Setup" section below. Otherwise, you can delete them.) + +Running this command in verbose (`-vv`) mode: + +```sh +$ beet -vv (... paste here ...) +``` + +Led to this problem: + +``` +(paste here) +``` + +Here's a link to the music files that trigger the bug (if relevant): + + +### Setup + +* OS: +* Python version: +* beets version: +* Turning off plugins made problem go away (yes/no): + +My configuration (output of `beet config`) is: + +```yaml +(paste here) +``` diff --git a/.gitignore b/.gitignore index cde892b3b..b93d93305 100644 --- a/.gitignore +++ b/.gitignore @@ -1,39 +1,91 @@ - # general hidden files/directories - .DS_Store -.sconsign* -.svn -.tox -.coverage .idea -.ackrc # file patterns - -*.dylib -*.la -*.lo -*.o -*.pyc -*.pyo -*.so -*.tar.gz -*.tar.bz2 *~ -*.project -*.pydevproject -*.ropeproject -*.orig # Project Specific patterns - -dist/* -beets.egg-info/* -build/* -docs/_build/* man -htmlcov/* -.noseids -*.egg test/rsrc/lyrics/* + +# The rest is from https://www.gitignore.io/api/python + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ + +# Flask stuff: +instance/ +.webassets-cache + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# pyenv +.python-version + +# dotenv +.env + +# virtualenv +venv/ +ENV/ + +# Spyder project settings +.spyderproject + +# Rope project settings +.ropeproject + +# PyDev and Eclipse project settings +/.project +/.pydevproject +/.settings diff --git a/.hgignore b/.hgignore deleted file mode 100644 index 33acb4da3..000000000 --- a/.hgignore +++ /dev/null @@ -1,7 +0,0 @@ -^dist/ -^beets\.egg-info/ -^build/ -^MANIFEST$ -^docs/_build/ -^\.tox/ -^\.idea/ diff --git a/.hgtags b/.hgtags deleted file mode 100644 index 91ecdd73d..000000000 --- a/.hgtags +++ /dev/null @@ -1,29 +0,0 @@ -86681cf6e45cf8f8de36ffe4e543b8bdd0e92c70 1.0b2 -c367859a82b9f4db0a4e693db6e0cd9724f8f86d 1.0b1 -a5e6430ece5a806aae7e692bf274f700ba01c665 1.0b3 -127b1ca77a2b4d1bdff0fa2eac168684d7dfe29d 1.0b4 -7b14e7caeaeb15ccd3f280b8b745c9c8f1487b14 1.0b5 -fad79b29263e86815799d3049aaa2da5d4cd3a04 1.0b6 -5986215a08c24eea3eb48e1b13a4748b34040aa5 1.0b7 -cea5dcc51b047fa6535d535624363b50a991fb5b 1.0b8 -a256ec5b0b2de500305fd6656db0a195df273acc 1.0b9 -88807657483a916200296165933529da9a682528 1.0b10 -4ca1475821742002962df439f71f51d67640b91e 1.0b11 -284b58a9f9ce3a79f7d2bcc48819f2bb77773818 1.0b12 -b6c10981014a5b3a963460fca3b31cc62bf7ed2c 1.0b13 -d3dbc6df2b96f8ba5704305a893e3e63b7f9cd77 1.0b14 -618201431990382474829cf96ea58e3669159f9a 1.0b15 -c84744f4519be7416dc1653142f1763f406d6896 1.0rc1 -f3cd4c138c6f40dc324a23bf01c4c7d97766477e 1.0rc2 -6f29c0f4dc7025e8d8216ea960000c353886c4f4 v1.1.0-beta.1 -f28ea9e2ef8d39913d79dbba73db280ff0740c50 v1.1.0-beta.2 -8f070ce28a7b33d8509b29a8dbe937109bbdbd21 v1.1.0-beta.3 -97f04ce252332dbda013cbc478d702d54a8fc1bd v1.1.0 -b3f7b5267a2f7b46b826d087421d7f4569211240 v1.2.0 -b3f7b5267a2f7b46b826d087421d7f4569211240 v1.2.0 -ecff182221ec32a9f6549ad3ce8d2ab4c3e5568a v1.2.0 -bd7259ac13b54caecb1403f625688eb3eeeba8d6 v1.2.1 -c6af5962e25b915ce538af1c0b53a89ceb340b04 v1.2.2 -87945a0e217591a842307fa11e161d4912598c32 v1.3.0 -78ce7bd4a1d1ddcbbd2b624cdfcd70946640ae46 v1.3.1 -d3bb90ef6bc7f663f96dcc1bb5e46498662f16e7 v1.3.2 diff --git a/.travis.yml b/.travis.yml index 4a17ab2ea..2f15baf7e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,35 +1,67 @@ +dist: trusty +sudo: required language: python -sudo: false -branches: - only: - - master +env: + global: + # Undocumented feature of nose-show-skipped. + NOSE_SHOW_SKIPPED: 1 matrix: include: - - python: 2.7 - env: {TOX_ENV: py27cov, COVERAGE: 1} - - python: pypy - env: {TOX_ENV: pypy} - - python: 2.7 - env: {TOX_ENV: docs, NONTEST: 1} - - python: 2.7 - env: {TOX_ENV: flake8, NONTEST: 1} - + - python: 2.7.13 + env: {TOX_ENV: py27-cov, COVERAGE: 1} + - python: 2.7.13 + env: {TOX_ENV: py27-test} + - python: 3.4 + env: {TOX_ENV: py34-test} + - python: 3.4_with_system_site_packages + env: {TOX_ENV: py34-test} + - python: 3.5 + env: {TOX_ENV: py35-test} + - python: 3.6 + env: {TOX_ENV: py36-test} + # - python: pypy + # - env: {TOX_ENV: pypy-test} + - python: 3.4 + env: {TOX_ENV: py34-flake8} + - python: 2.7.13 + env: {TOX_ENV: docs} # Non-Python dependencies. addons: apt: + sources: + - sourceline: "deb http://archive.ubuntu.com/ubuntu/ trusty multiverse" + - sourceline: "deb http://archive.ubuntu.com/ubuntu/ trusty-updates multiverse" packages: - bash-completion + - gir1.2-gst-plugins-base-1.0 + - gir1.2-gstreamer-1.0 + - gstreamer1.0-plugins-good + - gstreamer1.0-plugins-bad + - imagemagick - mp3gain + - python-gi + - python-gst-1.0 + - python3-gi + - python3-gst-1.0 + - unrar # To install dependencies, tell tox to do everything but actually running the # test. install: - travis_retry pip install tox sphinx + # upgrade requests to satisfy sphinx linkcheck (for building man pages) + - if [[ $TRAVIS_PYTHON_VERSION == *_site_packages ]]; then pip install -U requests; fi - travis_retry tox -e $TOX_ENV --notest -script: tox -e $TOX_ENV +script: + # prevents "libdc1394 error: Failed to initialize libdc1394" errors + - sudo ln -s /dev/null /dev/raw1394 + - if [[ $TRAVIS_PYTHON_VERSION == *_site_packages ]]; then SITE_PACKAGES=--sitepackages; fi + # pip in trusty breaks on packages prefixed with "_". See https://github.com/pypa/pip/issues/3681 + - if [[ $TRAVIS_PYTHON_VERSION == 3.4_with_system_site_packages ]]; then sudo rm -rf /usr/lib/python3/dist-packages/_lxc-0.1.egg-info; fi + - tox -e $TOX_ENV $SITE_PACKAGES # Report coverage to codecov.io. before_install: @@ -37,6 +69,9 @@ before_install: after_success: - "[ ! -z $COVERAGE ] && codecov || true" +cache: + pip: true + notifications: irc: channels: diff --git a/LICENSE b/LICENSE index cddcf9900..b45de0fcf 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License -Copyright (c) 2010-2014 Adrian Sampson +Copyright (c) 2010-2016 Adrian Sampson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/MANIFEST.in b/MANIFEST.in index e040a9c34..f5459a443 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,6 +1,8 @@ # Include tests (but avoid including *.pyc, etc.) prune test recursive-include test/rsrc * +recursive-exclude test/rsrc *.pyc +recursive-exclude test/rsrc *.pyo include test/*.py # Include relevant text files. @@ -29,3 +31,6 @@ include beets/config_default.yaml # Shell completion template include beets/ui/completion_base.sh + +# Include extra bits +recursive-include extra * diff --git a/README.rst b/README.rst index eec817f94..a3ea6302f 100644 --- a/README.rst +++ b/README.rst @@ -1,12 +1,16 @@ -.. image:: https://travis-ci.org/sampsyo/beets.svg?branch=master - :target: https://travis-ci.org/sampsyo/beets - -.. image:: http://img.shields.io/codecov/c/github/sampsyo/beets.svg - :target: https://codecov.io/github/sampsyo/beets - .. image:: http://img.shields.io/pypi/v/beets.svg :target: https://pypi.python.org/pypi/beets +.. image:: http://img.shields.io/codecov/c/github/beetbox/beets.svg + :target: https://codecov.io/github/beetbox/beets + +.. image:: https://travis-ci.org/beetbox/beets.svg?branch=master + :target: https://travis-ci.org/beetbox/beets + + +beets +===== + Beets is the media library management system for obsessive-compulsive music geeks. @@ -31,7 +35,7 @@ imagine for your music collection. Via `plugins`_, beets becomes a panacea: - Fetch or calculate all the metadata you could possibly need: `album art`_, `lyrics`_, `genres`_, `tempos`_, `ReplayGain`_ levels, or `acoustic fingerprints`_. -- Get metadata from `MusicBrainz`_ or `Discogs`_. Or guess +- Get metadata from `MusicBrainz`_, `Discogs`_, and `Beatport`_. Or guess metadata using songs' filenames or their acoustic fingerprints. - `Transcode audio`_ to any format you like. - Check your library for `duplicate tracks and albums`_ or for `albums that @@ -64,11 +68,29 @@ shockingly simple if you know a little Python. .. _acoustic fingerprints: http://beets.readthedocs.org/page/plugins/chroma.html .. _ReplayGain: http://beets.readthedocs.org/page/plugins/replaygain.html -.. _tempos: http://beets.readthedocs.org/page/plugins/echonest.html +.. _tempos: http://beets.readthedocs.org/page/plugins/acousticbrainz.html .. _genres: http://beets.readthedocs.org/page/plugins/lastgenre.html .. _album art: http://beets.readthedocs.org/page/plugins/fetchart.html .. _lyrics: http://beets.readthedocs.org/page/plugins/lyrics.html .. _MusicBrainz: http://musicbrainz.org/ +.. _Beatport: https://www.beatport.com + +Install +------- + +You can install beets by typing ``pip install beets``. Then check out the +`Getting Started`_ guide. + +.. _Getting Started: http://beets.readthedocs.org/page/guides/main.html + +Contribute +---------- + +Check out the `Hacking`_ page on the wiki for tips on how to help out. +You might also be interested in the `For Developers`_ section in the docs. + +.. _Hacking: https://github.com/beetbox/beets/wiki/Hacking +.. _For Developers: http://docs.beets.io/page/dev/ Read More --------- @@ -76,18 +98,14 @@ Read More Learn more about beets at `its Web site`_. Follow `@b33ts`_ on Twitter for news and updates. -You can install beets by typing ``pip install beets``. Then check out the -`Getting Started`_ guide. - -.. _its Web site: http://beets.radbox.org/ -.. _Getting Started: http://beets.readthedocs.org/page/guides/main.html +.. _its Web site: http://beets.io/ .. _@b33ts: http://twitter.com/b33ts/ Authors ------- Beets is by `Adrian Sampson`_ with a supporting cast of thousands. For help, -please contact the `mailing list`_. +please visit our `forum`_. -.. _mailing list: https://groups.google.com/forum/#!forum/beets-users -.. _Adrian Sampson: http://homes.cs.washington.edu/~asampson/ +.. _forum: https://discourse.beets.io +.. _Adrian Sampson: http://www.cs.cornell.edu/~asampson/ diff --git a/appveyor.yml b/appveyor.yml index be561eaaf..938d3a5a4 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,20 +1,29 @@ version: "{build}" build: off deploy: off +skip_commits: + # add [appveyor skip] as an alias for [skip appveyor] (like [ci skip]) + message: /\[appveyor skip\]/ environment: + # Undocumented feature of nose-show-skipped. + NOSE_SHOW_SKIPPED: 1 + matrix: - - PYTHON: "C:\\Python27" - TOXENV: py27 + - PYTHON: C:\Python27 + TOX_ENV: py27-test + - PYTHON: C:\Python35 + TOX_ENV: py35-test + - PYTHON: C:\Python36 + TOX_ENV: py36-test # Install Tox for running tests. install: + - cinst imagemagick -y + # TODO: remove --allow-empty-checksums when unrar offers a proper checksum + - cinst unrar -y --allow-empty-checksums - "%PYTHON%/Scripts/pip.exe install tox" + - "%PYTHON%/Scripts/tox.exe -e %TOX_ENV% --notest" test_script: - - "%PYTHON%/Scripts/tox.exe" - -# Allow all failures for now: the tests don't yet pass! -matrix: - allow_failures: - - TOXENV: py27 + - "%PYTHON%/Scripts/tox.exe -e %TOX_ENV%" diff --git a/beet b/beet index e30c8b6eb..21fa085b9 100755 --- a/beet +++ b/beet @@ -1,7 +1,8 @@ #!/usr/bin/env python +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,6 +15,8 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. +from __future__ import division, absolute_import, print_function + import beets.ui if __name__ == '__main__': diff --git a/beets/__init__.py b/beets/__init__.py index 4c8fa25df..b8fe2a840 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,26 +13,30 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import absolute_import, unicode_literals +from __future__ import division, absolute_import, print_function import os -import beets.library from beets.util import confit -__version__ = '1.3.15' -__author__ = 'Adrian Sampson ' +__version__ = u'1.4.7' +__author__ = u'Adrian Sampson ' -Library = beets.library.Library -config = confit.LazyConfig('beets', __name__) +class IncludeLazyConfig(confit.LazyConfig): + """A version of Confit's LazyConfig that also merges in data from + YAML files specified in an `include` setting. + """ + def read(self, user=True, defaults=True): + super(IncludeLazyConfig, self).read(user, defaults) -try: - included_filenames = config['include'].get(list) -except confit.NotFoundError: - included_filenames = [] + try: + for view in self['include']: + filename = view.as_filename() + if os.path.isfile(filename): + self.set_file(filename) + except confit.NotFoundError: + pass -for filename in included_filenames: - filename = os.path.join(config.config_dir(), filename) - if os.path.isfile(filename): - config.set_file(filename) + +config = IncludeLazyConfig('beets', __name__) diff --git a/beets/__main__.py b/beets/__main__.py new file mode 100644 index 000000000..8010ca0dd --- /dev/null +++ b/beets/__main__.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2017, Adrian Sampson. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""The __main__ module lets you run the beets CLI interface by typing +`python -m beets`. +""" + +from __future__ import division, absolute_import, print_function + +import sys +from .ui import main + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/beets/art.py b/beets/art.py index 79bdfefe4..979a6f722 100644 --- a/beets/art.py +++ b/beets/art.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -16,13 +17,14 @@ music and items' embedded album art. """ +from __future__ import division, absolute_import, print_function + import subprocess import platform from tempfile import NamedTemporaryFile -import imghdr import os -from beets.util import displayable_path, syspath +from beets.util import displayable_path, syspath, bytestring_path from beets.util.artresizer import ArtResizer from beets import mediafile @@ -121,26 +123,49 @@ def check_art_similarity(log, item, imagepath, compare_threshold): is_windows = platform.system() == "Windows" # Converting images to grayscale tends to minimize the weight - # of colors in the diff score. + # of colors in the diff score. So we first convert both images + # to grayscale and then pipe them into the `compare` command. + # On Windows, ImageMagick doesn't support the magic \\?\ prefix + # on paths, so we pass `prefix=False` to `syspath`. + convert_cmd = ['convert', syspath(imagepath, prefix=False), + syspath(art, prefix=False), + '-colorspace', 'gray', 'MIFF:-'] + compare_cmd = ['compare', '-metric', 'PHASH', '-', 'null:'] + log.debug(u'comparing images with pipeline {} | {}', + convert_cmd, compare_cmd) convert_proc = subprocess.Popen( - [b'convert', syspath(imagepath), syspath(art), - b'-colorspace', b'gray', b'MIFF:-'], + convert_cmd, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, close_fds=not is_windows, ) compare_proc = subprocess.Popen( - [b'compare', b'-metric', b'PHASH', b'-', b'null:'], + compare_cmd, stdin=convert_proc.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=not is_windows, ) - convert_proc.stdout.close() + # Check the convert output. We're not interested in the + # standard output; that gets piped to the next stage. + convert_proc.stdout.close() + convert_stderr = convert_proc.stderr.read() + convert_proc.stderr.close() + convert_proc.wait() + if convert_proc.returncode: + log.debug( + u'ImageMagick convert failed with status {}: {!r}', + convert_proc.returncode, + convert_stderr, + ) + return + + # Check the compare output. stdout, stderr = compare_proc.communicate() if compare_proc.returncode: if compare_proc.returncode != 1: - log.debug(u'IM phashes compare failed for {0}, {1}', + log.debug(u'ImageMagick compare failed: {0}, {1}', displayable_path(imagepath), displayable_path(art)) return @@ -154,7 +179,7 @@ def check_art_similarity(log, item, imagepath, compare_threshold): log.debug(u'IM output is not a number: {0!r}', out_str) return - log.debug(u'compare PHASH score is {0}', phash_diff) + log.debug(u'ImageMagick compare score: {0}', phash_diff) return phash_diff <= compare_threshold return True @@ -162,18 +187,18 @@ def check_art_similarity(log, item, imagepath, compare_threshold): def extract(log, outpath, item): art = get_art(log, item) - + outpath = bytestring_path(outpath) if not art: log.info(u'No album art present in {0}, skipping.', item) return # Add an extension to the filename. - ext = imghdr.what(None, h=art) + ext = mediafile.image_extension(art) if not ext: log.warning(u'Unknown image type in {0}.', displayable_path(item.path)) return - outpath += b'.' + ext + outpath += bytestring_path('.' + ext) log.info(u'Extracting album art from: {0} to: {1}', item, displayable_path(outpath)) diff --git a/beets/autotag/__init__.py b/beets/autotag/__init__.py index 6ccd59d09..09564f49d 100644 --- a/beets/autotag/__init__.py +++ b/beets/autotag/__init__.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,15 +16,14 @@ """Facilities for automatically determining files' correct metadata. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from beets import logging from beets import config # Parts of external interface. from .hooks import AlbumInfo, TrackInfo, AlbumMatch, TrackMatch # noqa -from .match import tag_item, tag_album # noqa +from .match import tag_item, tag_album, Proposal # noqa from .match import Recommendation # noqa # Global logger. @@ -44,6 +44,16 @@ def apply_item_metadata(item, track_info): item.mb_artistid = track_info.artist_id if track_info.data_source: item.data_source = track_info.data_source + + if track_info.lyricist is not None: + item.lyricist = track_info.lyricist + if track_info.composer is not None: + item.composer = track_info.composer + if track_info.composer_sort is not None: + item.composer_sort = track_info.composer_sort + if track_info.arranger is not None: + item.arranger = track_info.arranger + # At the moment, the other metadata is left intact (including album # and track number). Perhaps these should be emptied? @@ -52,13 +62,20 @@ def apply_metadata(album_info, mapping): """Set the items' metadata to match an AlbumInfo object using a mapping from Items to TrackInfo objects. """ - for item, track_info in mapping.iteritems(): - # Album, artist, track count. - if track_info.artist: - item.artist = track_info.artist + for item, track_info in mapping.items(): + # Artist or artist credit. + if config['artist_credit']: + item.artist = (track_info.artist_credit or + track_info.artist or + album_info.artist_credit or + album_info.artist) + item.albumartist = (album_info.artist_credit or + album_info.artist) else: - item.artist = album_info.artist - item.albumartist = album_info.artist + item.artist = (track_info.artist or album_info.artist) + item.albumartist = album_info.artist + + # Album. item.album = album_info.album # Artist sort and credit names. @@ -97,8 +114,9 @@ def apply_metadata(album_info, mapping): if config['per_disc_numbering']: # We want to let the track number be zero, but if the medium index # is not provided we need to fall back to the overall index. - item.track = track_info.medium_index - if item.track is None: + if track_info.medium_index is not None: + item.track = track_info.medium_index + else: item.track = track_info.index item.tracktotal = track_info.medium_total or len(album_info.tracks) else: @@ -141,3 +159,14 @@ def apply_metadata(album_info, mapping): if track_info.media is not None: item.media = track_info.media + + if track_info.lyricist is not None: + item.lyricist = track_info.lyricist + if track_info.composer is not None: + item.composer = track_info.composer + if track_info.composer_sort is not None: + item.composer_sort = track_info.composer_sort + if track_info.arranger is not None: + item.arranger = track_info.arranger + + item.track_alt = track_info.track_alt diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 5c4ce082e..053d050c6 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -13,18 +14,20 @@ # included in all copies or substantial portions of the Software. """Glue between metadata sources and the matching logic.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from collections import namedtuple +from functools import total_ordering import re from beets import logging from beets import plugins from beets import config +from beets.util import as_string from beets.autotag import mb from jellyfish import levenshtein_distance from unidecode import unidecode +import six log = logging.getLogger('beets') @@ -104,7 +107,7 @@ class AlbumInfo(object): # Work around a bug in python-musicbrainz-ngs that causes some # strings to be bytes rather than Unicode. # https://github.com/alastair/python-musicbrainz-ngs/issues/85 - def decode(self, codec='utf8'): + def decode(self, codec='utf-8'): """Ensure that all string attributes on this object, and the constituent `TrackInfo` objects, are decoded to Unicode. """ @@ -139,6 +142,11 @@ class TrackInfo(object): - ``artist_credit``: Recording-specific artist name - ``data_source``: The original data source (MusicBrainz, Discogs, etc.) - ``data_url``: The data source release URL. + - ``lyricist``: individual track lyricist name + - ``composer``: individual track composer name + - ``composer_sort``: individual track composer sort name + - ``arranger`: individual track arranger name + - ``track_alt``: alternative track number (tape, vinyl, etc.) Only ``title`` and ``track_id`` are required. The rest of the fields may be None. The indices ``index``, ``medium``, and ``medium_index`` @@ -148,7 +156,8 @@ class TrackInfo(object): length=None, index=None, medium=None, medium_index=None, medium_total=None, artist_sort=None, disctitle=None, artist_credit=None, data_source=None, data_url=None, - media=None): + media=None, lyricist=None, composer=None, composer_sort=None, + arranger=None, track_alt=None): self.title = title self.track_id = track_id self.artist = artist @@ -164,9 +173,14 @@ class TrackInfo(object): self.artist_credit = artist_credit self.data_source = data_source self.data_url = data_url + self.lyricist = lyricist + self.composer = composer + self.composer_sort = composer_sort + self.arranger = arranger + self.track_alt = track_alt # As above, work around a bug in python-musicbrainz-ngs. - def decode(self, codec='utf8'): + def decode(self, codec='utf-8'): """Ensure that all string attributes on this object are decoded to Unicode. """ @@ -203,10 +217,10 @@ def _string_dist_basic(str1, str2): transliteration/lowering to ASCII characters. Normalized by string length. """ - assert isinstance(str1, unicode) - assert isinstance(str2, unicode) - str1 = unidecode(str1).decode('ascii') - str2 = unidecode(str2).decode('ascii') + assert isinstance(str1, six.text_type) + assert isinstance(str2, six.text_type) + str1 = as_string(unidecode(str1)) + str2 = as_string(unidecode(str2)) str1 = re.sub(r'[^a-z0-9]', '', str1.lower()) str2 = re.sub(r'[^a-z0-9]', '', str2.lower()) if not str1 and not str2: @@ -288,6 +302,8 @@ class LazyClassProperty(object): return self.value +@total_ordering +@six.python_2_unicode_compatible class Distance(object): """Keeps track of multiple distance penalties. Provides a single weighted distance for all penalties as well as a weighted distance @@ -297,7 +313,7 @@ class Distance(object): self._penalties = {} @LazyClassProperty - def _weights(cls): + def _weights(cls): # noqa """A dictionary from keys to floating-point weights. """ weights_view = config['match']['distance_weights'] @@ -323,7 +339,7 @@ class Distance(object): """Return the maximum distance penalty (normalization factor). """ dist_max = 0.0 - for key, penalty in self._penalties.iteritems(): + for key, penalty in self._penalties.items(): dist_max += len(penalty) * self._weights[key] return dist_max @@ -332,7 +348,7 @@ class Distance(object): """Return the raw (denormalized) distance. """ dist_raw = 0.0 - for key, penalty in self._penalties.iteritems(): + for key, penalty in self._penalties.items(): dist_raw += sum(penalty) * self._weights[key] return dist_raw @@ -349,12 +365,21 @@ class Distance(object): # Convert distance into a negative float we can sort items in # ascending order (for keys, when the penalty is equal) and # still get the items with the biggest distance first. - return sorted(list_, key=lambda (key, dist): (0 - dist, key)) + return sorted( + list_, + key=lambda key_and_dist: (-key_and_dist[1], key_and_dist[0]) + ) + + def __hash__(self): + return id(self) + + def __eq__(self, other): + return self.distance == other # Behave like a float. - def __cmp__(self, other): - return cmp(self.distance, other) + def __lt__(self, other): + return self.distance < other def __float__(self): return self.distance @@ -365,7 +390,7 @@ class Distance(object): def __rsub__(self, other): return other - self.distance - def __unicode__(self): + def __str__(self): return "{0:.2f}".format(self.distance) # Behave like a dict. @@ -393,9 +418,9 @@ class Distance(object): """ if not isinstance(dist, Distance): raise ValueError( - '`dist` must be a Distance object, not {0}'.format(type(dist)) + u'`dist` must be a Distance object, not {0}'.format(type(dist)) ) - for key, penalties in dist._penalties.iteritems(): + for key, penalties in dist._penalties.items(): self._penalties.setdefault(key, []).extend(penalties) # Adding components. @@ -417,7 +442,7 @@ class Distance(object): """ if not 0.0 <= dist <= 1.0: raise ValueError( - '`dist` must be between 0.0 and 1.0, not {0}'.format(dist) + u'`dist` must be between 0.0 and 1.0, not {0}'.format(dist) ) self._penalties.setdefault(key, []).append(dist) @@ -526,20 +551,29 @@ def track_for_mbid(recording_id): exc.log(log) +@plugins.notify_info_yielded(u'albuminfo_received') def albums_for_id(album_id): """Get a list of albums for an ID.""" - candidates = [album_for_mbid(album_id)] - candidates.extend(plugins.album_for_id(album_id)) - return filter(None, candidates) + a = album_for_mbid(album_id) + if a: + yield a + for a in plugins.album_for_id(album_id): + if a: + yield a +@plugins.notify_info_yielded(u'trackinfo_received') def tracks_for_id(track_id): """Get a list of tracks for an ID.""" - candidates = [track_for_mbid(track_id)] - candidates.extend(plugins.track_for_id(track_id)) - return filter(None, candidates) + t = track_for_mbid(track_id) + if t: + yield t + for t in plugins.track_for_id(track_id): + if t: + yield t +@plugins.notify_info_yielded(u'albuminfo_received') def album_candidates(items, artist, album, va_likely): """Search for album matches. ``items`` is a list of Item objects that make up the album. ``artist`` and ``album`` are the respective @@ -547,43 +581,42 @@ def album_candidates(items, artist, album, va_likely): entered by the user. ``va_likely`` is a boolean indicating whether the album is likely to be a "various artists" release. """ - out = [] - # Base candidates if we have album and artist to match. if artist and album: try: - out.extend(mb.match_album(artist, album, len(items))) + for candidate in mb.match_album(artist, album, len(items)): + yield candidate except mb.MusicBrainzAPIError as exc: exc.log(log) # Also add VA matches from MusicBrainz where appropriate. if va_likely and album: try: - out.extend(mb.match_album(None, album, len(items))) + for candidate in mb.match_album(None, album, len(items)): + yield candidate except mb.MusicBrainzAPIError as exc: exc.log(log) # Candidates from plugins. - out.extend(plugins.candidates(items, artist, album, va_likely)) - - return out + for candidate in plugins.candidates(items, artist, album, va_likely): + yield candidate +@plugins.notify_info_yielded(u'trackinfo_received') def item_candidates(item, artist, title): """Search for item matches. ``item`` is the Item to be matched. ``artist`` and ``title`` are strings and either reflect the item or are specified by the user. """ - out = [] # MusicBrainz candidates. if artist and title: try: - out.extend(mb.match_track(artist, title)) + for candidate in mb.match_track(artist, title): + yield candidate except mb.MusicBrainzAPIError as exc: exc.log(log) # Plugin candidates. - out.extend(plugins.item_candidates(item, artist, title)) - - return out + for candidate in plugins.item_candidates(item, artist, title): + yield candidate diff --git a/beets/autotag/match.py b/beets/autotag/match.py index c747f47c2..71b62adb7 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -16,12 +17,12 @@ releases and tracks. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import datetime import re from munkres import Munkres +from collections import namedtuple from beets import logging from beets import plugins @@ -52,6 +53,13 @@ class Recommendation(OrderedEnum): strong = 3 +# A structure for holding a set of possible matches to choose between. This +# consists of a list of possible candidates (i.e., AlbumInfo or TrackInfo +# objects) and a recommendation value. + +Proposal = namedtuple('Proposal', ('candidates', 'recommendation')) + + # Primary matching functionality. def current_metadata(items): @@ -95,7 +103,9 @@ def assign_items(items, tracks): costs.append(row) # Find a minimum-cost bipartite matching. + log.debug('Computing track assignment...') matching = Munkres().compute(costs) + log.debug('...done.') # Produce the output matching. mapping = dict((items[i], tracks[j]) for (i, j) in matching) @@ -237,7 +247,7 @@ def distance(items, album_info, mapping): # Tracks. dist.tracks = {} - for item, track in mapping.iteritems(): + for item, track in mapping.items(): dist.tracks[track] = track_distance(item, track, album_info.va) dist.add('tracks', dist.tracks[track].distance) @@ -260,19 +270,23 @@ def match_by_id(items): AlbumInfo object for the corresponding album. Otherwise, returns None. """ - # Is there a consensus on the MB album ID? - albumids = [item.mb_albumid for item in items if item.mb_albumid] - if not albumids: - log.debug(u'No album IDs found.') + albumids = (item.mb_albumid for item in items if item.mb_albumid) + + # Did any of the items have an MB album ID? + try: + first = next(albumids) + except StopIteration: + log.debug(u'No album ID found.') return None + # Is there a consensus on the MB album ID? + for other in albumids: + if other != first: + log.debug(u'No album ID consensus.') + return None # If all album IDs are equal, look up the album. - if bool(reduce(lambda x, y: x if x == y else (), albumids)): - albumid = albumids[0] - log.debug(u'Searching for discovered album ID: {0}', albumid) - return hooks.album_for_mbid(albumid) - else: - log.debug(u'No album ID consensus.') + log.debug(u'Searching for discovered album ID: {0}', first) + return hooks.album_for_mbid(first) def _recommendation(results): @@ -311,10 +325,10 @@ def _recommendation(results): keys = set(min_dist.keys()) if isinstance(results[0], hooks.AlbumMatch): for track_dist in min_dist.tracks.values(): - keys.update(track_dist.keys()) + keys.update(list(track_dist.keys())) max_rec_view = config['match']['max_rec'] for key in keys: - if key in max_rec_view.keys(): + if key in list(max_rec_view.keys()): max_rec = max_rec_view[key].as_choice({ 'strong': Recommendation.strong, 'medium': Recommendation.medium, @@ -326,17 +340,23 @@ def _recommendation(results): return rec +def _sort_candidates(candidates): + """Sort candidates by distance.""" + return sorted(candidates, key=lambda match: match.distance) + + def _add_candidate(items, results, info): """Given a candidate AlbumInfo object, attempt to add the candidate to the output dictionary of AlbumMatch objects. This involves checking the track count, ordering the items, checking for duplicates, and calculating the distance. """ - log.debug(u'Candidate: {0} - {1}', info.artist, info.album) + log.debug(u'Candidate: {0} - {1} ({2})', + info.artist, info.album, info.album_id) # Discard albums with zero tracks. if not info.tracks: - log.debug('No tracks.') + log.debug(u'No tracks.') return # Don't duplicate. @@ -369,18 +389,20 @@ def _add_candidate(items, results, info): def tag_album(items, search_artist=None, search_album=None, - search_id=None): - """Return a tuple of a artist name, an album name, a list of - `AlbumMatch` candidates from the metadata backend, and a - `Recommendation`. + search_ids=[]): + """Return a tuple of the current artist name, the current album + name, and a `Proposal` containing `AlbumMatch` candidates. The artist and album are the most common values of these fields among `items`. The `AlbumMatch` objects are generated by searching the metadata backends. By default, the metadata of the items is used for the - search. This can be customized by setting the parameters. The - `mapping` field of the album has the matched `items` as keys. + search. This can be customized by setting the parameters. + `search_ids` is a list of metadata backend IDs: if specified, + it will restrict the candidates to those IDs, ignoring + `search_artist` and `search album`. The `mapping` field of the + album has the matched `items` as keys. The recommendation is calculated from the match quality of the candidates. @@ -396,9 +418,11 @@ def tag_album(items, search_artist=None, search_album=None, candidates = {} # Search by explicit ID. - if search_id is not None: - log.debug(u'Searching for album ID: {0}', search_id) - search_cands = hooks.albums_for_id(search_id) + if search_ids: + for search_id in search_ids: + log.debug(u'Searching for album ID: {0}', search_id) + for id_candidate in hooks.albums_for_id(search_id): + _add_candidate(items, candidates, id_candidate) # Use existing metadata or text search. else: @@ -406,7 +430,7 @@ def tag_album(items, search_artist=None, search_album=None, id_info = match_by_id(items) if id_info: _add_candidate(items, candidates, id_info) - rec = _recommendation(candidates.values()) + rec = _recommendation(list(candidates.values())) log.debug(u'Album ID match recommendation is {0}', rec) if candidates and not config['import']['timid']: # If we have a very good MBID match, return immediately. @@ -414,7 +438,8 @@ def tag_album(items, search_artist=None, search_album=None, # matches. if rec == Recommendation.strong: log.debug(u'ID match.') - return cur_artist, cur_album, candidates.values(), rec + return cur_artist, cur_album, \ + Proposal(list(candidates.values()), rec) # Search terms. if not (search_artist and search_album): @@ -429,51 +454,55 @@ def tag_album(items, search_artist=None, search_album=None, log.debug(u'Album might be VA: {0}', va_likely) # Get the results from the data sources. - search_cands = hooks.album_candidates(items, search_artist, - search_album, va_likely) - - log.debug(u'Evaluating {0} candidates.', len(search_cands)) - for info in search_cands: - _add_candidate(items, candidates, info) + for matched_candidate in hooks.album_candidates(items, + search_artist, + search_album, + va_likely): + _add_candidate(items, candidates, matched_candidate) + log.debug(u'Evaluating {0} candidates.', len(candidates)) # Sort and get the recommendation. - candidates = sorted(candidates.itervalues()) + candidates = _sort_candidates(candidates.values()) rec = _recommendation(candidates) - return cur_artist, cur_album, candidates, rec + return cur_artist, cur_album, Proposal(candidates, rec) def tag_item(item, search_artist=None, search_title=None, - search_id=None): - """Attempts to find metadata for a single track. Returns a - `(candidates, recommendation)` pair where `candidates` is a list of - TrackMatch objects. `search_artist` and `search_title` may be used + search_ids=[]): + """Find metadata for a single track. Return a `Proposal` consisting + of `TrackMatch` objects. + + `search_artist` and `search_title` may be used to override the current metadata for the purposes of the MusicBrainz - title; likewise `search_id`. + title. `search_ids` may be used for restricting the search to a list + of metadata backend IDs. """ # Holds candidates found so far: keys are MBIDs; values are # (distance, TrackInfo) pairs. candidates = {} # First, try matching by MusicBrainz ID. - trackid = search_id or item.mb_trackid - if trackid: - log.debug(u'Searching for track ID: {0}', trackid) - for track_info in hooks.tracks_for_id(trackid): - dist = track_distance(item, track_info, incl_artist=True) - candidates[track_info.track_id] = \ - hooks.TrackMatch(dist, track_info) - # If this is a good match, then don't keep searching. - rec = _recommendation(candidates.values()) - if rec == Recommendation.strong and not config['import']['timid']: - log.debug(u'Track ID match.') - return candidates.values(), rec + trackids = search_ids or [t for t in [item.mb_trackid] if t] + if trackids: + for trackid in trackids: + log.debug(u'Searching for track ID: {0}', trackid) + for track_info in hooks.tracks_for_id(trackid): + dist = track_distance(item, track_info, incl_artist=True) + candidates[track_info.track_id] = \ + hooks.TrackMatch(dist, track_info) + # If this is a good match, then don't keep searching. + rec = _recommendation(_sort_candidates(candidates.values())) + if rec == Recommendation.strong and \ + not config['import']['timid']: + log.debug(u'Track ID match.') + return Proposal(_sort_candidates(candidates.values()), rec) # If we're searching by ID, don't proceed. - if search_id is not None: + if search_ids: if candidates: - return candidates.values(), rec + return Proposal(_sort_candidates(candidates.values()), rec) else: - return [], Recommendation.none + return Proposal([], Recommendation.none) # Search terms. if not (search_artist and search_title): @@ -487,6 +516,6 @@ def tag_item(item, search_artist=None, search_title=None, # Sort by distance and return with recommendation. log.debug(u'Found {0} candidates.', len(candidates)) - candidates = sorted(candidates.itervalues()) + candidates = _sort_candidates(candidates.values()) rec = _recommendation(candidates) - return candidates, rec + return Proposal(candidates, rec) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index ff267634f..0539c909e 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,25 +15,31 @@ """Searches for albums in the MusicBrainz database. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import musicbrainzngs import re import traceback -from urlparse import urljoin +from six.moves.urllib.parse import urljoin from beets import logging import beets.autotag.hooks import beets from beets import util from beets import config +import six VARIOUS_ARTISTS_ID = '89ad4ac3-39f7-470e-963a-56509c546377' -BASE_URL = 'http://musicbrainz.org/' + +if util.SNI_SUPPORTED: + BASE_URL = 'https://musicbrainz.org/' +else: + BASE_URL = 'http://musicbrainz.org/' + +SKIPPED_TRACKS = ['[data track]'] musicbrainzngs.set_useragent('beets', beets.__version__, - 'http://beets.radbox.org/') + 'http://beets.io/') class MusicBrainzAPIError(util.HumanReadableException): @@ -42,7 +49,7 @@ class MusicBrainzAPIError(util.HumanReadableException): def __init__(self, reason, verb, query, tb=None): self.query = query if isinstance(reason, musicbrainzngs.WebServiceError): - reason = 'MusicBrainz not reachable' + reason = u'MusicBrainz not reachable' super(MusicBrainzAPIError, self).__init__(reason, verb, tb) def get_message(self): @@ -53,8 +60,12 @@ class MusicBrainzAPIError(util.HumanReadableException): log = logging.getLogger('beets') RELEASE_INCLUDES = ['artists', 'media', 'recordings', 'release-groups', - 'labels', 'artist-credits', 'aliases'] + 'labels', 'artist-credits', 'aliases', + 'recording-level-rels', 'work-rels', + 'work-level-rels', 'artist-rels'] TRACK_INCLUDES = ['artists', 'aliases'] +if 'work-level-rels' in musicbrainzngs.VALID_INCLUDES['recording']: + TRACK_INCLUDES += ['work-level-rels', 'artist-rels'] def track_url(trackid): @@ -69,7 +80,8 @@ def configure(): """Set up the python-musicbrainz-ngs module according to settings from the beets configuration. This should be called at startup. """ - musicbrainzngs.set_hostname(config['musicbrainz']['host'].get(unicode)) + hostname = config['musicbrainz']['host'].as_str() + musicbrainzngs.set_hostname(hostname) musicbrainzngs.set_rate_limit( config['musicbrainz']['ratelimit_interval'].as_number(), config['musicbrainz']['ratelimit'].get(int), @@ -99,6 +111,24 @@ def _preferred_alias(aliases): return matches[0] +def _preferred_release_event(release): + """Given a release, select and return the user's preferred release + event as a tuple of (country, release_date). Fall back to the + default release event if a preferred event is not found. + """ + countries = config['match']['preferred']['countries'].as_str_seq() + + for country in countries: + for event in release.get('release-event-list', {}): + try: + if country in event['area']['iso-3166-1-code-list']: + return country, event['date'] + except KeyError: + pass + + return release.get('country'), release.get('date') + + def _flatten_artist_credit(credit): """Given a list representing an ``artist-credit`` block, flatten the data into a triple of joined artist name strings: canonical, sort, and @@ -108,7 +138,7 @@ def _flatten_artist_credit(credit): artist_sort_parts = [] artist_credit_parts = [] for el in credit: - if isinstance(el, basestring): + if isinstance(el, six.string_types): # Join phrase. artist_parts.append(el) artist_credit_parts.append(el) @@ -161,7 +191,7 @@ def track_info(recording, index=None, medium=None, medium_index=None, medium=medium, medium_index=medium_index, medium_total=medium_total, - data_source='MusicBrainz', + data_source=u'MusicBrainz', data_url=track_url(recording['id']), ) @@ -177,6 +207,37 @@ def track_info(recording, index=None, medium=None, medium_index=None, if recording.get('length'): info.length = int(recording['length']) / (1000.0) + lyricist = [] + composer = [] + composer_sort = [] + for work_relation in recording.get('work-relation-list', ()): + if work_relation['type'] != 'performance': + continue + for artist_relation in work_relation['work'].get( + 'artist-relation-list', ()): + if 'type' in artist_relation: + type = artist_relation['type'] + if type == 'lyricist': + lyricist.append(artist_relation['artist']['name']) + elif type == 'composer': + composer.append(artist_relation['artist']['name']) + composer_sort.append( + artist_relation['artist']['sort-name']) + if lyricist: + info.lyricist = u', '.join(lyricist) + if composer: + info.composer = u', '.join(composer) + info.composer_sort = u', '.join(composer_sort) + + arranger = [] + for artist_relation in recording.get('artist-relation-list', ()): + if 'type' in artist_relation: + type = artist_relation['type'] + if type == 'arranger': + arranger.append(artist_relation['artist']['name']) + if arranger: + info.arranger = u', '.join(arranger) + info.decode() return info @@ -216,6 +277,9 @@ def album_info(release): disctitle = medium.get('title') format = medium.get('format') + if format in config['match']['ignored_media'].as_str_seq(): + continue + all_tracks = medium['track-list'] if 'data-track-list' in medium: all_tracks += medium['data-track-list'] @@ -225,6 +289,16 @@ def album_info(release): all_tracks.insert(0, medium['pregap']) for track in all_tracks: + + if ('title' in track['recording'] and + track['recording']['title'] in SKIPPED_TRACKS): + continue + + if ('video' in track['recording'] and + track['recording']['video'] == 'true' and + config['match']['ignore_video_tracks']): + continue + # Basic information from the recording. index += 1 ti = track_info( @@ -236,6 +310,7 @@ def album_info(release): ) ti.disctitle = disctitle ti.media = format + ti.track_alt = track['number'] # Prefer track data, where present, over recording data. if track.get('title'): @@ -259,13 +334,14 @@ def album_info(release): mediums=len(release['medium-list']), artist_sort=artist_sort_name, artist_credit=artist_credit_name, - data_source='MusicBrainz', + data_source=u'MusicBrainz', data_url=album_url(release['id']), ) info.va = info.artist_id == VARIOUS_ARTISTS_ID + if info.va: + info.artist = config['va_name'].as_str() info.asin = release.get('asin') info.releasegroup_id = release['release-group']['id'] - info.country = release.get('country') info.albumstatus = release.get('status') # Build up the disambiguation string from the release group and release. @@ -276,14 +352,28 @@ def album_info(release): disambig.append(release.get('disambiguation')) info.albumdisambig = u', '.join(disambig) - # Release type not always populated. + # Get the "classic" Release type. This data comes from a legacy API + # feature before MusicBrainz supported multiple release types. if 'type' in release['release-group']: reltype = release['release-group']['type'] if reltype: info.albumtype = reltype.lower() - # Release dates. - release_date = release.get('date') + # Log the new-style "primary" and "secondary" release types. + # Eventually, we'd like to actually store this data, but we just log + # it for now to help understand the differences. + if 'primary-type' in release['release-group']: + rel_primarytype = release['release-group']['primary-type'] + if rel_primarytype: + log.debug('primary MB release type: ' + rel_primarytype.lower()) + if 'secondary-type-list' in release['release-group']: + if release['release-group']['secondary-type-list']: + log.debug('secondary MB release type(s): ' + ', '.join( + [secondarytype.lower() for secondarytype in + release['release-group']['secondary-type-list']])) + + # Release events. + info.country, release_date = _preferred_release_event(release) release_group_date = release['release-group'].get('first-release-date') if not release_date: # Fall back if release-specific date is not available. @@ -331,13 +421,14 @@ def match_album(artist, album, tracks=None): # Various Artists search. criteria['arid'] = VARIOUS_ARTISTS_ID if tracks is not None: - criteria['tracks'] = unicode(tracks) + criteria['tracks'] = six.text_type(tracks) # Abort if we have no search terms. - if not any(criteria.itervalues()): + if not any(criteria.values()): return try: + log.debug(u'Searching for MusicBrainz releases with: {!r}', criteria) res = musicbrainzngs.search_releases( limit=config['musicbrainz']['searchlimit'].get(int), **criteria) except musicbrainzngs.MusicBrainzError as exc: @@ -360,7 +451,7 @@ def match_track(artist, title): 'recording': title.lower().strip(), } - if not any(criteria.itervalues()): + if not any(criteria.values()): return try: @@ -378,7 +469,7 @@ def _parse_id(s): no ID can be found, return None. """ # Find the first thing that looks like a UUID/MBID. - match = re.search('[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}', s) + match = re.search(u'[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}', s) if match: return match.group() @@ -388,6 +479,7 @@ def album_for_id(releaseid): object or None if the album is not found. May raise a MusicBrainzAPIError. """ + log.debug(u'Requesting MusicBrainz release {}', releaseid) albumid = _parse_id(releaseid) if not albumid: log.debug(u'Invalid MBID ({0}).', releaseid) @@ -399,7 +491,7 @@ def album_for_id(releaseid): log.debug(u'Album ID match failed.') return None except musicbrainzngs.MusicBrainzError as exc: - raise MusicBrainzAPIError(exc, 'get release by ID', albumid, + raise MusicBrainzAPIError(exc, u'get release by ID', albumid, traceback.format_exc()) return album_info(res['release']) @@ -418,6 +510,6 @@ def track_for_id(releaseid): log.debug(u'Track ID match failed.') return None except musicbrainzngs.MusicBrainzError as exc: - raise MusicBrainzAPIError(exc, 'get recording by ID', trackid, + raise MusicBrainzAPIError(exc, u'get recording by ID', trackid, traceback.format_exc()) return track_info(res['recording']) diff --git a/beets/config_default.yaml b/beets/config_default.yaml index f708702a8..273f94235 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -6,9 +6,12 @@ import: copy: yes move: no link: no + hardlink: no delete: no resume: ask incremental: no + incremental_skip_later: no + from_scratch: no quiet_fallback: skip none_rec_action: ask timid: no @@ -22,9 +25,15 @@ import: flat: no group_albums: no pretend: false + search_ids: [] + duplicate_action: ask + bell: no + set_fields: {} clutter: ["Thumbs.DB", ".DS_Store"] -ignore: [".*", "*~", "System Volume Information"] +ignore: [".*", "*~", "System Volume Information", "lost+found"] +ignore_hidden: yes + replace: '[\\/]': _ '^\.': _ @@ -33,6 +42,7 @@ replace: '\.$': _ '\s+$': '' '^\s+': '' + '^-': _ path_sep_replace: _ asciify_paths: false art_filename: cover @@ -46,7 +56,9 @@ per_disc_numbering: no verbose: 0 terminal_encoding: original_date: no +artist_credit: no id3v23: no +va_name: "Various Artists" ui: terminal_width: 80 @@ -64,6 +76,7 @@ ui: format_item: $artist - $album - $title format_album: $albumartist - $album time_format: '%Y-%m-%d %H:%M:%S' +format_raw_length: no sort_album: albumartist+ album+ sort_item: artist+ album+ disc+ track+ @@ -115,5 +128,7 @@ match: original_year: no ignored: [] required: [] + ignored_media: [] + ignore_video_tracks: yes track_length_grace: 10 track_length_max: 30 diff --git a/beets/dbcore/__init__.py b/beets/dbcore/__init__.py index 093591882..689e7202c 100644 --- a/beets/dbcore/__init__.py +++ b/beets/dbcore/__init__.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,7 +16,7 @@ """DBCore is an abstract database package that forms the basis for beets' Library. """ -from __future__ import absolute_import +from __future__ import division, absolute_import, print_function from .db import Model, Database from .query import Query, FieldQuery, MatchQuery, AndQuery, OrQuery diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py old mode 100644 new mode 100755 index df796a134..0f4dc1513 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,8 +15,7 @@ """The central Model and Database constructs for DBCore. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import time import os @@ -27,8 +27,19 @@ import collections import beets from beets.util.functemplate import Template +from beets.util import py3_path from beets.dbcore import types from .query import MatchQuery, NullSort, TrueQuery +import six + + +class DBAccessError(Exception): + """The SQLite database became inaccessible. + + This can happen when trying to read or write the database when, for + example, the database file is deleted or otherwise disappears. There + is probably no way to recover from this error. + """ class FormattedMapping(collections.Mapping): @@ -66,10 +77,10 @@ class FormattedMapping(collections.Mapping): def _get_formatted(self, model, key): value = model._type(key).format(model.get(key)) if isinstance(value, bytes): - value = value.decode('utf8', 'ignore') + value = value.decode('utf-8', 'ignore') if self.for_path: - sep_repl = beets.config['path_sep_replace'].get(unicode) + sep_repl = beets.config['path_sep_replace'].as_str() for sep in (os.path.sep, os.path.altsep): if sep: value = value.replace(sep, sep_repl) @@ -176,9 +187,9 @@ class Model(object): ordinary construction are bypassed. """ obj = cls(db) - for key, value in fixed_values.iteritems(): + for key, value in fixed_values.items(): obj._values_fixed[key] = cls._type(key).from_sql(value) - for key, value in flex_values.iteritems(): + for key, value in flex_values.items(): obj._values_flex[key] = cls._type(key).from_sql(value) return obj @@ -200,20 +211,37 @@ class Model(object): exception is raised otherwise. """ if not self._db: - raise ValueError('{0} has no database'.format(type(self).__name__)) + raise ValueError( + u'{0} has no database'.format(type(self).__name__) + ) if need_id and not self.id: - raise ValueError('{0} has no id'.format(type(self).__name__)) + raise ValueError(u'{0} has no id'.format(type(self).__name__)) + + def copy(self): + """Create a copy of the model object. + + The field values and other state is duplicated, but the new copy + remains associated with the same database as the old object. + (A simple `copy.deepcopy` will not work because it would try to + duplicate the SQLite connection.) + """ + new = self.__class__() + new._db = self._db + new._values_fixed = self._values_fixed.copy() + new._values_flex = self._values_flex.copy() + new._dirty = self._dirty.copy() + return new # Essential field accessors. @classmethod - def _type(self, key): + def _type(cls, key): """Get the type of a field, a `Type` instance. If the field has no explicit type, it is given the base `Type`, which does no conversion. """ - return self._fields.get(key) or self._types.get(key) or types.DEFAULT + return cls._fields.get(key) or cls._types.get(key) or types.DEFAULT def __getitem__(self, key): """Get the value for a field. Raise a KeyError if the field is @@ -223,14 +251,15 @@ class Model(object): if key in getters: # Computed. return getters[key](self) elif key in self._fields: # Fixed. - return self._values_fixed.get(key) + return self._values_fixed.get(key, self._type(key).null) elif key in self._values_flex: # Flexible. return self._values_flex[key] else: raise KeyError(key) - def __setitem__(self, key, value): - """Assign the value for a field. + def _setitem(self, key, value): + """Assign the value for a field, return whether new and old value + differ. """ # Choose where to place the value. if key in self._fields: @@ -244,9 +273,17 @@ class Model(object): # Assign value and possibly mark as dirty. old_value = source.get(key) source[key] = value - if self._always_dirty or old_value != value: + changed = old_value != value + if self._always_dirty or changed: self._dirty.add(key) + return changed + + def __setitem__(self, key, value): + """Assign the value for a field. + """ + self._setitem(key, value) + def __delitem__(self, key): """Remove a flexible attribute from the model. """ @@ -254,29 +291,29 @@ class Model(object): del self._values_flex[key] self._dirty.add(key) # Mark for dropping on store. elif key in self._getters(): # Computed. - raise KeyError('computed field {0} cannot be deleted'.format(key)) + raise KeyError(u'computed field {0} cannot be deleted'.format(key)) elif key in self._fields: # Fixed. - raise KeyError('fixed field {0} cannot be deleted'.format(key)) + raise KeyError(u'fixed field {0} cannot be deleted'.format(key)) else: - raise KeyError('no such field {0}'.format(key)) + raise KeyError(u'no such field {0}'.format(key)) def keys(self, computed=False): """Get a list of available field names for this object. The `computed` parameter controls whether computed (plugin-provided) fields are included in the key list. """ - base_keys = list(self._fields) + self._values_flex.keys() + base_keys = list(self._fields) + list(self._values_flex.keys()) if computed: - return base_keys + self._getters().keys() + return base_keys + list(self._getters().keys()) else: return base_keys @classmethod - def all_keys(self): + def all_keys(cls): """Get a list of available keys for objects of this type. Includes fixed and computed fields. """ - return list(self._fields) + self._getters().keys() + return list(cls._fields) + list(cls._getters().keys()) # Act like a dictionary. @@ -317,12 +354,12 @@ class Model(object): def __getattr__(self, key): if key.startswith('_'): - raise AttributeError('model has no attribute {0!r}'.format(key)) + raise AttributeError(u'model has no attribute {0!r}'.format(key)) else: try: return self[key] except KeyError: - raise AttributeError('no such field {0!r}'.format(key)) + raise AttributeError(u'no such field {0!r}'.format(key)) def __setattr__(self, key, value): if key.startswith('_'): @@ -338,15 +375,19 @@ class Model(object): # Database interaction (CRUD methods). - def store(self): + def store(self, fields=None): """Save the object's metadata into the library database. + :param fields: the fields to be stored. If not specified, all fields + will be. """ + if fields is None: + fields = self._fields self._check_db() # Build assignments for query. assignments = [] subvars = [] - for key in self._fields: + for key in fields: if key != 'id' and key in self._dirty: self._dirty.remove(key) assignments.append(key + '=?') @@ -389,7 +430,7 @@ class Model(object): """ self._check_db() stored_obj = self._db._get(type(self), self.id) - assert stored_obj is not None, "object {0} not in DB".format(self.id) + assert stored_obj is not None, u"object {0} not in DB".format(self.id) self._values_fixed = {} self._values_flex = {} self.update(dict(stored_obj)) @@ -450,7 +491,7 @@ class Model(object): separators will be added to the template. """ # Perform substitution. - if isinstance(template, basestring): + if isinstance(template, six.string_types): template = Template(template) return template.substitute(self.formatted(for_path), self._template_funcs()) @@ -461,11 +502,16 @@ class Model(object): def _parse(cls, key, string): """Parse a string as a value for the given key. """ - if not isinstance(string, basestring): - raise TypeError("_parse() argument must be a string") + if not isinstance(string, six.string_types): + raise TypeError(u"_parse() argument must be a string") return cls._type(key).parse(string) + def set_parse(self, key, string): + """Set the object's key to a value represented by a string. + """ + self[key] = self._parse(key, string) + # Database controller and supporting interfaces. @@ -555,13 +601,13 @@ class Results(object): 'SELECT * FROM {0} WHERE entity_id=?'.format( self.model_class._flex_table ), - (row[b'id'],) + (row['id'],) ) cols = dict(row) values = dict((k, v) for (k, v) in cols.items() if not k[:4] == 'flex') - flex_values = dict((row[b'key'], row[b'value']) for row in flex_rows) + flex_values = dict((row['key'], row['value']) for row in flex_rows) # Construct the Python object obj = self.model_class._awaken(self.db, values, flex_values) @@ -586,6 +632,11 @@ class Results(object): return self._row_count def __nonzero__(self): + """Does this result contain any objects? + """ + return self.__bool__() + + def __bool__(self): """Does this result contain any objects? """ return bool(len(self)) @@ -602,10 +653,10 @@ class Results(object): it = iter(self) try: for i in range(n): - it.next() - return it.next() + next(it) + return next(it) except StopIteration: - raise IndexError('result index {0} out of range'.format(n)) + raise IndexError(u'result index {0} out of range'.format(n)) def get(self): """Return the first matching object, or None if no objects @@ -613,7 +664,7 @@ class Results(object): """ it = iter(self) try: - return it.next() + return next(it) except StopIteration: return None @@ -662,8 +713,18 @@ class Transaction(object): """Execute an SQL statement with substitution values and return the row ID of the last affected row. """ - cursor = self.db._connection().execute(statement, subvals) - return cursor.lastrowid + try: + cursor = self.db._connection().execute(statement, subvals) + return cursor.lastrowid + except sqlite3.OperationalError as e: + # In two specific cases, SQLite reports an error while accessing + # the underlying database file. We surface these exceptions as + # DBAccessError so the application can abort. + if e.args[0] in ("attempt to write a readonly database", + "unable to open database file"): + raise DBAccessError(e.args[0]) + else: + raise def script(self, statements): """Execute a string containing multiple SQL statements.""" @@ -678,8 +739,9 @@ class Database(object): """The Model subclasses representing tables in this database. """ - def __init__(self, path): + def __init__(self, path, timeout=5.0): self.path = path + self.timeout = timeout self._connections = {} self._tx_stacks = defaultdict(list) @@ -714,18 +776,36 @@ class Database(object): if thread_id in self._connections: return self._connections[thread_id] else: - # Make a new connection. - conn = sqlite3.connect( - self.path, - timeout=beets.config['timeout'].as_number(), - ) - - # Access SELECT results like dictionaries. - conn.row_factory = sqlite3.Row - + conn = self._create_connection() self._connections[thread_id] = conn return conn + def _create_connection(self): + """Create a SQLite connection to the underlying database. + + Makes a new connection every time. If you need to configure the + connection settings (e.g., add custom functions), override this + method. + """ + # Make a new connection. The `sqlite3` module can't use + # bytestring paths here on Python 3, so we need to + # provide a `str` using `py3_path`. + conn = sqlite3.connect( + py3_path(self.path), timeout=self.timeout + ) + + # Access SELECT results like dictionaries. + conn.row_factory = sqlite3.Row + return conn + + def _close(self): + """Close the all connections to the underlying SQLite database + from all threads. This does not render the database object + unusable; new connections can still be opened on demand. + """ + with self._shared_map_lock: + self._connections.clear() + @contextlib.contextmanager def _tx_stack(self): """A context manager providing access to the current thread's diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index c04e734b8..8fb64e206 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,14 +15,18 @@ """The Query type hierarchy for DBCore. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import re from operator import mul from beets import util from datetime import datetime, timedelta import unicodedata +from functools import reduce +import six + +if not six.PY2: + buffer = memoryview # sqlite won't accept memoryview in python 2 class ParsingError(ValueError): @@ -35,34 +40,36 @@ class InvalidQueryError(ParsingError): The query should be a unicode string or a list, which will be space-joined. """ + def __init__(self, query, explanation): if isinstance(query, list): query = " ".join(query) - message = "'{0}': {1}".format(query, explanation) + message = u"'{0}': {1}".format(query, explanation) super(InvalidQueryError, self).__init__(message) -class InvalidQueryArgumentTypeError(ParsingError): +class InvalidQueryArgumentValueError(ParsingError): """Represent a query argument that could not be converted as expected. It exists to be caught in upper stack levels so a meaningful (i.e. with the query) InvalidQueryError can be raised. """ + def __init__(self, what, expected, detail=None): - message = "'{0}' is not {1}".format(what, expected) + message = u"'{0}' is not {1}".format(what, expected) if detail: - message = "{0}: {1}".format(message, detail) - super(InvalidQueryArgumentTypeError, self).__init__(message) + message = u"{0}: {1}".format(message, detail) + super(InvalidQueryArgumentValueError, self).__init__(message) class Query(object): """An abstract class representing a query into the item database. """ + def clause(self): """Generate an SQLite expression implementing the query. - Return a clause string, a sequence of substitution values for - the clause, and a Query object representing the "remainder" - Returns (clause, subvals) where clause is a valid sqlite + + Return (clause, subvals) where clause is a valid sqlite WHERE clause implementing the query and subvals is a list of items to be substituted for ?s in the clause. """ @@ -91,6 +98,7 @@ class FieldQuery(Query): string. Subclasses may also provide `col_clause` to implement the same matching functionality in SQLite. """ + def __init__(self, field, pattern, fast=True): self.field = field self.pattern = pattern @@ -130,6 +138,7 @@ class FieldQuery(Query): class MatchQuery(FieldQuery): """A query that looks for exact matches in an item field.""" + def col_clause(self): return self.field + " = ?", [self.pattern] @@ -139,6 +148,7 @@ class MatchQuery(FieldQuery): class NoneQuery(FieldQuery): + """A query that checks whether a field is null.""" def __init__(self, field, fast=True): super(NoneQuery, self).__init__(field, None, fast) @@ -147,9 +157,9 @@ class NoneQuery(FieldQuery): return self.field + " IS NULL", () @classmethod - def match(self, item): + def match(cls, item): try: - return item[self.field] is None + return item[cls.field] is None except KeyError: return True @@ -161,6 +171,7 @@ class StringFieldQuery(FieldQuery): """A FieldQuery that converts values to strings before matching them. """ + @classmethod def value_match(cls, pattern, value): """Determine whether the value matches the pattern. The value @@ -178,11 +189,12 @@ class StringFieldQuery(FieldQuery): class SubstringQuery(StringFieldQuery): """A query that matches a substring in a specific item field.""" + def col_clause(self): pattern = (self.pattern - .replace('\\', '\\\\') - .replace('%', '\\%') - .replace('_', '\\_')) + .replace('\\', '\\\\') + .replace('%', '\\%') + .replace('_', '\\_')) search = '%' + pattern + '%' clause = self.field + " like ? escape '\\'" subvals = [search] @@ -200,6 +212,7 @@ class RegexpQuery(StringFieldQuery): Raises InvalidQueryError when the pattern is not a valid regular expression. """ + def __init__(self, field, pattern, fast=True): super(RegexpQuery, self).__init__(field, pattern, fast) pattern = self._normalize(pattern) @@ -207,9 +220,9 @@ class RegexpQuery(StringFieldQuery): self.pattern = re.compile(self.pattern) except re.error as exc: # Invalid regular expression. - raise InvalidQueryArgumentTypeError(pattern, - "a regular expression", - format(exc)) + raise InvalidQueryArgumentValueError(pattern, + u"a regular expression", + format(exc)) @staticmethod def _normalize(s): @@ -227,9 +240,10 @@ class BooleanQuery(MatchQuery): """Matches a boolean field. Pattern should either be a boolean or a string reflecting a boolean. """ + def __init__(self, field, pattern, fast=True): super(BooleanQuery, self).__init__(field, pattern, fast) - if isinstance(pattern, basestring): + if isinstance(pattern, six.string_types): self.pattern = util.str2bool(pattern) self.pattern = int(self.pattern) @@ -240,17 +254,16 @@ class BytesQuery(MatchQuery): `unicode` equivalently in Python 2. Always use this query instead of `MatchQuery` when matching on BLOB values. """ + def __init__(self, field, pattern): super(BytesQuery, self).__init__(field, pattern) - # Use a buffer representation of the pattern for SQLite + # Use a buffer/memoryview representation of the pattern for SQLite # matching. This instructs SQLite to treat the blob as binary # rather than encoded Unicode. - if isinstance(self.pattern, basestring): - # Implicitly coerce Unicode strings to their bytes - # equivalents. - if isinstance(self.pattern, unicode): - self.pattern = self.pattern.encode('utf8') + if isinstance(self.pattern, (six.text_type, bytes)): + if isinstance(self.pattern, six.text_type): + self.pattern = self.pattern.encode('utf-8') self.buf_pattern = buffer(self.pattern) elif isinstance(self.pattern, buffer): self.buf_pattern = self.pattern @@ -268,6 +281,7 @@ class NumericQuery(FieldQuery): Raises InvalidQueryError when the pattern does not represent an int or a float. """ + def _convert(self, s): """Convert a string to a numeric type (float or int). @@ -283,7 +297,7 @@ class NumericQuery(FieldQuery): try: return float(s) except ValueError: - raise InvalidQueryArgumentTypeError(s, "an int or a float") + raise InvalidQueryArgumentValueError(s, u"an int or a float") def __init__(self, field, pattern, fast=True): super(NumericQuery, self).__init__(field, pattern, fast) @@ -304,7 +318,7 @@ class NumericQuery(FieldQuery): if self.field not in item: return False value = item[self.field] - if isinstance(value, basestring): + if isinstance(value, six.string_types): value = self._convert(value) if self.point is not None: @@ -328,13 +342,14 @@ class NumericQuery(FieldQuery): elif self.rangemax is not None: return u'{0} <= ?'.format(self.field), (self.rangemax,) else: - return '1', () + return u'1', () class CollectionQuery(Query): """An abstract query class that aggregates other queries. Can be indexed like a list to access the sub-queries. """ + def __init__(self, subqueries=()): self.subqueries = subqueries @@ -353,7 +368,7 @@ class CollectionQuery(Query): return item in self.subqueries def clause_with_joiner(self, joiner): - """Returns a clause created by joining together the clauses of + """Return a clause created by joining together the clauses of all subqueries with the string joiner (padded by spaces). """ clause_parts = [] @@ -369,7 +384,7 @@ class CollectionQuery(Query): return clause, subvals def __repr__(self): - return "{0.__class__.__name__}({0.subqueries})".format(self) + return "{0.__class__.__name__}({0.subqueries!r})".format(self) def __eq__(self, other): return super(CollectionQuery, self).__eq__(other) and \ @@ -387,6 +402,7 @@ class AnyFieldQuery(CollectionQuery): any field. The individual field query class is provided to the constructor. """ + def __init__(self, pattern, fields, cls): self.pattern = pattern self.fields = fields @@ -407,7 +423,7 @@ class AnyFieldQuery(CollectionQuery): return False def __repr__(self): - return ("{0.__class__.__name__}({0.pattern!r}, {0.fields}, " + return ("{0.__class__.__name__}({0.pattern!r}, {0.fields!r}, " "{0.query_class.__name__})".format(self)) def __eq__(self, other): @@ -422,6 +438,7 @@ class MutableCollectionQuery(CollectionQuery): """A collection query whose subqueries may be modified after the query is initialized. """ + def __setitem__(self, key, value): self.subqueries[key] = value @@ -431,6 +448,7 @@ class MutableCollectionQuery(CollectionQuery): class AndQuery(MutableCollectionQuery): """A conjunction of a list of other queries.""" + def clause(self): return self.clause_with_joiner('and') @@ -440,6 +458,7 @@ class AndQuery(MutableCollectionQuery): class OrQuery(MutableCollectionQuery): """A conjunction of a list of other queries.""" + def clause(self): return self.clause_with_joiner('or') @@ -447,8 +466,40 @@ class OrQuery(MutableCollectionQuery): return any([q.match(item) for q in self.subqueries]) +class NotQuery(Query): + """A query that matches the negation of its `subquery`, as a shorcut for + performing `not(subquery)` without using regular expressions. + """ + + def __init__(self, subquery): + self.subquery = subquery + + def clause(self): + clause, subvals = self.subquery.clause() + if clause: + return 'not ({0})'.format(clause), subvals + else: + # If there is no clause, there is nothing to negate. All the logic + # is handled by match() for slow queries. + return clause, subvals + + def match(self, item): + return not self.subquery.match(item) + + def __repr__(self): + return "{0.__class__.__name__}({0.subquery!r})".format(self) + + def __eq__(self, other): + return super(NotQuery, self).__eq__(other) and \ + self.subquery == other.subquery + + def __hash__(self): + return hash(('not', hash(self.subquery))) + + class TrueQuery(Query): """A query that always matches.""" + def clause(self): return '1', () @@ -458,6 +509,7 @@ class TrueQuery(Query): class FalseQuery(Query): """A query that never matches.""" + def clause(self): return '0', () @@ -471,9 +523,13 @@ def _to_epoch_time(date): """Convert a `datetime` object to an integer number of seconds since the (local) Unix epoch. """ - epoch = datetime.fromtimestamp(0) - delta = date - epoch - return int(delta.total_seconds()) + if hasattr(date, 'timestamp'): + # The `timestamp` method exists on Python 3.3+. + return int(date.timestamp()) + else: + epoch = datetime.fromtimestamp(0) + delta = date - epoch + return int(delta.total_seconds()) def _parse_periods(pattern): @@ -497,35 +553,81 @@ class Period(object): instants of time during January 2014. """ - precisions = ('year', 'month', 'day') - date_formats = ('%Y', '%Y-%m', '%Y-%m-%d') + precisions = ('year', 'month', 'day', 'hour', 'minute', 'second') + date_formats = ( + ('%Y',), # year + ('%Y-%m',), # month + ('%Y-%m-%d',), # day + ('%Y-%m-%dT%H', '%Y-%m-%d %H'), # hour + ('%Y-%m-%dT%H:%M', '%Y-%m-%d %H:%M'), # minute + ('%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S') # second + ) + relative_units = {'y': 365, 'm': 30, 'w': 7, 'd': 1} + relative_re = '(?P[+|-]?)(?P[0-9]+)' + \ + '(?P[y|m|w|d])' def __init__(self, date, precision): """Create a period with the given date (a `datetime` object) and - precision (a string, one of "year", "month", or "day"). + precision (a string, one of "year", "month", "day", "hour", "minute", + or "second"). """ if precision not in Period.precisions: - raise ValueError('Invalid precision {0}'.format(precision)) + raise ValueError(u'Invalid precision {0}'.format(precision)) self.date = date self.precision = precision @classmethod def parse(cls, string): """Parse a date and return a `Period` object or `None` if the - string is empty. + string is empty, or raise an InvalidQueryArgumentValueError if + the string cannot be parsed to a date. + + The date may be absolute or relative. Absolute dates look like + `YYYY`, or `YYYY-MM-DD`, or `YYYY-MM-DD HH:MM:SS`, etc. Relative + dates have three parts: + + - Optionally, a ``+`` or ``-`` sign indicating the future or the + past. The default is the future. + - A number: how much to add or subtract. + - A letter indicating the unit: days, weeks, months or years + (``d``, ``w``, ``m`` or ``y``). A "month" is exactly 30 days + and a "year" is exactly 365 days. """ + + def find_date_and_format(string): + for ord, format in enumerate(cls.date_formats): + for format_option in format: + try: + date = datetime.strptime(string, format_option) + return date, ord + except ValueError: + # Parsing failed. + pass + return (None, None) + if not string: return None - ordinal = string.count('-') - if ordinal >= len(cls.date_formats): - # Too many components. - return None - date_format = cls.date_formats[ordinal] - try: - date = datetime.strptime(string, date_format) - except ValueError: - # Parsing failed. - return None + + # Check for a relative date. + match_dq = re.match(cls.relative_re, string) + if match_dq: + sign = match_dq.group('sign') + quantity = match_dq.group('quantity') + timespan = match_dq.group('timespan') + + # Add or subtract the given amount of time from the current + # date. + multiplier = -1 if sign == '-' else 1 + days = cls.relative_units[timespan] + date = datetime.now() + \ + timedelta(days=int(quantity) * days) * multiplier + return cls(date, cls.precisions[5]) + + # Check for an absolute date. + date, ordinal = find_date_and_format(string) + if date is None: + raise InvalidQueryArgumentValueError(string, + 'a valid date/time string') precision = cls.precisions[ordinal] return cls(date, precision) @@ -544,8 +646,14 @@ class Period(object): return date.replace(year=date.year + 1, month=1) elif 'day' == precision: return date + timedelta(days=1) + elif 'hour' == precision: + return date + timedelta(hours=1) + elif 'minute' == precision: + return date + timedelta(minutes=1) + elif 'second' == precision: + return date + timedelta(seconds=1) else: - raise ValueError('unhandled precision {0}'.format(precision)) + raise ValueError(u'unhandled precision {0}'.format(precision)) class DateInterval(object): @@ -557,7 +665,7 @@ class DateInterval(object): def __init__(self, start, end): if start is not None and end is not None and not start < end: - raise ValueError("start date {0} is not before end date {1}" + raise ValueError(u"start date {0} is not before end date {1}" .format(start, end)) self.start = start self.end = end @@ -578,7 +686,7 @@ class DateInterval(object): return True def __str__(self): - return'[{0}, {1})'.format(self.start, self.end) + return '[{0}, {1})'.format(self.start, self.end) class DateQuery(FieldQuery): @@ -590,14 +698,17 @@ class DateQuery(FieldQuery): The value of a date field can be matched against a date interval by using an ellipsis interval syntax similar to that of NumericQuery. """ + def __init__(self, field, pattern, fast=True): super(DateQuery, self).__init__(field, pattern, fast) start, end = _parse_periods(pattern) self.interval = DateInterval.from_periods(start, end) def match(self, item): + if self.field not in item: + return False timestamp = float(item[self.field]) - date = datetime.utcfromtimestamp(timestamp) + date = datetime.fromtimestamp(timestamp) return self.interval.contains(date) _clause_tmpl = "{0} {1} ?" @@ -623,6 +734,34 @@ class DateQuery(FieldQuery): return clause, subvals +class DurationQuery(NumericQuery): + """NumericQuery that allow human-friendly (M:SS) time interval formats. + + Converts the range(s) to a float value, and delegates on NumericQuery. + + Raises InvalidQueryError when the pattern does not represent an int, float + or M:SS time interval. + """ + + def _convert(self, s): + """Convert a M:SS or numeric string to a float. + + Return None if `s` is empty. + Raise an InvalidQueryError if the string cannot be converted. + """ + if not s: + return None + try: + return util.raw_seconds_short(s) + except ValueError: + try: + return float(s) + except ValueError: + raise InvalidQueryArgumentValueError( + s, + u"a M:SS string or a float") + + # Sorting. class Sort(object): @@ -712,7 +851,7 @@ class MultipleSort(Sort): return items def __repr__(self): - return u'MultipleSort({0})'.format(repr(self.sorts)) + return 'MultipleSort({!r})'.format(self.sorts) def __hash__(self): return hash(tuple(self.sorts)) @@ -726,6 +865,7 @@ class FieldSort(Sort): """An abstract sort criterion that orders by a specific field (of any kind). """ + def __init__(self, field, ascending=True, case_insensitive=True): self.field = field self.ascending = ascending @@ -737,15 +877,15 @@ class FieldSort(Sort): # attributes with different types without falling over. def key(item): - field_val = getattr(item, self.field) - if self.case_insensitive and isinstance(field_val, unicode): + field_val = item.get(self.field, '') + if self.case_insensitive and isinstance(field_val, six.text_type): field_val = field_val.lower() return field_val return sorted(objs, key=key, reverse=not self.ascending) def __repr__(self): - return u'<{0}: {1}{2}>'.format( + return '<{0}: {1}{2}>'.format( type(self).__name__, self.field, '+' if self.ascending else '-', @@ -763,6 +903,7 @@ class FieldSort(Sort): class FixedFieldSort(FieldSort): """Sort object to sort on a fixed field. """ + def order_clause(self): order = "ASC" if self.ascending else "DESC" if self.case_insensitive: @@ -779,13 +920,15 @@ class SlowFieldSort(FieldSort): """A sort criterion by some model field other than a fixed field: i.e., a computed or flexible field. """ + def is_slow(self): return True class NullSort(Sort): """No sorting. Leave results unsorted.""" - def sort(items): + + def sort(self, items): return items def __nonzero__(self): diff --git a/beets/dbcore/queryparse.py b/beets/dbcore/queryparse.py index 89b7bd64a..bc9cc77ec 100644 --- a/beets/dbcore/queryparse.py +++ b/beets/dbcore/queryparse.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -23,6 +24,8 @@ import beets PARSE_QUERY_PART_REGEX = re.compile( # Non-capturing optional segment for the keyword. + r'(-|\^)?' # Negation prefixes. + r'(?:' r'(\S+?)' # The field key. r'(? (None, 'stapler', SubstringQuery) - 'color:red' -> ('color', 'red', SubstringQuery) - ':^Quiet' -> (None, '^Quiet', RegexpQuery) - 'color::b..e' -> ('color', 'b..e', RegexpQuery) + The function returns a tuple consisting of: + - The field name: a string or None if it's not present. + - The pattern, a string. + - The query class to use, which inherits from the base + :class:`Query` type. + - A negation flag, a bool. - Prefixes may be "escaped" with a backslash to disable the keying - behavior. + The three optional parameters determine which query class is used (i.e., + the third return value). They are: + - `query_classes`, which maps field names to query classes. These + are used when no explicit prefix is present. + - `prefixes`, which maps prefix strings to query classes. + - `default_class`, the fallback when neither the field nor a prefix + indicates a query class. + + So the precedence for determining which query class to return is: + prefix, followed by field, and finally the default. + + For example, assuming the `:` prefix is used for `RegexpQuery`: + - `'stapler'` -> `(None, 'stapler', SubstringQuery, False)` + - `'color:red'` -> `('color', 'red', SubstringQuery, False)` + - `':^Quiet'` -> `(None, '^Quiet', RegexpQuery, False)`, because + the `^` follows the `:` + - `'color::b..e'` -> `('color', 'b..e', RegexpQuery, False)` + - `'-color:red'` -> `('color', 'red', SubstringQuery, True)` """ + # Apply the regular expression and extract the components. part = part.strip() match = PARSE_QUERY_PART_REGEX.match(part) - assert match # Regex should always match. - key = match.group(1) - term = match.group(2).replace('\:', ':') + assert match # Regex should always match + negate = bool(match.group(1)) + key = match.group(2) + term = match.group(3).replace('\:', ':') - # Match the search term against the list of prefixes. + # Check whether there's a prefix in the query and use the + # corresponding query type. for pre, query_class in prefixes.items(): if term.startswith(pre): - return key, term[len(pre):], query_class + return key, term[len(pre):], query_class, negate - # No matching prefix: use type-based or fallback/default query. + # No matching prefix, so use either the query class determined by + # the field or the default as a fallback. query_class = query_classes.get(key, default_class) - return key, term, query_class + return key, term, query_class, negate def construct_query_part(model_cls, prefixes, query_part): - """Create a query from a single query component, `query_part`, for - querying instances of `model_cls`. Return a `Query` instance. + """Parse a *query part* string and return a :class:`Query` object. + + :param model_cls: The :class:`Model` class that this is a query for. + This is used to determine the appropriate query types for the + model's fields. + :param prefixes: A map from prefix strings to :class:`Query` types. + :param query_part: The string to parse. + + See the documentation for `parse_query_part` for more information on + query part syntax. """ - # Shortcut for empty query parts. + # A shortcut for empty query parts. if not query_part: return query.TrueQuery() - # Get the query classes for each possible field. + # Use `model_cls` to build up a map from field names to `Query` + # classes. query_classes = {} for k, t in itertools.chain(model_cls._fields.items(), model_cls._types.items()): query_classes[k] = t.query # Parse the string. - key, pattern, query_class = \ + key, pattern, query_class, negate = \ parse_query_part(query_part, query_classes, prefixes) - # No key specified. + # If there's no key (field name) specified, this is a "match + # anything" query. if key is None: if issubclass(query_class, query.FieldQuery): # The query type matches a specific field, but none was # specified. So we use a version of the query that matches # any field. - return query.AnyFieldQuery(pattern, model_cls._search_fields, - query_class) + q = query.AnyFieldQuery(pattern, model_cls._search_fields, + query_class) + if negate: + return query.NotQuery(q) + else: + return q else: - # Other query type. - return query_class(pattern) + # Non-field query type. + if negate: + return query.NotQuery(query_class(pattern)) + else: + return query_class(pattern) + # Otherwise, this must be a `FieldQuery`. Use the field name to + # construct the query object. key = key.lower() - return query_class(key.lower(), pattern, key in model_cls._fields) + q = query_class(key.lower(), pattern, key in model_cls._fields) + if negate: + return query.NotQuery(q) + return q def query_from_strings(query_cls, model_cls, prefixes, query_parts): diff --git a/beets/dbcore/types.py b/beets/dbcore/types.py index 7f3b2e39e..b909904bd 100644 --- a/beets/dbcore/types.py +++ b/beets/dbcore/types.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,11 +15,14 @@ """Representation of type information for DBCore model fields. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from . import query from beets.util import str2bool +import six + +if not six.PY2: + buffer = memoryview # sqlite won't accept memoryview in python 2 # Abstract base. @@ -37,7 +41,7 @@ class Type(object): """The `Query` subclass to be used when querying the field. """ - model_type = unicode + model_type = six.text_type """The Python type that is used to represent the value in the model. The model is guaranteed to return a value of this type if the field @@ -61,9 +65,9 @@ class Type(object): if value is None: value = u'' if isinstance(value, bytes): - value = value.decode('utf8', 'ignore') + value = value.decode('utf-8', 'ignore') - return unicode(value) + return six.text_type(value) def parse(self, string): """Parse a (possibly human-written) string and return the @@ -97,12 +101,12 @@ class Type(object): https://docs.python.org/2/library/sqlite3.html#sqlite-and-python-types Flexible fields have the type affinity `TEXT`. This means the - `sql_value` is either a `buffer` or a `unicode` object` and the - method must handle these in addition. + `sql_value` is either a `buffer`/`memoryview` or a `unicode` object` + and the method must handle these in addition. """ if isinstance(sql_value, buffer): - sql_value = bytes(sql_value).decode('utf8', 'ignore') - if isinstance(sql_value, unicode): + sql_value = bytes(sql_value).decode('utf-8', 'ignore') + if isinstance(sql_value, six.text_type): return self.parse(sql_value) else: return self.normalize(sql_value) @@ -194,7 +198,7 @@ class Boolean(Type): model_type = bool def format(self, value): - return unicode(bool(value)) + return six.text_type(bool(value)) def parse(self, string): return str2bool(string) diff --git a/beets/importer.py b/beets/importer.py index 844b66086..4e4084eec 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function """Provides the basic, interface-agnostic workflow for importing and autotagging music files. @@ -37,18 +37,19 @@ from beets import dbcore from beets import plugins from beets import util from beets import config -from beets.util import pipeline, sorted_walk, ancestry +from beets.util import pipeline, sorted_walk, ancestry, MoveOperation from beets.util import syspath, normpath, displayable_path from enum import Enum from beets import mediafile action = Enum('action', - ['SKIP', 'ASIS', 'TRACKS', 'MANUAL', 'APPLY', 'MANUAL_ID', - 'ALBUMS']) + ['SKIP', 'ASIS', 'TRACKS', 'APPLY', 'ALBUMS', 'RETAG']) +# The RETAG action represents "don't apply any match, but do record +# new metadata". It's not reachable via the standard command prompt but +# can be used by plugins. QUEUE_SIZE = 128 SINGLE_ARTIST_THRESH = 0.25 -VARIOUS_ARTISTS = u'Various Artists' PROGRESS_KEY = 'tagprogress' HISTORY_KEY = 'taghistory' @@ -67,7 +68,7 @@ class ImportAbort(Exception): def _open_state(): """Reads the state file, returning a dictionary.""" try: - with open(config['statefile'].as_filename()) as f: + with open(config['statefile'].as_filename(), 'rb') as f: return pickle.load(f) except Exception as exc: # The `pickle` module can emit all sorts of exceptions during @@ -81,7 +82,7 @@ def _open_state(): def _save_state(state): """Writes the state dictionary out to disk.""" try: - with open(config['statefile'].as_filename(), 'w') as f: + with open(config['statefile'].as_filename(), 'wb') as f: pickle.dump(state, f) except IOError as exc: log.error(u'state file could not be written: {0}', exc) @@ -186,12 +187,13 @@ class ImportSession(object): self.logger = self._setup_logging(loghandler) self.paths = paths self.query = query - self.seen_idents = set() self._is_resuming = dict() + self._merged_items = set() + self._merged_dirs = set() # Normalize the paths. if self.paths: - self.paths = map(normpath, self.paths) + self.paths = list(map(normpath, self.paths)) def _setup_logging(self, loghandler): logger = logging.getLogger(__name__) @@ -220,13 +222,19 @@ class ImportSession(object): iconfig['resume'] = False iconfig['incremental'] = False - # Copy, move, and link are mutually exclusive. + # Copy, move, link, and hardlink are mutually exclusive. if iconfig['move']: iconfig['copy'] = False iconfig['link'] = False + iconfig['hardlink'] = False elif iconfig['link']: iconfig['copy'] = False iconfig['move'] = False + iconfig['hardlink'] = False + elif iconfig['hardlink']: + iconfig['copy'] = False + iconfig['move'] = False + iconfig['link'] = False # Only delete when copying. if not iconfig['copy']: @@ -249,17 +257,17 @@ class ImportSession(object): if duplicate: # Duplicate: log all three choices (skip, keep both, and trump). if task.should_remove_duplicates: - self.tag_log('duplicate-replace', paths) + self.tag_log(u'duplicate-replace', paths) elif task.choice_flag in (action.ASIS, action.APPLY): - self.tag_log('duplicate-keep', paths) + self.tag_log(u'duplicate-keep', paths) elif task.choice_flag is (action.SKIP): - self.tag_log('duplicate-skip', paths) + self.tag_log(u'duplicate-skip', paths) else: # Non-duplicate: log "skip" and "asis" choices. if task.choice_flag is action.ASIS: - self.tag_log('asis', paths) + self.tag_log(u'asis', paths) elif task.choice_flag is action.SKIP: - self.tag_log('skip', paths) + self.tag_log(u'skip', paths) def should_resume(self, path): raise NotImplementedError @@ -294,14 +302,19 @@ class ImportSession(object): # Split directory tasks into one task for each album. stages += [group_albums(self)] + # These stages either talk to the user to get a decision or, + # in the case of a non-autotagged import, just choose to + # import everything as-is. In *both* cases, these stages + # also add the music to the library database, so later + # stages need to read and write data from there. if self.config['autotag']: stages += [lookup_candidates(self), user_query(self)] else: stages += [import_asis(self)] - stages += [apply_choices(self)] - # Plugin stages. + for stage_func in plugins.early_import_stages(): + stages.append(plugin_stage(self, stage_func)) for stage_func in plugins.import_stages(): stages.append(plugin_stage(self, stage_func)) @@ -327,7 +340,7 @@ class ImportSession(object): been imported in a previous session. """ if self.is_resuming(toppath) \ - and all(map(lambda p: progress_element(toppath, p), paths)): + and all([progress_element(toppath, p) for p in paths]): return True if self.config['incremental'] \ and tuple(paths) in self.history_dirs: @@ -341,6 +354,24 @@ class ImportSession(object): self._history_dirs = history_get() return self._history_dirs + def already_merged(self, paths): + """Returns true if all the paths being imported were part of a merge + during previous tasks. + """ + for path in paths: + if path not in self._merged_items \ + and path not in self._merged_dirs: + return False + return True + + def mark_merged(self, paths): + """Mark paths and directories as merged for future reimport tasks. + """ + self._merged_items.update(paths) + dirs = set([os.path.dirname(path) if os.path.isfile(path) else path + for path in paths]) + self._merged_dirs.update(dirs) + def is_resuming(self, toppath): """Return `True` if user wants to resume import of this path. @@ -358,8 +389,8 @@ class ImportSession(object): # Either accept immediately or prompt for input to decide. if self.want_resume is True or \ self.should_resume(toppath): - log.warn(u'Resuming interrupted import of {0}', - util.displayable_path(toppath)) + log.warning(u'Resuming interrupted import of {0}', + util.displayable_path(toppath)) self._is_resuming[toppath] = True else: # Clear progress; we're starting from the top. @@ -410,7 +441,7 @@ class ImportTask(BaseImportTask): from the `candidates` list. * `find_duplicates()` Returns a list of albums from `lib` with the - same artist and album name as the task. + same artist and album name as the task. * `apply_metadata()` Sets the attributes of the items from the task's `match` attribute. @@ -420,6 +451,9 @@ class ImportTask(BaseImportTask): * `manipulate_files()` Copy, move, and write files depending on the session configuration. + * `set_fields()` Sets the fields given at CLI or configuration to + the specified values. + * `finalize()` Update the import progress and cleanup the file system. """ @@ -431,16 +465,18 @@ class ImportTask(BaseImportTask): self.candidates = [] self.rec = None self.should_remove_duplicates = False + self.should_merge_duplicates = False self.is_album = True + self.search_ids = [] # user-supplied candidate IDs. def set_choice(self, choice): """Given an AlbumMatch or TrackMatch object or an action constant, indicates that an action has been selected for this task. """ # Not part of the task structure: - assert choice not in (action.MANUAL, action.MANUAL_ID) assert choice != action.APPLY # Only used internally. - if choice in (action.SKIP, action.ASIS, action.TRACKS, action.ALBUMS): + if choice in (action.SKIP, action.ASIS, action.TRACKS, action.ALBUMS, + action.RETAG): self.choice_flag = choice self.match = None else: @@ -476,10 +512,10 @@ class ImportTask(BaseImportTask): """Returns identifying metadata about the current choice. For albums, this is an (artist, album) pair. For items, this is (artist, title). May only be called when the choice flag is ASIS - (in which case the data comes from the files' current metadata) - or APPLY (data comes from the choice). + or RETAG (in which case the data comes from the files' current + metadata) or APPLY (data comes from the choice). """ - if self.choice_flag is action.ASIS: + if self.choice_flag in (action.ASIS, action.RETAG): return (self.cur_artist, self.cur_album) elif self.choice_flag is action.APPLY: return (self.match.info.artist, self.match.info.album) @@ -490,16 +526,20 @@ class ImportTask(BaseImportTask): If the tasks applies an album match the method only returns the matched items. """ - if self.choice_flag == action.ASIS: + if self.choice_flag in (action.ASIS, action.RETAG): return list(self.items) elif self.choice_flag == action.APPLY: - return self.match.mapping.keys() + return list(self.match.mapping.keys()) else: assert False def apply_metadata(self): """Copy metadata from match info to the items. """ + if config['import']['from_scratch']: + for item in self.match.mapping: + item.clear() + autotag.apply_metadata(self.match.info, self.match.mapping) def duplicate_items(self, lib): @@ -520,13 +560,29 @@ class ImportTask(BaseImportTask): util.prune_dirs(os.path.dirname(item.path), lib.directory) + def set_fields(self): + """Sets the fields given at CLI or configuration to the specified + values. + """ + for field, view in config['import']['set_fields'].items(): + value = view.get() + log.debug(u'Set field {1}={2} for {0}', + displayable_path(self.paths), + field, + value) + self.album[field] = value + self.album.store() + def finalize(self, session): """Save progress, clean up files, and emit plugin event. """ # Update progress. if session.want_resume: self.save_progress() - if session.config['incremental']: + if session.config['incremental'] and not ( + # Should we skip recording to incremental list? + self.skip and session.config['incremental_skip_later'] + ): self.save_history() self.cleanup(copy=session.config['copy'], @@ -577,14 +633,16 @@ class ImportTask(BaseImportTask): return tasks def lookup_candidates(self): - """Retrieve and store candidates for this album. + """Retrieve and store candidates for this album. User-specified + candidate IDs are stored in self.search_ids: if present, the + initial lookup is restricted to only those IDs. """ - artist, album, candidates, recommendation = \ - autotag.tag_album(self.items) + artist, album, prop = \ + autotag.tag_album(self.items, search_ids=self.search_ids) self.cur_artist = artist self.cur_album = album - self.candidates = candidates - self.rec = recommendation + self.candidates = prop.candidates + self.rec = prop.recommendation def find_duplicates(self, lib): """Return a list of albums from `lib` with the same artist and @@ -604,15 +662,19 @@ class ImportTask(BaseImportTask): )) for album in lib.albums(duplicate_query): - # Check whether the album is identical in contents, in which - # case it is not a duplicate (will be replaced). + # Check whether the album paths are all present in the task + # i.e. album is being completely re-imported by the task, + # in which case it is not a duplicate (will be replaced). album_paths = set(i.path for i in album.items()) - if album_paths != task_paths: + if not (album_paths <= task_paths): duplicates.append(album) return duplicates def align_album_level_fields(self): - """Make the some album fields equal across `self.items` + """Make some album fields equal across `self.items`. For the + RETAG action, we assume that the responsible for returning it + (ie. a plugin) always ensures that the first item contains + valid data on the relevant fields. """ changes = {} @@ -629,10 +691,10 @@ class ImportTask(BaseImportTask): changes['comp'] = False else: # VA. - changes['albumartist'] = VARIOUS_ARTISTS + changes['albumartist'] = config['va_name'].as_str() changes['comp'] = True - elif self.choice_flag == action.APPLY: + elif self.choice_flag in (action.APPLY, action.RETAG): # Applying autotagged metadata. Just get AA from the first # item. if not self.items[0].albumartist: @@ -644,20 +706,28 @@ class ImportTask(BaseImportTask): for item in self.items: item.update(changes) - def manipulate_files(self, move=False, copy=False, write=False, - link=False, session=None): + def manipulate_files(self, operation=None, write=False, session=None): + """ Copy, move, link or hardlink (depending on `operation`) the files + as well as write metadata. + + `operation` should be an instance of `util.MoveOperation`. + + If `write` is `True` metadata is written to the files. + """ + items = self.imported_items() # Save the original paths of all items for deletion and pruning # in the next step (finalization). self.old_paths = [item.path for item in items] for item in items: - if move or copy or link: + if operation is not None: # In copy and link modes, treat re-imports specially: # move in-library files. (Out-of-library files are # copied/moved as usual). old_path = item.path - if (copy or link) and self.replaced_items[item] and \ - session.lib.directory in util.ancestry(old_path): + if (operation != MoveOperation.MOVE + and self.replaced_items[item] + and session.lib.directory in util.ancestry(old_path)): item.move() # We moved the item, so remove the # now-nonexistent file from old_paths. @@ -665,9 +735,9 @@ class ImportTask(BaseImportTask): else: # A normal import. Just copy files and keep track of # old paths. - item.move(copy, link) + item.move(operation) - if write and self.apply: + if write and (self.apply or self.choice_flag == action.RETAG): item.try_write() with session.lib.transaction(): @@ -716,6 +786,7 @@ class ImportTask(BaseImportTask): if replaced_album: self.album.added = replaced_album.added self.album.update(replaced_album._values_flex) + self.album.artpath = replaced_album.artpath self.album.store() log.debug( u'Reimported album: added {0}, flexible ' @@ -801,8 +872,8 @@ class SingletonImportTask(ImportTask): self.paths = [item.path] def chosen_ident(self): - assert self.choice_flag in (action.ASIS, action.APPLY) - if self.choice_flag is action.ASIS: + assert self.choice_flag in (action.ASIS, action.APPLY, action.RETAG) + if self.choice_flag in (action.ASIS, action.RETAG): return (self.item.artist, self.item.title) elif self.choice_flag is action.APPLY: return (self.match.info.artist, self.match.info.title) @@ -818,9 +889,9 @@ class SingletonImportTask(ImportTask): plugins.send('item_imported', lib=lib, item=item) def lookup_candidates(self): - candidates, recommendation = autotag.tag_item(self.item) - self.candidates = candidates - self.rec = recommendation + prop = autotag.tag_item(self.item, search_ids=self.search_ids) + self.candidates = prop.candidates + self.rec = prop.recommendation def find_duplicates(self, lib): """Return a list of items from `lib` that have the same artist @@ -861,6 +932,19 @@ class SingletonImportTask(ImportTask): def reload(self): self.item.load() + def set_fields(self): + """Sets the fields given at CLI or configuration to the specified + values. + """ + for field, view in config['import']['set_fields'].items(): + value = view.get() + log.debug(u'Set field {1}={2} for {0}', + displayable_path(self.paths), + field, + value) + self.item[field] = value + self.item.store() + # FIXME The inheritance relationships are inverted. This is why there # are so many methods which pass. More responsibility should be delegated to @@ -931,7 +1015,7 @@ class ArchiveImportTask(SentinelImportTask): return False for path_test, _ in cls.handlers(): - if path_test(path): + if path_test(util.py3_path(path)): return True return False @@ -972,12 +1056,12 @@ class ArchiveImportTask(SentinelImportTask): `toppath` to that directory. """ for path_test, handler_class in self.handlers(): - if path_test(self.toppath): + if path_test(util.py3_path(self.toppath)): break try: extract_to = mkdtemp() - archive = handler_class(self.toppath, mode='r') + archive = handler_class(util.py3_path(self.toppath), mode='r') archive.extractall(extract_to) finally: archive.close() @@ -1135,8 +1219,8 @@ class ImportTaskFactory(object): if not (self.session.config['move'] or self.session.config['copy']): - log.warn(u"Archive importing requires either " - "'copy' or 'move' to be enabled.") + log.warning(u"Archive importing requires either " + u"'copy' or 'move' to be enabled.") return log.debug(u'Extracting archive: {0}', @@ -1166,12 +1250,33 @@ class ImportTaskFactory(object): # Silently ignore non-music files. pass elif isinstance(exc.reason, mediafile.UnreadableFileError): - log.warn(u'unreadable file: {0}', displayable_path(path)) + log.warning(u'unreadable file: {0}', displayable_path(path)) else: log.error(u'error reading {0}: {1}', displayable_path(path), exc) +# Pipeline utilities + +def _freshen_items(items): + # Clear IDs from re-tagged items so they appear "fresh" when + # we add them back to the library. + for item in items: + item.id = None + item.album_id = None + + +def _extend_pipeline(tasks, *stages): + # Return pipeline extension for stages with list of tasks + if type(tasks) == list: + task_iter = iter(tasks) + else: + task_iter = tasks + + ipl = pipeline.Pipeline([task_iter] + list(stages)) + return pipeline.multiple(ipl.pull()) + + # Full-album pipeline stages. def read_tasks(session): @@ -1191,8 +1296,8 @@ def read_tasks(session): skipped += task_factory.skipped if not task_factory.imported: - log.warn(u'No files imported from {0}', - displayable_path(toppath)) + log.warning(u'No files imported from {0}', + displayable_path(toppath)) # Show skipped directories (due to incremental/resume). if skipped: @@ -1217,12 +1322,7 @@ def query_tasks(session): log.debug(u'yielding album {0}: {1} - {2}', album.id, album.albumartist, album.album) items = list(album.items()) - - # Clear IDs from re-tagged items so they appear "fresh" when - # we add them back to the library. - for item in items: - item.id = None - item.album_id = None + _freshen_items(items) task = ImportTask(None, [album.item_dir()], items) for task in task.handle_created(session): @@ -1243,6 +1343,11 @@ def lookup_candidates(session, task): plugins.send('import_task_start', session=session, task=task) log.debug(u'Looking up: {0}', displayable_path(task.paths)) + + # Restrict the initial lookup to IDs specified by the user via the -m + # option. Currently all the IDs are passed onto the tasks directly. + task.search_ids = session.config['search_ids'].as_str_seq() + task.lookup_candidates() @@ -1263,6 +1368,9 @@ def user_query(session, task): if task.skip: return task + if session.already_merged(task.paths): + return pipeline.BUBBLE + # Ask the user for a choice. task.choose_match(session) plugins.send('import_task_choice', session=session, task=task) @@ -1277,24 +1385,39 @@ def user_query(session, task): yield new_task yield SentinelImportTask(task.toppath, task.paths) - ipl = pipeline.Pipeline([ - emitter(task), - lookup_candidates(session), - user_query(session), - ]) - return pipeline.multiple(ipl.pull()) + return _extend_pipeline(emitter(task), + lookup_candidates(session), + user_query(session)) # As albums: group items by albums and create task for each album if task.choice_flag is action.ALBUMS: - ipl = pipeline.Pipeline([ - iter([task]), - group_albums(session), - lookup_candidates(session), - user_query(session) - ]) - return pipeline.multiple(ipl.pull()) + return _extend_pipeline([task], + group_albums(session), + lookup_candidates(session), + user_query(session)) resolve_duplicates(session, task) + + if task.should_merge_duplicates: + # Create a new task for tagging the current items + # and duplicates together + duplicate_items = task.duplicate_items(session.lib) + + # Duplicates would be reimported so make them look "fresh" + _freshen_items(duplicate_items) + duplicate_paths = [item.path for item in duplicate_items] + + # Record merged paths in the session so they are not reimported + session.mark_merged(duplicate_paths) + + merged_task = ImportTask(None, task.paths + duplicate_paths, + task.items + duplicate_items) + + return _extend_pipeline([merged_task], + lookup_candidates(session), + user_query(session)) + + apply_choice(session, task) return task @@ -1302,13 +1425,40 @@ def resolve_duplicates(session, task): """Check if a task conflicts with items or albums already imported and ask the session to resolve this. """ - if task.choice_flag in (action.ASIS, action.APPLY): - ident = task.chosen_ident() + if task.choice_flag in (action.ASIS, action.APPLY, action.RETAG): found_duplicates = task.find_duplicates(session.lib) - if ident in session.seen_idents or found_duplicates: - session.resolve_duplicate(task, found_duplicates) + if found_duplicates: + log.debug(u'found duplicates: {}'.format( + [o.id for o in found_duplicates] + )) + + # Get the default action to follow from config. + duplicate_action = config['import']['duplicate_action'].as_choice({ + u'skip': u's', + u'keep': u'k', + u'remove': u'r', + u'merge': u'm', + u'ask': u'a', + }) + log.debug(u'default action for duplicates: {0}', duplicate_action) + + if duplicate_action == u's': + # Skip new. + task.set_choice(action.SKIP) + elif duplicate_action == u'k': + # Keep both. Do nothing; leave the choice intact. + pass + elif duplicate_action == u'r': + # Remove old. + task.should_remove_duplicates = True + elif duplicate_action == u'm': + # Merge duplicates together + task.should_merge_duplicates = True + else: + # No default action set; ask the session. + session.resolve_duplicate(task, found_duplicates) + session.log_choice(task, True) - session.seen_idents.add(ident) @pipeline.mutator_stage @@ -1321,14 +1471,14 @@ def import_asis(session, task): if task.skip: return - log.info('{}', displayable_path(task.paths)) + log.info(u'{}', displayable_path(task.paths)) task.set_choice(action.ASIS) + apply_choice(session, task) -@pipeline.mutator_stage -def apply_choices(session, task): - """A coroutine for applying changes to albums and singletons during - the autotag process. +def apply_choice(session, task): + """Apply the task's choice to the Album or Item it contains and add + it to the library. """ if task.skip: return @@ -1340,6 +1490,14 @@ def apply_choices(session, task): task.add(session.lib) + # If ``set_fields`` is set, set those fields to the + # configured values. + # NOTE: This cannot be done before the ``task.add()`` call above, + # because then the ``ImportTask`` won't have an `album` for which + # it can set the fields. + if config['import']['set_fields']: + task.set_fields() + @pipeline.mutator_stage def plugin_stage(session, func, task): @@ -1368,11 +1526,20 @@ def manipulate_files(session, task): if task.should_remove_duplicates: task.remove_duplicates(session.lib) + if session.config['move']: + operation = MoveOperation.MOVE + elif session.config['copy']: + operation = MoveOperation.COPY + elif session.config['link']: + operation = MoveOperation.LINK + elif session.config['hardlink']: + operation = MoveOperation.HARDLINK + else: + operation = None + task.manipulate_files( - move=session.config['move'], - copy=session.config['copy'], + operation, write=session.config['write'], - link=session.config['link'], session=session, ) @@ -1419,8 +1586,16 @@ def group_albums(session): task = pipeline.multiple(tasks) -MULTIDISC_MARKERS = (r'dis[ck]', r'cd') -MULTIDISC_PAT_FMT = r'^(.*%s[\W_]*)\d' +MULTIDISC_MARKERS = (br'dis[ck]', br'cd') +MULTIDISC_PAT_FMT = br'^(.*%s[\W_]*)\d' + + +def is_subdir_of_any_in_list(path, dirs): + """Returns True if path os a subdirectory of any directory in dirs + (a list). In other case, returns False. + """ + ancestors = ancestry(path) + return any(d in ancestors for d in dirs) def albums_in_dir(path): @@ -1431,15 +1606,18 @@ def albums_in_dir(path): """ collapse_pat = collapse_paths = collapse_items = None ignore = config['ignore'].as_str_seq() + ignore_hidden = config['ignore_hidden'].get(bool) - for root, dirs, files in sorted_walk(path, ignore=ignore, logger=log): + for root, dirs, files in sorted_walk(path, ignore=ignore, + ignore_hidden=ignore_hidden, + logger=log): items = [os.path.join(root, f) for f in files] # If we're currently collapsing the constituent directories in a # multi-disc album, check whether we should continue collapsing # and add the current directory. If so, just add the directory # and move on to the next directory. If not, stop collapsing. if collapse_paths: - if (not collapse_pat and collapse_paths[0] in ancestry(root)) or \ + if (is_subdir_of_any_in_list(root, collapse_paths)) or \ (collapse_pat and collapse_pat.match(os.path.basename(root))): # Still collapsing. @@ -1460,7 +1638,9 @@ def albums_in_dir(path): # named in this way. start_collapsing = False for marker in MULTIDISC_MARKERS: - marker_pat = re.compile(MULTIDISC_PAT_FMT % marker, re.I) + # We're using replace on %s due to lack of .format() on bytestrings + p = MULTIDISC_PAT_FMT.replace(b'%s', marker) + marker_pat = re.compile(p, re.I) match = marker_pat.match(os.path.basename(root)) # Is this directory the root of a nested multi-disc album? @@ -1469,13 +1649,16 @@ def albums_in_dir(path): start_collapsing = True subdir_pat = None for subdir in dirs: + subdir = util.bytestring_path(subdir) # The first directory dictates the pattern for # the remaining directories. if not subdir_pat: match = marker_pat.match(subdir) if match: + match_group = re.escape(match.group(1)) subdir_pat = re.compile( - br'^%s\d' % re.escape(match.group(1)), re.I + b''.join([b'^', match_group, br'\d']), + re.I ) else: start_collapsing = False @@ -1497,7 +1680,8 @@ def albums_in_dir(path): # Set the current pattern to match directories with the same # prefix as this one, followed by a digit. collapse_pat = re.compile( - br'^%s\d' % re.escape(match.group(1)), re.I + b''.join([b'^', re.escape(match.group(1)), br'\d']), + re.I ) break diff --git a/beets/library.py b/beets/library.py index 10cddc69d..64035e642 100644 --- a/beets/library.py +++ b/beets/library.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,28 +15,34 @@ """The core data store and collection logic for beets. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import os import sys -import shlex import unicodedata import time import re -from unidecode import unidecode -import platform +import six from beets import logging -from beets.mediafile import MediaFile, MutagenError, UnreadableFileError +from beets.mediafile import MediaFile, UnreadableFileError from beets import plugins from beets import util -from beets.util import bytestring_path, syspath, normpath, samefile +from beets.util import bytestring_path, syspath, normpath, samefile, \ + MoveOperation from beets.util.functemplate import Template from beets import dbcore from beets.dbcore import types import beets +# To use the SQLite "blob" type, it doesn't suffice to provide a byte +# string; SQLite treats that as encoded text. Wrapping it in a `buffer` or a +# `memoryview`, depending on the Python version, tells it that we +# actually mean non-text data. +if six.PY2: + BLOB_TYPE = buffer # noqa: F821 +else: + BLOB_TYPE = memoryview log = logging.getLogger('beets') @@ -50,20 +57,20 @@ class PathQuery(dbcore.FieldQuery): and case-sensitive otherwise. """ - escape_re = re.compile(r'[\\_%]') - escape_char = b'\\' - def __init__(self, field, pattern, fast=True, case_sensitive=None): - """Create a path query. + """Create a path query. `pattern` must be a path, either to a + file or a directory. `case_sensitive` can be a bool or `None`, indicating that the - behavior should depend on the platform (the default). + behavior should depend on the filesystem. """ super(PathQuery, self).__init__(field, pattern, fast) - # By default, the case sensitivity depends on the platform. + # By default, the case sensitivity depends on the filesystem + # that the query path is located on. if case_sensitive is None: - case_sensitive = platform.system() != 'Windows' + path = util.bytestring_path(util.normpath(pattern)) + case_sensitive = beets.util.case_sensitive(path) self.case_sensitive = case_sensitive # Use a normalized-case pattern for case-insensitive matches. @@ -84,28 +91,31 @@ class PathQuery(dbcore.FieldQuery): colon = query_part.find(':') if colon != -1: query_part = query_part[:colon] - return (os.sep in query_part - and os.path.exists(syspath(normpath(query_part)))) + + # Test both `sep` and `altsep` (i.e., both slash and backslash on + # Windows). + return ( + (os.sep in query_part or + (os.altsep and os.altsep in query_part)) and + os.path.exists(syspath(normpath(query_part))) + ) def match(self, item): path = item.path if self.case_sensitive else item.path.lower() return (path == self.file_path) or path.startswith(self.dir_path) def col_clause(self): - if self.case_sensitive: - file_blob = buffer(self.file_path) - dir_blob = buffer(self.dir_path) - return '({0} = ?) || (substr({0}, 1, ?) = ?)'.format(self.field), \ - (file_blob, len(dir_blob), dir_blob) + file_blob = BLOB_TYPE(self.file_path) + dir_blob = BLOB_TYPE(self.dir_path) - escape = lambda m: self.escape_char + m.group(0) - dir_pattern = self.escape_re.sub(escape, self.dir_path) - dir_blob = buffer(dir_pattern + b'%') - file_pattern = self.escape_re.sub(escape, self.file_path) - file_blob = buffer(file_pattern) - return '({0} LIKE ? ESCAPE ?) || ({0} LIKE ? ESCAPE ?)'.format( - self.field), (file_blob, self.escape_char, dir_blob, - self.escape_char) + if self.case_sensitive: + query_part = '({0} = ?) || (substr({0}, 1, ?) = ?)' + else: + query_part = '(BYTELOWER({0}) = BYTELOWER(?)) || \ + (substr(BYTELOWER({0}), 1, ?) = BYTELOWER(?))' + + return query_part.format(self.field), \ + (file_blob, len(dir_blob), dir_blob) # Library-specific field types. @@ -116,14 +126,15 @@ class DateType(types.Float): query = dbcore.query.DateQuery def format(self, value): - return time.strftime(beets.config['time_format'].get(unicode), + return time.strftime(beets.config['time_format'].as_str(), time.localtime(value or 0)) def parse(self, string): try: # Try a formatted date string. return time.mktime( - time.strptime(string, beets.config['time_format'].get(unicode)) + time.strptime(string, + beets.config['time_format'].as_str()) ) except ValueError: # Fall back to a plain timestamp number. @@ -134,10 +145,27 @@ class DateType(types.Float): class PathType(types.Type): + """A dbcore type for filesystem paths. These are represented as + `bytes` objects, in keeping with the Unix filesystem abstraction. + """ + sql = u'BLOB' query = PathQuery model_type = bytes + def __init__(self, nullable=False): + """Create a path type object. `nullable` controls whether the + type may be missing, i.e., None. + """ + self.nullable = nullable + + @property + def null(self): + if self.nullable: + return None + else: + return b'' + def format(self, value): return util.displayable_path(value) @@ -145,12 +173,11 @@ class PathType(types.Type): return normpath(bytestring_path(string)) def normalize(self, value): - if isinstance(value, unicode): + if isinstance(value, six.text_type): # Paths stored internally as encoded bytes. return bytestring_path(value) - elif isinstance(value, buffer): - # SQLite must store bytestings as buffers to avoid decoding. + elif isinstance(value, BLOB_TYPE): # We unwrap buffers to bytes. return bytes(value) @@ -162,7 +189,7 @@ class PathType(types.Type): def to_sql(self, value): if isinstance(value, bytes): - value = buffer(value) + value = BLOB_TYPE(value) return value @@ -179,11 +206,14 @@ class MusicalKey(types.String): r'bb': 'a#', } + null = None + def parse(self, key): key = key.lower() for flat, sharp in self.ENHARMONIC.items(): key = re.sub(flat, sharp, key) key = re.sub(r'[\W\s]+minor', 'm', key) + key = re.sub(r'[\W\s]+major', '', key) return key.capitalize() def normalize(self, key): @@ -193,6 +223,28 @@ class MusicalKey(types.String): return self.parse(key) +class DurationType(types.Float): + """Human-friendly (M:SS) representation of a time interval.""" + query = dbcore.query.DurationQuery + + def format(self, value): + if not beets.config['format_raw_length'].get(bool): + return beets.ui.human_seconds_short(value or 0.0) + else: + return value + + def parse(self, string): + try: + # Try to format back hh:ss to seconds. + return util.raw_seconds_short(string) + except ValueError: + # Fall back to a plain float. + try: + return float(string) + except ValueError: + return self.null + + # Library-specific sort types. class SmartArtistSort(dbcore.query.Sort): @@ -230,7 +282,7 @@ PF_KEY_DEFAULT = 'default' # Exceptions. - +@six.python_2_unicode_compatible class FileOperationError(Exception): """Indicates an error when interacting with a file on disk. Possibilities include an unsupported media type, a permissions @@ -244,35 +296,39 @@ class FileOperationError(Exception): self.path = path self.reason = reason - def __unicode__(self): + def text(self): """Get a string representing the error. Describes both the underlying reason and the file path in question. """ return u'{0}: {1}'.format( util.displayable_path(self.path), - unicode(self.reason) + six.text_type(self.reason) ) - def __str__(self): - return unicode(self).encode('utf8') + # define __str__ as text to avoid infinite loop on super() calls + # with @six.python_2_unicode_compatible + __str__ = text +@six.python_2_unicode_compatible class ReadError(FileOperationError): """An error while reading a file (i.e. in `Item.read`). """ - def __unicode__(self): - return u'error reading ' + super(ReadError, self).__unicode__() + def __str__(self): + return u'error reading ' + super(ReadError, self).text() +@six.python_2_unicode_compatible class WriteError(FileOperationError): """An error while writing a file (i.e. in `Item.write`). """ - def __unicode__(self): - return u'error writing ' + super(WriteError, self).__unicode__() + def __str__(self): + return u'error writing ' + super(WriteError, self).text() # Item and Album model classes. +@six.python_2_unicode_compatible class LibModel(dbcore.Model): """Shared concrete functionality for Items and Albums. """ @@ -286,8 +342,8 @@ class LibModel(dbcore.Model): funcs.update(plugins.template_funcs()) return funcs - def store(self): - super(LibModel, self).store() + def store(self, fields=None): + super(LibModel, self).store(fields) plugins.send('database_change', lib=self._db, model=self) def remove(self): @@ -300,20 +356,16 @@ class LibModel(dbcore.Model): def __format__(self, spec): if not spec: - spec = beets.config[self._format_config_key].get(unicode) - result = self.evaluate_template(spec) - if isinstance(spec, bytes): - # if spec is a byte string then we must return a one as well - return result.encode('utf8') - else: - return result + spec = beets.config[self._format_config_key].as_str() + assert isinstance(spec, six.text_type) + return self.evaluate_template(spec) def __str__(self): - return format(self).encode('utf8') - - def __unicode__(self): return format(self) + def __bytes__(self): + return self.__str__().encode('utf-8') + class FormattedItemMapping(dbcore.db.FormattedMapping): """Add lookup for album-level fields. @@ -383,7 +435,10 @@ class Item(LibModel): 'albumartist_sort': types.STRING, 'albumartist_credit': types.STRING, 'genre': types.STRING, + 'lyricist': types.STRING, 'composer': types.STRING, + 'composer_sort': types.STRING, + 'arranger': types.STRING, 'grouping': types.STRING, 'year': types.PaddedInt(4), 'month': types.PaddedInt(2), @@ -419,12 +474,14 @@ class Item(LibModel): 'rg_track_peak': types.NULL_FLOAT, 'rg_album_gain': types.NULL_FLOAT, 'rg_album_peak': types.NULL_FLOAT, + 'r128_track_gain': types.PaddedInt(6), + 'r128_album_gain': types.PaddedInt(6), 'original_year': types.PaddedInt(4), 'original_month': types.PaddedInt(2), 'original_day': types.PaddedInt(2), 'initial_key': MusicalKey(), - 'length': types.FLOAT, + 'length': DurationType(), 'bitrate': types.ScaledInt(1000, u'kbps'), 'format': types.STRING, 'samplerate': types.ScaledInt(1000, u'kHz'), @@ -486,15 +543,15 @@ class Item(LibModel): """ # Encode unicode paths and read buffers. if key == 'path': - if isinstance(value, unicode): + if isinstance(value, six.text_type): value = bytestring_path(value) - elif isinstance(value, buffer): + elif isinstance(value, BLOB_TYPE): value = bytes(value) - if key in MediaFile.fields(): - self.mtime = 0 # Reset mtime on dirty. + changed = super(Item, self)._setitem(key, value) - super(Item, self).__setitem__(key, value) + if changed and key in MediaFile.fields(): + self.mtime = 0 # Reset mtime on dirty. def update(self, values): """Set all key/value pairs in the mapping. If mtime is @@ -504,6 +561,11 @@ class Item(LibModel): if self.mtime == 0 and 'mtime' in values: self.mtime = values['mtime'] + def clear(self): + """Set all key/value pairs to None.""" + for key in self._media_fields: + setattr(self, key, None) + def get_album(self): """Get the Album object that this item belongs to, if any, or None if the item is a singleton or is not associated with a @@ -530,12 +592,12 @@ class Item(LibModel): read_path = normpath(read_path) try: mediafile = MediaFile(syspath(read_path)) - except (OSError, IOError, UnreadableFileError) as exc: + except UnreadableFileError as exc: raise ReadError(read_path, exc) for key in self._media_fields: value = getattr(mediafile, key) - if isinstance(value, (int, long)): + if isinstance(value, six.integer_types): if value.bit_length() > 63: value = 0 self[key] = value @@ -577,14 +639,14 @@ class Item(LibModel): try: mediafile = MediaFile(syspath(path), id3v23=beets.config['id3v23'].get(bool)) - except (OSError, IOError, UnreadableFileError) as exc: - raise ReadError(self.path, exc) + except UnreadableFileError as exc: + raise ReadError(path, exc) # Write the tags to the file. mediafile.update(item_tags) try: mediafile.save() - except (OSError, IOError, MutagenError) as exc: + except UnreadableFileError as exc: raise WriteError(self.path, exc) # The file has a new mtime. @@ -602,48 +664,61 @@ class Item(LibModel): self.write(path, tags) return True except FileOperationError as exc: - log.error("{0}", exc) + log.error(u"{0}", exc) return False - def try_sync(self, write=None): - """Synchronize the item with the database and the media file - tags, updating them with this object's current state. + def try_sync(self, write, move, with_album=True): + """Synchronize the item with the database and, possibly, updates its + tags on disk and its path (by moving the file). - By default, the current `path` for the item is used to write - tags. If `write` is `False`, no tags are written. If `write` is - a path, tags are written to that file instead. + `write` indicates whether to write new tags into the file. Similarly, + `move` controls whether the path should be updated. In the + latter case, files are *only* moved when they are inside their + library's directory (if any). - Similar to calling :meth:`write` and :meth:`store`. + Similar to calling :meth:`write`, :meth:`move`, and :meth:`store` + (conditionally). """ - if write is True: - write = None - if write is not False: - self.try_write(path=write) + if write: + self.try_write() + if move: + # Check whether this file is inside the library directory. + if self._db and self._db.directory in util.ancestry(self.path): + log.debug(u'moving {0} to synchronize path', + util.displayable_path(self.path)) + self.move(with_album=with_album) self.store() # Files themselves. - def move_file(self, dest, copy=False, link=False): - """Moves or copies the item's file, updating the path value if - the move succeeds. If a file exists at ``dest``, then it is - slightly modified to be unique. + def move_file(self, dest, operation=MoveOperation.MOVE): + """Move, copy, link or hardlink the item's depending on `operation`, + updating the path value if the move succeeds. + + If a file exists at `dest`, then it is slightly modified to be unique. + + `operation` should be an instance of `util.MoveOperation`. """ if not util.samefile(self.path, dest): dest = util.unique_path(dest) - if copy: - util.copy(self.path, dest) - plugins.send("item_copied", item=self, source=self.path, - destination=dest) - elif link: - util.link(self.path, dest) - plugins.send("item_linked", item=self, source=self.path, - destination=dest) - else: + if operation == MoveOperation.MOVE: plugins.send("before_item_moved", item=self, source=self.path, destination=dest) util.move(self.path, dest) plugins.send("item_moved", item=self, source=self.path, destination=dest) + elif operation == MoveOperation.COPY: + util.copy(self.path, dest) + plugins.send("item_copied", item=self, source=self.path, + destination=dest) + elif operation == MoveOperation.LINK: + util.link(self.path, dest) + plugins.send("item_linked", item=self, source=self.path, + destination=dest) + elif operation == MoveOperation.HARDLINK: + util.hardlink(self.path, dest) + plugins.send("item_hardlinked", item=self, source=self.path, + destination=dest) # Either copying or moving succeeded, so update the stored path. self.path = dest @@ -690,26 +765,27 @@ class Item(LibModel): self._db._memotable = {} - def move(self, copy=False, link=False, basedir=None, with_album=True): + def move(self, operation=MoveOperation.MOVE, basedir=None, + with_album=True, store=True): """Move the item to its designated location within the library directory (provided by destination()). Subdirectories are created as needed. If the operation succeeds, the item's path field is updated to reflect the new location. - If `copy` is true, moving the file is copied rather than moved. - Similarly, `link` creates a symlink instead. + Instead of moving the item it can also be copied, linked or hardlinked + depending on `operation` which should be an instance of + `util.MoveOperation`. - basedir overrides the library base directory for the - destination. + `basedir` overrides the library base directory for the destination. - If the item is in an album, the album is given an opportunity to - move its art. (This can be disabled by passing - with_album=False.) + If the item is in an album and `with_album` is `True`, the album is + given an opportunity to move its art. - The item is stored to the database if it is in the database, so - any dirty fields prior to the move() call will be written as a - side effect. You probably want to call save() to commit the DB - transaction. + By default, the item is stored to the database if it is in the + database, so any dirty fields prior to the move() call will be written + as a side effect. + If `store` is `False` however, the item won't be stored and you'll + have to manually store it after invoking this method. """ self._check_db() dest = self.destination(basedir=basedir) @@ -719,18 +795,20 @@ class Item(LibModel): # Perform the move and store the change. old_path = self.path - self.move_file(dest, copy, link) - self.store() + self.move_file(dest, operation) + if store: + self.store() # If this item is in an album, move its art. if with_album: album = self.get_album() if album: - album.move_art(copy) - album.store() + album.move_art(operation) + if store: + album.store() # Prune vacated directory. - if not copy: + if operation == MoveOperation.MOVE: util.prune_dirs(os.path.dirname(old_path), self._db.directory) # Templating. @@ -765,7 +843,7 @@ class Item(LibModel): if query == PF_KEY_DEFAULT: break else: - assert False, "no default path format" + assert False, u"no default path format" if isinstance(path_format, Template): subpath_tmpl = path_format else: @@ -781,7 +859,10 @@ class Item(LibModel): subpath = unicodedata.normalize('NFC', subpath) if beets.config['asciify_paths']: - subpath = unidecode(subpath) + subpath = util.asciify_path( + subpath, + beets.config['path_sep_replace'].as_str() + ) maxlen = beets.config['max_filename_length'].get(int) if not maxlen: @@ -795,12 +876,15 @@ class Item(LibModel): if fellback: # Print an error message if legalization fell back to # default replacements because of the maximum length. - log.warning('Fell back to default replacements when naming ' - 'file {}. Configure replacements to avoid lengthening ' - 'the filename.', subpath) + log.warning( + u'Fell back to default replacements when naming ' + u'file {}. Configure replacements to avoid lengthening ' + u'the filename.', + subpath + ) if fragment: - return subpath + return util.as_string(subpath) else: return normpath(os.path.join(basedir, subpath)) @@ -815,7 +899,7 @@ class Album(LibModel): _always_dirty = True _fields = { 'id': types.PRIMARY_ID, - 'artpath': PathType(), + 'artpath': PathType(True), 'added': DateType(), 'albumartist': types.STRING, @@ -842,6 +926,7 @@ class Album(LibModel): 'albumdisambig': types.STRING, 'rg_album_gain': types.NULL_FLOAT, 'rg_album_peak': types.NULL_FLOAT, + 'r128_album_gain': types.PaddedInt(6), 'original_year': types.PaddedInt(4), 'original_month': types.PaddedInt(2), 'original_day': types.PaddedInt(2), @@ -885,6 +970,7 @@ class Album(LibModel): 'albumdisambig', 'rg_album_gain', 'rg_album_peak', + 'r128_album_gain', 'original_year', 'original_month', 'original_day', @@ -929,9 +1015,12 @@ class Album(LibModel): for item in self.items(): item.remove(delete, False) - def move_art(self, copy=False, link=False): - """Move or copy any existing album art so that it remains in the - same directory as the items. + def move_art(self, operation=MoveOperation.MOVE): + """Move, copy, link or hardlink (depending on `operation`) any + existing album art so that it remains in the same directory as + the items. + + `operation` should be an instance of `util.MoveOperation`. """ old_art = self.artpath if not old_art: @@ -945,39 +1034,47 @@ class Album(LibModel): log.debug(u'moving album art {0} to {1}', util.displayable_path(old_art), util.displayable_path(new_art)) - if copy: - util.copy(old_art, new_art) - elif link: - util.link(old_art, new_art) - else: + if operation == MoveOperation.MOVE: util.move(old_art, new_art) + util.prune_dirs(os.path.dirname(old_art), self._db.directory) + elif operation == MoveOperation.COPY: + util.copy(old_art, new_art) + elif operation == MoveOperation.LINK: + util.link(old_art, new_art) + elif operation == MoveOperation.HARDLINK: + util.hardlink(old_art, new_art) self.artpath = new_art - # Prune old path when moving. - if not copy: - util.prune_dirs(os.path.dirname(old_art), - self._db.directory) + def move(self, operation=MoveOperation.MOVE, basedir=None, store=True): + """Move, copy, link or hardlink (depending on `operation`) + all items to their destination. Any album art moves along with them. - def move(self, copy=False, link=False, basedir=None): - """Moves (or copies) all items to their destination. Any album - art moves along with them. basedir overrides the library base - directory for the destination. The album is stored to the - database, persisting any modifications to its metadata. + `basedir` overrides the library base directory for the destination. + + `operation` should be an instance of `util.MoveOperation`. + + By default, the album is stored to the database, persisting any + modifications to its metadata. If `store` is `False` however, + the album is not stored automatically, and you'll have to manually + store it after invoking this method. """ basedir = basedir or self._db.directory # Ensure new metadata is available to items for destination # computation. - self.store() + if store: + self.store() # Move items. items = list(self.items()) for item in items: - item.move(copy, link, basedir=basedir, with_album=False) + item.move(operation, basedir=basedir, with_album=False, + store=store) # Move art. - self.move_art(copy, link) - self.store() + self.move_art(operation) + if store: + self.store() def item_dir(self): """Returns the directory containing the album's first item, @@ -985,7 +1082,7 @@ class Album(LibModel): """ item = self.items().get() if not item: - raise ValueError('empty album') + raise ValueError(u'empty album') return os.path.dirname(item.path) def _albumtotal(self): @@ -1021,10 +1118,14 @@ class Album(LibModel): image = bytestring_path(image) item_dir = item_dir or self.item_dir() - filename_tmpl = Template(beets.config['art_filename'].get(unicode)) + filename_tmpl = Template( + beets.config['art_filename'].as_str()) subpath = self.evaluate_template(filename_tmpl, True) if beets.config['asciify_paths']: - subpath = unidecode(subpath) + subpath = util.asciify_path( + subpath, + beets.config['path_sep_replace'].as_str() + ) subpath = util.sanitize_path(subpath, replacements=self._db.replacements) subpath = bytestring_path(subpath) @@ -1065,9 +1166,11 @@ class Album(LibModel): plugins.send('art_set', album=self) - def store(self): + def store(self, fields=None): """Update the database with the album information. The album's tracks are also updated. + :param fields: The fields to be stored. If not specified, all fields + will be. """ # Get modified track fields. track_updates = {} @@ -1076,22 +1179,25 @@ class Album(LibModel): track_updates[key] = self[key] with self._db.transaction(): - super(Album, self).store() + super(Album, self).store(fields) if track_updates: for item in self.items(): for key, value in track_updates.items(): item[key] = value item.store() - def try_sync(self, write=True): - """Synchronize the album and its items with the database and - their files by updating them with this object's current state. + def try_sync(self, write, move): + """Synchronize the album and its items with the database. + Optionally, also write any new tags into the files and update + their paths. - `write` indicates whether to write tags to the item files. + `write` indicates whether to write tags to the item files, and + `move` controls whether files (both audio and album art) are + moved. """ self.store() for item in self.items(): - item.try_sync(bool(write)) + item.try_sync(write, move) # Query construction helpers. @@ -1136,19 +1242,28 @@ def parse_query_string(s, model_cls): The string is split into components using shell-like syntax. """ - assert isinstance(s, unicode), "Query is not unicode: {0!r}".format(s) - - # A bug in Python < 2.7.3 prevents correct shlex splitting of - # Unicode strings. - # http://bugs.python.org/issue6988 - s = s.encode('utf8') + message = u"Query is not unicode: {0!r}".format(s) + assert isinstance(s, six.text_type), message try: - parts = [p.decode('utf8') for p in shlex.split(s)] + parts = util.shlex_split(s) except ValueError as exc: raise dbcore.InvalidQueryError(s, exc) return parse_query_parts(parts, model_cls) +def _sqlite_bytelower(bytestring): + """ A custom ``bytelower`` sqlite function so we can compare + bytestrings in a semi case insensitive fashion. This is to work + around sqlite builds are that compiled with + ``-DSQLITE_LIKE_DOESNT_MATCH_BLOBS``. See + ``https://github.com/beetbox/beets/issues/2172`` for details. + """ + if not six.PY2: + return bytestring.lower() + + return buffer(bytes(bytestring).lower()) # noqa: F821 + + # The Library: interface to the database. class Library(dbcore.Database): @@ -1161,9 +1276,8 @@ class Library(dbcore.Database): path_formats=((PF_KEY_DEFAULT, '$artist/$album/$track $title'),), replacements=None): - if path != ':memory:': - self.path = bytestring_path(normpath(path)) - super(Library, self).__init__(path) + timeout = beets.config['timeout'].as_number() + super(Library, self).__init__(path, timeout=timeout) self.directory = bytestring_path(normpath(directory)) self.path_formats = path_formats @@ -1171,6 +1285,11 @@ class Library(dbcore.Database): self._memotable = {} # Used for template substitution performance. + def _create_connection(self): + conn = super(Library, self)._create_connection() + conn.create_function('bytelower', 1, _sqlite_bytelower) + return conn + # Adding objects to the database. def add(self, obj): @@ -1217,11 +1336,11 @@ class Library(dbcore.Database): # Parse the query, if necessary. try: parsed_sort = None - if isinstance(query, basestring): + if isinstance(query, six.string_types): query, parsed_sort = parse_query_string(query, model_cls) elif isinstance(query, (list, tuple)): query, parsed_sort = parse_query_parts(query, model_cls) - except dbcore.query.InvalidQueryArgumentTypeError as exc: + except dbcore.query.InvalidQueryArgumentValueError as exc: raise dbcore.InvalidQueryError(query, exc) # Any non-null sort specified by the parsed query overrides the @@ -1294,7 +1413,7 @@ class DefaultTemplateFunctions(object): additional context to the functions -- specifically, the Item being evaluated. """ - _prefix = b'tmpl_' + _prefix = 'tmpl_' def __init__(self, item=None, lib=None): """Parametrize the functions. If `item` or `lib` is None, then @@ -1361,22 +1480,24 @@ class DefaultTemplateFunctions(object): def tmpl_asciify(s): """Translate non-ASCII characters to their ASCII equivalents. """ - return unidecode(s) + return util.asciify_path(s, beets.config['path_sep_replace'].as_str()) @staticmethod def tmpl_time(s, fmt): """Format a time value using `strftime`. """ - cur_fmt = beets.config['time_format'].get(unicode) + cur_fmt = beets.config['time_format'].as_str() return time.strftime(fmt, time.strptime(s, cur_fmt)) - def tmpl_aunique(self, keys=None, disam=None): + def tmpl_aunique(self, keys=None, disam=None, bracket=None): """Generate a string that is guaranteed to be unique among all albums in the library who share the same set of keys. A fields from "disam" is used in the string if one is sufficient to disambiguate the albums. Otherwise, a fallback opaque value is used. Both "keys" and "disam" should be given as - whitespace-separated lists of field names. + whitespace-separated lists of field names, while "bracket" is a + pair of characters to be used as brackets surrounding the + disambiguator or empty to have no brackets. """ # Fast paths: no album, no item or library, or memoized value. if not self.item or not self.lib: @@ -1390,9 +1511,19 @@ class DefaultTemplateFunctions(object): keys = keys or 'albumartist album' disam = disam or 'albumtype year label catalognum albumdisambig' + if bracket is None: + bracket = '[]' keys = keys.split() disam = disam.split() + # Assign a left and right bracket or leave blank if argument is empty. + if len(bracket) == 2: + bracket_l = bracket[0] + bracket_r = bracket[1] + else: + bracket_l = u'' + bracket_r = u'' + album = self.lib.get_album(self.item) if not album: # Do nothing for singletons. @@ -1402,7 +1533,7 @@ class DefaultTemplateFunctions(object): # Find matching albums to disambiguate with. subqueries = [] for key in keys: - value = getattr(album, key) + value = album.get(key, '') subqueries.append(dbcore.MatchQuery(key, value)) albums = self.lib.albums(dbcore.AndQuery(subqueries)) @@ -1415,7 +1546,7 @@ class DefaultTemplateFunctions(object): # Find the first disambiguator that distinguishes the albums. for disambiguator in disam: # Get the value for each album for the current field. - disam_values = set([getattr(a, disambiguator) for a in albums]) + disam_values = set([a.get(disambiguator, '') for a in albums]) # If the set of unique values is equal to the number of # albums in the disambiguation set, we're done -- this is @@ -1425,16 +1556,51 @@ class DefaultTemplateFunctions(object): else: # No disambiguator distinguished all fields. - res = u' {0}'.format(album.id) + res = u' {1}{0}{2}'.format(album.id, bracket_l, bracket_r) self.lib._memotable[memokey] = res return res # Flatten disambiguation value into a string. disam_value = album.formatted(True).get(disambiguator) - res = u' [{0}]'.format(disam_value) + + # Return empty string if disambiguator is empty. + if disam_value: + res = u' {1}{0}{2}'.format(disam_value, bracket_l, bracket_r) + else: + res = u'' + self.lib._memotable[memokey] = res return res + @staticmethod + def tmpl_first(s, count=1, skip=0, sep=u'; ', join_str=u'; '): + """ Gets the item(s) from x to y in a string separated by something + and join then with something + + :param s: the string + :param count: The number of items included + :param skip: The number of items skipped + :param sep: the separator. Usually is '; ' (default) or '/ ' + :param join_str: the string which will join the items, default '; '. + """ + skip = int(skip) + count = skip + int(count) + return join_str.join(s.split(sep)[skip:count]) + + def tmpl_ifdef(self, field, trueval=u'', falseval=u''): + """ If field exists return trueval or the field (default) + otherwise, emit return falseval (if provided). + + :param field: The name of the field + :param trueval: The string if the condition is true + :param falseval: The string if the condition is false + :return: The string, based on condition + """ + if self.item.formatted().get(field): + return trueval if trueval else self.item.formatted().get(field) + else: + return falseval + # Get the name of tmpl_* functions in the above class. DefaultTemplateFunctions._func_names = \ diff --git a/beets/logging.py b/beets/logging.py index dee5faf35..d5ec7b73f 100644 --- a/beets/logging.py +++ b/beets/logging.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -20,13 +21,13 @@ that when getLogger(name) instantiates a logger that logger uses {}-style formatting. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from copy import copy from logging import * # noqa import subprocess import threading +import six def logsafe(val): @@ -42,7 +43,7 @@ def logsafe(val): example. """ # Already Unicode. - if isinstance(val, unicode): + if isinstance(val, six.text_type): return val # Bytestring: needs decoding. @@ -51,16 +52,16 @@ def logsafe(val): # (a) only do this for paths, if they can be given a distinct # type, and (b) warn the developer if they do this for other # bytestrings. - return val.decode('utf8', 'replace') + return val.decode('utf-8', 'replace') # A "problem" object: needs a workaround. elif isinstance(val, subprocess.CalledProcessError): try: - return unicode(val) + return six.text_type(val) except UnicodeDecodeError: # An object with a broken __unicode__ formatter. Use __str__ # instead. - return str(val).decode('utf8', 'replace') + return str(val).decode('utf-8', 'replace') # Other objects are used as-is so field access, etc., still works in # the format string. @@ -126,7 +127,7 @@ my_manager = copy(Logger.manager) my_manager.loggerClass = BeetsLogger -def getLogger(name=None): +def getLogger(name=None): # noqa if name: return my_manager.getLogger(name) else: diff --git a/beets/mediafile.py b/beets/mediafile.py index 64ab49ac2..34ad49af7 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -32,35 +33,32 @@ Internally ``MediaFile`` uses ``MediaField`` descriptors to access the data from the tags. In turn ``MediaField`` uses a number of ``StorageStyle`` strategies to handle format specific logic. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import mutagen -import mutagen.mp3 -import mutagen.oggopus -import mutagen.oggvorbis +import mutagen.id3 import mutagen.mp4 import mutagen.flac -import mutagen.monkeysaudio import mutagen.asf -import mutagen.aiff + +import codecs import datetime import re import base64 +import binascii import math import struct import imghdr import os import traceback import enum - -from beets import logging -from beets.util import displayable_path, syspath +import logging +import six __all__ = ['UnreadableFileError', 'FileTypeError', 'MediaFile'] -log = logging.getLogger('beets') +log = logging.getLogger(__name__) # Human-readable type names. TYPES = { @@ -75,16 +73,19 @@ TYPES = { 'mpc': 'Musepack', 'asf': 'Windows Media', 'aiff': 'AIFF', + 'dsf': 'DSD Stream File', } +PREFERRED_IMAGE_EXTENSIONS = {'jpeg': 'jpg'} + # Exceptions. class UnreadableFileError(Exception): """Mutagen is not able to extract information from the file. """ - def __init__(self, path): - Exception.__init__(self, displayable_path(path)) + def __init__(self, path, msg): + Exception.__init__(self, msg if msg else repr(path)) class FileTypeError(UnreadableFileError): @@ -94,11 +95,10 @@ class FileTypeError(UnreadableFileError): mutagen type is not supported by `Mediafile`. """ def __init__(self, path, mutagen_type=None): - path = displayable_path(path) if mutagen_type is None: - msg = path + msg = u'{0!r}: not in a recognized format'.format(path) else: - msg = u'{0}: of mutagen type {1}'.format(path, mutagen_type) + msg = u'{0}: of mutagen type {1}'.format(repr(path), mutagen_type) Exception.__init__(self, msg) @@ -106,10 +106,37 @@ class MutagenError(UnreadableFileError): """Raised when Mutagen fails unexpectedly---probably due to a bug. """ def __init__(self, path, mutagen_exc): - msg = u'{0}: {1}'.format(displayable_path(path), mutagen_exc) + msg = u'{0}: {1}'.format(repr(path), mutagen_exc) Exception.__init__(self, msg) +# Interacting with Mutagen. + +def mutagen_call(action, path, func, *args, **kwargs): + """Call a Mutagen function with appropriate error handling. + + `action` is a string describing what the function is trying to do, + and `path` is the relevant filename. The rest of the arguments + describe the callable to invoke. + + We require at least Mutagen 1.33, where `IOError` is *never* used, + neither for internal parsing errors *nor* for ordinary IO error + conditions such as a bad filename. Mutagen-specific parsing errors and IO + errors are reraised as `UnreadableFileError`. Other exceptions + raised inside Mutagen---i.e., bugs---are reraised as `MutagenError`. + """ + try: + return func(*args, **kwargs) + except mutagen.MutagenError as exc: + log.debug(u'%s failed: %s', action, six.text_type(exc)) + raise UnreadableFileError(path, six.text_type(exc)) + except Exception as exc: + # Isolate bugs in Mutagen. + log.debug(u'%s', traceback.format_exc()) + log.error(u'uncaught Mutagen exception in %s: %s', action, exc) + raise MutagenError(path, exc) + + # Utility. def _safe_cast(out_type, val): @@ -127,14 +154,13 @@ def _safe_cast(out_type, val): return int(val) else: # Process any other type as a string. - if not isinstance(val, basestring): - val = unicode(val) + if isinstance(val, bytes): + val = val.decode('utf-8', 'ignore') + elif not isinstance(val, six.string_types): + val = six.text_type(val) # Get a number from the front of the string. - val = re.match(r'[0-9]*', val.strip()).group(0) - if not val: - return 0 - else: - return int(val) + match = re.match(r'[\+-]?[0-9]+', val.strip()) + return int(match.group(0)) if match else 0 elif out_type == bool: try: @@ -143,21 +169,24 @@ def _safe_cast(out_type, val): except ValueError: return False - elif out_type == unicode: + elif out_type == six.text_type: if isinstance(val, bytes): - return val.decode('utf8', 'ignore') - elif isinstance(val, unicode): + return val.decode('utf-8', 'ignore') + elif isinstance(val, six.text_type): return val else: - return unicode(val) + return six.text_type(val) elif out_type == float: if isinstance(val, int) or isinstance(val, float): return float(val) else: - if not isinstance(val, basestring): - val = unicode(val) - match = re.match(r'[\+-]?[0-9\.]+', val.strip()) + if isinstance(val, bytes): + val = val.decode('utf-8', 'ignore') + else: + val = six.text_type(val) + match = re.match(r'[\+-]?([0-9]+\.?[0-9]*|[0-9]*\.[0-9]+)', + val.strip()) if match: val = match.group(0) if val: @@ -179,14 +208,14 @@ def _unpack_asf_image(data): of exceptions (out-of-bounds, etc.). We should clean this up sometime so that the failure modes are well-defined. """ - type, size = struct.unpack_from(b' 0 else None + if text_delimiter_index > 0: + comment = frame.value[0:text_delimiter_index] + comment = comment.decode('utf-8', 'replace') + else: + comment = None image_data = frame.value[text_delimiter_index + 1:] images.append(Image(data=image_data, type=cover_type, desc=comment)) @@ -1028,7 +1141,7 @@ class APEv2ImageStorageStyle(ListStorageStyle): for image in values: image_type = image.type or ImageType.other comment = image.desc or '' - image_data = comment.encode('utf8') + b'\x00' + image.data + image_data = comment.encode('utf-8') + b'\x00' + image.data cover_tag = self.TAG_NAMES[image_type] mutagen_file[cover_tag] = image_data @@ -1062,7 +1175,7 @@ class MediaField(object): getting this property. """ - self.out_type = kwargs.get(b'out_type', unicode) + self.out_type = kwargs.get('out_type', six.text_type) self._styles = styles def styles(self, mutagen_file): @@ -1101,7 +1214,7 @@ class MediaField(object): return 0.0 elif self.out_type == bool: return False - elif self.out_type == unicode: + elif self.out_type == six.text_type: return u'' @@ -1126,7 +1239,7 @@ class ListMediaField(MediaField): """Returns a ``MediaField`` descriptor that gets and sets the first item. """ - options = {b'out_type': self.out_type} + options = {'out_type': self.out_type} return MediaField(*self._styles, **options) @@ -1147,7 +1260,7 @@ class DateField(MediaField): storage styles do not return a value. """ super(DateField, self).__init__(*date_styles) - year_style = kwargs.get(b'year', None) + year_style = kwargs.get('year', None) if year_style: self._year_field = MediaField(*year_style) @@ -1182,9 +1295,9 @@ class DateField(MediaField): """ # Get the underlying data and split on hyphens and slashes. datestring = super(DateField, self).__get__(mediafile, None) - if isinstance(datestring, basestring): - datestring = re.sub(r'[Tt ].*$', '', unicode(datestring)) - items = re.split('[-/]', unicode(datestring)) + if isinstance(datestring, six.string_types): + datestring = re.sub(r'[Tt ].*$', '', six.text_type(datestring)) + items = re.split('[-/]', six.text_type(datestring)) else: items = [] @@ -1203,7 +1316,7 @@ class DateField(MediaField): for item in items: try: items_.append(int(item)) - except: + except (TypeError, ValueError): items_.append(None) return items_ @@ -1221,7 +1334,7 @@ class DateField(MediaField): date.append(u'{0:02d}'.format(int(month))) if month and day: date.append(u'{0:02d}'.format(int(day))) - date = map(unicode, date) + date = map(six.text_type, date) super(DateField, self).__set__(mediafile, u'-'.join(date)) if hasattr(self, '_year_field'): @@ -1329,40 +1442,9 @@ class MediaFile(object): By default, MP3 files are saved with ID3v2.4 tags. You can use the older ID3v2.3 standard by specifying the `id3v23` option. """ - path = syspath(path) self.path = path - unreadable_exc = ( - mutagen.mp3.error, - mutagen.id3.error, - mutagen.flac.error, - mutagen.monkeysaudio.MonkeysAudioHeaderError, - mutagen.mp4.error, - mutagen.oggopus.error, - mutagen.oggvorbis.error, - mutagen.ogg.error, - mutagen.asf.error, - mutagen.apev2.error, - mutagen.aiff.error, - ) - try: - self.mgfile = mutagen.File(path) - except unreadable_exc as exc: - log.debug(u'header parsing failed: {0}', unicode(exc)) - raise UnreadableFileError(path) - except IOError as exc: - if type(exc) == IOError: - # This is a base IOError, not a subclass from Mutagen or - # anywhere else. - raise - else: - log.debug('{}', traceback.format_exc()) - raise MutagenError(path, exc) - except Exception as exc: - # Isolate bugs in Mutagen. - log.debug('{}', traceback.format_exc()) - log.error(u'uncaught Mutagen exception in open: {0}', exc) - raise MutagenError(path, exc) + self.mgfile = mutagen_call('open', path, mutagen.File, path) if self.mgfile is None: # Mutagen couldn't guess the type @@ -1370,20 +1452,10 @@ class MediaFile(object): elif (type(self.mgfile).__name__ == 'M4A' or type(self.mgfile).__name__ == 'MP4'): info = self.mgfile.info - if hasattr(info, 'codec'): - if info.codec and info.codec.startswith('alac'): - self.type = 'alac' - else: - self.type = 'aac' + if info.codec and info.codec.startswith('alac'): + self.type = 'alac' else: - # This hack differentiates AAC and ALAC on versions of - # Mutagen < 1.26. Once Mutagen > 1.26 is out and - # required by beets, we can remove this. - if hasattr(self.mgfile.info, 'bitrate') and \ - self.mgfile.info.bitrate > 0: - self.type = 'aac' - else: - self.type = 'alac' + self.type = 'aac' elif (type(self.mgfile).__name__ == 'ID3' or type(self.mgfile).__name__ == 'MP3'): self.type = 'mp3' @@ -1403,6 +1475,8 @@ class MediaFile(object): self.type = 'asf' elif type(self.mgfile).__name__ == 'AIFF': self.type = 'aiff' + elif type(self.mgfile).__name__ == 'DSF': + self.type = 'dsf' else: raise FileTypeError(path, type(self.mgfile).__name__) @@ -1414,7 +1488,8 @@ class MediaFile(object): self.id3v23 = id3v23 and self.type == 'mp3' def save(self): - """Write the object's tags back to the file. + """Write the object's tags back to the file. May + throw `UnreadableFileError`. """ # Possibly save the tags to ID3v2.3. kwargs = {} @@ -1426,27 +1501,13 @@ class MediaFile(object): id3.update_to_v23() kwargs['v2_version'] = 3 - # Isolate bugs in Mutagen. - try: - self.mgfile.save(**kwargs) - except (IOError, OSError): - # Propagate these through: they don't represent Mutagen bugs. - raise - except Exception as exc: - log.debug('{}', traceback.format_exc()) - log.error(u'uncaught Mutagen exception in save: {0}', exc) - raise MutagenError(self.path, exc) + mutagen_call('save', self.path, self.mgfile.save, **kwargs) def delete(self): - """Remove the current metadata tag from the file. + """Remove the current metadata tag from the file. May + throw `UnreadableFileError`. """ - try: - self.mgfile.delete() - except NotImplementedError: - # For Mutagen types that don't support deletion (notably, - # ASF), just delete each tag individually. - for tag in self.mgfile.keys(): - del self.mgfile[tag] + mutagen_call('delete', self.path, self.mgfile.delete) # Convenient access to the set of available fields. @@ -1458,7 +1519,12 @@ class MediaFile(object): """ for property, descriptor in cls.__dict__.items(): if isinstance(descriptor, MediaField): - yield property.decode('utf8') + if isinstance(property, bytes): + # On Python 2, class field names are bytes. This method + # produces text strings. + yield property.decode('utf8', 'ignore') + else: + yield property @classmethod def _field_sort_name(cls, name): @@ -1535,45 +1601,64 @@ class MediaFile(object): title = MediaField( MP3StorageStyle('TIT2'), - MP4StorageStyle(b"\xa9nam"), + MP4StorageStyle('\xa9nam'), StorageStyle('TITLE'), ASFStorageStyle('Title'), ) artist = MediaField( MP3StorageStyle('TPE1'), - MP4StorageStyle(b"\xa9ART"), + MP4StorageStyle('\xa9ART'), StorageStyle('ARTIST'), ASFStorageStyle('Author'), ) album = MediaField( MP3StorageStyle('TALB'), - MP4StorageStyle(b"\xa9alb"), + MP4StorageStyle('\xa9alb'), StorageStyle('ALBUM'), ASFStorageStyle('WM/AlbumTitle'), ) genres = ListMediaField( MP3ListStorageStyle('TCON'), - MP4ListStorageStyle(b"\xa9gen"), + MP4ListStorageStyle('\xa9gen'), ListStorageStyle('GENRE'), ASFStorageStyle('WM/Genre'), ) genre = genres.single_field() + lyricist = MediaField( + MP3StorageStyle('TEXT'), + MP4StorageStyle('----:com.apple.iTunes:LYRICIST'), + StorageStyle('LYRICIST'), + ASFStorageStyle('WM/Writer'), + ) composer = MediaField( MP3StorageStyle('TCOM'), - MP4StorageStyle(b"\xa9wrt"), + MP4StorageStyle('\xa9wrt'), StorageStyle('COMPOSER'), ASFStorageStyle('WM/Composer'), ) + composer_sort = MediaField( + MP3StorageStyle('TSOC'), + MP4StorageStyle('soco'), + StorageStyle('COMPOSERSORT'), + ASFStorageStyle('WM/Composersortorder'), + ) + arranger = MediaField( + MP3PeopleStorageStyle('TIPL', involvement='arranger'), + MP4StorageStyle('----:com.apple.iTunes:Arranger'), + StorageStyle('ARRANGER'), + ASFStorageStyle('beets/Arranger'), + ) + grouping = MediaField( MP3StorageStyle('TIT1'), - MP4StorageStyle(b"\xa9grp"), + MP4StorageStyle('\xa9grp'), StorageStyle('GROUPING'), ASFStorageStyle('WM/ContentGroupDescription'), ) track = MediaField( MP3SlashPackStorageStyle('TRCK', pack_pos=0), - MP4TupleStorageStyle(b'trkn', index=0), + MP4TupleStorageStyle('trkn', index=0), StorageStyle('TRACK'), StorageStyle('TRACKNUMBER'), ASFStorageStyle('WM/TrackNumber'), @@ -1581,7 +1666,7 @@ class MediaFile(object): ) tracktotal = MediaField( MP3SlashPackStorageStyle('TRCK', pack_pos=1), - MP4TupleStorageStyle(b'trkn', index=1), + MP4TupleStorageStyle('trkn', index=1), StorageStyle('TRACKTOTAL'), StorageStyle('TRACKC'), StorageStyle('TOTALTRACKS'), @@ -1590,7 +1675,7 @@ class MediaFile(object): ) disc = MediaField( MP3SlashPackStorageStyle('TPOS', pack_pos=0), - MP4TupleStorageStyle(b'disk', index=0), + MP4TupleStorageStyle('disk', index=0), StorageStyle('DISC'), StorageStyle('DISCNUMBER'), ASFStorageStyle('WM/PartOfSet'), @@ -1598,7 +1683,7 @@ class MediaFile(object): ) disctotal = MediaField( MP3SlashPackStorageStyle('TPOS', pack_pos=1), - MP4TupleStorageStyle(b'disk', index=1), + MP4TupleStorageStyle('disk', index=1), StorageStyle('DISCTOTAL'), StorageStyle('DISCC'), StorageStyle('TOTALDISCS'), @@ -1607,13 +1692,13 @@ class MediaFile(object): ) lyrics = MediaField( MP3DescStorageStyle(key='USLT'), - MP4StorageStyle(b"\xa9lyr"), + MP4StorageStyle('\xa9lyr'), StorageStyle('LYRICS'), ASFStorageStyle('WM/Lyrics'), ) comments = MediaField( MP3DescStorageStyle(key='COMM'), - MP4StorageStyle(b"\xa9cmt"), + MP4StorageStyle('\xa9cmt'), StorageStyle('DESCRIPTION'), StorageStyle('COMMENT'), ASFStorageStyle('WM/Comments'), @@ -1621,111 +1706,111 @@ class MediaFile(object): ) bpm = MediaField( MP3StorageStyle('TBPM'), - MP4StorageStyle(b'tmpo', as_type=int), + MP4StorageStyle('tmpo', as_type=int), StorageStyle('BPM'), ASFStorageStyle('WM/BeatsPerMinute'), out_type=int, ) comp = MediaField( MP3StorageStyle('TCMP'), - MP4BoolStorageStyle(b'cpil'), + MP4BoolStorageStyle('cpil'), StorageStyle('COMPILATION'), ASFStorageStyle('WM/IsCompilation', as_type=bool), out_type=bool, ) albumartist = MediaField( MP3StorageStyle('TPE2'), - MP4StorageStyle(b'aART'), + MP4StorageStyle('aART'), StorageStyle('ALBUM ARTIST'), StorageStyle('ALBUMARTIST'), ASFStorageStyle('WM/AlbumArtist'), ) albumtype = MediaField( MP3DescStorageStyle(u'MusicBrainz Album Type'), - MP4StorageStyle(b'----:com.apple.iTunes:MusicBrainz Album Type'), + MP4StorageStyle('----:com.apple.iTunes:MusicBrainz Album Type'), StorageStyle('MUSICBRAINZ_ALBUMTYPE'), ASFStorageStyle('MusicBrainz/Album Type'), ) label = MediaField( MP3StorageStyle('TPUB'), - MP4StorageStyle(b'----:com.apple.iTunes:Label'), - MP4StorageStyle(b'----:com.apple.iTunes:publisher'), + MP4StorageStyle('----:com.apple.iTunes:Label'), + MP4StorageStyle('----:com.apple.iTunes:publisher'), StorageStyle('LABEL'), StorageStyle('PUBLISHER'), # Traktor ASFStorageStyle('WM/Publisher'), ) artist_sort = MediaField( MP3StorageStyle('TSOP'), - MP4StorageStyle(b"soar"), + MP4StorageStyle('soar'), StorageStyle('ARTISTSORT'), ASFStorageStyle('WM/ArtistSortOrder'), ) albumartist_sort = MediaField( MP3DescStorageStyle(u'ALBUMARTISTSORT'), - MP4StorageStyle(b"soaa"), + MP4StorageStyle('soaa'), StorageStyle('ALBUMARTISTSORT'), ASFStorageStyle('WM/AlbumArtistSortOrder'), ) asin = MediaField( MP3DescStorageStyle(u'ASIN'), - MP4StorageStyle(b"----:com.apple.iTunes:ASIN"), + MP4StorageStyle('----:com.apple.iTunes:ASIN'), StorageStyle('ASIN'), ASFStorageStyle('MusicBrainz/ASIN'), ) catalognum = MediaField( MP3DescStorageStyle(u'CATALOGNUMBER'), - MP4StorageStyle(b"----:com.apple.iTunes:CATALOGNUMBER"), + MP4StorageStyle('----:com.apple.iTunes:CATALOGNUMBER'), StorageStyle('CATALOGNUMBER'), ASFStorageStyle('WM/CatalogNo'), ) disctitle = MediaField( MP3StorageStyle('TSST'), - MP4StorageStyle(b"----:com.apple.iTunes:DISCSUBTITLE"), + MP4StorageStyle('----:com.apple.iTunes:DISCSUBTITLE'), StorageStyle('DISCSUBTITLE'), ASFStorageStyle('WM/SetSubTitle'), ) encoder = MediaField( MP3StorageStyle('TENC'), - MP4StorageStyle(b"\xa9too"), + MP4StorageStyle('\xa9too'), StorageStyle('ENCODEDBY'), StorageStyle('ENCODER'), ASFStorageStyle('WM/EncodedBy'), ) script = MediaField( MP3DescStorageStyle(u'Script'), - MP4StorageStyle(b"----:com.apple.iTunes:SCRIPT"), + MP4StorageStyle('----:com.apple.iTunes:SCRIPT'), StorageStyle('SCRIPT'), ASFStorageStyle('WM/Script'), ) language = MediaField( MP3StorageStyle('TLAN'), - MP4StorageStyle(b"----:com.apple.iTunes:LANGUAGE"), + MP4StorageStyle('----:com.apple.iTunes:LANGUAGE'), StorageStyle('LANGUAGE'), ASFStorageStyle('WM/Language'), ) country = MediaField( - MP3DescStorageStyle('MusicBrainz Album Release Country'), - MP4StorageStyle(b"----:com.apple.iTunes:MusicBrainz " - b"Album Release Country"), + MP3DescStorageStyle(u'MusicBrainz Album Release Country'), + MP4StorageStyle('----:com.apple.iTunes:MusicBrainz ' + 'Album Release Country'), StorageStyle('RELEASECOUNTRY'), ASFStorageStyle('MusicBrainz/Album Release Country'), ) albumstatus = MediaField( MP3DescStorageStyle(u'MusicBrainz Album Status'), - MP4StorageStyle(b"----:com.apple.iTunes:MusicBrainz Album Status"), + MP4StorageStyle('----:com.apple.iTunes:MusicBrainz Album Status'), StorageStyle('MUSICBRAINZ_ALBUMSTATUS'), ASFStorageStyle('MusicBrainz/Album Status'), ) media = MediaField( MP3StorageStyle('TMED'), - MP4StorageStyle(b"----:com.apple.iTunes:MEDIA"), + MP4StorageStyle('----:com.apple.iTunes:MEDIA'), StorageStyle('MEDIA'), ASFStorageStyle('WM/Media'), ) albumdisambig = MediaField( # This tag mapping was invented for beets (not used by Picard, etc). MP3DescStorageStyle(u'MusicBrainz Album Comment'), - MP4StorageStyle(b"----:com.apple.iTunes:MusicBrainz Album Comment"), + MP4StorageStyle('----:com.apple.iTunes:MusicBrainz Album Comment'), StorageStyle('MUSICBRAINZ_ALBUMCOMMENT'), ASFStorageStyle('MusicBrainz/Album Comment'), ) @@ -1733,7 +1818,7 @@ class MediaFile(object): # Release date. date = DateField( MP3StorageStyle('TDRC'), - MP4StorageStyle(b"\xa9day"), + MP4StorageStyle('\xa9day'), StorageStyle('DATE'), ASFStorageStyle('WM/Year'), year=(StorageStyle('YEAR'),)) @@ -1745,7 +1830,7 @@ class MediaFile(object): # *Original* release date. original_date = DateField( MP3StorageStyle('TDOR'), - MP4StorageStyle(b'----:com.apple.iTunes:ORIGINAL YEAR'), + MP4StorageStyle('----:com.apple.iTunes:ORIGINAL YEAR'), StorageStyle('ORIGINALDATE'), ASFStorageStyle('WM/OriginalReleaseYear')) @@ -1756,13 +1841,13 @@ class MediaFile(object): # Nonstandard metadata. artist_credit = MediaField( MP3DescStorageStyle(u'Artist Credit'), - MP4StorageStyle(b"----:com.apple.iTunes:Artist Credit"), + MP4StorageStyle('----:com.apple.iTunes:Artist Credit'), StorageStyle('ARTIST_CREDIT'), ASFStorageStyle('beets/Artist Credit'), ) albumartist_credit = MediaField( MP3DescStorageStyle(u'Album Artist Credit'), - MP4StorageStyle(b"----:com.apple.iTunes:Album Artist Credit"), + MP4StorageStyle('----:com.apple.iTunes:Album Artist Credit'), StorageStyle('ALBUMARTIST_CREDIT'), ASFStorageStyle('beets/Album Artist Credit'), ) @@ -1776,31 +1861,31 @@ class MediaFile(object): # MusicBrainz IDs. mb_trackid = MediaField( MP3UFIDStorageStyle(owner='http://musicbrainz.org'), - MP4StorageStyle(b'----:com.apple.iTunes:MusicBrainz Track Id'), + MP4StorageStyle('----:com.apple.iTunes:MusicBrainz Track Id'), StorageStyle('MUSICBRAINZ_TRACKID'), ASFStorageStyle('MusicBrainz/Track Id'), ) mb_albumid = MediaField( MP3DescStorageStyle(u'MusicBrainz Album Id'), - MP4StorageStyle(b'----:com.apple.iTunes:MusicBrainz Album Id'), + MP4StorageStyle('----:com.apple.iTunes:MusicBrainz Album Id'), StorageStyle('MUSICBRAINZ_ALBUMID'), ASFStorageStyle('MusicBrainz/Album Id'), ) mb_artistid = MediaField( MP3DescStorageStyle(u'MusicBrainz Artist Id'), - MP4StorageStyle(b'----:com.apple.iTunes:MusicBrainz Artist Id'), + MP4StorageStyle('----:com.apple.iTunes:MusicBrainz Artist Id'), StorageStyle('MUSICBRAINZ_ARTISTID'), ASFStorageStyle('MusicBrainz/Artist Id'), ) mb_albumartistid = MediaField( MP3DescStorageStyle(u'MusicBrainz Album Artist Id'), - MP4StorageStyle(b'----:com.apple.iTunes:MusicBrainz Album Artist Id'), + MP4StorageStyle('----:com.apple.iTunes:MusicBrainz Album Artist Id'), StorageStyle('MUSICBRAINZ_ALBUMARTISTID'), ASFStorageStyle('MusicBrainz/Album Artist Id'), ) mb_releasegroupid = MediaField( MP3DescStorageStyle(u'MusicBrainz Release Group Id'), - MP4StorageStyle(b'----:com.apple.iTunes:MusicBrainz Release Group Id'), + MP4StorageStyle('----:com.apple.iTunes:MusicBrainz Release Group Id'), StorageStyle('MUSICBRAINZ_RELEASEGROUPID'), ASFStorageStyle('MusicBrainz/Release Group Id'), ) @@ -1808,13 +1893,13 @@ class MediaFile(object): # Acoustid fields. acoustid_fingerprint = MediaField( MP3DescStorageStyle(u'Acoustid Fingerprint'), - MP4StorageStyle(b'----:com.apple.iTunes:Acoustid Fingerprint'), + MP4StorageStyle('----:com.apple.iTunes:Acoustid Fingerprint'), StorageStyle('ACOUSTID_FINGERPRINT'), ASFStorageStyle('Acoustid/Fingerprint'), ) acoustid_id = MediaField( MP3DescStorageStyle(u'Acoustid Id'), - MP4StorageStyle(b'----:com.apple.iTunes:Acoustid Id'), + MP4StorageStyle('----:com.apple.iTunes:Acoustid Id'), StorageStyle('ACOUSTID_ID'), ASFStorageStyle('Acoustid/Id'), ) @@ -1835,11 +1920,11 @@ class MediaFile(object): id3_lang='eng' ), MP4StorageStyle( - b'----:com.apple.iTunes:replaygain_track_gain', - float_places=2, suffix=b' dB' + '----:com.apple.iTunes:replaygain_track_gain', + float_places=2, suffix=' dB' ), MP4SoundCheckStorageStyle( - b'----:com.apple.iTunes:iTunNORM', + '----:com.apple.iTunes:iTunNORM', index=0 ), StorageStyle( @@ -1861,9 +1946,9 @@ class MediaFile(object): u'replaygain_album_gain', float_places=2, suffix=u' dB' ), - MP4SoundCheckStorageStyle( - b'----:com.apple.iTunes:iTunNORM', - index=1 + MP4StorageStyle( + '----:com.apple.iTunes:replaygain_album_gain', + float_places=2, suffix=' dB' ), StorageStyle( u'REPLAYGAIN_ALBUM_GAIN', @@ -1890,11 +1975,11 @@ class MediaFile(object): id3_lang='eng' ), MP4StorageStyle( - b'----:com.apple.iTunes:replaygain_track_peak', + '----:com.apple.iTunes:replaygain_track_peak', float_places=6 ), MP4SoundCheckStorageStyle( - b'----:com.apple.iTunes:iTunNORM', + '----:com.apple.iTunes:iTunNORM', index=1 ), StorageStyle(u'REPLAYGAIN_TRACK_PEAK', float_places=6), @@ -1911,7 +1996,7 @@ class MediaFile(object): float_places=6 ), MP4StorageStyle( - b'----:com.apple.iTunes:replaygain_album_peak', + '----:com.apple.iTunes:replaygain_album_peak', float_places=6 ), StorageStyle(u'REPLAYGAIN_ALBUM_PEAK', float_places=6), @@ -1919,9 +2004,41 @@ class MediaFile(object): out_type=float, ) + # EBU R128 fields. + r128_track_gain = MediaField( + MP3DescStorageStyle( + u'R128_TRACK_GAIN' + ), + MP4StorageStyle( + '----:com.apple.iTunes:R128_TRACK_GAIN' + ), + StorageStyle( + u'R128_TRACK_GAIN' + ), + ASFStorageStyle( + u'R128_TRACK_GAIN' + ), + out_type=int, + ) + r128_album_gain = MediaField( + MP3DescStorageStyle( + u'R128_ALBUM_GAIN' + ), + MP4StorageStyle( + '----:com.apple.iTunes:R128_ALBUM_GAIN' + ), + StorageStyle( + u'R128_ALBUM_GAIN' + ), + ASFStorageStyle( + u'R128_ALBUM_GAIN' + ), + out_type=int, + ) + initial_key = MediaField( MP3StorageStyle('TKEY'), - MP4StorageStyle(b'----:com.apple.iTunes:initialkey'), + MP4StorageStyle('----:com.apple.iTunes:initialkey'), StorageStyle('INITIALKEY'), ASFStorageStyle('INITIALKEY'), ) @@ -1954,13 +2071,6 @@ class MediaFile(object): @property def channels(self): """The number of channels in the audio (an int).""" - if isinstance(self.mgfile.info, mutagen.mp3.MPEGInfo): - return { - mutagen.mp3.STEREO: 2, - mutagen.mp3.JOINTSTEREO: 2, - mutagen.mp3.DUALCHANNEL: 2, - mutagen.mp3.MONO: 1, - }[self.mgfile.info.mode] if hasattr(self.mgfile.info, 'channels'): return self.mgfile.info.channels return 0 diff --git a/beets/plugins.py b/beets/plugins.py old mode 100755 new mode 100644 index d06debe22..1bd2cacd5 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,8 +15,7 @@ """Support for beets plugins.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import inspect import traceback @@ -27,8 +27,9 @@ from functools import wraps import beets from beets import logging from beets import mediafile +import six -PLUGIN_NAMESPACE = b'beetsplug' +PLUGIN_NAMESPACE = 'beetsplug' # Plugins using the Last.fm API can share the same API key. LASTFM_KEY = '2dc3914abf35f0d9c92d97d8f8e42b43' @@ -54,10 +55,10 @@ class PluginLogFilter(logging.Filter): def filter(self, record): if hasattr(record.msg, 'msg') and isinstance(record.msg.msg, - basestring): + six.string_types): # A _LogMessage from our hacked-up Logging replacement. record.msg.msg = self.prefix + record.msg.msg - elif isinstance(record.msg, basestring): + elif isinstance(record.msg, six.string_types): record.msg = self.prefix + record.msg return True @@ -72,7 +73,7 @@ class BeetsPlugin(object): def __init__(self, name=None): """Perform one-time plugin setup. """ - self.name = name or self.__module__.decode('utf8').split('.')[-1] + self.name = name or self.__module__.split('.')[-1] self.config = beets.config[self.name] if not self.template_funcs: self.template_funcs = {} @@ -80,6 +81,7 @@ class BeetsPlugin(object): self.template_fields = {} if not self.album_template_fields: self.album_template_fields = {} + self.early_import_stages = [] self.import_stages = [] self._log = log.getChild(self.name) @@ -93,6 +95,22 @@ class BeetsPlugin(object): """ return () + def _set_stage_log_level(self, stages): + """Adjust all the stages in `stages` to WARNING logging level. + """ + return [self._set_log_level_and_params(logging.WARNING, stage) + for stage in stages] + + def get_early_import_stages(self): + """Return a list of functions that should be called as importer + pipelines stages early in the pipeline. + + The callables are wrapped versions of the functions in + `self.early_import_stages`. Wrapping provides some bookkeeping for the + plugin: specifically, the logging level is adjusted to WARNING. + """ + return self._set_stage_log_level(self.early_import_stages) + def get_import_stages(self): """Return a list of functions that should be called as importer pipelines stages. @@ -101,8 +119,7 @@ class BeetsPlugin(object): `self.import_stages`. Wrapping provides some bookkeeping for the plugin: specifically, the logging level is adjusted to WARNING. """ - return [self._set_log_level_and_params(logging.WARNING, import_stage) - for import_stage in self.import_stages] + return self._set_stage_log_level(self.import_stages) def _set_log_level_and_params(self, base_log_level, func): """Wrap `func` to temporarily set this plugin's logger level to @@ -247,26 +264,25 @@ def load_plugins(names=()): BeetsPlugin subclasses desired. """ for name in names: - bname = name.encode('utf8') - modname = b'%s.%s' % (PLUGIN_NAMESPACE, bname) + modname = '{0}.{1}'.format(PLUGIN_NAMESPACE, name) try: try: namespace = __import__(modname, None, None) except ImportError as exc: # Again, this is hacky: if exc.args[0].endswith(' ' + name): - log.warn(u'** plugin {0} not found', name) + log.warning(u'** plugin {0} not found', name) else: raise else: - for obj in getattr(namespace, bname).__dict__.values(): + for obj in getattr(namespace, name).__dict__.values(): if isinstance(obj, type) and issubclass(obj, BeetsPlugin) \ and obj != BeetsPlugin and obj not in _classes: _classes.add(obj) - except: - log.warn( - '** error loading plugin {}:\n{}', + except Exception: + log.warning( + u'** error loading plugin {}:\n{}', name, traceback.format_exc(), ) @@ -313,7 +329,7 @@ def queries(): def types(model_cls): # Gives us `item_types` and `album_types` - attr_name = b'{0}_types'.format(model_cls.__name__.lower()) + attr_name = '{0}_types'.format(model_cls.__name__.lower()) types = {} for plugin in find_plugins(): plugin_types = getattr(plugin, attr_name, {}) @@ -321,8 +337,8 @@ def types(model_cls): if field in types and plugin_types[field] != types[field]: raise PluginConflictException( u'Plugin {0} defines flexible field {1} ' - 'which has already been defined with ' - 'another type.'.format(plugin.name, field) + u'which has already been defined with ' + u'another type.'.format(plugin.name, field) ) types.update(plugin_types) return types @@ -351,41 +367,35 @@ def album_distance(items, album_info, mapping): def candidates(items, artist, album, va_likely): """Gets MusicBrainz candidates for an album from each plugin. """ - out = [] for plugin in find_plugins(): - out.extend(plugin.candidates(items, artist, album, va_likely)) - return out + for candidate in plugin.candidates(items, artist, album, va_likely): + yield candidate def item_candidates(item, artist, title): """Gets MusicBrainz candidates for an item from the plugins. """ - out = [] for plugin in find_plugins(): - out.extend(plugin.item_candidates(item, artist, title)) - return out + for item_candidate in plugin.item_candidates(item, artist, title): + yield item_candidate def album_for_id(album_id): """Get AlbumInfo objects for a given ID string. """ - out = [] for plugin in find_plugins(): - res = plugin.album_for_id(album_id) - if res: - out.append(res) - return out + album = plugin.album_for_id(album_id) + if album: + yield album def track_for_id(track_id): """Get TrackInfo objects for a given ID string. """ - out = [] for plugin in find_plugins(): - res = plugin.track_for_id(track_id) - if res: - out.append(res) - return out + track = plugin.track_for_id(track_id) + if track: + yield track def template_funcs(): @@ -399,6 +409,14 @@ def template_funcs(): return funcs +def early_import_stages(): + """Get a list of early import stage functions defined by plugins.""" + stages = [] + for plugin in find_plugins(): + stages += plugin.get_early_import_stages() + return stages + + def import_stages(): """Get a list of import stage functions defined by plugins.""" stages = [] @@ -484,7 +502,64 @@ def sanitize_choices(choices, choices_all): others = [x for x in choices_all if x not in choices] res = [] for s in choices: - if s in list(choices_all) + ['*']: - if not (s in seen or seen.add(s)): - res.extend(list(others) if s == '*' else [s]) + if s not in seen: + if s in list(choices_all): + res.append(s) + elif s == '*': + res.extend(others) + seen.add(s) return res + + +def sanitize_pairs(pairs, pairs_all): + """Clean up a single-element mapping configuration attribute as returned + by `confit`'s `Pairs` template: keep only two-element tuples present in + pairs_all, remove duplicate elements, expand ('str', '*') and ('*', '*') + wildcards while keeping the original order. Note that ('*', '*') and + ('*', 'whatever') have the same effect. + + For example, + + >>> sanitize_pairs( + ... [('foo', 'baz bar'), ('key', '*'), ('*', '*')], + ... [('foo', 'bar'), ('foo', 'baz'), ('foo', 'foobar'), + ... ('key', 'value')] + ... ) + [('foo', 'baz'), ('foo', 'bar'), ('key', 'value'), ('foo', 'foobar')] + """ + pairs_all = list(pairs_all) + seen = set() + others = [x for x in pairs_all if x not in pairs] + res = [] + for k, values in pairs: + for v in values.split(): + x = (k, v) + if x in pairs_all: + if x not in seen: + seen.add(x) + res.append(x) + elif k == '*': + new = [o for o in others if o not in seen] + seen.update(new) + res.extend(new) + elif v == '*': + new = [o for o in others if o not in seen and o[0] == k] + seen.update(new) + res.extend(new) + return res + + +def notify_info_yielded(event): + """Makes a generator send the event 'event' every time it yields. + This decorator is supposed to decorate a generator, but any function + returning an iterable should work. + Each yielded value is passed to plugins using the 'info' parameter of + 'send'. + """ + def decorator(generator): + def decorated(*args, **kwargs): + for v in generator(*args, **kwargs): + send(event, info=v) + yield v + return decorated + return decorator diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 768eb76c7..af2b79a19 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -17,10 +18,8 @@ interface. To invoke the CLI, just call beets.ui.main(). The actual CLI commands are implemented in the ui.commands module. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function -import locale import optparse import textwrap import sys @@ -31,6 +30,7 @@ import re import struct import traceback import os.path +from six.moves import input from beets import logging from beets import library @@ -38,12 +38,14 @@ from beets import plugins from beets import util from beets.util.functemplate import Template from beets import config -from beets.util import confit +from beets.util import confit, as_string from beets.autotag import mb from beets.dbcore import query as db_query +from beets.dbcore import db +import six # On Windows platforms, use colorama to support "ANSI" terminal colors. -if sys.platform == b'win32': +if sys.platform == 'win32': try: import colorama except ImportError: @@ -59,8 +61,8 @@ log.propagate = False # Don't propagate to root handler. PF_KEY_QUERIES = { - 'comp': 'comp:true', - 'singleton': 'singleton:true', + 'comp': u'comp:true', + 'singleton': u'singleton:true', } @@ -70,43 +72,50 @@ class UserError(Exception): """ -# Utilities. +# Encoding utilities. + + +def _in_encoding(): + """Get the encoding to use for *inputting* strings from the console. + """ + return _stream_encoding(sys.stdin) + def _out_encoding(): """Get the encoding to use for *outputting* strings to the console. """ + return _stream_encoding(sys.stdout) + + +def _stream_encoding(stream, default='utf-8'): + """A helper for `_in_encoding` and `_out_encoding`: get the stream's + preferred encoding, using a configured override or a default + fallback if neither is not specified. + """ # Configured override? encoding = config['terminal_encoding'].get() if encoding: return encoding - # For testing: When sys.stdout is a StringIO under the test harness, - # it doesn't have an `encodiing` attribute. Just use UTF-8. - if not hasattr(sys.stdout, 'encoding'): - return 'utf8' + # For testing: When sys.stdout or sys.stdin is a StringIO under the + # test harness, it doesn't have an `encoding` attribute. Just use + # UTF-8. + if not hasattr(stream, 'encoding'): + return default # Python's guessed output stream encoding, or UTF-8 as a fallback # (e.g., when piped to a file). - return sys.stdout.encoding or 'utf8' - - -def _arg_encoding(): - """Get the encoding for command-line arguments (and other OS - locale-sensitive strings). - """ - try: - return locale.getdefaultlocale()[1] or 'utf8' - except ValueError: - # Invalid locale environment variable setting. To avoid - # failing entirely for no good reason, assume UTF-8. - return 'utf8' + return stream.encoding or default def decargs(arglist): """Given a list of command-line argument bytestrings, attempts to - decode them to Unicode strings. + decode them to Unicode strings when running under Python 2. """ - return [s.decode(_arg_encoding()) for s in arglist] + if six.PY2: + return [s.decode(util.arg_encoding()) for s in arglist] + else: + return arglist def print_(*strings, **kwargs): @@ -114,47 +123,99 @@ def print_(*strings, **kwargs): is not in the terminal's encoding's character set, just silently replaces it. - If the arguments are strings then they're expected to share the same - type: either bytes or unicode. + The arguments must be Unicode strings: `unicode` on Python 2; `str` on + Python 3. The `end` keyword argument behaves similarly to the built-in `print` - (it defaults to a newline). The value should have the same string - type as the arguments. + (it defaults to a newline). """ - end = kwargs.get('end') + if not strings: + strings = [u''] + assert isinstance(strings[0], six.text_type) - if not strings or isinstance(strings[0], unicode): - txt = u' '.join(strings) - txt += u'\n' if end is None else end + txt = u' '.join(strings) + txt += kwargs.get('end', u'\n') + + # Encode the string and write it to stdout. + if six.PY2: + # On Python 2, sys.stdout expects bytes. + out = txt.encode(_out_encoding(), 'replace') + sys.stdout.write(out) else: - txt = b' '.join(strings) - txt += b'\n' if end is None else end + # On Python 3, sys.stdout expects text strings and uses the + # exception-throwing encoding error policy. To avoid throwing + # errors and use our configurable encoding override, we use the + # underlying bytes buffer instead. + if hasattr(sys.stdout, 'buffer'): + out = txt.encode(_out_encoding(), 'replace') + sys.stdout.buffer.write(out) + sys.stdout.buffer.flush() + else: + # In our test harnesses (e.g., DummyOut), sys.stdout.buffer + # does not exist. We instead just record the text string. + sys.stdout.write(txt) - # Always send bytes to the stdout stream. - if isinstance(txt, unicode): - txt = txt.encode(_out_encoding(), 'replace') - sys.stdout.write(txt) +# Configuration wrappers. +def _bool_fallback(a, b): + """Given a boolean or None, return the original value or a fallback. + """ + if a is None: + assert isinstance(b, bool) + return b + else: + assert isinstance(a, bool) + return a + + +def should_write(write_opt=None): + """Decide whether a command that updates metadata should also write + tags, using the importer configuration as the default. + """ + return _bool_fallback(write_opt, config['import']['write'].get(bool)) + + +def should_move(move_opt=None): + """Decide whether a command that updates metadata should also move + files when they're inside the library, using the importer + configuration as the default. + + Specifically, commands should move files after metadata updates only + when the importer is configured *either* to move *or* to copy files. + They should avoid moving files when the importer is configured not + to touch any filenames. + """ + return _bool_fallback( + move_opt, + config['import']['move'].get(bool) or + config['import']['copy'].get(bool) + ) + + +# Input prompts. def input_(prompt=None): - """Like `raw_input`, but decodes the result to a Unicode string. + """Like `input`, but decodes the result to a Unicode string. Raises a UserError if stdin is not available. The prompt is sent to stdout rather than stderr. A printed between the prompt and the input cursor. """ # raw_input incorrectly sends prompts to stderr, not stdout, so we - # use print() explicitly to display prompts. + # use print_() explicitly to display prompts. # http://bugs.python.org/issue1927 if prompt: - print_(prompt, end=' ') + print_(prompt, end=u' ') try: - resp = raw_input() + resp = input() except EOFError: - raise UserError('stdin stream ended while input required') + raise UserError(u'stdin stream ended while input required') - return resp.decode(sys.stdin.encoding or 'utf8', 'ignore') + if six.PY2: + return resp.decode(_in_encoding(), 'ignore') + else: + return resp def input_options(options, require=False, prompt=None, fallback_prompt=None, @@ -198,7 +259,7 @@ def input_options(options, require=False, prompt=None, fallback_prompt=None, found_letter = letter break else: - raise ValueError('no unambiguous lettering found') + raise ValueError(u'no unambiguous lettering found') letters[found_letter.lower()] = option index = option.index(found_letter) @@ -206,7 +267,7 @@ def input_options(options, require=False, prompt=None, fallback_prompt=None, # Mark the option's shortcut letter for display. if not require and ( (default is None and not numrange and first) or - (isinstance(default, basestring) and + (isinstance(default, six.string_types) and found_letter.lower() == default.lower())): # The first option is the default; mark it. show_letter = '[%s]' % found_letter.upper() @@ -242,11 +303,11 @@ def input_options(options, require=False, prompt=None, fallback_prompt=None, prompt_part_lengths = [] if numrange: if isinstance(default, int): - default_name = unicode(default) + default_name = six.text_type(default) default_name = colorize('action_default', default_name) tmpl = '# selection (default %s)' prompt_parts.append(tmpl % default_name) - prompt_part_lengths.append(len(tmpl % unicode(default))) + prompt_part_lengths.append(len(tmpl % six.text_type(default))) else: prompt_parts.append('# selection') prompt_part_lengths.append(len(prompt_parts[-1])) @@ -281,9 +342,9 @@ def input_options(options, require=False, prompt=None, fallback_prompt=None, # Make a fallback prompt too. This is displayed if the user enters # something that is not recognized. if not fallback_prompt: - fallback_prompt = 'Enter one of ' + fallback_prompt = u'Enter one of ' if numrange: - fallback_prompt += '%i-%i, ' % numrange + fallback_prompt += u'%i-%i, ' % numrange fallback_prompt += ', '.join(display_letters) + ':' resp = input_(prompt) @@ -322,21 +383,52 @@ def input_yn(prompt, require=False): "yes" unless `require` is `True`, in which case there is no default. """ sel = input_options( - ('y', 'n'), require, prompt, 'Enter Y or N:' + ('y', 'n'), require, prompt, u'Enter Y or N:' ) - return sel == 'y' + return sel == u'y' +def input_select_objects(prompt, objs, rep): + """Prompt to user to choose all, none, or some of the given objects. + Return the list of selected objects. + + `prompt` is the prompt string to use for each question (it should be + phrased as an imperative verb). `rep` is a function to call on each + object to print it out when confirming objects individually. + """ + choice = input_options( + (u'y', u'n', u's'), False, + u'%s? (Yes/no/select)' % prompt) + print() # Blank line. + + if choice == u'y': # Yes. + return objs + + elif choice == u's': # Select. + out = [] + for obj in objs: + rep(obj) + if input_yn(u'%s? (yes/no)' % prompt, True): + out.append(obj) + print() # go to a new line + return out + + else: # No. + return [] + + +# Human output formatting. + def human_bytes(size): """Formats size, a number of bytes, in a human-readable way.""" - powers = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'H'] + powers = [u'', u'K', u'M', u'G', u'T', u'P', u'E', u'Z', u'Y', u'H'] unit = 'B' for power in powers: if size < 1024: - return "%3.1f %s%s" % (size, power, unit) + return u"%3.1f %s%s" % (size, power, unit) size /= 1024.0 - unit = 'iB' - return "big" + unit = u'iB' + return u"big" def human_seconds(interval): @@ -344,13 +436,13 @@ def human_seconds(interval): interval using English words. """ units = [ - (1, 'second'), - (60, 'minute'), - (60, 'hour'), - (24, 'day'), - (7, 'week'), - (52, 'year'), - (10, 'decade'), + (1, u'second'), + (60, u'minute'), + (60, u'hour'), + (24, u'day'), + (7, u'week'), + (52, u'year'), + (10, u'decade'), ] for i in range(len(units) - 1): increment, suffix = units[i] @@ -363,7 +455,7 @@ def human_seconds(interval): increment, suffix = units[-1] interval /= float(increment) - return "%3.1f %ss" % (interval, suffix) + return u"%3.1f %ss" % (interval, suffix) def human_seconds_short(interval): @@ -374,6 +466,8 @@ def human_seconds_short(interval): return u'%i:%02i' % (interval // 60, interval % 60) +# Colorization. + # ANSI terminal colorization code heavily inspired by pygments: # http://dev.pocoo.org/hg/pygments-main/file/b2deea5b5030/pygments/console.py # (pygments is by Tim Hatch, Armin Ronacher, et al.) @@ -422,7 +516,7 @@ def _colorize(color, text): elif color in LIGHT_COLORS: escape = COLOR_ESCAPE + "%i;01m" % (LIGHT_COLORS[color] + 30) else: - raise ValueError('no such color %s', color) + raise ValueError(u'no such color %s', color) return escape + text + RESET_COLOR @@ -433,7 +527,8 @@ def colorize(color_name, text): if config['ui']['color']: global COLORS if not COLORS: - COLORS = dict((name, config['ui']['colors'][name].get(unicode)) + COLORS = dict((name, + config['ui']['colors'][name].as_str()) for name in COLOR_NAMES) # In case a 3rd party plugin is still passing the actual color ('red') # instead of the abstract color name ('text_error') @@ -453,10 +548,11 @@ def _colordiff(a, b, highlight='text_highlight', highlighted intelligently to show differences; other values are stringified and highlighted in their entirety. """ - if not isinstance(a, basestring) or not isinstance(b, basestring): + if not isinstance(a, six.string_types) \ + or not isinstance(b, six.string_types): # Non-strings: use ordinary equality. - a = unicode(a) - b = unicode(b) + a = six.text_type(a) + b = six.text_type(b) if a == b: return a, b else: @@ -504,7 +600,7 @@ def colordiff(a, b, highlight='text_highlight'): if config['ui']['color']: return _colordiff(a, b, highlight) else: - return unicode(a), unicode(b) + return six.text_type(a), six.text_type(b) def get_path_formats(subview=None): @@ -515,7 +611,7 @@ def get_path_formats(subview=None): subview = subview or config['paths'] for query, view in subview.items(): query = PF_KEY_QUERIES.get(query, query) # Expand common queries. - path_formats.append((query, Template(view.get(unicode)))) + path_formats.append((query, Template(view.as_str()))) return path_formats @@ -553,7 +649,7 @@ def term_width(): except IOError: return fallback try: - height, width = struct.unpack(b'hh', buf) + height, width = struct.unpack('hh', buf) except struct.error: return fallback return width @@ -583,7 +679,7 @@ def _field_diff(field, old, new): # For strings, highlight changes. For others, colorize the whole # thing. - if isinstance(oldval, basestring): + if isinstance(oldval, six.string_types): oldstr, newstr = colordiff(oldval, newstr) else: oldstr = colorize('text_error', oldstr) @@ -653,8 +749,8 @@ def show_path_changes(path_changes): sources, destinations = zip(*path_changes) # Ensure unicode output - sources = map(util.displayable_path, sources) - destinations = map(util.displayable_path, destinations) + sources = list(map(util.displayable_path, sources)) + destinations = list(map(util.displayable_path, destinations)) # Calculate widths for terminal split col_width = (term_width() - len(' -> ')) // 2 @@ -674,6 +770,34 @@ def show_path_changes(path_changes): log.info(u'{0} {1} -> {2}', source, ' ' * pad, dest) +# Helper functions for option parsing. + +def _store_dict(option, opt_str, value, parser): + """Custom action callback to parse options which have ``key=value`` + pairs as values. All such pairs passed for this option are + aggregated into a dictionary. + """ + dest = option.dest + option_values = getattr(parser.values, dest, None) + + if option_values is None: + # This is the first supplied ``key=value`` pair of option. + # Initialize empty dictionary and get a reference to it. + setattr(parser.values, dest, dict()) + option_values = getattr(parser.values, dest) + + try: + key, value = map(lambda s: util.text_string(s), value.split('=')) + if not (key and value): + raise ValueError + except ValueError: + raise UserError( + "supplied argument `{0}' is not of the form `key=value'" + .format(value)) + + option_values[key] = value + + class CommonOptionsParser(optparse.OptionParser, object): """Offers a simple way to add common formatting options. @@ -704,7 +828,7 @@ class CommonOptionsParser(optparse.OptionParser, object): Sets the album property on the options extracted from the CLI. """ album = optparse.Option(*flags, action='store_true', - help='match albums instead of tracks') + help=u'match albums instead of tracks') self.add_option(album) self._album_flags = set(flags) @@ -716,7 +840,14 @@ class CommonOptionsParser(optparse.OptionParser, object): if store_true: setattr(parser.values, option.dest, True) - value = fmt or value and unicode(value) or '' + # Use the explicitly specified format, or the string from the option. + if fmt: + value = fmt + elif value: + value, = decargs([value]) + else: + value = u'' + parser.values.format = value if target: config[target._format_config_key].set(value) @@ -747,9 +878,9 @@ class CommonOptionsParser(optparse.OptionParser, object): """ path = optparse.Option(*flags, nargs=0, action='callback', callback=self._set_format, - callback_kwargs={'fmt': '$path', + callback_kwargs={'fmt': u'$path', 'store_true': True}, - help='print paths for matched items or albums') + help=u'print paths for matched items or albums') self.add_option(path) def add_format_option(self, flags=('-f', '--format'), target=None): @@ -769,7 +900,7 @@ class CommonOptionsParser(optparse.OptionParser, object): """ kwargs = {} if target: - if isinstance(target, basestring): + if isinstance(target, six.string_types): target = {'item': library.Item, 'album': library.Album}[target] kwargs['target'] = target @@ -777,7 +908,7 @@ class CommonOptionsParser(optparse.OptionParser, object): opt = optparse.Option(*flags, action='callback', callback=self._set_format, callback_kwargs=kwargs, - help='print with custom format') + help=u'print with custom format') self.add_option(opt) def add_all_common_options(self): @@ -828,7 +959,7 @@ class Subcommand(object): def root_parser(self, root_parser): self._root_parser = root_parser self.parser.prog = '{0} {1}'.format( - root_parser.get_prog_name().decode('utf8'), self.name) + as_string(root_parser.get_prog_name()), self.name) class SubcommandsOptionParser(CommonOptionsParser): @@ -843,7 +974,7 @@ class SubcommandsOptionParser(CommonOptionsParser): """ # A more helpful default usage. if 'usage' not in kwargs: - kwargs['usage'] = """ + kwargs['usage'] = u""" %prog COMMAND [ARGS...] %prog help COMMAND""" kwargs['add_help_option'] = False @@ -906,7 +1037,8 @@ class SubcommandsOptionParser(CommonOptionsParser): result.append(name) help_width = formatter.width - help_position help_lines = textwrap.wrap(subcommand.help, help_width) - result.append("%*s%s\n" % (indent_first, "", help_lines[0])) + help_line = help_lines[0] if help_lines else '' + result.append("%*s%s\n" % (indent_first, "", help_line)) result.extend(["%*s%s\n" % (help_position, "", line) for line in help_lines[1:]]) formatter.dedent() @@ -951,7 +1083,7 @@ class SubcommandsOptionParser(CommonOptionsParser): cmdname = args.pop(0) subcommand = self._subcommand_for_name(cmdname) if not subcommand: - raise UserError("unknown command '{0}'".format(cmdname)) + raise UserError(u"unknown command '{0}'".format(cmdname)) suboptions, subargs = subcommand.parse_args(args) return subcommand, suboptions, subargs @@ -960,54 +1092,24 @@ class SubcommandsOptionParser(CommonOptionsParser): optparse.Option.ALWAYS_TYPED_ACTIONS += ('callback',) -def vararg_callback(option, opt_str, value, parser): - """Callback for an option with variable arguments. - Manually collect arguments right of a callback-action - option (ie. with action="callback"), and add the resulting - list to the destination var. - - Usage: - parser.add_option("-c", "--callback", dest="vararg_attr", - action="callback", callback=vararg_callback) - - Details: - http://docs.python.org/2/library/optparse.html#callback-example-6-variable - -arguments - """ - value = [value] - - def floatable(str): - try: - float(str) - return True - except ValueError: - return False - - for arg in parser.rargs: - # stop on --foo like options - if arg[:2] == "--" and len(arg) > 2: - break - # stop on -a, but not on -3 or -3.0 - if arg[:1] == "-" and len(arg) > 1 and not floatable(arg): - break - value.append(arg) - - del parser.rargs[:len(value) - 1] - setattr(parser.values, option.dest, value) - - # The main entry point and bootstrapping. def _load_plugins(config): """Load the plugins specified in the configuration. """ - paths = config['pluginpath'].get(confit.StrSeq(split=False)) - paths = map(util.normpath, paths) - log.debug('plugin paths: {0}', util.displayable_path(paths)) + paths = config['pluginpath'].as_str_seq(split=False) + paths = [util.normpath(p) for p in paths] + log.debug(u'plugin paths: {0}', util.displayable_path(paths)) + # On Python 3, the search paths need to be unicode. + paths = [util.py3_path(p) for p in paths] + + # Extend the `beetsplug` package to include the plugin paths. import beetsplug beetsplug.__path__ = paths + beetsplug.__path__ - # For backwards compatibility. + + # For backwards compatibility, also support plugin paths that + # *contain* a `beetsplug` package. sys.path += paths plugins.load_plugins(config['plugins'].as_str_seq()) @@ -1048,10 +1150,12 @@ def _configure(options): # Add any additional config files specified with --config. This # special handling lets specified plugins get loaded before we # finish parsing the command line. - if getattr(options, b'config', None) is not None: - config_path = options.config + if getattr(options, 'config', None) is not None: + overlay_path = options.config del options.config - config.set_file(config_path) + config.set_file(overlay_path) + else: + overlay_path = None config.set_args(options) # Configure the logger. @@ -1060,24 +1164,9 @@ def _configure(options): else: log.set_global_level(logging.INFO) - # Ensure compatibility with old (top-level) color configuration. - # Deprecation msg to motivate user to switch to config['ui']['color]. - if config['color'].exists(): - log.warning(u'Warning: top-level configuration of `color` ' - u'is deprecated. Configure color use under `ui`. ' - u'See documentation for more info.') - config['ui']['color'].set(config['color'].get(bool)) - - # Compatibility from list_format_{item,album} to format_{item,album} - for elem in ('item', 'album'): - old_key = 'list_format_{0}'.format(elem) - if config[old_key].exists(): - new_key = 'format_{0}'.format(elem) - log.warning('Warning: configuration uses "{0}" which is deprecated' - ' in favor of "{1}" now that it affects all commands. ' - 'See changelog & documentation.'.format(old_key, - new_key)) - config[new_key].set(config[old_key]) + if overlay_path: + log.debug(u'overlaying configuration: {0}', + util.displayable_path(overlay_path)) config_path = config.user_config_path() if os.path.isfile(config_path): @@ -1095,7 +1184,7 @@ def _configure(options): def _open_library(config): """Create a new library instance from the configuration. """ - dbpath = config['library'].as_filename() + dbpath = util.bytestring_path(config['library'].as_filename()) try: lib = library.Library( dbpath, @@ -1105,7 +1194,7 @@ def _open_library(config): ) lib.get_item(0) # Test database connection. except (sqlite3.OperationalError, sqlite3.DatabaseError): - log.debug('{}', traceback.format_exc()) + log.debug(u'{}', traceback.format_exc()) raise UserError(u"database file {0} could not be opened".format( util.displayable_path(dbpath) )) @@ -1124,15 +1213,15 @@ def _raw_main(args, lib=None): parser.add_format_option(flags=('--format-item',), target=library.Item) parser.add_format_option(flags=('--format-album',), target=library.Album) parser.add_option('-l', '--library', dest='library', - help='library database file to use') + help=u'library database file to use') parser.add_option('-d', '--directory', dest='directory', - help="destination music directory") + help=u"destination music directory") parser.add_option('-v', '--verbose', dest='verbose', action='count', - help='print debugging information') + help=u'log more details (use twice for even more)') parser.add_option('-c', '--config', dest='config', - help='path to configuration file') + help=u'path to configuration file') parser.add_option('-h', '--help', dest='help', action='store_true', - help='how this help message and exit') + help=u'show this help message and exit') parser.add_option('--version', dest='version', action='store_true', help=optparse.SUPPRESS_HELP) @@ -1146,6 +1235,7 @@ def _raw_main(args, lib=None): from beets.ui.commands import config_edit return config_edit() + test_lib = bool(lib) subcommands, plugins, lib = _setup(options, lib) parser.add_subcommand(*subcommands) @@ -1153,6 +1243,9 @@ def _raw_main(args, lib=None): subcommand.func(lib, suboptions, subargs) plugins.send('cli_exit', lib=lib) + if not test_lib: + # Clean up the library unless it came from the test harness. + lib._close() def main(args=None): @@ -1183,9 +1276,16 @@ def main(args=None): except IOError as exc: if exc.errno == errno.EPIPE: # "Broken pipe". End silently. - pass + sys.stderr.close() else: raise except KeyboardInterrupt: # Silently ignore ^C except in verbose mode. - log.debug('{}', traceback.format_exc()) + log.debug(u'{}', traceback.format_exc()) + except db.DBAccessError as exc: + log.error( + u'database access error: {0}\n' + u'the library file might have a permissions problem', + exc + ) + sys.exit(1) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index f3386cf71..610ae551e 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -16,11 +17,13 @@ interface. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import os import re +from platform import python_version +from collections import namedtuple, Counter +from itertools import chain import beets from beets import ui @@ -31,13 +34,17 @@ from beets.autotag import hooks from beets import plugins from beets import importer from beets import util -from beets.util import syspath, normpath, ancestry, displayable_path +from beets.util import syspath, normpath, ancestry, displayable_path, \ + MoveOperation from beets import library from beets import config from beets import logging from beets.util.confit import _package_path +import six +from . import _store_dict VARIOUS_ARTISTS = u'Various Artists' +PromptChoice = namedtuple('PromptChoice', ['short', 'long', 'callback']) # Global logger. log = logging.getLogger('beets') @@ -68,30 +75,47 @@ def _do_query(lib, query, album, also_items=True): items = list(lib.items(query)) if album and not albums: - raise ui.UserError('No matching albums found.') + raise ui.UserError(u'No matching albums found.') elif not album and not items: - raise ui.UserError('No matching items found.') + raise ui.UserError(u'No matching items found.') return items, albums # fields: Shows a list of available fields for queries and format strings. +def _print_keys(query): + """Given a SQLite query result, print the `key` field of each + returned row, with indentation of 2 spaces. + """ + for row in query: + print_(u' ' * 2 + row['key']) + + def fields_func(lib, opts, args): def _print_rows(names): names.sort() - print_(" " + "\n ".join(names)) + print_(u' ' + u'\n '.join(names)) - print_("Item fields:") + print_(u"Item fields:") _print_rows(library.Item.all_keys()) - print_("Album fields:") + print_(u"Album fields:") _print_rows(library.Album.all_keys()) + with lib.transaction() as tx: + # The SQL uses the DISTINCT to get unique values from the query + unique_fields = 'SELECT DISTINCT key FROM (%s)' + + print_(u"Item flexible attributes:") + _print_keys(tx.query(unique_fields % library.Item._flex_table)) + + print_(u"Album flexible attributes:") + _print_keys(tx.query(unique_fields % library.Album._flex_table)) fields_cmd = ui.Subcommand( 'fields', - help='show fields available for queries and format strings' + help=u'show fields available for queries and format strings' ) fields_cmd.func = fields_func default_commands.append(fields_cmd) @@ -104,7 +128,7 @@ class HelpCommand(ui.Subcommand): def __init__(self): super(HelpCommand, self).__init__( 'help', aliases=('?',), - help='give detailed help on a specific sub-command', + help=u'give detailed help on a specific sub-command', ) def func(self, lib, opts, args): @@ -112,7 +136,7 @@ class HelpCommand(ui.Subcommand): cmdname = args[0] helpcommand = self.root_parser._subcommand_for_name(cmdname) if not helpcommand: - raise ui.UserError("unknown command '{0}'".format(cmdname)) + raise ui.UserError(u"unknown command '{0}'".format(cmdname)) helpcommand.print_help() else: self.root_parser.print_help() @@ -136,14 +160,14 @@ def disambig_string(info): if isinstance(info, hooks.AlbumInfo): if info.media: - if info.mediums > 1: + if info.mediums and info.mediums > 1: disambig.append(u'{0}x{1}'.format( info.mediums, info.media )) else: disambig.append(info.media) if info.year: - disambig.append(unicode(info.year)) + disambig.append(six.text_type(info.year)) if info.country: disambig.append(info.country) if info.label: @@ -159,7 +183,7 @@ def dist_string(dist): """Formats a distance (a float) as a colorized similarity percentage string. """ - out = '%.1f%%' % ((1 - dist) * 100) + out = u'%.1f%%' % ((1 - dist) * 100) if dist <= config['match']['strong_rec_thresh'].as_number(): out = ui.colorize('text_success', out) elif dist <= config['match']['medium_rec_thresh'].as_number(): @@ -182,7 +206,7 @@ def penalty_string(distance, limit=None): if penalties: if limit and len(penalties) > limit: penalties = penalties[:limit] + ['...'] - return ui.colorize('text_warning', '(%s)' % ', '.join(penalties)) + return ui.colorize('text_warning', u'(%s)' % ', '.join(penalties)) def show_change(cur_artist, cur_album, match): @@ -216,9 +240,9 @@ def show_change(cur_artist, cur_album, match): if mediums > 1: return u'{0}-{1}'.format(medium, medium_index) else: - return unicode(medium_index) + return six.text_type(medium_index or index) else: - return unicode(index) + return six.text_type(index) # Identify the album in question. if cur_artist != match.info.artist or \ @@ -233,21 +257,21 @@ def show_change(cur_artist, cur_album, match): artist_l, artist_r = ui.colordiff(artist_l, artist_r) album_l, album_r = ui.colordiff(album_l, album_r) - print_("Correcting tags from:") + print_(u"Correcting tags from:") show_album(artist_l, album_l) - print_("To:") + print_(u"To:") show_album(artist_r, album_r) else: print_(u"Tagging:\n {0.artist} - {0.album}".format(match.info)) # Data URL. if match.info.data_url: - print_('URL:\n %s' % match.info.data_url) + print_(u'URL:\n %s' % match.info.data_url) # Info line. info = [] # Similarity. - info.append('(Similarity: %s)' % dist_string(match.distance)) + info.append(u'(Similarity: %s)' % dist_string(match.distance)) # Penalties. penalties = penalty_string(match.distance) if penalties: @@ -255,12 +279,12 @@ def show_change(cur_artist, cur_album, match): # Disambiguation. disambig = disambig_string(match.info) if disambig: - info.append(ui.colorize('text_highlight_minor', '(%s)' % disambig)) + info.append(ui.colorize('text_highlight_minor', u'(%s)' % disambig)) print_(' '.join(info)) # Tracks. - pairs = match.mapping.items() - pairs.sort(key=lambda (_, track_info): track_info.index) + pairs = list(match.mapping.items()) + pairs.sort(key=lambda item_and_track_info: item_and_track_info[1].index) # Build up LHS and RHS for track difference display. The `lines` list # contains ``(lhs, rhs, width)`` tuples where `width` is the length (in @@ -273,16 +297,16 @@ def show_change(cur_artist, cur_album, match): if medium != track_info.medium or disctitle != track_info.disctitle: media = match.info.media or 'Media' if match.info.mediums > 1 and track_info.disctitle: - lhs = '%s %s: %s' % (media, track_info.medium, - track_info.disctitle) + lhs = u'%s %s: %s' % (media, track_info.medium, + track_info.disctitle) elif match.info.mediums > 1: - lhs = '%s %s' % (media, track_info.medium) + lhs = u'%s %s' % (media, track_info.medium) elif track_info.disctitle: - lhs = '%s: %s' % (media, track_info.disctitle) + lhs = u'%s: %s' % (media, track_info.disctitle) else: lhs = None if lhs: - lines.append((lhs, '', 0)) + lines.append((lhs, u'', 0)) medium, disctitle = track_info.medium, track_info.disctitle # Titles. @@ -325,9 +349,9 @@ def show_change(cur_artist, cur_album, match): rhs += ' %s' % penalties if lhs != rhs: - lines.append((' * %s' % lhs, rhs, lhs_width)) + lines.append((u' * %s' % lhs, rhs, lhs_width)) elif config['import']['detail']: - lines.append((' * %s' % lhs, '', lhs_width)) + lines.append((u' * %s' % lhs, '', lhs_width)) # Print each track in two columns, or across two lines. col_width = (ui.term_width() - len(''.join([' * ', ' -> ']))) // 2 @@ -344,22 +368,22 @@ def show_change(cur_artist, cur_album, match): # Missing and unmatched tracks. if match.extra_tracks: - print_('Missing tracks ({0}/{1} - {2:.1%}):'.format( + print_(u'Missing tracks ({0}/{1} - {2:.1%}):'.format( len(match.extra_tracks), len(match.info.tracks), len(match.extra_tracks) / len(match.info.tracks) )) for track_info in match.extra_tracks: - line = ' ! %s (#%s)' % (track_info.title, format_index(track_info)) + line = u' ! %s (#%s)' % (track_info.title, format_index(track_info)) if track_info.length: - line += ' (%s)' % ui.human_seconds_short(track_info.length) + line += u' (%s)' % ui.human_seconds_short(track_info.length) print_(ui.colorize('text_warning', line)) if match.extra_items: - print_('Unmatched tracks ({0}):'.format(len(match.extra_items))) + print_(u'Unmatched tracks ({0}):'.format(len(match.extra_items))) for item in match.extra_items: - line = ' ! %s (#%s)' % (item.title, format_index(item)) + line = u' ! %s (#%s)' % (item.title, format_index(item)) if item.length: - line += ' (%s)' % ui.human_seconds_short(item.length) + line += u' (%s)' % ui.human_seconds_short(item.length) print_(ui.colorize('text_warning', line)) @@ -374,22 +398,22 @@ def show_item_change(item, match): cur_artist, new_artist = ui.colordiff(cur_artist, new_artist) cur_title, new_title = ui.colordiff(cur_title, new_title) - print_("Correcting track tags from:") - print_(" %s - %s" % (cur_artist, cur_title)) - print_("To:") - print_(" %s - %s" % (new_artist, new_title)) + print_(u"Correcting track tags from:") + print_(u" %s - %s" % (cur_artist, cur_title)) + print_(u"To:") + print_(u" %s - %s" % (new_artist, new_title)) else: - print_("Tagging track: %s - %s" % (cur_artist, cur_title)) + print_(u"Tagging track: %s - %s" % (cur_artist, cur_title)) # Data URL. if match.info.data_url: - print_('URL:\n %s' % match.info.data_url) + print_(u'URL:\n %s' % match.info.data_url) # Info line. info = [] # Similarity. - info.append('(Similarity: %s)' % dist_string(match.distance)) + info.append(u'(Similarity: %s)' % dist_string(match.distance)) # Penalties. penalties = penalty_string(match.distance) if penalties: @@ -397,7 +421,7 @@ def show_item_change(item, match): # Disambiguation. disambig = disambig_string(match.info) if disambig: - info.append(ui.colorize('text_highlight_minor', '(%s)' % disambig)) + info.append(ui.colorize('text_highlight_minor', u'(%s)' % disambig)) print_(' '.join(info)) @@ -411,7 +435,7 @@ def summarize_items(items, singleton): """ summary_parts = [] if not singleton: - summary_parts.append("{0} items".format(len(items))) + summary_parts.append(u"{0} items".format(len(items))) format_counts = {} for item in items: @@ -421,22 +445,24 @@ def summarize_items(items, singleton): summary_parts.append(items[0].format) else: # Enumerate all the formats by decreasing frequencies: - for fmt, count in sorted(format_counts.items(), - key=lambda (f, c): (-c, f)): + for fmt, count in sorted( + format_counts.items(), + key=lambda fmt_and_count: (-fmt_and_count[1], fmt_and_count[0]) + ): summary_parts.append('{0} {1}'.format(fmt, count)) if items: average_bitrate = sum([item.bitrate for item in items]) / len(items) total_duration = sum([item.length for item in items]) total_filesize = sum([item.filesize for item in items]) - summary_parts.append('{0}kbps'.format(int(average_bitrate / 1000))) + summary_parts.append(u'{0}kbps'.format(int(average_bitrate / 1000))) summary_parts.append(ui.human_seconds_short(total_duration)) summary_parts.append(ui.human_bytes(total_filesize)) - return ', '.join(summary_parts) + return u', '.join(summary_parts) -def _summary_judment(rec): +def _summary_judgment(rec): """Determines whether a decision should be made without even asking the user. This occurs in quiet mode and when an action is chosen for NONE recommendations. Return an action or None if the user should be @@ -463,14 +489,15 @@ def _summary_judment(rec): return None if action == importer.action.SKIP: - print_('Skipping.') + print_(u'Skipping.') elif action == importer.action.ASIS: - print_('Importing as-is.') + print_(u'Importing as-is.') return action def choose_candidate(candidates, singleton, rec, cur_artist=None, - cur_album=None, item=None, itemcount=None): + cur_album=None, item=None, itemcount=None, + choices=[]): """Given a sorted list of candidates, ask the user for a selection of which candidate to use. Applies to both full albums and singletons (tracks). Candidates are either AlbumMatch or TrackMatch @@ -478,8 +505,12 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, `cur_album`, and `itemcount` must be provided. For singletons, `item` must be provided. - Returns the result of the choice, which may SKIP, ASIS, TRACKS, or - MANUAL or a candidate (an AlbumMatch/TrackMatch object). + `choices` is a list of `PromptChoice`s to be used in each prompt. + + Returns one of the following: + * the result of the choice, which may be SKIP or ASIS + * a candidate (an AlbumMatch/TrackMatch object) + * a chosen `PromptChoice` from `choices` """ # Sanity check. if singleton: @@ -488,35 +519,22 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, assert cur_artist is not None assert cur_album is not None + # Build helper variables for the prompt choices. + choice_opts = tuple(c.long for c in choices) + choice_actions = {c.short: c for c in choices} + # Zero candidates. if not candidates: if singleton: - print_("No matching recordings found.") - opts = ('Use as-is', 'Skip', 'Enter search', 'enter Id', - 'aBort') + print_(u"No matching recordings found.") else: - print_("No matching release found for {0} tracks." + print_(u"No matching release found for {0} tracks." .format(itemcount)) - print_('For help, see: ' - 'http://beets.readthedocs.org/en/latest/faq.html#nomatch') - opts = ('Use as-is', 'as Tracks', 'Group albums', 'Skip', - 'Enter search', 'enter Id', 'aBort') - sel = ui.input_options(opts) - if sel == 'u': - return importer.action.ASIS - elif sel == 't': - assert not singleton - return importer.action.TRACKS - elif sel == 'e': - return importer.action.MANUAL - elif sel == 's': - return importer.action.SKIP - elif sel == 'b': - raise importer.ImportAbort() - elif sel == 'i': - return importer.action.MANUAL_ID - elif sel == 'g': - return importer.action.ALBUMS + print_(u'For help, see: ' + u'http://beets.readthedocs.org/en/latest/faq.html#nomatch') + sel = ui.input_options(choice_opts) + if sel in choice_actions: + return choice_actions[sel] else: assert False @@ -559,35 +577,17 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, disambig = disambig_string(match.info) if disambig: line.append(ui.colorize('text_highlight_minor', - '(%s)' % disambig)) + u'(%s)' % disambig)) - print_(' '.join(line)) + print_(u' '.join(line)) # Ask the user for a choice. - if singleton: - opts = ('Skip', 'Use as-is', 'Enter search', 'enter Id', - 'aBort') - else: - opts = ('Skip', 'Use as-is', 'as Tracks', 'Group albums', - 'Enter search', 'enter Id', 'aBort') - sel = ui.input_options(opts, numrange=(1, len(candidates))) - if sel == 's': - return importer.action.SKIP - elif sel == 'u': - return importer.action.ASIS - elif sel == 'm': + sel = ui.input_options(choice_opts, + numrange=(1, len(candidates))) + if sel == u'm': pass - elif sel == 'e': - return importer.action.MANUAL - elif sel == 't': - assert not singleton - return importer.action.TRACKS - elif sel == 'b': - raise importer.ImportAbort() - elif sel == 'i': - return importer.action.MANUAL_ID - elif sel == 'g': - return importer.action.ALBUMS + elif sel in choice_actions: + return choice_actions[sel] else: # Numerical selection. match = candidates[sel - 1] if sel != 1: @@ -607,55 +607,65 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, return match # Ask for confirmation. - if singleton: - opts = ('Apply', 'More candidates', 'Skip', 'Use as-is', - 'Enter search', 'enter Id', 'aBort') - else: - opts = ('Apply', 'More candidates', 'Skip', 'Use as-is', - 'as Tracks', 'Group albums', 'Enter search', 'enter Id', - 'aBort') default = config['import']['default_action'].as_choice({ - 'apply': 'a', - 'skip': 's', - 'asis': 'u', - 'none': None, + u'apply': u'a', + u'skip': u's', + u'asis': u'u', + u'none': None, }) if default is None: require = True - sel = ui.input_options(opts, require=require, default=default) - if sel == 'a': + # Bell ring when user interaction is needed. + if config['import']['bell']: + ui.print_(u'\a', end=u'') + sel = ui.input_options((u'Apply', u'More candidates') + choice_opts, + require=require, default=default) + if sel == u'a': return match - elif sel == 'g': - return importer.action.ALBUMS - elif sel == 's': - return importer.action.SKIP - elif sel == 'u': - return importer.action.ASIS - elif sel == 't': - assert not singleton - return importer.action.TRACKS - elif sel == 'e': - return importer.action.MANUAL - elif sel == 'b': - raise importer.ImportAbort() - elif sel == 'i': - return importer.action.MANUAL_ID + elif sel in choice_actions: + return choice_actions[sel] -def manual_search(singleton): - """Input either an artist and album (for full albums) or artist and +def manual_search(session, task): + """Get a new `Proposal` using manual search criteria. + + Input either an artist and album (for full albums) or artist and track name (for singletons) for manual search. """ - artist = input_('Artist:') - name = input_('Track:' if singleton else 'Album:') - return artist.strip(), name.strip() + artist = input_(u'Artist:').strip() + name = input_(u'Album:' if task.is_album else u'Track:').strip() + + if task.is_album: + _, _, prop = autotag.tag_album( + task.items, artist, name + ) + return prop + else: + return autotag.tag_item(task.item, artist, name) -def manual_id(singleton): - """Input an ID, either for an album ("release") or a track ("recording"). +def manual_id(session, task): + """Get a new `Proposal` using a manually-entered ID. + + Input an ID, either for an album ("release") or a track ("recording"). """ - prompt = u'Enter {0} ID:'.format('recording' if singleton else 'release') - return input_(prompt).strip() + prompt = u'Enter {0} ID:'.format(u'release' if task.is_album + else u'recording') + search_id = input_(prompt).strip() + + if task.is_album: + _, _, prop = autotag.tag_album( + task.items, search_ids=search_id.split() + ) + return prop + else: + return autotag.tag_item(task.item, search_ids=search_id.split()) + + +def abort_action(session, task): + """A prompt choice callback that aborts the importer. + """ + raise importer.ImportAbort() class TerminalImportSession(importer.ImportSession): @@ -672,7 +682,7 @@ class TerminalImportSession(importer.ImportSession): u' ({0} items)'.format(len(task.items))) # Take immediate action if appropriate. - action = _summary_judment(task.rec) + action = _summary_judgment(task.rec) if action == importer.action.APPLY: match = task.candidates[0] show_change(task.cur_artist, task.cur_album, match) @@ -681,32 +691,34 @@ class TerminalImportSession(importer.ImportSession): return action # Loop until we have a choice. - candidates, rec = task.candidates, task.rec while True: - # Ask for a choice from the user. + # Ask for a choice from the user. The result of + # `choose_candidate` may be an `importer.action`, an + # `AlbumMatch` object for a specific selection, or a + # `PromptChoice`. + choices = self._get_choices(task) choice = choose_candidate( - candidates, False, rec, task.cur_artist, task.cur_album, - itemcount=len(task.items) + task.candidates, False, task.rec, task.cur_artist, + task.cur_album, itemcount=len(task.items), choices=choices ) - # Choose which tags to use. - if choice in (importer.action.SKIP, importer.action.ASIS, - importer.action.TRACKS, importer.action.ALBUMS): + # Basic choices that require no more action here. + if choice in (importer.action.SKIP, importer.action.ASIS): # Pass selection to main control flow. return choice - elif choice is importer.action.MANUAL: - # Try again with manual search terms. - search_artist, search_album = manual_search(False) - _, _, candidates, rec = autotag.tag_album( - task.items, search_artist, search_album - ) - elif choice is importer.action.MANUAL_ID: - # Try a manually-entered ID. - search_id = manual_id(False) - if search_id: - _, _, candidates, rec = autotag.tag_album( - task.items, search_id=search_id - ) + + # Plugin-provided choices. We invoke the associated callback + # function. + elif choice in choices: + post_choice = choice.callback(self, task) + if isinstance(post_choice, importer.action): + return post_choice + elif isinstance(post_choice, autotag.Proposal): + # Use the new candidates and continue around the loop. + task.candidates = post_choice.candidates + task.rec = post_choice.recommendation + + # Otherwise, we have a specific match selection. else: # We have a candidate! Finish tagging. Here, choice is an # AlbumMatch object. @@ -718,11 +730,11 @@ class TerminalImportSession(importer.ImportSession): either an action constant or a TrackMatch object. """ print_() - print_(task.item.path) + print_(displayable_path(task.item.path)) candidates, rec = task.candidates, task.rec # Take immediate action if appropriate. - action = _summary_judment(task.rec) + action = _summary_judgment(task.rec) if action == importer.action.APPLY: match = candidates[0] show_item_change(task.item, match) @@ -732,23 +744,21 @@ class TerminalImportSession(importer.ImportSession): while True: # Ask for a choice. - choice = choose_candidate(candidates, True, rec, item=task.item) + choices = self._get_choices(task) + choice = choose_candidate(candidates, True, rec, item=task.item, + choices=choices) if choice in (importer.action.SKIP, importer.action.ASIS): return choice - elif choice == importer.action.TRACKS: - assert False # TRACKS is only legal for albums. - elif choice == importer.action.MANUAL: - # Continue in the loop with a new set of candidates. - search_artist, search_title = manual_search(True) - candidates, rec = autotag.tag_item(task.item, search_artist, - search_title) - elif choice == importer.action.MANUAL_ID: - # Ask for a track ID. - search_id = manual_id(True) - if search_id: - candidates, rec = autotag.tag_item(task.item, - search_id=search_id) + + elif choice in choices: + post_choice = choice.callback(self, task) + if isinstance(post_choice, importer.action): + return post_choice + elif isinstance(post_choice, autotag.Proposal): + candidates = post_choice.candidates + rec = post_choice.recommendation + else: # Chose a candidate. assert isinstance(choice, autotag.TrackMatch) @@ -758,63 +768,114 @@ class TerminalImportSession(importer.ImportSession): """Decide what to do when a new album or item seems similar to one that's already in the library. """ - log.warn(u"This {0} is already in the library!", - ("album" if task.is_album else "item")) - - # skip empty albums (coming from a previous failed import session) - if task.is_album: - real_duplicates = [dup for dup in found_duplicates if dup.items()] - if not real_duplicates: - log.info("All duplicates are empty, we ignore them") - task.should_remove_duplicates = True - return - else: - real_duplicates = found_duplicates + log.warning(u"This {0} is already in the library!", + (u"album" if task.is_album else u"item")) if config['import']['quiet']: # In quiet mode, don't prompt -- just skip. log.info(u'Skipping.') - sel = 's' + sel = u's' else: # Print some detail about the existing and new items so the # user can make an informed decision. - for duplicate in real_duplicates: - print_("Old: " + summarize_items( + for duplicate in found_duplicates: + print_(u"Old: " + summarize_items( list(duplicate.items()) if task.is_album else [duplicate], not task.is_album, )) - if real_duplicates != found_duplicates: # there's empty albums - count = len(found_duplicates) - len(real_duplicates) - print_("Old: {0} empty album{1}".format( - count, "s" if count > 1 else "")) - - print_("New: " + summarize_items( + print_(u"New: " + summarize_items( task.imported_items(), not task.is_album, )) sel = ui.input_options( - ('Skip new', 'Keep both', 'Remove old') + (u'Skip new', u'Keep both', u'Remove old', u'Merge all') ) - if sel == 's': + if sel == u's': # Skip new. task.set_choice(importer.action.SKIP) - elif sel == 'k': + elif sel == u'k': # Keep both. Do nothing; leave the choice intact. pass - elif sel == 'r': + elif sel == u'r': # Remove old. task.should_remove_duplicates = True + elif sel == u'm': + task.should_merge_duplicates = True else: assert False def should_resume(self, path): return ui.input_yn(u"Import of the directory:\n{0}\n" - "was interrupted. Resume (Y/n)?" + u"was interrupted. Resume (Y/n)?" .format(displayable_path(path))) + def _get_choices(self, task): + """Get the list of prompt choices that should be presented to the + user. This consists of both built-in choices and ones provided by + plugins. + + The `before_choose_candidate` event is sent to the plugins, with + session and task as its parameters. Plugins are responsible for + checking the right conditions and returning a list of `PromptChoice`s, + which is flattened and checked for conflicts. + + If two or more choices have the same short letter, a warning is + emitted and all but one choices are discarded, giving preference + to the default importer choices. + + Returns a list of `PromptChoice`s. + """ + # Standard, built-in choices. + choices = [ + PromptChoice(u's', u'Skip', + lambda s, t: importer.action.SKIP), + PromptChoice(u'u', u'Use as-is', + lambda s, t: importer.action.ASIS) + ] + if task.is_album: + choices += [ + PromptChoice(u't', u'as Tracks', + lambda s, t: importer.action.TRACKS), + PromptChoice(u'g', u'Group albums', + lambda s, t: importer.action.ALBUMS), + ] + choices += [ + PromptChoice(u'e', u'Enter search', manual_search), + PromptChoice(u'i', u'enter Id', manual_id), + PromptChoice(u'b', u'aBort', abort_action), + ] + + # Send the before_choose_candidate event and flatten list. + extra_choices = list(chain(*plugins.send('before_choose_candidate', + session=self, task=task))) + + # Add a "dummy" choice for the other baked-in option, for + # duplicate checking. + all_choices = [ + PromptChoice(u'a', u'Apply', None), + ] + choices + extra_choices + + # Check for conflicts. + short_letters = [c.short for c in all_choices] + if len(short_letters) != len(set(short_letters)): + # Duplicate short letter has been found. + duplicates = [i for i, count in Counter(short_letters).items() + if count > 1] + for short in duplicates: + # Keep the first of the choices, removing the rest. + dup_choices = [c for c in all_choices if c.short == short] + for c in dup_choices[1:]: + log.warning(u"Prompt choice '{0}' removed due to conflict " + u"with '{1}' (short letter: '{2}')", + c.long, dup_choices[0].long, c.short) + extra_choices.remove(c) + + return choices + extra_choices + + # The import command. @@ -830,7 +891,7 @@ def import_files(lib, paths, query): # Check parameter consistency. if config['import']['quiet'] and config['import']['timid']: - raise ui.UserError("can't be both quiet and timid") + raise ui.UserError(u"can't be both quiet and timid") # Open the log. if config['import']['log'].get() is not None: @@ -870,85 +931,111 @@ def import_func(lib, opts, args): query = None paths = args if not paths: - raise ui.UserError('no path specified') + raise ui.UserError(u'no path specified') + + # On Python 2, we get filenames as raw bytes, which is what we + # need. On Python 3, we need to undo the "helpful" conversion to + # Unicode strings to get the real bytestring filename. + if not six.PY2: + paths = [p.encode(util.arg_encoding(), 'surrogateescape') + for p in paths] import_files(lib, paths, query) import_cmd = ui.Subcommand( - 'import', help='import new music', aliases=('imp', 'im') + u'import', help=u'import new music', aliases=(u'imp', u'im') ) import_cmd.parser.add_option( - '-c', '--copy', action='store_true', default=None, - help="copy tracks into library directory (default)" + u'-c', u'--copy', action='store_true', default=None, + help=u"copy tracks into library directory (default)" ) import_cmd.parser.add_option( - '-C', '--nocopy', action='store_false', dest='copy', - help="don't copy tracks (opposite of -c)" + u'-C', u'--nocopy', action='store_false', dest='copy', + help=u"don't copy tracks (opposite of -c)" ) import_cmd.parser.add_option( - '-w', '--write', action='store_true', default=None, - help="write new metadata to files' tags (default)" + u'-m', u'--move', action='store_true', dest='move', + help=u"move tracks into the library (overrides -c)" ) import_cmd.parser.add_option( - '-W', '--nowrite', action='store_false', dest='write', - help="don't write metadata (opposite of -w)" + u'-w', u'--write', action='store_true', default=None, + help=u"write new metadata to files' tags (default)" ) import_cmd.parser.add_option( - '-a', '--autotag', action='store_true', dest='autotag', - help="infer tags for imported files (default)" + u'-W', u'--nowrite', action='store_false', dest='write', + help=u"don't write metadata (opposite of -w)" ) import_cmd.parser.add_option( - '-A', '--noautotag', action='store_false', dest='autotag', - help="don't infer tags for imported files (opposite of -a)" + u'-a', u'--autotag', action='store_true', dest='autotag', + help=u"infer tags for imported files (default)" ) import_cmd.parser.add_option( - '-p', '--resume', action='store_true', default=None, - help="resume importing if interrupted" + u'-A', u'--noautotag', action='store_false', dest='autotag', + help=u"don't infer tags for imported files (opposite of -a)" ) import_cmd.parser.add_option( - '-P', '--noresume', action='store_false', dest='resume', - help="do not try to resume importing" + u'-p', u'--resume', action='store_true', default=None, + help=u"resume importing if interrupted" ) import_cmd.parser.add_option( - '-q', '--quiet', action='store_true', dest='quiet', - help="never prompt for input: skip albums instead" + u'-P', u'--noresume', action='store_false', dest='resume', + help=u"do not try to resume importing" ) import_cmd.parser.add_option( - '-l', '--log', dest='log', - help='file to log untaggable albums for later review' + u'-q', u'--quiet', action='store_true', dest='quiet', + help=u"never prompt for input: skip albums instead" ) import_cmd.parser.add_option( - '-s', '--singletons', action='store_true', - help='import individual tracks instead of full albums' + u'-l', u'--log', dest='log', + help=u'file to log untaggable albums for later review' ) import_cmd.parser.add_option( - '-t', '--timid', dest='timid', action='store_true', - help='always confirm all actions' + u'-s', u'--singletons', action='store_true', + help=u'import individual tracks instead of full albums' ) import_cmd.parser.add_option( - '-L', '--library', dest='library', action='store_true', - help='retag items matching a query' + u'-t', u'--timid', dest='timid', action='store_true', + help=u'always confirm all actions' ) import_cmd.parser.add_option( - '-i', '--incremental', dest='incremental', action='store_true', - help='skip already-imported directories' + u'-L', u'--library', dest='library', action='store_true', + help=u'retag items matching a query' ) import_cmd.parser.add_option( - '-I', '--noincremental', dest='incremental', action='store_false', - help='do not skip already-imported directories' + u'-i', u'--incremental', dest='incremental', action='store_true', + help=u'skip already-imported directories' ) import_cmd.parser.add_option( - '--flat', dest='flat', action='store_true', - help='import an entire tree as a single album' + u'-I', u'--noincremental', dest='incremental', action='store_false', + help=u'do not skip already-imported directories' ) import_cmd.parser.add_option( - '-g', '--group-albums', dest='group_albums', action='store_true', - help='group tracks in a folder into separate albums' + u'--from-scratch', dest='from_scratch', action='store_true', + help=u'erase existing metadata before applying new metadata' ) import_cmd.parser.add_option( - '--pretend', dest='pretend', action='store_true', - help='just print the files to import' + u'--flat', dest='flat', action='store_true', + help=u'import an entire tree as a single album' +) +import_cmd.parser.add_option( + u'-g', u'--group-albums', dest='group_albums', action='store_true', + help=u'group tracks in a folder into separate albums' +) +import_cmd.parser.add_option( + u'--pretend', dest='pretend', action='store_true', + help=u'just print the files to import' +) +import_cmd.parser.add_option( + u'-S', u'--search-id', dest='search_ids', action='append', + metavar='ID', + help=u'restrict matching to a specific metadata backend ID' +) +import_cmd.parser.add_option( + u'--set', dest='set_fields', action='callback', + callback=_store_dict, + metavar='FIELD=VALUE', + help=u'set the given fields to the supplied values' ) import_cmd.func = import_func default_commands.append(import_cmd) @@ -956,7 +1043,7 @@ default_commands.append(import_cmd) # list: Query and show library contents. -def list_items(lib, query, album, fmt=''): +def list_items(lib, query, album, fmt=u''): """Print out items in lib matching query. If album, then search for albums instead of single items. """ @@ -972,9 +1059,9 @@ def list_func(lib, opts, args): list_items(lib, decargs(args), opts.album) -list_cmd = ui.Subcommand('list', help='query the library', aliases=('ls',)) -list_cmd.parser.usage += "\n" \ - 'Example: %prog -f \'$album: $title\' artist:beatles' +list_cmd = ui.Subcommand(u'list', help=u'query the library', aliases=(u'ls',)) +list_cmd.parser.usage += u"\n" \ + u'Example: %prog -f \'$album: $title\' artist:beatles' list_cmd.parser.add_all_common_options() list_cmd.func = list_func default_commands.append(list_cmd) @@ -982,11 +1069,18 @@ default_commands.append(list_cmd) # update: Update library contents according to on-disk tags. -def update_items(lib, query, album, move, pretend): +def update_items(lib, query, album, move, pretend, fields): """For all the items matched by the query, update the library to reflect the item's embedded tags. + :param fields: The fields to be stored. If not specified, all fields will + be. """ with lib.transaction(): + if move and fields is not None and 'path' not in fields: + # Special case: if an item needs to be moved, the path field has to + # updated; otherwise the new path will not be reflected in the + # database. + fields.append('path') items, _ = _do_query(lib, query, album) # Walk through the items and pick up their changes. @@ -1022,27 +1116,28 @@ def update_items(lib, query, album, move, pretend): old_item = lib.get_item(item.id) if old_item.albumartist == old_item.artist == item.artist: item.albumartist = old_item.albumartist - item._dirty.discard('albumartist') + item._dirty.discard(u'albumartist') # Check for and display changes. - changed = ui.show_model_changes(item, - fields=library.Item._media_fields) + changed = ui.show_model_changes( + item, + fields=fields or library.Item._media_fields) # Save changes. if not pretend: if changed: # Move the item if it's in the library. if move and lib.directory in ancestry(item.path): - item.move() + item.move(store=False) - item.store() + item.store(fields=fields) affected_albums.add(item.album_id) else: # The file's mtime was different, but there were no # changes to the metadata. Store the new mtime, # which is set in the call to read(), so we don't # check this again in the future. - item.store() + item.store(fields=fields) # Skip album changes while pretending. if pretend: @@ -1061,30 +1156,46 @@ def update_items(lib, query, album, move, pretend): # Update album structure to reflect an item in it. for key in library.Album.item_keys: album[key] = first_item[key] - album.store() + album.store(fields=fields) # Move album art (and any inconsistent items). if move and lib.directory in ancestry(first_item.path): log.debug(u'moving album {0}', album_id) - album.move() + + # Manually moving and storing the album. + items = list(album.items()) + for item in items: + item.move(store=False) + item.store(fields=fields) + album.move(store=False) + album.store(fields=fields) def update_func(lib, opts, args): - update_items(lib, decargs(args), opts.album, opts.move, opts.pretend) + update_items(lib, decargs(args), opts.album, ui.should_move(opts.move), + opts.pretend, opts.fields) update_cmd = ui.Subcommand( - 'update', help='update the library', aliases=('upd', 'up',) + u'update', help=u'update the library', aliases=(u'upd', u'up',) ) update_cmd.parser.add_album_option() update_cmd.parser.add_format_option() update_cmd.parser.add_option( - '-M', '--nomove', action='store_false', default=True, dest='move', - help="don't move files in library" + u'-m', u'--move', action='store_true', dest='move', + help=u"move files in the library directory" ) update_cmd.parser.add_option( - '-p', '--pretend', action='store_true', - help="show all changes but do nothing" + u'-M', u'--nomove', action='store_false', dest='move', + help=u"don't move files in library" +) +update_cmd.parser.add_option( + u'-p', u'--pretend', action='store_true', + help=u"show all changes but do nothing" +) +update_cmd.parser.add_option( + u'-F', u'--field', default=None, action='append', dest='fields', + help=u'list of fields to update' ) update_cmd.func = update_func default_commands.append(update_cmd) @@ -1092,31 +1203,33 @@ default_commands.append(update_cmd) # remove: Remove items from library, delete files. -def remove_items(lib, query, album, delete): +def remove_items(lib, query, album, delete, force): """Remove items matching query from lib. If album, then match and remove whole albums. If delete, also remove files from disk. """ # Get the matching items. items, albums = _do_query(lib, query, album) - # Prepare confirmation with user. - print_() - if delete: - fmt = u'$path - $title' - prompt = 'Really DELETE %i file%s (y/n)?' % \ - (len(items), 's' if len(items) > 1 else '') - else: - fmt = '' - prompt = 'Really remove %i item%s from the library (y/n)?' % \ - (len(items), 's' if len(items) > 1 else '') + # Confirm file removal if not forcing removal. + if not force: + # Prepare confirmation with user. + print_() + if delete: + fmt = u'$path - $title' + prompt = u'Really DELETE %i file%s (y/n)?' % \ + (len(items), 's' if len(items) > 1 else '') + else: + fmt = u'' + prompt = u'Really remove %i item%s from the library (y/n)?' % \ + (len(items), 's' if len(items) > 1 else '') - # Show all the items. - for item in items: - ui.print_(format(item, fmt)) + # Show all the items. + for item in items: + ui.print_(format(item, fmt)) - # Confirm with user. - if not ui.input_yn(prompt, True): - return + # Confirm with user. + if not ui.input_yn(prompt, True): + return # Remove (and possibly delete) items. with lib.transaction(): @@ -1125,15 +1238,19 @@ def remove_items(lib, query, album, delete): def remove_func(lib, opts, args): - remove_items(lib, decargs(args), opts.album, opts.delete) + remove_items(lib, decargs(args), opts.album, opts.delete, opts.force) remove_cmd = ui.Subcommand( - 'remove', help='remove matching items from the library', aliases=('rm',) + u'remove', help=u'remove matching items from the library', aliases=(u'rm',) ) remove_cmd.parser.add_option( - "-d", "--delete", action="store_true", - help="also remove files from disk" + u"-d", u"--delete", action="store_true", + help=u"also remove files from disk" +) +remove_cmd.parser.add_option( + u"-f", u"--force", action="store_true", + help=u"do not ask when removing items" ) remove_cmd.parser.add_album_option() remove_cmd.func = remove_func @@ -1155,7 +1272,10 @@ def show_stats(lib, query, exact): for item in items: if exact: - total_size += os.path.getsize(item.path) + try: + total_size += os.path.getsize(syspath(item.path)) + except OSError as exc: + log.info(u'could not get size of {}: {}', item.path, exc) else: total_size += int(item.length * item.bitrate / 8) total_time += item.length @@ -1165,11 +1285,11 @@ def show_stats(lib, query, exact): if item.album_id: albums.add(item.album_id) - size_str = '' + ui.human_bytes(total_size) + size_str = u'' + ui.human_bytes(total_size) if exact: - size_str += ' ({0} bytes)'.format(total_size) + size_str += u' ({0} bytes)'.format(total_size) - print_("""Tracks: {0} + print_(u"""Tracks: {0} Total time: {1}{2} {3}: {4} Artists: {5} @@ -1177,8 +1297,8 @@ Albums: {6} Album artists: {7}""".format( total_items, ui.human_seconds(total_time), - ' ({0:.2f} seconds)'.format(total_time) if exact else '', - 'Total size' if exact else 'Approximate total size', + u' ({0:.2f} seconds)'.format(total_time) if exact else '', + u'Total size' if exact else u'Approximate total size', size_str, len(artists), len(albums), @@ -1191,11 +1311,11 @@ def stats_func(lib, opts, args): stats_cmd = ui.Subcommand( - 'stats', help='show statistics about the library or a query' + u'stats', help=u'show statistics about the library or a query' ) stats_cmd.parser.add_option( - '-e', '--exact', action='store_true', - help='exact size and time' + u'-e', u'--exact', action='store_true', + help=u'exact size and time' ) stats_cmd.func = stats_func default_commands.append(stats_cmd) @@ -1204,17 +1324,18 @@ default_commands.append(stats_cmd) # version: Show current beets version. def show_version(lib, opts, args): - print_('beets version %s' % beets.__version__) + print_(u'beets version %s' % beets.__version__) + print_(u'Python version {}'.format(python_version())) # Show plugins. names = sorted(p.name for p in plugins.find_plugins()) if names: - print_('plugins:', ', '.join(names)) + print_(u'plugins:', ', '.join(names)) else: - print_('no plugins loaded') + print_(u'no plugins loaded') version_cmd = ui.Subcommand( - 'version', help='output version information' + u'version', help=u'output version information' ) version_cmd.func = show_version default_commands.append(version_cmd) @@ -1241,48 +1362,54 @@ def modify_items(lib, mods, dels, query, write, move, album, confirm): # Apply changes *temporarily*, preview them, and collect modified # objects. - print_('Modifying {0} {1}s.' - .format(len(objs), 'album' if album else 'item')) + print_(u'Modifying {0} {1}s.' + .format(len(objs), u'album' if album else u'item')) changed = set() for obj in objs: - obj.update(mods) - for field in dels: - try: - del obj[field] - except KeyError: - pass - if ui.show_model_changes(obj): + if print_and_modify(obj, mods, dels): changed.add(obj) # Still something to do? if not changed: - print_('No changes to make.') + print_(u'No changes to make.') return # Confirm action. if confirm: if write and move: - extra = ', move and write tags' + extra = u', move and write tags' elif write: - extra = ' and write tags' + extra = u' and write tags' elif move: - extra = ' and move' + extra = u' and move' else: - extra = '' + extra = u'' - if not ui.input_yn('Really modify%s (Y/n)?' % extra): - return + changed = ui.input_select_objects( + u'Really modify%s' % extra, changed, + lambda o: print_and_modify(o, mods, dels) + ) # Apply changes to database and files with lib.transaction(): for obj in changed: - if move: - cur_path = obj.path - if lib.directory in ancestry(cur_path): # In library? - log.debug(u'moving object {0}', displayable_path(cur_path)) - obj.move() + obj.try_sync(write, move) - obj.try_sync(write) + +def print_and_modify(obj, mods, dels): + """Print the modifications to an item and return a bool indicating + whether any changes were made. + + `mods` is a dictionary of fields and values to update on the object; + `dels` is a sequence of fields to delete. + """ + obj.update(mods) + for field in dels: + try: + del obj[field] + except KeyError: + pass + return ui.show_model_changes(obj) def modify_parse_args(args): @@ -1307,33 +1434,35 @@ def modify_parse_args(args): def modify_func(lib, opts, args): query, mods, dels = modify_parse_args(decargs(args)) if not mods and not dels: - raise ui.UserError('no modifications specified') - write = opts.write if opts.write is not None else \ - config['import']['write'].get(bool) - modify_items(lib, mods, dels, query, write, opts.move, opts.album, - not opts.yes) + raise ui.UserError(u'no modifications specified') + modify_items(lib, mods, dels, query, ui.should_write(opts.write), + ui.should_move(opts.move), opts.album, not opts.yes) modify_cmd = ui.Subcommand( - 'modify', help='change metadata fields', aliases=('mod',) + u'modify', help=u'change metadata fields', aliases=(u'mod',) ) modify_cmd.parser.add_option( - '-M', '--nomove', action='store_false', default=True, dest='move', - help="don't move files in library" + u'-m', u'--move', action='store_true', dest='move', + help=u"move files in the library directory" ) modify_cmd.parser.add_option( - '-w', '--write', action='store_true', default=None, - help="write new metadata to files' tags (default)" + u'-M', u'--nomove', action='store_false', dest='move', + help=u"don't move files in library" ) modify_cmd.parser.add_option( - '-W', '--nowrite', action='store_false', dest='write', - help="don't write metadata (opposite of -w)" + u'-w', u'--write', action='store_true', default=None, + help=u"write new metadata to files' tags (default)" +) +modify_cmd.parser.add_option( + u'-W', u'--nowrite', action='store_false', dest='write', + help=u"don't write metadata (opposite of -w)" ) modify_cmd.parser.add_album_option() modify_cmd.parser.add_format_option(target='item') modify_cmd.parser.add_option( - '-y', '--yes', action='store_true', - help='skip confirmation' + u'-y', u'--yes', action='store_true', + help=u'skip confirmation' ) modify_cmd.func = modify_func default_commands.append(modify_cmd) @@ -1341,7 +1470,8 @@ default_commands.append(modify_cmd) # move: Move/copy files to the library or a new base directory. -def move_items(lib, dest, query, copy, album, pretend): +def move_items(lib, dest, query, copy, album, pretend, confirm=False, + export=False): """Moves or copies items to a new base directory, given by dest. If dest is None, then the library's base directory is used, making the command "consolidate" files. @@ -1349,10 +1479,20 @@ def move_items(lib, dest, query, copy, album, pretend): items, albums = _do_query(lib, query, album, False) objs = albums if album else items - action = 'Copying' if copy else 'Moving' - entity = 'album' if album else 'item' + # Filter out files that don't need to be moved. + isitemmoved = lambda item: item.path != item.destination(basedir=dest) + isalbummoved = lambda album: any(isitemmoved(i) for i in album.items()) + objs = [o for o in objs if (isalbummoved if album else isitemmoved)(o)] + + copy = copy or export # Exporting always copies. + action = u'Copying' if copy else u'Moving' + act = u'copy' if copy else u'move' + entity = u'album' if album else u'item' log.info(u'{0} {1} {2}{3}.', action, len(objs), entity, - 's' if len(objs) > 1 else '') + u's' if len(objs) != 1 else u'') + if not objs: + return + if pretend: if album: show_path_changes([(item.path, item.destination(basedir=dest)) @@ -1361,11 +1501,25 @@ def move_items(lib, dest, query, copy, album, pretend): show_path_changes([(obj.path, obj.destination(basedir=dest)) for obj in objs]) else: + if confirm: + objs = ui.input_select_objects( + u'Really %s' % act, objs, + lambda o: show_path_changes( + [(o.path, o.destination(basedir=dest))])) + for obj in objs: log.debug(u'moving: {0}', util.displayable_path(obj.path)) - obj.move(copy, basedir=dest) - obj.store() + if export: + # Copy without affecting the database. + obj.move(operation=MoveOperation.COPY, basedir=dest, + store=False) + else: + # Ordinary move/copy: store the new path. + if copy: + obj.move(operation=MoveOperation.COPY, basedir=dest) + else: + obj.move(operation=MoveOperation.MOVE, basedir=dest) def move_func(lib, opts, args): @@ -1373,25 +1527,35 @@ def move_func(lib, opts, args): if dest is not None: dest = normpath(dest) if not os.path.isdir(dest): - raise ui.UserError('no such directory: %s' % dest) + raise ui.UserError(u'no such directory: %s' % dest) - move_items(lib, dest, decargs(args), opts.copy, opts.album, opts.pretend) + move_items(lib, dest, decargs(args), opts.copy, opts.album, opts.pretend, + opts.timid, opts.export) move_cmd = ui.Subcommand( - 'move', help='move or copy items', aliases=('mv',) + u'move', help=u'move or copy items', aliases=(u'mv',) ) move_cmd.parser.add_option( - '-d', '--dest', metavar='DIR', dest='dest', - help='destination directory' + u'-d', u'--dest', metavar='DIR', dest='dest', + help=u'destination directory' ) move_cmd.parser.add_option( - '-c', '--copy', default=False, action='store_true', - help='copy instead of moving' + u'-c', u'--copy', default=False, action='store_true', + help=u'copy instead of moving' ) move_cmd.parser.add_option( - '-p', '--pretend', default=False, action='store_true', - help='show how files would be moved, but don\'t touch anything') + u'-p', u'--pretend', default=False, action='store_true', + help=u'show how files would be moved, but don\'t touch anything' +) +move_cmd.parser.add_option( + u'-t', u'--timid', dest='timid', action='store_true', + help=u'always confirm all actions' +) +move_cmd.parser.add_option( + u'-e', u'--export', default=False, action='store_true', + help=u'copy without changing the database path' +) move_cmd.parser.add_album_option() move_cmd.func = move_func default_commands.append(move_cmd) @@ -1423,21 +1587,23 @@ def write_items(lib, query, pretend, force): changed = ui.show_model_changes(item, clean_item, library.Item._media_tag_fields, force) if (changed or force) and not pretend: - item.try_sync() + # We use `try_sync` here to keep the mtime up to date in the + # database. + item.try_sync(True, False) def write_func(lib, opts, args): write_items(lib, decargs(args), opts.pretend, opts.force) -write_cmd = ui.Subcommand('write', help='write tag information to files') +write_cmd = ui.Subcommand(u'write', help=u'write tag information to files') write_cmd.parser.add_option( - '-p', '--pretend', action='store_true', - help="show all changes but do nothing" + u'-p', u'--pretend', action='store_true', + help=u"show all changes but do nothing" ) write_cmd.parser.add_option( - '-f', '--force', action='store_true', - help="write tags even if the existing tags match the database" + u'-f', u'--force', action='store_true', + help=u"write tags even if the existing tags match the database" ) write_cmd.func = write_func default_commands.append(write_cmd) @@ -1465,7 +1631,7 @@ def config_func(lib, opts, args): filenames.insert(0, user_path) for filename in filenames: - print_(filename) + print_(displayable_path(filename)) # Open in editor. elif opts.edit: @@ -1473,7 +1639,8 @@ def config_func(lib, opts, args): # Dump configuration. else: - print_(config.dump(full=opts.defaults, redact=opts.redact)) + config_out = config.dump(full=opts.defaults, redact=opts.redact) + print_(util.text_string(config_out)) def config_edit(): @@ -1481,35 +1648,35 @@ def config_edit(): An empty config file is created if no existing config file exists. """ path = config.user_config_path() - editor = os.environ.get('EDITOR') + editor = util.editor_command() try: if not os.path.isfile(path): open(path, 'w+').close() util.interactive_open([path], editor) except OSError as exc: - message = "Could not edit configuration: {0}".format(exc) + message = u"Could not edit configuration: {0}".format(exc) if not editor: - message += ". Please set the EDITOR environment variable" + message += u". Please set the EDITOR environment variable" raise ui.UserError(message) -config_cmd = ui.Subcommand('config', - help='show or edit the user configuration') +config_cmd = ui.Subcommand(u'config', + help=u'show or edit the user configuration') config_cmd.parser.add_option( - '-p', '--paths', action='store_true', - help='show files that configuration was loaded from' + u'-p', u'--paths', action='store_true', + help=u'show files that configuration was loaded from' ) config_cmd.parser.add_option( - '-e', '--edit', action='store_true', - help='edit user configuration with $EDITOR' + u'-e', u'--edit', action='store_true', + help=u'edit user configuration with $EDITOR' ) config_cmd.parser.add_option( - '-d', '--defaults', action='store_true', - help='include the default configuration' + u'-d', u'--defaults', action='store_true', + help=u'include the default configuration' ) config_cmd.parser.add_option( - '-c', '--clear', action='store_false', + u'-c', u'--clear', action='store_false', dest='redact', default=True, - help='do not redact sensitive fields' + help=u'do not redact sensitive fields' ) config_cmd.func = config_func default_commands.append(config_cmd) @@ -1519,17 +1686,19 @@ default_commands.append(config_cmd) def print_completion(*args): for line in completion_script(default_commands + plugins.commands()): - print_(line, end='') + print_(line, end=u'') if not any(map(os.path.isfile, BASH_COMPLETION_PATHS)): - log.warn(u'Warning: Unable to find the bash-completion package. ' - u'Command line completion might not work.') + log.warning(u'Warning: Unable to find the bash-completion package. ' + u'Command line completion might not work.') BASH_COMPLETION_PATHS = map(syspath, [ u'/etc/bash_completion', u'/usr/share/bash-completion/bash_completion', - u'/usr/share/local/bash-completion/bash_completion', - u'/opt/local/share/bash-completion/bash_completion', # SmartOS - u'/usr/local/etc/bash_completion', # Homebrew + u'/usr/local/share/bash-completion/bash_completion', + # SmartOS + u'/opt/local/share/bash-completion/bash_completion', + # Homebrew (before bash-completion2) + u'/usr/local/etc/bash_completion', ]) @@ -1541,7 +1710,7 @@ def completion_script(commands): """ base_script = os.path.join(_package_path('beets.ui'), 'completion_base.sh') with open(base_script, 'r') as base_script: - yield base_script.read() + yield util.text_string(base_script.read()) options = {} aliases = {} @@ -1556,12 +1725,12 @@ def completion_script(commands): if re.match(r'^\w+$', alias): aliases[alias] = name - options[name] = {'flags': [], 'opts': []} + options[name] = {u'flags': [], u'opts': []} for opts in cmd.parser._get_all_options()[1:]: if opts.action in ('store_true', 'store_false'): - option_type = 'flags' + option_type = u'flags' else: - option_type = 'opts' + option_type = u'opts' options[name][option_type].extend( opts._short_opts + opts._long_opts @@ -1569,47 +1738,52 @@ def completion_script(commands): # Add global options options['_global'] = { - 'flags': ['-v', '--verbose'], - 'opts': '-l --library -c --config -d --directory -h --help'.split(' ') + u'flags': [u'-v', u'--verbose'], + u'opts': + u'-l --library -c --config -d --directory -h --help'.split(u' ') } # Add flags common to all commands options['_common'] = { - 'flags': ['-h', '--help'] + u'flags': [u'-h', u'--help'] } # Start generating the script - yield "_beet() {\n" + yield u"_beet() {\n" # Command names - yield " local commands='%s'\n" % ' '.join(command_names) - yield "\n" + yield u" local commands='%s'\n" % ' '.join(command_names) + yield u"\n" # Command aliases - yield " local aliases='%s'\n" % ' '.join(aliases.keys()) + yield u" local aliases='%s'\n" % ' '.join(aliases.keys()) for alias, cmd in aliases.items(): - yield " local alias__%s=%s\n" % (alias, cmd) - yield '\n' + yield u" local alias__%s=%s\n" % (alias.replace('-', '_'), cmd) + yield u'\n' # Fields - yield " fields='%s'\n" % ' '.join( - set(library.Item._fields.keys() + library.Album._fields.keys()) + yield u" fields='%s'\n" % ' '.join( + set( + list(library.Item._fields.keys()) + + list(library.Album._fields.keys()) + ) ) # Command options for cmd, opts in options.items(): for option_type, option_list in opts.items(): if option_list: - option_list = ' '.join(option_list) - yield " local %s__%s='%s'\n" % (option_type, cmd, option_list) + option_list = u' '.join(option_list) + yield u" local %s__%s='%s'\n" % ( + option_type, cmd.replace('-', '_'), option_list) - yield ' _beet_dispatch\n' - yield '}\n' + yield u' _beet_dispatch\n' + yield u'}\n' completion_cmd = ui.Subcommand( 'completion', - help='print shell script that provides command line completion' + help=u'print shell script that provides command line completion' ) completion_cmd.func = print_completion completion_cmd.hide = True diff --git a/beets/ui/completion_base.sh b/beets/ui/completion_base.sh index ce3fb6e27..1eaa4db3d 100644 --- a/beets/ui/completion_base.sh +++ b/beets/ui/completion_base.sh @@ -70,7 +70,7 @@ _beet_dispatch() { # Replace command shortcuts if [[ -n $cmd ]] && _list_include_item "$aliases" "$cmd"; then - eval "cmd=\$alias__$cmd" + eval "cmd=\$alias__${cmd//-/_}" fi case $cmd in @@ -94,8 +94,8 @@ _beet_dispatch() { _beet_complete() { if [[ $cur == -* ]]; then local opts flags completions - eval "opts=\$opts__$cmd" - eval "flags=\$flags__$cmd" + eval "opts=\$opts__${cmd//-/_}" + eval "flags=\$flags__${cmd//-/_}" completions="${flags___common} ${opts} ${flags}" COMPREPLY+=( $(compgen -W "$completions" -- $cur) ) else @@ -129,7 +129,7 @@ _beet_complete_global() { COMPREPLY+=( $(compgen -W "$completions" -- $cur) ) elif [[ -n $cur ]] && _list_include_item "$aliases" "$cur"; then local cmd - eval "cmd=\$alias__$cur" + eval "cmd=\$alias__${cur//-/_}" COMPREPLY+=( "$cmd" ) else COMPREPLY+=( $(compgen -W "$commands" -- $cur) ) @@ -138,7 +138,7 @@ _beet_complete_global() { _beet_complete_query() { local opts - eval "opts=\$opts__$cmd" + eval "opts=\$opts__${cmd//-/_}" if [[ $cur == -* ]] || _list_include_item "$opts" "$prev"; then _beet_complete diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 158a6c8e1..69870edf2 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,11 +15,11 @@ """Miscellaneous utility functions.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) - +from __future__ import division, absolute_import, print_function import os import sys +import errno +import locale import re import shutil import fnmatch @@ -27,10 +28,15 @@ import traceback import subprocess import platform import shlex +from beets.util import hidden +import six +from unidecode import unidecode +from enum import Enum MAX_FILENAME_LENGTH = 200 WINDOWS_MAGIC_PREFIX = u'\\\\?\\' +SNI_SUPPORTED = sys.version_info >= (2, 7, 9) class HumanReadableException(Exception): @@ -57,22 +63,22 @@ class HumanReadableException(Exception): def _gerund(self): """Generate a (likely) gerund form of the English verb. """ - if ' ' in self.verb: + if u' ' in self.verb: return self.verb - gerund = self.verb[:-1] if self.verb.endswith('e') else self.verb - gerund += 'ing' + gerund = self.verb[:-1] if self.verb.endswith(u'e') else self.verb + gerund += u'ing' return gerund def _reasonstr(self): """Get the reason as a string.""" - if isinstance(self.reason, unicode): + if isinstance(self.reason, six.text_type): return self.reason - elif isinstance(self.reason, basestring): # Byte string. - return self.reason.decode('utf8', 'ignore') + elif isinstance(self.reason, bytes): + return self.reason.decode('utf-8', 'ignore') elif hasattr(self.reason, 'strerror'): # i.e., EnvironmentError return self.reason.strerror else: - return u'"{0}"'.format(unicode(self.reason)) + return u'"{0}"'.format(six.text_type(self.reason)) def get_message(self): """Create the human-readable description of the error, sans @@ -119,6 +125,15 @@ class FilesystemError(HumanReadableException): return u'{0} {1}'.format(self._reasonstr(), clause) +class MoveOperation(Enum): + """The file operations that e.g. various move functions can carry out. + """ + MOVE = 0 + COPY = 1 + LINK = 2 + HARDLINK = 3 + + def normpath(path): """Provide the canonical form of the path suitable for storing in the database. @@ -152,21 +167,22 @@ def ancestry(path): return out -def sorted_walk(path, ignore=(), logger=None): +def sorted_walk(path, ignore=(), ignore_hidden=False, logger=None): """Like `os.walk`, but yields things in case-insensitive sorted, breadth-first order. Directory and file names matching any glob pattern in `ignore` are skipped. If `logger` is provided, then warning messages are logged there when a directory cannot be listed. """ - # Make sure the path isn't a Unicode string. + # Make sure the pathes aren't Unicode strings. path = bytestring_path(path) + ignore = [bytestring_path(i) for i in ignore] # Get all the directories and files at this level. try: contents = os.listdir(syspath(path)) except OSError as exc: if logger: - logger.warn(u'could not list directory {0}: {1}'.format( + logger.warning(u'could not list directory {0}: {1}'.format( displayable_path(path), exc.strerror )) return @@ -186,10 +202,11 @@ def sorted_walk(path, ignore=(), logger=None): # Add to output as either a file or a directory. cur = os.path.join(path, base) - if os.path.isdir(syspath(cur)): - dirs.append(base) - else: - files.append(base) + if (ignore_hidden and not hidden.is_hidden(cur)) or not ignore_hidden: + if os.path.isdir(syspath(cur)): + dirs.append(base) + else: + files.append(base) # Sort lists (case-insensitive) and yield the current level. dirs.sort(key=bytes.lower) @@ -200,7 +217,7 @@ def sorted_walk(path, ignore=(), logger=None): for base in dirs: cur = os.path.join(path, base) # yield from sorted_walk(...) - for res in sorted_walk(cur, ignore, logger): + for res in sorted_walk(cur, ignore, ignore_hidden, logger): yield res @@ -263,7 +280,9 @@ def prune_dirs(path, root=None, clutter=('.DS_Store', 'Thumbs.db')): if not os.path.exists(directory): # Directory gone already. continue - if fnmatch_all(os.listdir(directory), clutter): + clutter = [bytestring_path(c) for c in clutter] + match_paths = [bytestring_path(d) for d in os.listdir(directory)] + if fnmatch_all(match_paths, clutter): # Directory contains only clutter (or nothing). try: shutil.rmtree(directory) @@ -297,18 +316,30 @@ def components(path): return comps +def arg_encoding(): + """Get the encoding for command-line arguments (and other OS + locale-sensitive strings). + """ + try: + return locale.getdefaultlocale()[1] or 'utf-8' + except ValueError: + # Invalid locale environment variable setting. To avoid + # failing entirely for no good reason, assume UTF-8. + return 'utf-8' + + def _fsencoding(): """Get the system's filesystem encoding. On Windows, this is always UTF-8 (not MBCS). """ encoding = sys.getfilesystemencoding() or sys.getdefaultencoding() - if encoding == b'mbcs': + if encoding == 'mbcs': # On Windows, a broken encoding known to Python as "MBCS" is # used for the filesystem. However, we only use the Unicode API # for Windows paths, so the encoding is actually immaterial so # we can avoid dealing with this nastiness. We arbitrarily # choose UTF-8. - encoding = b'utf8' + encoding = 'utf-8' return encoding @@ -323,14 +354,17 @@ def bytestring_path(path): # On Windows, remove the magic prefix added by `syspath`. This makes # ``bytestring_path(syspath(X)) == X``, i.e., we can safely # round-trip through `syspath`. - if os.path.__name__ == b'ntpath' and path.startswith(WINDOWS_MAGIC_PREFIX): + if os.path.__name__ == 'ntpath' and path.startswith(WINDOWS_MAGIC_PREFIX): path = path[len(WINDOWS_MAGIC_PREFIX):] - # Try to encode with default encodings, but fall back to UTF8. + # Try to encode with default encodings, but fall back to utf-8. try: return path.encode(_fsencoding()) except (UnicodeError, LookupError): - return path.encode('utf8') + return path.encode('utf-8') + + +PATH_SEP = bytestring_path(os.sep) def displayable_path(path, separator=u'; '): @@ -340,16 +374,16 @@ def displayable_path(path, separator=u'; '): """ if isinstance(path, (list, tuple)): return separator.join(displayable_path(p) for p in path) - elif isinstance(path, unicode): + elif isinstance(path, six.text_type): return path elif not isinstance(path, bytes): # A non-string object: just get its unicode representation. - return unicode(path) + return six.text_type(path) try: return path.decode(_fsencoding(), 'ignore') except (UnicodeError, LookupError): - return path.decode('utf8', 'ignore') + return path.decode('utf-8', 'ignore') def syspath(path, prefix=True): @@ -360,15 +394,15 @@ def syspath(path, prefix=True): *really* know what you're doing. """ # Don't do anything if we're not on windows - if os.path.__name__ != b'ntpath': + if os.path.__name__ != 'ntpath': return path - if not isinstance(path, unicode): + if not isinstance(path, six.text_type): # Beets currently represents Windows paths internally with UTF-8 # arbitrarily. But earlier versions used MBCS because it is # reported as the FS encoding by Windows. Try both. try: - path = path.decode('utf8') + path = path.decode('utf-8') except UnicodeError: # The encoding should always be MBCS, Windows' broken # Unicode representation. @@ -388,6 +422,8 @@ def syspath(path, prefix=True): def samefile(p1, p2): """Safer equality for paths.""" + if p1 == p2: + return True return shutil._samefile(syspath(p1), syspath(p2)) @@ -415,7 +451,7 @@ def copy(path, dest, replace=False): path = syspath(path) dest = syspath(dest) if not replace and os.path.exists(dest): - raise FilesystemError('file exists', 'copy', (path, dest)) + raise FilesystemError(u'file exists', 'copy', (path, dest)) try: shutil.copyfile(path, dest) except (OSError, IOError) as exc: @@ -436,8 +472,7 @@ def move(path, dest, replace=False): path = syspath(path) dest = syspath(dest) if os.path.exists(dest) and not replace: - raise FilesystemError('file exists', 'rename', (path, dest), - traceback.format_exc()) + raise FilesystemError(u'file exists', 'rename', (path, dest)) # First, try renaming the file. try: @@ -455,23 +490,52 @@ def move(path, dest, replace=False): def link(path, dest, replace=False): """Create a symbolic link from path to `dest`. Raises an OSError if `dest` already exists, unless `replace` is True. Does nothing if - `path` == `dest`.""" - if (samefile(path, dest)): + `path` == `dest`. + """ + if samefile(path, dest): return - path = syspath(path) - dest = syspath(dest) - if os.path.exists(dest) and not replace: - raise FilesystemError('file exists', 'rename', (path, dest), - traceback.format_exc()) + if os.path.exists(syspath(dest)) and not replace: + raise FilesystemError(u'file exists', 'rename', (path, dest)) try: - os.symlink(path, dest) - except OSError: - raise FilesystemError('Operating system does not support symbolic ' - 'links.', 'link', (path, dest), + os.symlink(syspath(path), syspath(dest)) + except NotImplementedError: + # raised on python >= 3.2 and Windows versions before Vista + raise FilesystemError(u'OS does not support symbolic links.' + 'link', (path, dest), traceback.format_exc()) + except OSError as exc: + # TODO: Windows version checks can be removed for python 3 + if hasattr('sys', 'getwindowsversion'): + if sys.getwindowsversion()[0] < 6: # is before Vista + exc = u'OS does not support symbolic links.' + raise FilesystemError(exc, 'link', (path, dest), traceback.format_exc()) +def hardlink(path, dest, replace=False): + """Create a hard link from path to `dest`. Raises an OSError if + `dest` already exists, unless `replace` is True. Does nothing if + `path` == `dest`. + """ + if samefile(path, dest): + return + + if os.path.exists(syspath(dest)) and not replace: + raise FilesystemError(u'file exists', 'rename', (path, dest)) + try: + os.link(syspath(path), syspath(dest)) + except NotImplementedError: + raise FilesystemError(u'OS does not support hard links.' + 'link', (path, dest), traceback.format_exc()) + except OSError as exc: + if exc.errno == errno.EXDEV: + raise FilesystemError(u'Cannot hard link across devices.' + 'link', (path, dest), traceback.format_exc()) + else: + raise FilesystemError(exc, 'link', (path, dest), + traceback.format_exc()) + + def unique_path(path): """Returns a version of ``path`` that does not exist on the filesystem. Specifically, if ``path` itself already exists, then @@ -489,7 +553,8 @@ def unique_path(path): num = 0 while True: num += 1 - new_path = b'%s.%i%s' % (base, num, ext) + suffix = u'.{}'.format(num).encode() + ext + new_path = base + suffix if not os.path.exists(new_path): return new_path @@ -593,7 +658,7 @@ def legalize_path(path, replacements, length, extension, fragment): if fragment: # Outputting Unicode. - extension = extension.decode('utf8', 'ignore') + extension = extension.decode('utf-8', 'ignore') first_stage_path, _ = _legalize_stage( path, replacements, length, extension, fragment @@ -617,23 +682,59 @@ def legalize_path(path, replacements, length, extension, fragment): return second_stage_path, retruncated +def py3_path(path): + """Convert a bytestring path to Unicode on Python 3 only. On Python + 2, return the bytestring path unchanged. + + This helps deal with APIs on Python 3 that *only* accept Unicode + (i.e., `str` objects). I philosophically disagree with this + decision, because paths are sadly bytes on Unix, but that's the way + it is. So this function helps us "smuggle" the true bytes data + through APIs that took Python 3's Unicode mandate too seriously. + """ + if isinstance(path, six.text_type): + return path + assert isinstance(path, bytes) + if six.PY2: + return path + return os.fsdecode(path) + + def str2bool(value): """Returns a boolean reflecting a human-entered string.""" - return value.lower() in ('yes', '1', 'true', 't', 'y') + return value.lower() in (u'yes', u'1', u'true', u't', u'y') def as_string(value): """Convert a value to a Unicode object for matching with a query. None becomes the empty string. Bytestrings are silently decoded. """ + if six.PY2: + buffer_types = buffer, memoryview # noqa: F821 + else: + buffer_types = memoryview + if value is None: return u'' - elif isinstance(value, buffer): - return bytes(value).decode('utf8', 'ignore') + elif isinstance(value, buffer_types): + return bytes(value).decode('utf-8', 'ignore') elif isinstance(value, bytes): - return value.decode('utf8', 'ignore') + return value.decode('utf-8', 'ignore') else: - return unicode(value) + return six.text_type(value) + + +def text_string(value, encoding='utf-8'): + """Convert a string, which can either be bytes or unicode, to + unicode. + + Text (unicode) is left untouched; bytes are decoded. This is useful + to convert from a "native string" (bytes on Python 2, str on Python + 3) to a consistently unicode value. + """ + if isinstance(value, bytes): + return value.decode(encoding) + return value def plurality(objs): @@ -643,7 +744,7 @@ def plurality(objs): """ c = Counter(objs) if not c: - raise ValueError('sequence must be non-empty') + raise ValueError(u'sequence must be non-empty') return c.most_common(1)[0] @@ -653,19 +754,19 @@ def cpu_count(): """ # Adapted from the soundconverter project: # https://github.com/kassoulet/soundconverter - if sys.platform == b'win32': + if sys.platform == 'win32': try: num = int(os.environ['NUMBER_OF_PROCESSORS']) except (ValueError, KeyError): num = 0 - elif sys.platform == b'darwin': + elif sys.platform == 'darwin': try: - num = int(command_output([b'/usr/sbin/sysctl', b'-n', b'hw.ncpu'])) + num = int(command_output(['/usr/sbin/sysctl', '-n', 'hw.ncpu'])) except (ValueError, OSError, subprocess.CalledProcessError): num = 0 else: try: - num = os.sysconf(b'SC_NPROCESSORS_ONLN') + num = os.sysconf('SC_NPROCESSORS_ONLN') except (ValueError, OSError, AttributeError): num = 0 if num >= 1: @@ -674,10 +775,28 @@ def cpu_count(): return 1 +def convert_command_args(args): + """Convert command arguments to bytestrings on Python 2 and + surrogate-escaped strings on Python 3.""" + assert isinstance(args, list) + + def convert(arg): + if six.PY2: + if isinstance(arg, six.text_type): + arg = arg.encode(arg_encoding()) + else: + if isinstance(arg, bytes): + arg = arg.decode(arg_encoding(), 'surrogateescape') + return arg + + return [convert(a) for a in args] + + def command_output(cmd, shell=False): """Runs the command and returns its output after it has exited. - ``cmd`` is a list of byte string arguments starting with the command names. + ``cmd`` is a list of arguments starting with the command names. The + arguments are bytes on Unix and strings on Windows. If ``shell`` is true, ``cmd`` is assumed to be a string and passed to a shell to execute. @@ -688,18 +807,27 @@ def command_output(cmd, shell=False): This replaces `subprocess.check_output` which can have problems if lots of output is sent to stderr. """ + cmd = convert_command_args(cmd) + + try: # python >= 3.3 + devnull = subprocess.DEVNULL + except AttributeError: + devnull = open(os.devnull, 'r+b') + proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - close_fds=platform.system() != b'Windows', + stdin=devnull, + close_fds=platform.system() != 'Windows', shell=shell ) stdout, stderr = proc.communicate() if proc.returncode: raise subprocess.CalledProcessError( returncode=proc.returncode, - cmd=b' '.join(cmd), + cmd=' '.join(cmd), + output=stdout + stderr, ) return stdout @@ -711,7 +839,7 @@ def max_filename_length(path, limit=MAX_FILENAME_LENGTH): misreports its capacity). If it cannot be determined (e.g., on Windows), return `limit`. """ - if hasattr(os, b'statvfs'): + if hasattr(os, 'statvfs'): try: res = os.statvfs(path) except OSError: @@ -735,28 +863,149 @@ def open_anything(): return base_cmd -def interactive_open(targets, command=None): - """Open the files in `targets` by `exec`ing a new command. (The new - program takes over, and Python execution ends: this does not fork a - subprocess.) +def editor_command(): + """Get a command for opening a text file. - If `command` is provided, use it. Otherwise, use an OS-specific - command (from `open_anything`) to open the file. + Use the `EDITOR` environment variable by default. If it is not + present, fall back to `open_anything()`, the platform-specific tool + for opening files in general. + """ + editor = os.environ.get('EDITOR') + if editor: + return editor + return open_anything() + + +def shlex_split(s): + """Split a Unicode or bytes string according to shell lexing rules. + + Raise `ValueError` if the string is not a well-formed shell string. + This is a workaround for a bug in some versions of Python. + """ + if not six.PY2 or isinstance(s, bytes): # Shlex works fine. + return shlex.split(s) + + elif isinstance(s, six.text_type): + # Work around a Python bug. + # http://bugs.python.org/issue6988 + bs = s.encode('utf-8') + return [c.decode('utf-8') for c in shlex.split(bs)] + + else: + raise TypeError(u'shlex_split called with non-string') + + +def interactive_open(targets, command): + """Open the files in `targets` by `exec`ing a new `command`, given + as a Unicode string. (The new program takes over, and Python + execution ends: this does not fork a subprocess.) Can raise `OSError`. """ - if command: - command = command.encode('utf8') - try: - command = [c.decode('utf8') - for c in shlex.split(command)] - except ValueError: # Malformed shell tokens. - command = [command] - command.insert(0, command[0]) # for argv[0] + assert command + + # Split the command string into its arguments. + try: + args = shlex_split(command) + except ValueError: # Malformed shell tokens. + args = [command] + + args.insert(0, args[0]) # for argv[0] + + args += targets + + return os.execlp(*args) + + +def _windows_long_path_name(short_path): + """Use Windows' `GetLongPathNameW` via ctypes to get the canonical, + long path given a short filename. + """ + if not isinstance(short_path, six.text_type): + short_path = short_path.decode(_fsencoding()) + + import ctypes + buf = ctypes.create_unicode_buffer(260) + get_long_path_name_w = ctypes.windll.kernel32.GetLongPathNameW + return_value = get_long_path_name_w(short_path, buf, 260) + + if return_value == 0 or return_value > 260: + # An error occurred + return short_path else: - base_cmd = open_anything() - command = [base_cmd, base_cmd] + long_path = buf.value + # GetLongPathNameW does not change the case of the drive + # letter. + if len(long_path) > 1 and long_path[1] == ':': + long_path = long_path[0].upper() + long_path[1:] + return long_path - command += targets - return os.execlp(*command) +def case_sensitive(path): + """Check whether the filesystem at the given path is case sensitive. + + To work best, the path should point to a file or a directory. If the path + does not exist, assume a case sensitive file system on every platform + except Windows. + """ + # A fallback in case the path does not exist. + if not os.path.exists(syspath(path)): + # By default, the case sensitivity depends on the platform. + return platform.system() != 'Windows' + + # If an upper-case version of the path exists but a lower-case + # version does not, then the filesystem must be case-sensitive. + # (Otherwise, we have more work to do.) + if not (os.path.exists(syspath(path.lower())) and + os.path.exists(syspath(path.upper()))): + return True + + # Both versions of the path exist on the file system. Check whether + # they refer to different files by their inodes. Alas, + # `os.path.samefile` is only available on Unix systems on Python 2. + if platform.system() != 'Windows': + return not os.path.samefile(syspath(path.lower()), + syspath(path.upper())) + + # On Windows, we check whether the canonical, long filenames for the + # files are the same. + lower = _windows_long_path_name(path.lower()) + upper = _windows_long_path_name(path.upper()) + return lower != upper + + +def raw_seconds_short(string): + """Formats a human-readable M:SS string as a float (number of seconds). + + Raises ValueError if the conversion cannot take place due to `string` not + being in the right format. + """ + match = re.match(r'^(\d+):([0-5]\d)$', string) + if not match: + raise ValueError(u'String not in M:SS format') + minutes, seconds = map(int, match.groups()) + return float(minutes * 60 + seconds) + + +def asciify_path(path, sep_replace): + """Decodes all unicode characters in a path into ASCII equivalents. + + Substitutions are provided by the unidecode module. Path separators in the + input are preserved. + + Keyword arguments: + path -- The path to be asciified. + sep_replace -- the string to be used to replace extraneous path separators. + """ + # if this platform has an os.altsep, change it to os.sep. + if os.altsep: + path = path.replace(os.altsep, os.sep) + path_components = path.split(os.sep) + for index, item in enumerate(path_components): + path_components[index] = unidecode(item).replace(os.sep, sep_replace) + if os.altsep: + path_components[index] = unidecode(item).replace( + os.altsep, + sep_replace + ) + return os.sep.join(path_components) diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index 741ebda1b..c32f0f37d 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Fabrice Laporte +# Copyright 2016, Fabrice Laporte # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,24 +16,26 @@ """Abstraction layer to resize images using PIL, ImageMagick, or a public resizing proxy if neither is available. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function -import urllib import subprocess import os import re from tempfile import NamedTemporaryFile - +from six.moves.urllib.parse import urlencode from beets import logging from beets import util +import six # Resizing methods PIL = 1 IMAGEMAGICK = 2 WEBPROXY = 3 -PROXY_URL = 'http://images.weserv.nl/' +if util.SNI_SUPPORTED: + PROXY_URL = 'https://images.weserv.nl/' +else: + PROXY_URL = 'http://images.weserv.nl/' log = logging.getLogger('beets') @@ -41,9 +44,9 @@ def resize_url(url, maxwidth): """Return a proxied image URL that resizes the original image to maxwidth (preserving aspect ratio). """ - return '{0}?{1}'.format(PROXY_URL, urllib.urlencode({ + return '{0}?{1}'.format(PROXY_URL, urlencode({ 'url': url.replace('http://', ''), - 'w': bytes(maxwidth), + 'w': maxwidth, })) @@ -52,8 +55,8 @@ def temp_file_for(path): specified path. """ ext = os.path.splitext(path)[1] - with NamedTemporaryFile(suffix=ext, delete=False) as f: - return f.name + with NamedTemporaryFile(suffix=util.py3_path(ext), delete=False) as f: + return util.bytestring_path(f.name) def pil_resize(maxwidth, path_in, path_out=None): @@ -85,18 +88,18 @@ def im_resize(maxwidth, path_in, path_out=None): log.debug(u'artresizer: ImageMagick resizing {0} to {1}', util.displayable_path(path_in), util.displayable_path(path_out)) - # "-resize widthxheight>" shrinks images with dimension(s) larger - # than the corresponding width and/or height dimension(s). The > - # "only shrink" flag is prefixed by ^ escape char for Windows - # compatibility. + # "-resize WIDTHx>" shrinks images with the width larger + # than the given width while maintaining the aspect ratio + # with regards to the height. try: util.command_output([ - b'convert', util.syspath(path_in), - b'-resize', b'{0}x^>'.format(maxwidth), path_out + 'convert', util.syspath(path_in, prefix=False), + '-resize', '{0}x>'.format(maxwidth), + util.syspath(path_out, prefix=False), ]) except subprocess.CalledProcessError: - log.warn(u'artresizer: IM convert failed for {0}', - util.displayable_path(path_in)) + log.warning(u'artresizer: IM convert failed for {0}', + util.displayable_path(path_in)) return path_in return path_out @@ -112,23 +115,28 @@ def pil_getsize(path_in): try: im = Image.open(util.syspath(path_in)) return im.size - except IOError: - log.error(u"PIL cannot compute size of '{0}'", - util.displayable_path(path_in)) + except IOError as exc: + log.error(u"PIL could not read file {}: {}", + util.displayable_path(path_in), exc) def im_getsize(path_in): + cmd = ['identify', '-format', '%w %h', + util.syspath(path_in, prefix=False)] try: - out = util.command_output([b'identify', b'-format', b'%w %h', - util.syspath(path_in)]) - except subprocess.CalledProcessError: - log.warn(u'IM cannot compute size of {0}', - util.displayable_path(path_in)) + out = util.command_output(cmd) + except subprocess.CalledProcessError as exc: + log.warning(u'ImageMagick size query failed') + log.debug( + u'`convert` exited with (status {}) when ' + u'getting size with command {}:\n{}', + exc.returncode, cmd, exc.output.strip() + ) return try: return tuple(map(int, out.split(b' '))) except IndexError: - log.warn(u'Could not understand IM output: {0!r}', out) + log.warning(u'Could not understand IM output: {0!r}', out) BACKEND_GET_SIZE = { @@ -143,21 +151,20 @@ class Shareable(type): lazily-created shared instance of ``MyClass`` while calling ``MyClass()`` to construct a new object works as usual. """ - def __init__(cls, name, bases, dict): - super(Shareable, cls).__init__(name, bases, dict) - cls._instance = None + def __init__(self, name, bases, dict): + super(Shareable, self).__init__(name, bases, dict) + self._instance = None @property - def shared(cls): - if cls._instance is None: - cls._instance = cls() - return cls._instance + def shared(self): + if self._instance is None: + self._instance = self() + return self._instance -class ArtResizer(object): +class ArtResizer(six.with_metaclass(Shareable, object)): """A singleton class that performs image resizes. """ - __metaclass__ = Shareable def __init__(self): """Create a resizer object with an inferred method. @@ -212,25 +219,26 @@ class ArtResizer(object): @staticmethod def _check_method(): """Return a tuple indicating an available method and its version.""" - version = has_IM() + version = get_im_version() if version: return IMAGEMAGICK, version - version = has_PIL() + version = get_pil_version() if version: return PIL, version return WEBPROXY, (0) -def has_IM(): +def get_im_version(): """Return Image Magick version or None if it is unavailable - Try invoking ImageMagick's "convert".""" + Try invoking ImageMagick's "convert". + """ try: - out = util.command_output([b'identify', b'--version']) + out = util.command_output(['convert', '--version']) - if 'imagemagick' in out.lower(): - pattern = r".+ (\d+)\.(\d+)\.(\d+).*" + if b'imagemagick' in out.lower(): + pattern = br".+ (\d+)\.(\d+)\.(\d+).*" match = re.search(pattern, out) if match: return (int(match.group(1)), @@ -238,11 +246,12 @@ def has_IM(): int(match.group(3))) return (0,) - except (subprocess.CalledProcessError, OSError): + except (subprocess.CalledProcessError, OSError) as exc: + log.debug(u'ImageMagick check `convert --version` failed: {}', exc) return None -def has_PIL(): +def get_pil_version(): """Return Image Magick version or None if it is unavailable Try importing PIL.""" try: diff --git a/beets/util/bluelet.py b/beets/util/bluelet.py index 2fa10a57c..0da17559b 100644 --- a/beets/util/bluelet.py +++ b/beets/util/bluelet.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + """Extremely simple pure-Python implementation of coroutine-style asynchronous socket I/O. Inspired by, but inferior to, Eventlet. Bluelet can also be thought of as a less-terrible replacement for @@ -5,9 +7,9 @@ asyncore. Bluelet: easy concurrency without all the messy parallelism. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function +import six import socket import select import sys @@ -18,20 +20,6 @@ import time import collections -# A little bit of "six" (Python 2/3 compatibility): cope with PEP 3109 syntax -# changes. - -PY3 = sys.version_info[0] == 3 -if PY3: - def _reraise(typ, exc, tb): - raise exc.with_traceback(tb) -else: - exec(""" -def _reraise(typ, exc, tb): - raise typ, exc, tb -""") - - # Basic events used for thread scheduling. class Event(object): @@ -213,7 +201,7 @@ class ThreadException(Exception): self.exc_info = exc_info def reraise(self): - _reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2]) + six.reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2]) SUSPENDED = Event() # Special sentinel placeholder for suspended threads. @@ -281,7 +269,7 @@ def run(root_coro): except StopIteration: # Thread is done. complete_thread(coro, None) - except: + except BaseException: # Thread raised some other exception. del threads[coro] raise ThreadException(coro, sys.exc_info()) @@ -378,7 +366,7 @@ def run(root_coro): exit_te = te break - except: + except BaseException: # For instance, KeyboardInterrupt during select(). Raise # into root thread and terminate others. threads = {root_coro: ExceptionEvent(sys.exc_info())} @@ -553,7 +541,7 @@ def spawn(coro): and child coroutines run concurrently. """ if not isinstance(coro, types.GeneratorType): - raise ValueError('%s is not a coroutine' % coro) + raise ValueError(u'%s is not a coroutine' % coro) return SpawnEvent(coro) @@ -563,7 +551,7 @@ def call(coro): returns a value using end(), then this event returns that value. """ if not isinstance(coro, types.GeneratorType): - raise ValueError('%s is not a coroutine' % coro) + raise ValueError(u'%s is not a coroutine' % coro) return DelegationEvent(coro) diff --git a/beets/util/confit.py b/beets/util/confit.py index 4c5b30cb6..b5513f48e 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -1,5 +1,6 @@ -# This file is part of Confit. -# Copyright 2015, Adrian Sampson. +# -*- coding: utf-8 -*- +# This file is part of Confuse. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,21 +15,16 @@ """Worry-free YAML configuration files. """ -from __future__ import (unicode_literals, absolute_import, print_function, - division) +from __future__ import division, absolute_import, print_function import platform import os import pkgutil import sys import yaml -import types import collections import re -try: - from collections import OrderedDict -except ImportError: - from ordereddict import OrderedDict +from collections import OrderedDict UNIX_DIR_VAR = 'XDG_CONFIG_HOME' UNIX_DIR_FALLBACK = '~/.config' @@ -48,10 +44,9 @@ REDACTED_TOMBSTONE = 'REDACTED' # Utilities. PY3 = sys.version_info[0] == 3 -STRING = str if PY3 else unicode -BASESTRING = str if PY3 else basestring -NUMERIC_TYPES = (int, float) if PY3 else (int, float, long) -TYPE_TYPES = (type,) if PY3 else (type, types.ClassType) +STRING = str if PY3 else unicode # noqa: F821 +BASESTRING = str if PY3 else basestring # noqa: F821 +NUMERIC_TYPES = (int, float) if PY3 else (int, float, long) # noqa: F821 def iter_first(sequence): @@ -60,10 +55,7 @@ def iter_first(sequence): """ it = iter(sequence) try: - if PY3: - return next(it) - else: - return it.next() + return next(it) except StopIteration: raise ValueError() @@ -100,17 +92,17 @@ class ConfigReadError(ConfigError): self.filename = filename self.reason = reason - message = 'file {0} could not be read'.format(filename) + message = u'file {0} could not be read'.format(filename) if isinstance(reason, yaml.scanner.ScannerError) and \ reason.problem == YAML_TAB_PROBLEM: # Special-case error message for tab indentation in YAML markup. - message += ': found tab character at line {0}, column {1}'.format( + message += u': found tab character at line {0}, column {1}'.format( reason.problem_mark.line + 1, reason.problem_mark.column + 1, ) elif reason: # Generic error message uses exception's message. - message += ': {0}'.format(reason) + message += u': {0}'.format(reason) super(ConfigReadError, self).__init__(message) @@ -124,19 +116,19 @@ class ConfigSource(dict): def __init__(self, value, filename=None, default=False): super(ConfigSource, self).__init__(value) if filename is not None and not isinstance(filename, BASESTRING): - raise TypeError('filename must be a string or None') + raise TypeError(u'filename must be a string or None') self.filename = filename self.default = default def __repr__(self): - return 'ConfigSource({0}, {1}, {2})'.format( - super(ConfigSource, self).__repr__(), - repr(self.filename), - repr(self.default) + return 'ConfigSource({0!r}, {1!r}, {2!r})'.format( + super(ConfigSource, self), + self.filename, + self.default, ) @classmethod - def of(self, value): + def of(cls, value): """Given either a dictionary or a `ConfigSource` object, return a `ConfigSource` object. This lets a function accept either type of object as an argument. @@ -146,7 +138,7 @@ class ConfigSource(dict): elif isinstance(value, dict): return ConfigSource(value) else: - raise TypeError('source value must be a dict') + raise TypeError(u'source value must be a dict') class ConfigView(object): @@ -181,7 +173,7 @@ class ConfigView(object): try: return iter_first(pairs) except ValueError: - raise NotFoundError("{0} not found".format(self.name)) + raise NotFoundError(u"{0} not found".format(self.name)) def exists(self): """Determine whether the view has a setting in any source. @@ -215,10 +207,28 @@ class ConfigView(object): return '<{}: {}>'.format(self.__class__.__name__, self.name) def __iter__(self): - # Prevent list(config) from using __getitem__ and entering an - # infinite loop. - raise TypeError(u"{!r} object is not " - u"iterable".format(self.__class__.__name__)) + """Iterate over the keys of a dictionary view or the *subviews* + of a list view. + """ + # Try getting the keys, if this is a dictionary view. + try: + keys = self.keys() + for key in keys: + yield key + + except ConfigTypeError: + # Otherwise, try iterating over a list. + collection = self.get() + if not isinstance(collection, (list, tuple)): + raise ConfigTypeError( + u'{0} must be a dictionary or a list, not {1}'.format( + self.name, type(collection).__name__ + ) + ) + + # Yield all the indices in the list. + for index in range(len(collection)): + yield self[index] def __getitem__(self, key): """Get a subview of this view.""" @@ -235,10 +245,15 @@ class ConfigView(object): def set_args(self, namespace): """Overlay parsed command-line arguments, generated by a library - like argparse or optparse, onto this view's value. + like argparse or optparse, onto this view's value. ``namespace`` + can be a ``dict`` or namespace object. """ args = {} - for key, value in namespace.__dict__.items(): + if isinstance(namespace, dict): + items = namespace.items() + else: + items = namespace.__dict__.items() + for key, value in items: if value is not None: # Avoid unset options. args[key] = value self.set(args) @@ -289,7 +304,7 @@ class ConfigView(object): cur_keys = dic.keys() except AttributeError: raise ConfigTypeError( - '{0} must be a dict, not {1}'.format( + u'{0} must be a dict, not {1}'.format( self.name, type(dic).__name__ ) ) @@ -330,7 +345,7 @@ class ConfigView(object): it = iter(collection) except TypeError: raise ConfigTypeError( - '{0} must be an iterable, not {1}'.format( + u'{0} must be an iterable, not {1}'.format( self.name, type(collection).__name__ ) ) @@ -373,19 +388,42 @@ class ConfigView(object): """ return as_template(template).value(self, template) - # Old validation methods (deprecated). + # Shortcuts for common templates. def as_filename(self): + """Get the value as a path. Equivalent to `get(Filename())`. + """ return self.get(Filename()) def as_choice(self, choices): + """Get the value from a list of choices. Equivalent to + `get(Choice(choices))`. + """ return self.get(Choice(choices)) def as_number(self): + """Get the value as any number type: int or float. Equivalent to + `get(Number())`. + """ return self.get(Number()) - def as_str_seq(self): - return self.get(StrSeq()) + def as_str_seq(self, split=True): + """Get the value as a sequence of strings. Equivalent to + `get(StrSeq())`. + """ + return self.get(StrSeq(split=split)) + + def as_pairs(self, default_value=None): + """Get the value as a sequence of pairs of two strings. Equivalent to + `get(Pairs())`. + """ + return self.get(Pairs(default_value=default_value)) + + def as_str(self): + """Get the value as a (Unicode) string. Equivalent to + `get(unicode)` on Python 2 and `get(str)` on Python 3. + """ + return self.get(String()) # Redaction. @@ -470,12 +508,11 @@ class Subview(ConfigView): if not isinstance(self.key, int): self.name += '.' if isinstance(self.key, int): - self.name += '#{0}'.format(self.key) - elif isinstance(self.key, BASESTRING): - if isinstance(self.key, bytes): - self.name += self.key.decode('utf8') - else: - self.name += self.key + self.name += u'#{0}'.format(self.key) + elif isinstance(self.key, bytes): + self.name += self.key.decode('utf-8') + elif isinstance(self.key, STRING): + self.name += self.key else: self.name += repr(self.key) @@ -492,7 +529,7 @@ class Subview(ConfigView): except TypeError: # Not subscriptable. raise ConfigTypeError( - "{0} must be a collection, not {1}".format( + u"{0} must be a collection, not {1}".format( self.parent.name, type(collection).__name__ ) ) @@ -525,7 +562,7 @@ def _package_path(name): ``name == "__main__"``). """ loader = pkgutil.get_loader(name) - if loader is None or name == b'__main__': + if loader is None or name == '__main__': return None if hasattr(loader, 'get_filename'): @@ -602,7 +639,7 @@ class Loader(yaml.SafeLoader): else: raise yaml.constructor.ConstructorError( None, None, - 'expected a mapping node, but found %s' % node.id, + u'expected a mapping node, but found %s' % node.id, node.start_mark ) @@ -613,7 +650,7 @@ class Loader(yaml.SafeLoader): hash(key) except TypeError as exc: raise yaml.constructor.ConstructorError( - 'while constructing a mapping', + u'while constructing a mapping', node.start_mark, 'found unacceptable key (%s)' % exc, key_node.start_mark ) @@ -637,7 +674,7 @@ def load_yaml(filename): parsed, a ConfigReadError is raised. """ try: - with open(filename, 'r') as f: + with open(filename, 'rb') as f: return yaml.load(f, Loader=Loader) except (IOError, yaml.error.YAMLError) as exc: raise ConfigReadError(filename, exc) @@ -691,9 +728,9 @@ class Dumper(yaml.SafeDumper): """Represent bool as 'yes' or 'no' instead of 'true' or 'false'. """ if data: - value = 'yes' + value = u'yes' else: - value = 'no' + value = u'no' return self.represent_scalar('tag:yaml.org,2002:bool', value) def represent_none(self, data): @@ -818,7 +855,7 @@ class Configuration(RootView): appdir = os.environ[self._env_var] appdir = os.path.abspath(os.path.expanduser(appdir)) if os.path.isfile(appdir): - raise ConfigError('{0} must be a directory'.format( + raise ConfigError(u'{0} must be a directory'.format( self._env_var )) @@ -877,9 +914,10 @@ class Configuration(RootView): default_source = source break if default_source and default_source.filename: - with open(default_source.filename, 'r') as fp: + with open(default_source.filename, 'rb') as fp: default_data = fp.read() - yaml_out = restore_yaml_comments(yaml_out, default_data) + yaml_out = restore_yaml_comments(yaml_out, + default_data.decode('utf8')) return yaml_out @@ -940,7 +978,7 @@ should be raised when the value is missing. class Template(object): """A value template for configuration fields. - The template works like a type and instructs Confit about how to + The template works like a type and instructs Confuse about how to interpret a deserialized YAML value. This includes type conversions, providing a default value, and validating for errors. For example, a filepath type might expand tildes and check that the file exists. @@ -971,7 +1009,7 @@ class Template(object): return self.convert(value, view) elif self.default is REQUIRED: # Missing required value. This is an error. - raise NotFoundError("{0} not found".format(view.name)) + raise NotFoundError(u"{0} not found".format(view.name)) else: # Missing value, but not required. return self.default @@ -996,7 +1034,7 @@ class Template(object): """ exc_class = ConfigTypeError if type_error else ConfigValueError raise exc_class( - '{0}: {1}'.format(view.name, message) + u'{0}: {1}'.format(view.name, message) ) def __repr__(self): @@ -1017,7 +1055,7 @@ class Integer(Template): elif isinstance(value, float): return int(value) else: - self.fail('must be a number', view, True) + self.fail(u'must be a number', view, True) class Number(Template): @@ -1030,7 +1068,7 @@ class Number(Template): return value else: self.fail( - 'must be numeric, not {0}'.format(type(value).__name__), + u'must be numeric, not {0}'.format(type(value).__name__), view, True ) @@ -1092,12 +1130,12 @@ class String(Template): if isinstance(value, BASESTRING): if self.pattern and not self.regex.match(value): self.fail( - "must match the pattern {0}".format(self.pattern), + u"must match the pattern {0}".format(self.pattern), view ) return value else: - self.fail('must be a string', view, True) + self.fail(u'must be a string', view, True) class Choice(Template): @@ -1118,7 +1156,7 @@ class Choice(Template): """ if value not in self.choices: self.fail( - 'must be one of {0}, not {1}'.format( + u'must be one of {0}, not {1}'.format( repr(list(self.choices)), repr(value) ), view @@ -1187,7 +1225,7 @@ class OneOf(Template): raise ConfigTemplateError(exc) self.fail( - 'must be one of {0}, not {1}'.format( + u'must be one of {0}, not {1}'.format( repr(self.allowed), repr(value) ), view @@ -1210,30 +1248,77 @@ class StrSeq(Template): super(StrSeq, self).__init__() self.split = split + def _convert_value(self, x, view): + if isinstance(x, STRING): + return x + elif isinstance(x, bytes): + return x.decode('utf-8', 'ignore') + else: + self.fail(u'must be a list of strings', view, True) + def convert(self, value, view): if isinstance(value, bytes): - value = value.decode('utf8', 'ignore') + value = value.decode('utf-8', 'ignore') if isinstance(value, STRING): if self.split: - return value.split() + value = value.split() else: - return [value] + value = [value] + else: + try: + value = list(value) + except TypeError: + self.fail(u'must be a whitespace-separated string or a list', + view, True) + return [self._convert_value(v, view) for v in value] + + +class Pairs(StrSeq): + """A template for ordered key-value pairs. + + This can either be given with the same syntax as for `StrSeq` (i.e. without + values), or as a list of strings and/or single-element mappings such as:: + + - key: value + - [key, value] + - key + + The result is a list of two-element tuples. If no value is provided, the + `default_value` will be returned as the second element. + """ + + def __init__(self, default_value=None): + """Create a new template. + + `default` is the dictionary value returned for items that are not + a mapping, but a single string. + """ + super(Pairs, self).__init__(split=True) + self.default_value = default_value + + def _convert_value(self, x, view): try: - value = list(value) - except TypeError: - self.fail('must be a whitespace-separated string or a list', - view, True) - - def convert(x): - if isinstance(x, STRING): - return x - elif isinstance(x, bytes): - return x.decode('utf8', 'ignore') + return (super(Pairs, self)._convert_value(x, view), + self.default_value) + except ConfigTypeError: + if isinstance(x, collections.Mapping): + if len(x) != 1: + self.fail(u'must be a single-element mapping', view, True) + k, v = iter_first(x.items()) + elif isinstance(x, collections.Sequence): + if len(x) != 2: + self.fail(u'must be a two-element list', view, True) + k, v = x else: - self.fail('must be a list of strings', view, True) - return list(map(convert, value)) + # Is this even possible? -> Likely, if some !directive cause + # YAML to parse this to some custom type. + self.fail(u'must be a single string, mapping, or a list' + u'' + str(x), + view, True) + return (super(Pairs, self)._convert_value(k, view), + super(Pairs, self)._convert_value(v, view)) class Filename(Template): @@ -1282,19 +1367,19 @@ class Filename(Template): if not isinstance(template, (collections.Mapping, MappingTemplate)): # disallow config.get(Filename(relative_to='foo')) raise ConfigTemplateError( - 'relative_to may only be used when getting multiple values.' + u'relative_to may only be used when getting multiple values.' ) elif self.relative_to == view.key: raise ConfigTemplateError( - '{0} is relative to itself'.format(view.name) + u'{0} is relative to itself'.format(view.name) ) elif self.relative_to not in view.parent.keys(): # self.relative_to is not in the config self.fail( ( - 'needs sibling value "{0}" to expand relative path' + u'needs sibling value "{0}" to expand relative path' ).format(self.relative_to), view ) @@ -1316,12 +1401,12 @@ class Filename(Template): if next_relative in template.subtemplates: # we encountered this config key previously raise ConfigTemplateError(( - '{0} and {1} are recursively relative' + u'{0} and {1} are recursively relative' ).format(view.name, self.relative_to)) else: raise ConfigTemplateError(( - 'missing template for {0}, needed to expand {1}\'s' + - 'relative path' + u'missing template for {0}, needed to expand {1}\'s' + + u'relative path' ).format(self.relative_to, view.name)) next_template.subtemplates[next_relative] = rel_to_template @@ -1333,7 +1418,7 @@ class Filename(Template): path, source = view.first() if not isinstance(path, BASESTRING): self.fail( - 'must be a filename, not {0}'.format(type(path).__name__), + u'must be a filename, not {0}'.format(type(path).__name__), view, True ) @@ -1371,7 +1456,7 @@ class TypeTemplate(Template): def convert(self, value, view): if not isinstance(value, self.typ): self.fail( - 'must be a {0}, not {1}'.format( + u'must be a {0}, not {1}'.format( self.typ.__name__, type(value).__name__, ), @@ -1425,4 +1510,4 @@ def as_template(value): elif isinstance(value, type): return TypeTemplate(value) else: - raise ValueError('cannot convert to template: {0!r}'.format(value)) + raise ValueError(u'cannot convert to template: {0!r}'.format(value)) diff --git a/beets/util/enumeration.py b/beets/util/enumeration.py index dc0a6fa42..3e9467185 100644 --- a/beets/util/enumeration.py +++ b/beets/util/enumeration.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from enum import Enum diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index 3d5b0e871..0e13db4a0 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -26,13 +27,14 @@ This is sort of like a tiny, horrible degeneration of a real templating engine like Jinja2 or Mustache. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import re import ast import dis import types +import sys +import six SYMBOL_DELIM = u'$' FUNC_DELIM = u'%' @@ -41,8 +43,8 @@ GROUP_CLOSE = u'}' ARG_SEP = u',' ESCAPE_CHAR = u'$' -VARIABLE_PREFIX = b'__var_' -FUNCTION_PREFIX = b'__func_' +VARIABLE_PREFIX = '__var_' +FUNCTION_PREFIX = '__func_' class Environment(object): @@ -71,14 +73,14 @@ def ex_literal(val): value. """ if val is None: - return ast.Name(b'None', ast.Load()) - elif isinstance(val, (int, float, long)): + return ast.Name('None', ast.Load()) + elif isinstance(val, six.integer_types): return ast.Num(val) elif isinstance(val, bool): return ast.Name(bytes(val), ast.Load()) - elif isinstance(val, basestring): + elif isinstance(val, six.string_types): return ast.Str(val) - raise TypeError('no literal for {0}'.format(type(val))) + raise TypeError(u'no literal for {0}'.format(type(val))) def ex_varassign(name, expr): @@ -95,7 +97,7 @@ def ex_call(func, args): function may be an expression or the name of a function. Each argument may be an expression or a value to be used as a literal. """ - if isinstance(func, basestring): + if isinstance(func, six.string_types): func = ex_rvalue(func) args = list(args) @@ -103,7 +105,10 @@ def ex_call(func, args): if not isinstance(args[i], ast.expr): args[i] = ex_literal(args[i]) - return ast.Call(func, args, [], None, None) + if sys.version_info[:2] < (3, 5): + return ast.Call(func, args, [], None, None) + else: + return ast.Call(func, args, []) def compile_func(arg_names, statements, name='_the_func', debug=False): @@ -111,20 +116,35 @@ def compile_func(arg_names, statements, name='_the_func', debug=False): the resulting Python function. If `debug`, then print out the bytecode of the compiled function. """ - func_def = ast.FunctionDef( - name.encode('utf8'), - ast.arguments( - [ast.Name(n, ast.Param()) for n in arg_names], - None, None, - [ex_literal(None) for _ in arg_names], - ), - statements, - [], - ) + if six.PY2: + func_def = ast.FunctionDef( + name=name.encode('utf-8'), + args=ast.arguments( + args=[ast.Name(n, ast.Param()) for n in arg_names], + vararg=None, + kwarg=None, + defaults=[ex_literal(None) for _ in arg_names], + ), + body=statements, + decorator_list=[], + ) + else: + func_def = ast.FunctionDef( + name=name, + args=ast.arguments( + args=[ast.arg(arg=n, annotation=None) for n in arg_names], + kwonlyargs=[], + kw_defaults=[], + defaults=[ex_literal(None) for _ in arg_names], + ), + body=statements, + decorator_list=[], + ) + mod = ast.Module([func_def]) ast.fix_missing_locations(mod) - prog = compile(mod, b'', b'exec') + prog = compile(mod, '', 'exec') # Debug: show bytecode. if debug: @@ -134,7 +154,7 @@ def compile_func(arg_names, statements, name='_the_func', debug=False): dis.dis(const) the_locals = {} - exec prog in {}, the_locals + exec(prog, {}, the_locals) return the_locals[name] @@ -162,8 +182,12 @@ class Symbol(object): def translate(self): """Compile the variable lookup.""" - expr = ex_rvalue(VARIABLE_PREFIX + self.ident.encode('utf8')) - return [expr], set([self.ident.encode('utf8')]), set() + if six.PY2: + ident = self.ident.encode('utf-8') + else: + ident = self.ident + expr = ex_rvalue(VARIABLE_PREFIX + ident) + return [expr], set([ident]), set() class Call(object): @@ -188,15 +212,19 @@ class Call(object): except Exception as exc: # Function raised exception! Maybe inlining the name of # the exception will help debug. - return u'<%s>' % unicode(exc) - return unicode(out) + return u'<%s>' % six.text_type(exc) + return six.text_type(out) else: return self.original def translate(self): """Compile the function call.""" varnames = set() - funcnames = set([self.ident.encode('utf8')]) + if six.PY2: + ident = self.ident.encode('utf-8') + else: + ident = self.ident + funcnames = set([ident]) arg_exprs = [] for arg in self.args: @@ -207,18 +235,18 @@ class Call(object): # Create a subexpression that joins the result components of # the arguments. arg_exprs.append(ex_call( - ast.Attribute(ex_literal(u''), b'join', ast.Load()), + ast.Attribute(ex_literal(u''), 'join', ast.Load()), [ex_call( - b'map', + 'map', [ - ex_rvalue(b'unicode'), + ex_rvalue(six.text_type.__name__), ast.List(subexprs, ast.Load()), ] )], )) subexpr_call = ex_call( - FUNCTION_PREFIX + self.ident.encode('utf8'), + FUNCTION_PREFIX + ident, arg_exprs ) return [subexpr_call], varnames, funcnames @@ -240,11 +268,11 @@ class Expression(object): """ out = [] for part in self.parts: - if isinstance(part, basestring): + if isinstance(part, six.string_types): out.append(part) else: out.append(part.evaluate(env)) - return u''.join(map(unicode, out)) + return u''.join(map(six.text_type, out)) def translate(self): """Compile the expression to a list of Python AST expressions, a @@ -254,7 +282,7 @@ class Expression(object): varnames = set() funcnames = set() for part in self.parts: - if isinstance(part, basestring): + if isinstance(part, six.string_types): expressions.append(ex_literal(part)) else: e, v, f = part.translate() @@ -283,16 +311,24 @@ class Parser(object): replaced with a real, accepted parsing technique (PEG, parser generator, etc.). """ - def __init__(self, string): + def __init__(self, string, in_argument=False): + """ Create a new parser. + :param in_arguments: boolean that indicates the parser is to be + used for parsing function arguments, ie. considering commas + (`ARG_SEP`) a special character + """ self.string = string + self.in_argument = in_argument self.pos = 0 self.parts = [] # Common parsing resources. special_chars = (SYMBOL_DELIM, FUNC_DELIM, GROUP_OPEN, GROUP_CLOSE, - ARG_SEP, ESCAPE_CHAR) - special_char_re = re.compile(r'[%s]|$' % + ESCAPE_CHAR) + special_char_re = re.compile(r'[%s]|\Z' % u''.join(re.escape(c) for c in special_chars)) + escapable_chars = (SYMBOL_DELIM, FUNC_DELIM, GROUP_CLOSE, ARG_SEP) + terminator_chars = (GROUP_CLOSE,) def parse_expression(self): """Parse a template expression starting at ``pos``. Resulting @@ -300,16 +336,29 @@ class Parser(object): the ``parts`` field, a list. The ``pos`` field is updated to be the next character after the expression. """ + # Append comma (ARG_SEP) to the list of special characters only when + # parsing function arguments. + extra_special_chars = () + special_char_re = self.special_char_re + if self.in_argument: + extra_special_chars = (ARG_SEP,) + special_char_re = re.compile( + r'[%s]|\Z' % u''.join( + re.escape(c) for c in + self.special_chars + extra_special_chars + ) + ) + text_parts = [] while self.pos < len(self.string): char = self.string[self.pos] - if char not in self.special_chars: + if char not in self.special_chars + extra_special_chars: # A non-special character. Skip to the next special # character, treating the interstice as literal text. next_pos = ( - self.special_char_re.search( + special_char_re.search( self.string[self.pos:]).start() + self.pos ) text_parts.append(self.string[self.pos:next_pos]) @@ -320,14 +369,14 @@ class Parser(object): # The last character can never begin a structure, so we # just interpret it as a literal character (unless it # terminates the expression, as with , and }). - if char not in (GROUP_CLOSE, ARG_SEP): + if char not in self.terminator_chars + extra_special_chars: text_parts.append(char) self.pos += 1 break next_char = self.string[self.pos + 1] - if char == ESCAPE_CHAR and next_char in \ - (SYMBOL_DELIM, FUNC_DELIM, GROUP_CLOSE, ARG_SEP): + if char == ESCAPE_CHAR and next_char in (self.escapable_chars + + extra_special_chars): # An escaped special character ($$, $}, etc.). Note that # ${ is not an escape sequence: this is ambiguous with # the start of a symbol and it's not necessary (just @@ -347,7 +396,7 @@ class Parser(object): elif char == FUNC_DELIM: # Parse a function call. self.parse_call() - elif char in (GROUP_CLOSE, ARG_SEP): + elif char in self.terminator_chars + extra_special_chars: # Template terminated. break elif char == GROUP_OPEN: @@ -455,7 +504,7 @@ class Parser(object): expressions = [] while self.pos < len(self.string): - subparser = Parser(self.string[self.pos:]) + subparser = Parser(self.string[self.pos:], in_argument=True) subparser.parse_expression() # Extract and advance past the parsed expression. @@ -524,8 +573,9 @@ class Template(object): """ try: res = self.compiled(values, functions) - except: # Handle any exceptions thrown by compiled version. + except Exception: # Handle any exceptions thrown by compiled version. res = self.interpret(values, functions) + return res def translate(self): @@ -557,11 +607,11 @@ class Template(object): # Performance tests. -if __name__ == b'__main__': +if __name__ == '__main__': import timeit _tmpl = Template(u'foo $bar %baz{foozle $bar barzle} $bar') _vars = {'bar': 'qux'} - _funcs = {'baz': unicode.upper} + _funcs = {'baz': six.text_type.upper} interp_time = timeit.timeit('_tmpl.interpret(_vars, _funcs)', 'from __main__ import _tmpl, _vars, _funcs', number=10000) @@ -570,4 +620,4 @@ if __name__ == b'__main__': 'from __main__ import _tmpl, _vars, _funcs', number=10000) print(comp_time) - print('Speedup:', interp_time / comp_time) + print(u'Speedup:', interp_time / comp_time) diff --git a/beets/util/hidden.py b/beets/util/hidden.py new file mode 100644 index 000000000..ed97f2bfc --- /dev/null +++ b/beets/util/hidden.py @@ -0,0 +1,86 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Adrian Sampson. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Simple library to work out if a file is hidden on different platforms.""" +from __future__ import division, absolute_import, print_function + +import os +import stat +import ctypes +import sys +import beets.util + + +def _is_hidden_osx(path): + """Return whether or not a file is hidden on OS X. + + This uses os.lstat to work out if a file has the "hidden" flag. + """ + file_stat = os.lstat(beets.util.syspath(path)) + + if hasattr(file_stat, 'st_flags') and hasattr(stat, 'UF_HIDDEN'): + return bool(file_stat.st_flags & stat.UF_HIDDEN) + else: + return False + + +def _is_hidden_win(path): + """Return whether or not a file is hidden on Windows. + + This uses GetFileAttributes to work out if a file has the "hidden" flag + (FILE_ATTRIBUTE_HIDDEN). + """ + # FILE_ATTRIBUTE_HIDDEN = 2 (0x2) from GetFileAttributes documentation. + hidden_mask = 2 + + # Retrieve the attributes for the file. + attrs = ctypes.windll.kernel32.GetFileAttributesW(beets.util.syspath(path)) + + # Ensure we have valid attribues and compare them against the mask. + return attrs >= 0 and attrs & hidden_mask + + +def _is_hidden_dot(path): + """Return whether or not a file starts with a dot. + + Files starting with a dot are seen as "hidden" files on Unix-based OSes. + """ + return os.path.basename(path).startswith(b'.') + + +def is_hidden(path): + """Return whether or not a file is hidden. `path` should be a + bytestring filename. + + This method works differently depending on the platform it is called on. + + On OS X, it uses both the result of `is_hidden_osx` and `is_hidden_dot` to + work out if a file is hidden. + + On Windows, it uses the result of `is_hidden_win` to work out if a file is + hidden. + + On any other operating systems (i.e. Linux), it uses `is_hidden_dot` to + work out if a file is hidden. + """ + # Run platform specific functions depending on the platform + if sys.platform == 'darwin': + return _is_hidden_osx(path) or _is_hidden_dot(path) + elif sys.platform == 'win32': + return _is_hidden_win(path) + else: + return _is_hidden_dot(path) + +__all__ = ['is_hidden'] diff --git a/beets/util/pipeline.py b/beets/util/pipeline.py index a0bb6af38..39bc7152e 100644 --- a/beets/util/pipeline.py +++ b/beets/util/pipeline.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -31,15 +32,15 @@ To do so, pass an iterable of coroutines to the Pipeline constructor in place of any single coroutine. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function -import Queue +from six.moves import queue from threading import Thread, Lock import sys +import six -BUBBLE = b'__PIPELINE_BUBBLE__' -POISON = b'__PIPELINE_POISON__' +BUBBLE = '__PIPELINE_BUBBLE__' +POISON = '__PIPELINE_POISON__' DEFAULT_QUEUE_SIZE = 16 @@ -63,7 +64,17 @@ def _invalidate_queue(q, val=None, sync=True): q.mutex.acquire() try: - q.maxsize = 0 + # Originally, we set `maxsize` to 0 here, which is supposed to mean + # an unlimited queue size. However, there is a race condition since + # Python 3.2 when this attribute is changed while another thread is + # waiting in put()/get() due to a full/empty queue. + # Setting it to 2 is still hacky because Python does not give any + # guarantee what happens if Queue methods/attributes are overwritten + # when it is already in use. However, because of our dummy _put() + # and _get() methods, it provides a workaround to let the queue appear + # to be never empty or full. + # See issue https://github.com/beetbox/beets/issues/2078 + q.maxsize = 2 q._qsize = _qsize q._put = _put q._get = _get @@ -75,13 +86,13 @@ def _invalidate_queue(q, val=None, sync=True): q.mutex.release() -class CountedQueue(Queue.Queue): +class CountedQueue(queue.Queue): """A queue that keeps track of the number of threads that are still feeding into it. The queue is poisoned when all threads are finished with the queue. """ def __init__(self, maxsize=0): - Queue.Queue.__init__(self, maxsize) + queue.Queue.__init__(self, maxsize) self.nthreads = 0 self.poisoned = False @@ -248,7 +259,7 @@ class FirstPipelineThread(PipelineThread): # Get the value from the generator. try: - msg = self.coro.next() + msg = next(self.coro) except StopIteration: break @@ -259,7 +270,7 @@ class FirstPipelineThread(PipelineThread): return self.out_queue.put(msg) - except: + except BaseException: self.abort_all(sys.exc_info()) return @@ -281,7 +292,7 @@ class MiddlePipelineThread(PipelineThread): def run(self): try: # Prime the coroutine. - self.coro.next() + next(self.coro) while True: with self.abort_lock: @@ -307,7 +318,7 @@ class MiddlePipelineThread(PipelineThread): return self.out_queue.put(msg) - except: + except BaseException: self.abort_all(sys.exc_info()) return @@ -326,7 +337,7 @@ class LastPipelineThread(PipelineThread): def run(self): # Prime the coroutine. - self.coro.next() + next(self.coro) try: while True: @@ -346,7 +357,7 @@ class LastPipelineThread(PipelineThread): # Send to consumer. self.coro.send(msg) - except: + except BaseException: self.abort_all(sys.exc_info()) return @@ -361,7 +372,7 @@ class Pipeline(object): be at least two stages. """ if len(stages) < 2: - raise ValueError('pipeline must have at least two stages') + raise ValueError(u'pipeline must have at least two stages') self.stages = [] for stage in stages: if isinstance(stage, (list, tuple)): @@ -411,10 +422,10 @@ class Pipeline(object): try: # Using a timeout allows us to receive KeyboardInterrupt # exceptions during the join(). - while threads[-1].isAlive(): + while threads[-1].is_alive(): threads[-1].join(1) - except: + except BaseException: # Stop all the threads immediately. for thread in threads: thread.abort() @@ -431,7 +442,7 @@ class Pipeline(object): exc_info = thread.exc_info if exc_info: # Make the exception appear as it was raised originally. - raise exc_info[0], exc_info[1], exc_info[2] + six.reraise(exc_info[0], exc_info[1], exc_info[2]) def pull(self): """Yield elements from the end of the pipeline. Runs the stages @@ -444,7 +455,7 @@ class Pipeline(object): # "Prime" the coroutines. for coro in coros[1:]: - coro.next() + next(coro) # Begin the pipeline. for out in coros[0]: @@ -459,21 +470,21 @@ class Pipeline(object): yield msg # Smoke test. -if __name__ == b'__main__': +if __name__ == '__main__': import time # Test a normally-terminating pipeline both in sequence and # in parallel. def produce(): for i in range(5): - print('generating %i' % i) + print(u'generating %i' % i) time.sleep(1) yield i def work(): num = yield while True: - print('processing %i' % num) + print(u'processing %i' % num) time.sleep(2) num = yield num * 2 @@ -481,7 +492,7 @@ if __name__ == b'__main__': while True: num = yield time.sleep(1) - print('received %i' % num) + print(u'received %i' % num) ts_start = time.time() Pipeline([produce(), work(), consume()]).run_sequential() @@ -490,22 +501,22 @@ if __name__ == b'__main__': ts_par = time.time() Pipeline([produce(), (work(), work()), consume()]).run_parallel() ts_end = time.time() - print('Sequential time:', ts_seq - ts_start) - print('Parallel time:', ts_par - ts_seq) - print('Multiply-parallel time:', ts_end - ts_par) + print(u'Sequential time:', ts_seq - ts_start) + print(u'Parallel time:', ts_par - ts_seq) + print(u'Multiply-parallel time:', ts_end - ts_par) print() # Test a pipeline that raises an exception. def exc_produce(): for i in range(10): - print('generating %i' % i) + print(u'generating %i' % i) time.sleep(1) yield i def exc_work(): num = yield while True: - print('processing %i' % num) + print(u'processing %i' % num) time.sleep(3) if num == 3: raise Exception() @@ -514,6 +525,6 @@ if __name__ == b'__main__': def exc_consume(): while True: num = yield - print('received %i' % num) + print(u'received %i' % num) Pipeline([exc_produce(), exc_work(), exc_consume()]).run_parallel(1) diff --git a/beets/vfs.py b/beets/vfs.py index e3cebafb1..7f9a049ee 100644 --- a/beets/vfs.py +++ b/beets/vfs.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,8 +16,7 @@ """A simple utility for constructing filesystem-like trees from beets libraries. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from collections import namedtuple from beets import util diff --git a/beetsplug/__init__.py b/beetsplug/__init__.py index 811ee0539..febeb66f4 100644 --- a/beetsplug/__init__.py +++ b/beetsplug/__init__.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,8 +15,8 @@ """A namespace package for beets plugins.""" -# Make this a namespace package. -from __future__ import absolute_import +from __future__ import division, absolute_import, print_function +# Make this a namespace package. from pkgutil import extend_path __path__ = extend_path(__path__, __name__) diff --git a/beetsplug/absubmit.py b/beetsplug/absubmit.py new file mode 100644 index 000000000..0c288b9d8 --- /dev/null +++ b/beetsplug/absubmit.py @@ -0,0 +1,167 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Pieter Mulder. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Calculate acoustic information and submit to AcousticBrainz. +""" + +from __future__ import division, absolute_import, print_function + +import errno +import hashlib +import json +import os +import subprocess +import tempfile + +from distutils.spawn import find_executable +import requests + +from beets import plugins +from beets import util +from beets import ui + + +class ABSubmitError(Exception): + """Raised when failing to analyse file with extractor.""" + + +def call(args): + """Execute the command and return its output. + + Raise a AnalysisABSubmitError on failure. + """ + try: + return util.command_output(args) + except subprocess.CalledProcessError as e: + raise ABSubmitError( + u'{0} exited with status {1}'.format(args[0], e.returncode) + ) + + +class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): + + def __init__(self): + super(AcousticBrainzSubmitPlugin, self).__init__() + + self.config.add({'extractor': u''}) + + self.extractor = self.config['extractor'].as_str() + if self.extractor: + self.extractor = util.normpath(self.extractor) + # Expicit path to extractor + if not os.path.isfile(self.extractor): + raise ui.UserError( + u'Extractor command does not exist: {0}.'. + format(self.extractor) + ) + else: + # Implicit path to extractor, search for it in path + self.extractor = 'streaming_extractor_music' + try: + call([self.extractor]) + except OSError: + raise ui.UserError( + u'No extractor command found: please install the ' + u'extractor binary from http://acousticbrainz.org/download' + ) + except ABSubmitError: + # Extractor found, will exit with an error if not called with + # the correct amount of arguments. + pass + + # Get the executable location on the system, which we need + # to calculate the SHA-1 hash. + self.extractor = find_executable(self.extractor) + + # Calculate extractor hash. + self.extractor_sha = hashlib.sha1() + with open(self.extractor, 'rb') as extractor: + self.extractor_sha.update(extractor.read()) + self.extractor_sha = self.extractor_sha.hexdigest() + + base_url = 'https://acousticbrainz.org/api/v1/{mbid}/low-level' + + def commands(self): + cmd = ui.Subcommand( + 'absubmit', + help=u'calculate and submit AcousticBrainz analysis' + ) + cmd.func = self.command + return [cmd] + + def command(self, lib, opts, args): + # Get items from arguments + items = lib.items(ui.decargs(args)) + for item in items: + analysis = self._get_analysis(item) + if analysis: + self._submit_data(item, analysis) + + def _get_analysis(self, item): + mbid = item['mb_trackid'] + # If file has no mbid skip it. + if not mbid: + self._log.info(u'Not analysing {}, missing ' + u'musicbrainz track id.', item) + return None + + # Temporary file to save extractor output to, extractor only works + # if an output file is given. Here we use a temporary file to copy + # the data into a python object and then remove the file from the + # system. + tmp_file, filename = tempfile.mkstemp(suffix='.json') + try: + # Close the file, so the extractor can overwrite it. + os.close(tmp_file) + try: + call([self.extractor, util.syspath(item.path), filename]) + except ABSubmitError as e: + self._log.warning( + u'Failed to analyse {item} for AcousticBrainz: {error}', + item=item, error=e + ) + return None + with open(filename, 'rb') as tmp_file: + analysis = json.load(tmp_file) + # Add the hash to the output. + analysis['metadata']['version']['essentia_build_sha'] = \ + self.extractor_sha + return analysis + finally: + try: + os.remove(filename) + except OSError as e: + # ENOENT means file does not exist, just ignore this error. + if e.errno != errno.ENOENT: + raise + + def _submit_data(self, item, data): + mbid = item['mb_trackid'] + headers = {'Content-Type': 'application/json'} + response = requests.post(self.base_url.format(mbid=mbid), + json=data, headers=headers) + # Test that request was successful and raise an error on failure. + if response.status_code != 200: + try: + message = response.json()['message'] + except (ValueError, KeyError) as e: + message = u'unable to get error message: {}'.format(e) + self._log.error( + u'Failed to submit AcousticBrainz analysis of {item}: ' + u'{message}).', item=item, message=message + ) + else: + self._log.debug(u'Successfully submitted AcousticBrainz analysis ' + u'for {}.', item) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py new file mode 100644 index 000000000..f4960c301 --- /dev/null +++ b/beetsplug/acousticbrainz.py @@ -0,0 +1,305 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2015-2016, Ohm Patel. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Fetch various AcousticBrainz metadata using MBID. +""" +from __future__ import division, absolute_import, print_function + +import requests + +from collections import defaultdict +from beets import plugins, ui + +ACOUSTIC_BASE = "https://acousticbrainz.org/" +LEVELS = ["/low-level", "/high-level"] +ABSCHEME = { + 'highlevel': { + 'danceability': { + 'all': { + 'danceable': 'danceable' + } + }, + 'gender': { + 'value': 'gender' + }, + 'genre_rosamerica': { + 'value': 'genre_rosamerica' + }, + 'mood_acoustic': { + 'all': { + 'acoustic': 'mood_acoustic' + } + }, + 'mood_aggressive': { + 'all': { + 'aggressive': 'mood_aggressive' + } + }, + 'mood_electronic': { + 'all': { + 'electronic': 'mood_electronic' + } + }, + 'mood_happy': { + 'all': { + 'happy': 'mood_happy' + } + }, + 'mood_party': { + 'all': { + 'party': 'mood_party' + } + }, + 'mood_relaxed': { + 'all': { + 'relaxed': 'mood_relaxed' + } + }, + 'mood_sad': { + 'all': { + 'sad': 'mood_sad' + } + }, + 'ismir04_rhythm': { + 'value': 'rhythm' + }, + 'tonal_atonal': { + 'all': { + 'tonal': 'tonal' + } + }, + 'voice_instrumental': { + 'value': 'voice_instrumental' + }, + }, + 'lowlevel': { + 'average_loudness': 'average_loudness' + }, + 'rhythm': { + 'bpm': 'bpm' + }, + 'tonal': { + 'chords_changes_rate': 'chords_changes_rate', + 'chords_key': 'chords_key', + 'chords_number_rate': 'chords_number_rate', + 'chords_scale': 'chords_scale', + 'key_key': ('initial_key', 0), + 'key_scale': ('initial_key', 1), + 'key_strength': 'key_strength' + + } +} + + +class AcousticPlugin(plugins.BeetsPlugin): + def __init__(self): + super(AcousticPlugin, self).__init__() + + self.config.add({ + 'auto': True, + 'force': False, + 'tags': [] + }) + + if self.config['auto']: + self.register_listener('import_task_files', + self.import_task_files) + + def commands(self): + cmd = ui.Subcommand('acousticbrainz', + help=u"fetch metadata from AcousticBrainz") + cmd.parser.add_option( + u'-f', u'--force', dest='force_refetch', + action='store_true', default=False, + help=u're-download data when already present' + ) + + def func(lib, opts, args): + items = lib.items(ui.decargs(args)) + self._fetch_info(items, ui.should_write(), + opts.force_refetch or self.config['force']) + + cmd.func = func + return [cmd] + + def import_task_files(self, session, task): + """Function is called upon beet import. + """ + self._fetch_info(task.imported_items(), False, True) + + def _get_data(self, mbid): + data = {} + for url in _generate_urls(mbid): + self._log.debug(u'fetching URL: {}', url) + + try: + res = requests.get(url) + except requests.RequestException as exc: + self._log.info(u'request error: {}', exc) + return {} + + if res.status_code == 404: + self._log.info(u'recording ID {} not found', mbid) + return {} + + try: + data.update(res.json()) + except ValueError: + self._log.debug(u'Invalid Response: {}', res.text) + return {} + + return data + + def _fetch_info(self, items, write, force): + """Fetch additional information from AcousticBrainz for the `item`s. + """ + tags = self.config['tags'].as_str_seq() + for item in items: + # If we're not forcing re-downloading for all tracks, check + # whether the data is already present. We use one + # representative field name to check for previously fetched + # data. + if not force: + mood_str = item.get('mood_acoustic', u'') + if mood_str: + self._log.info(u'data already present for: {}', item) + continue + + # We can only fetch data for tracks with MBIDs. + if not item.mb_trackid: + continue + + self._log.info(u'getting data for: {}', item) + data = self._get_data(item.mb_trackid) + if data: + for attr, val in self._map_data_to_scheme(data, ABSCHEME): + if not tags or attr in tags: + self._log.debug(u'attribute {} of {} set to {}', + attr, + item, + val) + setattr(item, attr, val) + else: + self._log.debug(u'skipping attribute {} of {}' + u' (value {}) due to config', + attr, + item, + val) + item.store() + if write: + item.try_write() + + def _map_data_to_scheme(self, data, scheme): + """Given `data` as a structure of nested dictionaries, and `scheme` as a + structure of nested dictionaries , `yield` tuples `(attr, val)` where + `attr` and `val` are corresponding leaf nodes in `scheme` and `data`. + + As its name indicates, `scheme` defines how the data is structured, + so this function tries to find leaf nodes in `data` that correspond + to the leafs nodes of `scheme`, and not the other way around. + Leaf nodes of `data` that do not exist in the `scheme` do not matter. + If a leaf node of `scheme` is not present in `data`, + no value is yielded for that attribute and a simple warning is issued. + + Finally, to account for attributes of which the value is split between + several leaf nodes in `data`, leaf nodes of `scheme` can be tuples + `(attr, order)` where `attr` is the attribute to which the leaf node + belongs, and `order` is the place at which it should appear in the + value. The different `value`s belonging to the same `attr` are simply + joined with `' '`. This is hardcoded and not very flexible, but it gets + the job done. + + For example: + + >>> scheme = { + 'key1': 'attribute', + 'key group': { + 'subkey1': 'subattribute', + 'subkey2': ('composite attribute', 0) + }, + 'key2': ('composite attribute', 1) + } + >>> data = { + 'key1': 'value', + 'key group': { + 'subkey1': 'subvalue', + 'subkey2': 'part 1 of composite attr' + }, + 'key2': 'part 2' + } + >>> print(list(_map_data_to_scheme(data, scheme))) + [('subattribute', 'subvalue'), + ('attribute', 'value'), + ('composite attribute', 'part 1 of composite attr part 2')] + """ + # First, we traverse `scheme` and `data`, `yield`ing all the non + # composites attributes straight away and populating the dictionary + # `composites` with the composite attributes. + + # When we are finished traversing `scheme`, `composites` should + # map each composite attribute to an ordered list of the values + # belonging to the attribute, for example: + # `composites = {'initial_key': ['B', 'minor']}`. + + # The recursive traversal. + composites = defaultdict(list) + for attr, val in self._data_to_scheme_child(data, + scheme, + composites): + yield attr, val + + # When composites has been populated, yield the composite attributes + # by joining their parts. + for composite_attr, value_parts in composites.items(): + yield composite_attr, ' '.join(value_parts) + + def _data_to_scheme_child(self, subdata, subscheme, composites): + """The recursive business logic of :meth:`_map_data_to_scheme`: + Traverse two structures of nested dictionaries in parallel and `yield` + tuples of corresponding leaf nodes. + + If a leaf node belongs to a composite attribute (is a `tuple`), + populate `composites` rather than yielding straight away. + All the child functions for a single traversal share the same + `composites` instance, which is passed along. + """ + for k, v in subscheme.items(): + if k in subdata: + if type(v) == dict: + for attr, val in self._data_to_scheme_child(subdata[k], + v, + composites): + yield attr, val + elif type(v) == tuple: + composite_attribute, part_number = v + attribute_parts = composites[composite_attribute] + # Parts are not guaranteed to be inserted in order + while len(attribute_parts) <= part_number: + attribute_parts.append('') + attribute_parts[part_number] = subdata[k] + else: + yield v, subdata[k] + else: + self._log.warning(u'Acousticbrainz did not provide info' + u'about {}', k) + self._log.debug(u'Data {} could not be mapped to scheme {} ' + u'because key {} was not found', subdata, v, k) + + +def _generate_urls(mbid): + """Generates AcousticBrainz end point urls for given `mbid`. + """ + for level in LEVELS: + yield ACOUSTIC_BASE + mbid + level diff --git a/beetsplug/badfiles.py b/beetsplug/badfiles.py index d27208724..62c6d8af5 100644 --- a/beetsplug/badfiles.py +++ b/beetsplug/badfiles.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, François-Xavier Thomas. +# Copyright 2016, François-Xavier Thomas. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,8 +16,7 @@ """Use command-line tools to check for audio file corruption. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets.ui import Subcommand @@ -27,11 +27,29 @@ import shlex import os import errno import sys +import six + + +class CheckerCommandException(Exception): + """Raised when running a checker failed. + + Attributes: + checker: Checker command name. + path: Path to the file being validated. + errno: Error number from the checker execution error. + msg: Message from the checker execution error. + """ + + def __init__(self, cmd, oserror): + self.checker = cmd[0] + self.path = cmd[-1] + self.errno = oserror.errno + self.msg = str(oserror) class BadFiles(BeetsPlugin): def run_command(self, cmd): - self._log.debug("running command: {}", + self._log.debug(u"running command: {}", displayable_path(list2cmdline(cmd))) try: output = check_output(cmd, stderr=STDOUT) @@ -42,11 +60,7 @@ class BadFiles(BeetsPlugin): errors = 1 status = e.returncode except OSError as e: - if e.errno == errno.ENOENT: - ui.print_("command not found: {}".format(cmd[0])) - sys.exit(1) - else: - raise + raise CheckerCommandException(cmd, e) output = output.decode(sys.getfilesystemencoding()) return status, errors, [line for line in output.split("\n") if line] @@ -86,35 +100,53 @@ class BadFiles(BeetsPlugin): # First, check whether the path exists. If not, the user # should probably run `beet update` to cleanup your library. dpath = displayable_path(item.path) - self._log.debug("checking path: {}", dpath) + self._log.debug(u"checking path: {}", dpath) if not os.path.exists(item.path): - ui.print_("{}: file does not exist".format( + ui.print_(u"{}: file does not exist".format( ui.colorize('text_error', dpath))) # Run the checker against the file if one is found - ext = os.path.splitext(item.path)[1][1:] + ext = os.path.splitext(item.path)[1][1:].decode('utf8', 'ignore') checker = self.get_checker(ext) if not checker: + self._log.error(u"no checker specified in the config for {}", + ext) continue path = item.path - if not isinstance(path, unicode): + if not isinstance(path, six.text_type): path = item.path.decode(sys.getfilesystemencoding()) - status, errors, output = checker(path) + try: + status, errors, output = checker(path) + except CheckerCommandException as e: + if e.errno == errno.ENOENT: + self._log.error( + u"command not found: {} when validating file: {}", + e.checker, + e.path + ) + else: + self._log.error(u"error invoking {}: {}", e.checker, e.msg) + continue if status > 0: - ui.print_("{}: checker exited withs status {}" + ui.print_(u"{}: checker exited with status {}" .format(ui.colorize('text_error', dpath), status)) for line in output: - ui.print_(" {}".format(displayable_path(line))) + ui.print_(u" {}".format(displayable_path(line))) elif errors > 0: - ui.print_("{}: checker found {} errors or warnings" + ui.print_(u"{}: checker found {} errors or warnings" .format(ui.colorize('text_warning', dpath), errors)) for line in output: - ui.print_(" {}".format(displayable_path(line))) - else: - ui.print_("{}: ok".format(ui.colorize('text_success', dpath))) + ui.print_(u" {}".format(displayable_path(line))) + elif opts.verbose: + ui.print_(u"{}: ok".format(ui.colorize('text_success', dpath))) def commands(self): bad_command = Subcommand('bad', - help='check for corrupt or missing files') + help=u'check for corrupt or missing files') + bad_command.parser.add_option( + u'-v', u'--verbose', + action='store_true', default=False, dest='verbose', + help=u'view results for both the bad and uncorrupted files' + ) bad_command.func = self.check_bad return [bad_command] diff --git a/beetsplug/beatport.py b/beetsplug/beatport.py new file mode 100644 index 000000000..fc412d998 --- /dev/null +++ b/beetsplug/beatport.py @@ -0,0 +1,461 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Adrian Sampson. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Adds Beatport release and track search support to the autotagger +""" +from __future__ import division, absolute_import, print_function + +import json +import re +import six +from datetime import datetime, timedelta + +from requests_oauthlib import OAuth1Session +from requests_oauthlib.oauth1_session import (TokenRequestDenied, TokenMissing, + VerifierMissing) + +import beets +import beets.ui +from beets.autotag.hooks import AlbumInfo, TrackInfo, Distance +from beets.plugins import BeetsPlugin +from beets.util import confit + + +AUTH_ERRORS = (TokenRequestDenied, TokenMissing, VerifierMissing) +USER_AGENT = u'beets/{0} +http://beets.io/'.format(beets.__version__) + + +class BeatportAPIError(Exception): + pass + + +class BeatportObject(object): + def __init__(self, data): + self.beatport_id = data['id'] + self.name = six.text_type(data['name']) + if 'releaseDate' in data: + self.release_date = datetime.strptime(data['releaseDate'], + '%Y-%m-%d') + if 'artists' in data: + self.artists = [(x['id'], six.text_type(x['name'])) + for x in data['artists']] + if 'genres' in data: + self.genres = [six.text_type(x['name']) + for x in data['genres']] + + +class BeatportClient(object): + _api_base = 'https://oauth-api.beatport.com' + + def __init__(self, c_key, c_secret, auth_key=None, auth_secret=None): + """ Initiate the client with OAuth information. + + For the initial authentication with the backend `auth_key` and + `auth_secret` can be `None`. Use `get_authorize_url` and + `get_access_token` to obtain them for subsequent uses of the API. + + :param c_key: OAuth1 client key + :param c_secret: OAuth1 client secret + :param auth_key: OAuth1 resource owner key + :param auth_secret: OAuth1 resource owner secret + """ + self.api = OAuth1Session( + client_key=c_key, client_secret=c_secret, + resource_owner_key=auth_key, + resource_owner_secret=auth_secret, + callback_uri='oob') + self.api.headers = {'User-Agent': USER_AGENT} + + def get_authorize_url(self): + """ Generate the URL for the user to authorize the application. + + Retrieves a request token from the Beatport API and returns the + corresponding authorization URL on their end that the user has + to visit. + + This is the first step of the initial authorization process with the + API. Once the user has visited the URL, call + :py:method:`get_access_token` with the displayed data to complete + the process. + + :returns: Authorization URL for the user to visit + :rtype: unicode + """ + self.api.fetch_request_token( + self._make_url('/identity/1/oauth/request-token')) + return self.api.authorization_url( + self._make_url('/identity/1/oauth/authorize')) + + def get_access_token(self, auth_data): + """ Obtain the final access token and secret for the API. + + :param auth_data: URL-encoded authorization data as displayed at + the authorization url (obtained via + :py:meth:`get_authorize_url`) after signing in + :type auth_data: unicode + :returns: OAuth resource owner key and secret + :rtype: (unicode, unicode) tuple + """ + self.api.parse_authorization_response( + "http://beets.io/auth?" + auth_data) + access_data = self.api.fetch_access_token( + self._make_url('/identity/1/oauth/access-token')) + return access_data['oauth_token'], access_data['oauth_token_secret'] + + def search(self, query, release_type='release', details=True): + """ Perform a search of the Beatport catalogue. + + :param query: Query string + :param release_type: Type of releases to search for, can be + 'release' or 'track' + :param details: Retrieve additional information about the + search results. Currently this will fetch + the tracklist for releases and do nothing for + tracks + :returns: Search results + :rtype: generator that yields + py:class:`BeatportRelease` or + :py:class:`BeatportTrack` + """ + response = self._get('catalog/3/search', + query=query, perPage=5, + facets=['fieldType:{0}'.format(release_type)]) + for item in response: + if release_type == 'release': + if details: + release = self.get_release(item['id']) + else: + release = BeatportRelease(item) + yield release + elif release_type == 'track': + yield BeatportTrack(item) + + def get_release(self, beatport_id): + """ Get information about a single release. + + :param beatport_id: Beatport ID of the release + :returns: The matching release + :rtype: :py:class:`BeatportRelease` + """ + response = self._get('/catalog/3/releases', id=beatport_id) + release = BeatportRelease(response[0]) + release.tracks = self.get_release_tracks(beatport_id) + return release + + def get_release_tracks(self, beatport_id): + """ Get all tracks for a given release. + + :param beatport_id: Beatport ID of the release + :returns: Tracks in the matching release + :rtype: list of :py:class:`BeatportTrack` + """ + response = self._get('/catalog/3/tracks', releaseId=beatport_id, + perPage=100) + return [BeatportTrack(t) for t in response] + + def get_track(self, beatport_id): + """ Get information about a single track. + + :param beatport_id: Beatport ID of the track + :returns: The matching track + :rtype: :py:class:`BeatportTrack` + """ + response = self._get('/catalog/3/tracks', id=beatport_id) + return BeatportTrack(response[0]) + + def _make_url(self, endpoint): + """ Get complete URL for a given API endpoint. """ + if not endpoint.startswith('/'): + endpoint = '/' + endpoint + return self._api_base + endpoint + + def _get(self, endpoint, **kwargs): + """ Perform a GET request on a given API endpoint. + + Automatically extracts result data from the response and converts HTTP + exceptions into :py:class:`BeatportAPIError` objects. + """ + try: + response = self.api.get(self._make_url(endpoint), params=kwargs) + except Exception as e: + raise BeatportAPIError("Error connecting to Beatport API: {}" + .format(e.message)) + if not response: + raise BeatportAPIError( + "Error {0.status_code} for '{0.request.path_url}" + .format(response)) + return response.json()['results'] + + +@six.python_2_unicode_compatible +class BeatportRelease(BeatportObject): + def __str__(self): + if len(self.artists) < 4: + artist_str = ", ".join(x[1] for x in self.artists) + else: + artist_str = "Various Artists" + return u"".format( + artist_str, + self.name, + self.catalog_number, + ) + + def __repr__(self): + return six.text_type(self).encode('utf-8') + + def __init__(self, data): + BeatportObject.__init__(self, data) + if 'catalogNumber' in data: + self.catalog_number = data['catalogNumber'] + if 'label' in data: + self.label_name = data['label']['name'] + if 'category' in data: + self.category = data['category'] + if 'slug' in data: + self.url = "http://beatport.com/release/{0}/{1}".format( + data['slug'], data['id']) + + +@six.python_2_unicode_compatible +class BeatportTrack(BeatportObject): + def __str__(self): + artist_str = ", ".join(x[1] for x in self.artists) + return (u"" + .format(artist_str, self.name, self.mix_name)) + + def __repr__(self): + return six.text_type(self).encode('utf-8') + + def __init__(self, data): + BeatportObject.__init__(self, data) + if 'title' in data: + self.title = six.text_type(data['title']) + if 'mixName' in data: + self.mix_name = six.text_type(data['mixName']) + self.length = timedelta(milliseconds=data.get('lengthMs', 0) or 0) + if not self.length: + try: + min, sec = data.get('length', '0:0').split(':') + self.length = timedelta(minutes=int(min), seconds=int(sec)) + except ValueError: + pass + if 'slug' in data: + self.url = "http://beatport.com/track/{0}/{1}".format(data['slug'], + data['id']) + self.track_number = data.get('trackNumber') + + +class BeatportPlugin(BeetsPlugin): + def __init__(self): + super(BeatportPlugin, self).__init__() + self.config.add({ + 'apikey': '57713c3906af6f5def151b33601389176b37b429', + 'apisecret': 'b3fe08c93c80aefd749fe871a16cd2bb32e2b954', + 'tokenfile': 'beatport_token.json', + 'source_weight': 0.5, + }) + self.config['apikey'].redact = True + self.config['apisecret'].redact = True + self.client = None + self.register_listener('import_begin', self.setup) + + def setup(self, session=None): + c_key = self.config['apikey'].as_str() + c_secret = self.config['apisecret'].as_str() + + # Get the OAuth token from a file or log in. + try: + with open(self._tokenfile()) as f: + tokendata = json.load(f) + except IOError: + # No token yet. Generate one. + token, secret = self.authenticate(c_key, c_secret) + else: + token = tokendata['token'] + secret = tokendata['secret'] + + self.client = BeatportClient(c_key, c_secret, token, secret) + + def authenticate(self, c_key, c_secret): + # Get the link for the OAuth page. + auth_client = BeatportClient(c_key, c_secret) + try: + url = auth_client.get_authorize_url() + except AUTH_ERRORS as e: + self._log.debug(u'authentication error: {0}', e) + raise beets.ui.UserError(u'communication with Beatport failed') + + beets.ui.print_(u"To authenticate with Beatport, visit:") + beets.ui.print_(url) + + # Ask for the verifier data and validate it. + data = beets.ui.input_(u"Enter the string displayed in your browser:") + try: + token, secret = auth_client.get_access_token(data) + except AUTH_ERRORS as e: + self._log.debug(u'authentication error: {0}', e) + raise beets.ui.UserError(u'Beatport token request failed') + + # Save the token for later use. + self._log.debug(u'Beatport token {0}, secret {1}', token, secret) + with open(self._tokenfile(), 'w') as f: + json.dump({'token': token, 'secret': secret}, f) + + return token, secret + + def _tokenfile(self): + """Get the path to the JSON file for storing the OAuth token. + """ + return self.config['tokenfile'].get(confit.Filename(in_app_dir=True)) + + def album_distance(self, items, album_info, mapping): + """Returns the beatport source weight and the maximum source weight + for albums. + """ + dist = Distance() + if album_info.data_source == 'Beatport': + dist.add('source', self.config['source_weight'].as_number()) + return dist + + def track_distance(self, item, track_info): + """Returns the beatport source weight and the maximum source weight + for individual tracks. + """ + dist = Distance() + if track_info.data_source == 'Beatport': + dist.add('source', self.config['source_weight'].as_number()) + return dist + + def candidates(self, items, artist, release, va_likely): + """Returns a list of AlbumInfo objects for beatport search results + matching release and artist (if not various). + """ + if va_likely: + query = release + else: + query = '%s %s' % (artist, release) + try: + return self._get_releases(query) + except BeatportAPIError as e: + self._log.debug(u'API Error: {0} (query: {1})', e, query) + return [] + + def item_candidates(self, item, artist, title): + """Returns a list of TrackInfo objects for beatport search results + matching title and artist. + """ + query = '%s %s' % (artist, title) + try: + return self._get_tracks(query) + except BeatportAPIError as e: + self._log.debug(u'API Error: {0} (query: {1})', e, query) + return [] + + def album_for_id(self, release_id): + """Fetches a release by its Beatport ID and returns an AlbumInfo object + or None if the release is not found. + """ + self._log.debug(u'Searching for release {0}', release_id) + match = re.search(r'(^|beatport\.com/release/.+/)(\d+)$', release_id) + if not match: + return None + release = self.client.get_release(match.group(2)) + album = self._get_album_info(release) + return album + + def track_for_id(self, track_id): + """Fetches a track by its Beatport ID and returns a TrackInfo object + or None if the track is not found. + """ + self._log.debug(u'Searching for track {0}', track_id) + match = re.search(r'(^|beatport\.com/track/.+/)(\d+)$', track_id) + if not match: + return None + bp_track = self.client.get_track(match.group(2)) + track = self._get_track_info(bp_track) + return track + + def _get_releases(self, query): + """Returns a list of AlbumInfo objects for a beatport search query. + """ + # Strip non-word characters from query. Things like "!" and "-" can + # cause a query to return no results, even if they match the artist or + # album title. Use `re.UNICODE` flag to avoid stripping non-english + # word characters. + query = re.sub(r'\W+', ' ', query, flags=re.UNICODE) + # Strip medium information from query, Things like "CD1" and "disk 1" + # can also negate an otherwise positive result. + query = re.sub(r'\b(CD|disc)\s*\d+', '', query, flags=re.I) + albums = [self._get_album_info(x) + for x in self.client.search(query)] + return albums + + def _get_album_info(self, release): + """Returns an AlbumInfo object for a Beatport Release object. + """ + va = len(release.artists) > 3 + artist, artist_id = self._get_artist(release.artists) + if va: + artist = u"Various Artists" + tracks = [self._get_track_info(x) for x in release.tracks] + + return AlbumInfo(album=release.name, album_id=release.beatport_id, + artist=artist, artist_id=artist_id, tracks=tracks, + albumtype=release.category, va=va, + year=release.release_date.year, + month=release.release_date.month, + day=release.release_date.day, + label=release.label_name, + catalognum=release.catalog_number, media=u'Digital', + data_source=u'Beatport', data_url=release.url) + + def _get_track_info(self, track): + """Returns a TrackInfo object for a Beatport Track object. + """ + title = track.name + if track.mix_name != u"Original Mix": + title += u" ({0})".format(track.mix_name) + artist, artist_id = self._get_artist(track.artists) + length = track.length.total_seconds() + return TrackInfo(title=title, track_id=track.beatport_id, + artist=artist, artist_id=artist_id, + length=length, index=track.track_number, + medium_index=track.track_number, + data_source=u'Beatport', data_url=track.url) + + def _get_artist(self, artists): + """Returns an artist string (all artists) and an artist_id (the main + artist) for a list of Beatport release or track artists. + """ + artist_id = None + bits = [] + for artist in artists: + if not artist_id: + artist_id = artist[0] + name = artist[1] + # Strip disambiguation number. + name = re.sub(r' \(\d+\)$', '', name) + # Move articles to the front. + name = re.sub(r'^(.*?), (a|an|the)$', r'\2 \1', name, flags=re.I) + bits.append(name) + artist = ', '.join(bits).replace(' ,', ',') or None + return artist, artist_id + + def _get_tracks(self, query): + """Returns a list of TrackInfo objects for a Beatport query. + """ + bp_tracks = self.client.search(query, release_type='track') + tracks = [self._get_track_info(x) for x in bp_tracks] + return tracks diff --git a/beetsplug/bench.py b/beetsplug/bench.py index ebb9f981f..41f575cd2 100644 --- a/beetsplug/bench.py +++ b/beetsplug/bench.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -74,7 +75,7 @@ def match_benchmark(lib, prof, query=None, album_id=None): # Run the match. def _run_match(): - match.tag_album(items, search_id=album_id) + match.tag_album(items, search_ids=[album_id]) if prof: cProfile.runctx('_run_match()', {}, {'_run_match': _run_match}, 'match.prof') diff --git a/beetsplug/bpd/__init__.py b/beetsplug/bpd/__init__.py index ef02574fa..1049f0c76 100644 --- a/beetsplug/bpd/__init__.py +++ b/beetsplug/bpd/__init__.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -17,8 +18,7 @@ Beets library. Attempts to implement a compatible protocol to allow use of the wide range of MPD clients. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import re from string import Template @@ -35,17 +35,18 @@ from beets.util import bluelet from beets.library import Item from beets import dbcore from beets.mediafile import MediaFile +import six PROTOCOL_VERSION = '0.13.0' BUFSIZE = 1024 -HELLO = 'OK MPD %s' % PROTOCOL_VERSION -CLIST_BEGIN = 'command_list_begin' -CLIST_VERBOSE_BEGIN = 'command_list_ok_begin' -CLIST_END = 'command_list_end' -RESP_OK = 'OK' -RESP_CLIST_VERBOSE = 'list_OK' -RESP_ERR = 'ACK' +HELLO = u'OK MPD %s' % PROTOCOL_VERSION +CLIST_BEGIN = u'command_list_begin' +CLIST_VERBOSE_BEGIN = u'command_list_ok_begin' +CLIST_END = u'command_list_end' +RESP_OK = u'OK' +RESP_CLIST_VERBOSE = u'list_OK' +RESP_ERR = u'ACK' NEWLINE = u"\n" @@ -123,9 +124,9 @@ def make_bpd_error(s_code, s_message): pass return NewBPDError -ArgumentTypeError = make_bpd_error(ERROR_ARG, 'invalid type for argument') -ArgumentIndexError = make_bpd_error(ERROR_ARG, 'argument out of range') -ArgumentNotFoundError = make_bpd_error(ERROR_NO_EXIST, 'argument not found') +ArgumentTypeError = make_bpd_error(ERROR_ARG, u'invalid type for argument') +ArgumentIndexError = make_bpd_error(ERROR_ARG, u'argument out of range') +ArgumentNotFoundError = make_bpd_error(ERROR_NO_EXIST, u'argument not found') def cast_arg(t, val): @@ -268,7 +269,7 @@ class BaseServer(object): conn.authenticated = True else: conn.authenticated = False - raise BPDError(ERROR_PASSWORD, 'incorrect password') + raise BPDError(ERROR_PASSWORD, u'incorrect password') def cmd_commands(self, conn): """Lists the commands available to the user.""" @@ -305,12 +306,12 @@ class BaseServer(object): playlist, playlistlength, and xfade. """ yield ( - u'volume: ' + unicode(self.volume), - u'repeat: ' + unicode(int(self.repeat)), - u'random: ' + unicode(int(self.random)), - u'playlist: ' + unicode(self.playlist_version), - u'playlistlength: ' + unicode(len(self.playlist)), - u'xfade: ' + unicode(self.crossfade), + u'volume: ' + six.text_type(self.volume), + u'repeat: ' + six.text_type(int(self.repeat)), + u'random: ' + six.text_type(int(self.random)), + u'playlist: ' + six.text_type(self.playlist_version), + u'playlistlength: ' + six.text_type(len(self.playlist)), + u'xfade: ' + six.text_type(self.crossfade), ) if self.current_index == -1: @@ -323,8 +324,8 @@ class BaseServer(object): if self.current_index != -1: # i.e., paused or playing current_id = self._item_id(self.playlist[self.current_index]) - yield u'song: ' + unicode(self.current_index) - yield u'songid: ' + unicode(current_id) + yield u'song: ' + six.text_type(self.current_index) + yield u'songid: ' + six.text_type(current_id) if self.error: yield u'error: ' + self.error @@ -468,8 +469,8 @@ class BaseServer(object): Also a dummy implementation. """ for idx, track in enumerate(self.playlist): - yield u'cpos: ' + unicode(idx) - yield u'Id: ' + unicode(track.id) + yield u'cpos: ' + six.text_type(idx) + yield u'Id: ' + six.text_type(track.id) def cmd_currentsong(self, conn): """Sends information about the currently-playing song. @@ -569,12 +570,12 @@ class Connection(object): added after every string. Returns a Bluelet event that sends the data. """ - if isinstance(lines, basestring): + if isinstance(lines, six.string_types): lines = [lines] out = NEWLINE.join(lines) + NEWLINE log.debug('{}', out[:-1]) # Don't log trailing newline. - if isinstance(out, unicode): - out = out.encode('utf8') + if isinstance(out, six.text_type): + out = out.encode('utf-8') return self.sock.sendall(out) def do_command(self, command): @@ -603,7 +604,8 @@ class Connection(object): line = line.strip() if not line: break - log.debug('{}', line) + line = line.decode('utf8') # MPD protocol uses UTF-8. + log.debug(u'{}', line) if clist is not None: # Command list already opened. @@ -639,8 +641,8 @@ class Command(object): """A command issued by the client for processing by the server. """ - command_re = re.compile(br'^([^ \t]+)[ \t]*') - arg_re = re.compile(br'"((?:\\"|[^"])+)"|([^ \t"]+)') + command_re = re.compile(r'^([^ \t]+)[ \t]*') + arg_re = re.compile(r'"((?:\\"|[^"])+)"|([^ \t"]+)') def __init__(self, s): """Creates a new `Command` from the given string, `s`, parsing @@ -655,11 +657,10 @@ class Command(object): if match[0]: # Quoted argument. arg = match[0] - arg = arg.replace(b'\\"', b'"').replace(b'\\\\', b'\\') + arg = arg.replace(u'\\"', u'"').replace(u'\\\\', u'\\') else: # Unquoted argument. arg = match[1] - arg = arg.decode('utf8') self.args.append(arg) def run(self, conn): @@ -771,28 +772,28 @@ class Server(BaseServer): def _item_info(self, item): info_lines = [ u'file: ' + item.destination(fragment=True), - u'Time: ' + unicode(int(item.length)), + u'Time: ' + six.text_type(int(item.length)), u'Title: ' + item.title, u'Artist: ' + item.artist, u'Album: ' + item.album, u'Genre: ' + item.genre, ] - track = unicode(item.track) + track = six.text_type(item.track) if item.tracktotal: - track += u'/' + unicode(item.tracktotal) + track += u'/' + six.text_type(item.tracktotal) info_lines.append(u'Track: ' + track) - info_lines.append(u'Date: ' + unicode(item.year)) + info_lines.append(u'Date: ' + six.text_type(item.year)) try: pos = self._id_to_index(item.id) - info_lines.append(u'Pos: ' + unicode(pos)) + info_lines.append(u'Pos: ' + six.text_type(pos)) except ArgumentNotFoundError: # Don't include position if not in playlist. pass - info_lines.append(u'Id: ' + unicode(item.id)) + info_lines.append(u'Id: ' + six.text_type(item.id)) return info_lines @@ -806,9 +807,9 @@ class Server(BaseServer): """ # Path is ignored. Also, the real MPD does this asynchronously; # this is done inline. - print('Building directory tree...') + print(u'Building directory tree...') self.tree = vfs.libtree(self.lib) - print('... done.') + print(u'... done.') self.updated_time = time.time() # Path (directory tree) browsing. @@ -847,12 +848,12 @@ class Server(BaseServer): node = self._resolve_path(path) if isinstance(node, int): # Trying to list a track. - raise BPDError(ERROR_ARG, 'this is not a directory') + raise BPDError(ERROR_ARG, u'this is not a directory') else: for name, itemid in iter(sorted(node.files.items())): item = self.lib.get_item(itemid) yield self._item_info(item) - for name, _ in iter(sorted(node.dirs.iteritems())): + for name, _ in iter(sorted(node.dirs.items())): dirpath = self._path_join(path, name) if dirpath.startswith(u"/"): # Strip leading slash (libmpc rejects this). @@ -872,12 +873,12 @@ class Server(BaseServer): yield u'file: ' + basepath else: # List a directory. Recurse into both directories and files. - for name, itemid in sorted(node.files.iteritems()): + for name, itemid in sorted(node.files.items()): newpath = self._path_join(basepath, name) # "yield from" for v in self._listall(newpath, itemid, info): yield v - for name, subdir in sorted(node.dirs.iteritems()): + for name, subdir in sorted(node.dirs.items()): newpath = self._path_join(basepath, name) yield u'directory: ' + newpath for v in self._listall(newpath, subdir, info): @@ -902,11 +903,11 @@ class Server(BaseServer): yield self.lib.get_item(node) else: # Recurse into a directory. - for name, itemid in sorted(node.files.iteritems()): + for name, itemid in sorted(node.files.items()): # "yield from" for v in self._all_items(itemid): yield v - for name, subdir in sorted(node.dirs.iteritems()): + for name, subdir in sorted(node.dirs.items()): for v in self._all_items(subdir): yield v @@ -917,7 +918,7 @@ class Server(BaseServer): for item in self._all_items(self._resolve_path(path)): self.playlist.append(item) if send_id: - yield u'Id: ' + unicode(item.id) + yield u'Id: ' + six.text_type(item.id) self.playlist_version += 1 def cmd_add(self, conn, path): @@ -938,11 +939,11 @@ class Server(BaseServer): if self.current_index > -1: item = self.playlist[self.current_index] - yield u'bitrate: ' + unicode(item.bitrate / 1000) + yield u'bitrate: ' + six.text_type(item.bitrate / 1000) # Missing 'audio'. (pos, total) = self.player.time() - yield u'time: ' + unicode(pos) + u':' + unicode(total) + yield u'time: ' + six.text_type(pos) + u':' + six.text_type(total) # Also missing 'updating_db'. @@ -957,13 +958,13 @@ class Server(BaseServer): artists, albums, songs, totaltime = tx.query(statement)[0] yield ( - u'artists: ' + unicode(artists), - u'albums: ' + unicode(albums), - u'songs: ' + unicode(songs), - u'uptime: ' + unicode(int(time.time() - self.startup_time)), + u'artists: ' + six.text_type(artists), + u'albums: ' + six.text_type(albums), + u'songs: ' + six.text_type(songs), + u'uptime: ' + six.text_type(int(time.time() - self.startup_time)), u'playtime: ' + u'0', # Missing. - u'db_playtime: ' + unicode(int(totaltime)), - u'db_update: ' + unicode(int(self.updated_time)), + u'db_playtime: ' + six.text_type(int(totaltime)), + u'db_update: ' + six.text_type(int(self.updated_time)), ) # Searching. @@ -1059,7 +1060,7 @@ class Server(BaseServer): rows = tx.query(statement, subvals) for row in rows: - yield show_tag_canon + u': ' + unicode(row[0]) + yield show_tag_canon + u': ' + six.text_type(row[0]) def cmd_count(self, conn, tag, value): """Returns the number and total time of songs matching the @@ -1071,8 +1072,8 @@ class Server(BaseServer): for item in self.lib.items(dbcore.query.MatchQuery(key, value)): songs += 1 playtime += item.length - yield u'songs: ' + unicode(songs) - yield u'playtime: ' + unicode(int(playtime)) + yield u'songs: ' + six.text_type(songs) + yield u'playtime: ' + six.text_type(int(playtime)) # "Outputs." Just a dummy implementation because we don't control # any outputs. @@ -1167,24 +1168,25 @@ class BPDPlugin(BeetsPlugin): server.run() except NoGstreamerError: global_log.error(u'Gstreamer Python bindings not found.') - global_log.error(u'Install "python-gst0.10", "py27-gst-python", ' + global_log.error(u'Install "gstreamer1.0" and "python-gi"' u'or similar package to use BPD.') def commands(self): cmd = beets.ui.Subcommand( - 'bpd', help='run an MPD-compatible music player server' + 'bpd', help=u'run an MPD-compatible music player server' ) cmd.parser.add_option( '-d', '--debug', action='store_true', - help='dump all MPD traffic to stdout' + help=u'dump all MPD traffic to stdout' ) def func(lib, opts, args): - host = args.pop(0) if args else self.config['host'].get(unicode) + host = self.config['host'].as_str() + host = args.pop(0) if args else host port = args.pop(0) if args else self.config['port'].get(int) if args: - raise beets.ui.UserError('too many arguments') - password = self.config['password'].get(unicode) + raise beets.ui.UserError(u'too many arguments') + password = self.config['password'].as_str() volume = self.config['volume'].get(int) debug = opts.debug or False self.start_bpd(lib, host, int(port), password, volume, debug) diff --git a/beetsplug/bpd/gstplayer.py b/beetsplug/bpd/gstplayer.py index adac1f5a4..705692aa5 100644 --- a/beetsplug/bpd/gstplayer.py +++ b/beetsplug/bpd/gstplayer.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -16,20 +17,27 @@ music player. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function +import six import sys import time -import gobject -import thread +from six.moves import _thread import os import copy -import urllib +from six.moves import urllib +from beets import ui -import pygst -pygst.require('0.10') -import gst # noqa +import gi +gi.require_version('Gst', '1.0') +from gi.repository import GLib, Gst # noqa: E402 + + +Gst.init(None) + + +class QueryError(Exception): + pass class GstPlayer(object): @@ -57,8 +65,19 @@ class GstPlayer(object): # Set up the Gstreamer player. From the pygst tutorial: # http://pygstdocs.berlios.de/pygst-tutorial/playbin.html - self.player = gst.element_factory_make("playbin2", "player") - fakesink = gst.element_factory_make("fakesink", "fakesink") + #### + # Updated to GStreamer 1.0 with: + # https://wiki.ubuntu.com/Novacut/GStreamer1.0 + self.player = Gst.ElementFactory.make("playbin", "player") + + if self.player is None: + raise ui.UserError("Could not create playbin") + + fakesink = Gst.ElementFactory.make("fakesink", "fakesink") + + if fakesink is None: + raise ui.UserError("Could not create fakesink") + self.player.set_property("video-sink", fakesink) bus = self.player.get_bus() bus.add_signal_watch() @@ -74,23 +93,23 @@ class GstPlayer(object): """Returns the current state flag of the playbin.""" # gst's get_state function returns a 3-tuple; we just want the # status flag in position 1. - return self.player.get_state()[1] + return self.player.get_state(Gst.CLOCK_TIME_NONE)[1] def _handle_message(self, bus, message): """Callback for status updates from GStreamer.""" - if message.type == gst.MESSAGE_EOS: + if message.type == Gst.MessageType.EOS: # file finished playing - self.player.set_state(gst.STATE_NULL) + self.player.set_state(Gst.State.NULL) self.playing = False self.cached_time = None if self.finished_callback: self.finished_callback() - elif message.type == gst.MESSAGE_ERROR: + elif message.type == Gst.MessageType.ERROR: # error - self.player.set_state(gst.STATE_NULL) + self.player.set_state(Gst.State.NULL) err, debug = message.parse_error() - print("Error: {0}".format(err)) + print(u"Error: {0}".format(err)) self.playing = False def _set_volume(self, volume): @@ -109,27 +128,27 @@ class GstPlayer(object): """Immediately begin playing the audio file at the given path. """ - self.player.set_state(gst.STATE_NULL) - if isinstance(path, unicode): - path = path.encode('utf8') - uri = 'file://' + urllib.quote(path) + self.player.set_state(Gst.State.NULL) + if isinstance(path, six.text_type): + path = path.encode('utf-8') + uri = 'file://' + urllib.parse.quote(path) self.player.set_property("uri", uri) - self.player.set_state(gst.STATE_PLAYING) + self.player.set_state(Gst.State.PLAYING) self.playing = True def play(self): """If paused, resume playback.""" - if self._get_state() == gst.STATE_PAUSED: - self.player.set_state(gst.STATE_PLAYING) + if self._get_state() == Gst.State.PAUSED: + self.player.set_state(Gst.State.PLAYING) self.playing = True def pause(self): """Pause playback.""" - self.player.set_state(gst.STATE_PAUSED) + self.player.set_state(Gst.State.PAUSED) def stop(self): """Halt playback.""" - self.player.set_state(gst.STATE_NULL) + self.player.set_state(Gst.State.NULL) self.playing = False self.cached_time = None @@ -139,27 +158,36 @@ class GstPlayer(object): Call this function before trying to play any music with play_file() or play(). """ + # If we don't use the MainLoop, messages are never sent. - gobject.threads_init() def start(): - loop = gobject.MainLoop() + loop = GLib.MainLoop() loop.run() - thread.start_new_thread(start, ()) + + _thread.start_new_thread(start, ()) def time(self): """Returns a tuple containing (position, length) where both values are integers in seconds. If no stream is available, returns (0, 0). """ - fmt = gst.Format(gst.FORMAT_TIME) + fmt = Gst.Format(Gst.Format.TIME) try: - pos = self.player.query_position(fmt, None)[0] / (10 ** 9) - length = self.player.query_duration(fmt, None)[0] / (10 ** 9) + posq = self.player.query_position(fmt) + if not posq[0]: + raise QueryError("query_position failed") + pos = posq[1] // (10 ** 9) + + lengthq = self.player.query_duration(fmt) + if not lengthq[0]: + raise QueryError("query_duration failed") + length = lengthq[1] // (10 ** 9) + self.cached_time = (pos, length) return (pos, length) - except gst.QueryError: + except QueryError: # Stream not ready. For small gaps of time, for instance # after seeking, the time values are unavailable. For this # reason, we cache recent. @@ -175,9 +203,9 @@ class GstPlayer(object): self.stop() return - fmt = gst.Format(gst.FORMAT_TIME) + fmt = Gst.Format(Gst.Format.TIME) ns = position * 10 ** 9 # convert to nanoseconds - self.player.seek_simple(fmt, gst.SEEK_FLAG_FLUSH, ns) + self.player.seek_simple(fmt, Gst.SeekFlags.FLUSH, ns) # save new cached time self.cached_time = (position, cur_len) @@ -208,13 +236,15 @@ def play_complicated(paths): def next_song(): my_paths.pop(0) p.play_file(my_paths[0]) + p = GstPlayer(next_song) p.run() p.play_file(my_paths[0]) while my_paths: time.sleep(1) -if __name__ == b'__main__': + +if __name__ == '__main__': # A very simple command-line player. Just give it names of audio # files on the command line; these are all played in sequence. paths = [os.path.abspath(os.path.expanduser(p)) diff --git a/beetsplug/bpm.py b/beetsplug/bpm.py index 85c8d6636..20218bd33 100644 --- a/beetsplug/bpm.py +++ b/beetsplug/bpm.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, aroquen +# Copyright 2016, aroquen # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,10 +15,10 @@ """Determine BPM by pressing a key to the rhythm.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import time +from six.moves import input from beets import ui from beets.plugins import BeetsPlugin @@ -31,7 +32,7 @@ def bpm(max_strokes): dt = [] for i in range(max_strokes): # Press enter to the rhythm... - s = raw_input() + s = input() if s == '': t1 = time.time() # Only start measuring at the second stroke @@ -58,18 +59,20 @@ class BPMPlugin(BeetsPlugin): def commands(self): cmd = ui.Subcommand('bpm', - help='determine bpm of a song by pressing \ - a key to the rhythm') + help=u'determine bpm of a song by pressing ' + u'a key to the rhythm') cmd.func = self.command return [cmd] def command(self, lib, opts, args): - self.get_bpm(lib.items(ui.decargs(args))) + items = lib.items(ui.decargs(args)) + write = ui.should_write() + self.get_bpm(items, write) def get_bpm(self, items, write=False): overwrite = self.config['overwrite'].get(bool) if len(items) > 1: - raise ValueError('Can only get bpm of one song at time') + raise ValueError(u'Can only get bpm of one song at time') item = items[0] if item['bpm']: diff --git a/beetsplug/bucket.py b/beetsplug/bucket.py index d673b0bd4..c4be2a3df 100644 --- a/beetsplug/bucket.py +++ b/beetsplug/bucket.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Fabrice Laporte. +# Copyright 2016, Fabrice Laporte. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,17 +16,20 @@ """Provides the %bucket{} function for path formatting. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from datetime import datetime import re import string -from itertools import tee, izip +from six.moves import zip +from itertools import tee from beets import plugins, ui +ASCII_DIGITS = string.digits + string.ascii_lowercase + + class BucketError(Exception): pass @@ -34,7 +38,7 @@ def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) - return izip(a, b) + return zip(a, b) def span_from_str(span_str): @@ -45,7 +49,7 @@ def span_from_str(span_str): """Convert string to a 4 digits year """ if yearfrom < 100: - raise BucketError("%d must be expressed on 4 digits" % yearfrom) + raise BucketError(u"%d must be expressed on 4 digits" % yearfrom) # if two digits only, pick closest year that ends by these two # digits starting from yearfrom @@ -58,12 +62,12 @@ def span_from_str(span_str): years = [int(x) for x in re.findall('\d+', span_str)] if not years: - raise ui.UserError("invalid range defined for year bucket '%s': no " - "year found" % span_str) + raise ui.UserError(u"invalid range defined for year bucket '%s': no " + u"year found" % span_str) try: years = [normalize_year(x, years[0]) for x in years] except BucketError as exc: - raise ui.UserError("invalid range defined for year bucket '%s': %s" % + raise ui.UserError(u"invalid range defined for year bucket '%s': %s" % (span_str, exc)) res = {'from': years[0], 'str': span_str} @@ -118,8 +122,8 @@ def build_year_spans(year_spans_str): def str2fmt(s): """Deduces formatting syntax from a span string. """ - regex = re.compile("(?P\D*)(?P\d+)(?P\D*)" - "(?P\d*)(?P\D*)") + regex = re.compile(r"(?P\D*)(?P\d+)(?P\D*)" + r"(?P\d*)(?P\D*)") m = re.match(regex, s) res = {'fromnchars': len(m.group('fromyear')), @@ -134,9 +138,10 @@ def str2fmt(s): def format_span(fmt, yearfrom, yearto, fromnchars, tonchars): """Return a span string representation. """ - args = (bytes(yearfrom)[-fromnchars:]) + args = (str(yearfrom)[-fromnchars:]) if tonchars: - args = (bytes(yearfrom)[-fromnchars:], bytes(yearto)[-tonchars:]) + args = (str(yearfrom)[-fromnchars:], str(yearto)[-tonchars:]) + return fmt % args @@ -155,23 +160,23 @@ def build_alpha_spans(alpha_spans_str, alpha_regexs): [from...to] """ spans = [] - ASCII_DIGITS = string.digits + string.ascii_lowercase + for elem in alpha_spans_str: if elem in alpha_regexs: spans.append(re.compile(alpha_regexs[elem])) else: bucket = sorted([x for x in elem.lower() if x.isalnum()]) if bucket: - beginIdx = ASCII_DIGITS.index(bucket[0]) - endIdx = ASCII_DIGITS.index(bucket[-1]) + begin_index = ASCII_DIGITS.index(bucket[0]) + end_index = ASCII_DIGITS.index(bucket[-1]) else: - raise ui.UserError("invalid range defined for alpha bucket " - "'%s': no alphanumeric character found" % + raise ui.UserError(u"invalid range defined for alpha bucket " + u"'%s': no alphanumeric character found" % elem) spans.append( re.compile( - "^[" + ASCII_DIGITS[beginIdx:endIdx + 1] + - ASCII_DIGITS[beginIdx:endIdx + 1].upper() + "]" + "^[" + ASCII_DIGITS[begin_index:end_index + 1] + + ASCII_DIGITS[begin_index:end_index + 1].upper() + "]" ) ) return spans diff --git a/beetsplug/chroma.py b/beetsplug/chroma.py index f1ca233e0..574729560 100644 --- a/beetsplug/chroma.py +++ b/beetsplug/chroma.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,8 +16,7 @@ """Adds Chromaprint/Acoustid acoustic fingerprinting support to the autotagger. Requires the pyacoustid library. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from beets import plugins from beets import ui @@ -121,7 +121,7 @@ def _all_releases(items): for release_id in release_ids: relcounts[release_id] += 1 - for release_id, count in relcounts.iteritems(): + for release_id, count in relcounts.items(): if float(count) / len(items) > COMMON_REL_THRESH: yield release_id @@ -177,25 +177,24 @@ class AcoustidPlugin(plugins.BeetsPlugin): def commands(self): submit_cmd = ui.Subcommand('submit', - help='submit Acoustid fingerprints') + help=u'submit Acoustid fingerprints') def submit_cmd_func(lib, opts, args): try: - apikey = config['acoustid']['apikey'].get(unicode) + apikey = config['acoustid']['apikey'].as_str() except confit.NotFoundError: - raise ui.UserError('no Acoustid user API key provided') + raise ui.UserError(u'no Acoustid user API key provided') submit_items(self._log, apikey, lib.items(ui.decargs(args))) submit_cmd.func = submit_cmd_func fingerprint_cmd = ui.Subcommand( 'fingerprint', - help='generate fingerprints for items without them' + help=u'generate fingerprints for items without them' ) def fingerprint_cmd_func(lib, opts, args): for item in lib.items(ui.decargs(args)): - fingerprint_item(self._log, item, - write=config['import']['write'].get(bool)) + fingerprint_item(self._log, item, write=ui.should_write()) fingerprint_cmd.func = fingerprint_cmd_func return [submit_cmd, fingerprint_cmd] @@ -237,7 +236,7 @@ def submit_items(log, userkey, items, chunksize=64): try: acoustid.submit(API_KEY, userkey, data) except acoustid.AcoustidError as exc: - log.warn(u'acoustid submission error: {0}', exc) + log.warning(u'acoustid submission error: {0}', exc) del data[:] for item in items: @@ -296,7 +295,7 @@ def fingerprint_item(log, item, write=False): log.info(u'{0}: fingerprinting', util.displayable_path(item.path)) try: - _, fp = acoustid.fingerprint_file(item.path) + _, fp = acoustid.fingerprint_file(util.syspath(item.path)) item.acoustid_fingerprint = fp if write: log.info(u'{0}: writing fingerprint', diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 4c39c52a9..d1223596f 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Jakob Schnitzer. +# Copyright 2016, Jakob Schnitzer. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,20 +15,24 @@ """Converts tracks or albums to external directory """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import os import threading import subprocess import tempfile import shlex +import six from string import Template +import platform from beets import ui, util, plugins, config from beets.plugins import BeetsPlugin from beets.util.confit import ConfigTypeError from beets import art +from beets.util.artresizer import ArtResizer +from beets.library import parse_query_string +from beets.library import Item _fs_lock = threading.Lock() _temp_files = [] # Keep track of temporary transcoded files for deletion. @@ -38,7 +43,7 @@ ALIASES = { u'vorbis': u'ogg', } -LOSSLESS_FORMATS = ['ape', 'flac', 'alac', 'wav'] +LOSSLESS_FORMATS = ['ape', 'flac', 'alac', 'wav', 'aiff'] def replace_ext(path, ext): @@ -46,48 +51,55 @@ def replace_ext(path, ext): The new extension must not contain a leading dot. """ - return os.path.splitext(path)[0] + b'.' + ext + ext_dot = b'.' + ext + return os.path.splitext(path)[0] + ext_dot def get_format(fmt=None): - """Return the command tempate and the extension from the config. + """Return the command template and the extension from the config. """ if not fmt: - fmt = config['convert']['format'].get(unicode).lower() + fmt = config['convert']['format'].as_str().lower() fmt = ALIASES.get(fmt, fmt) try: format_info = config['convert']['formats'][fmt].get(dict) command = format_info['command'] - extension = format_info['extension'] + extension = format_info.get('extension', fmt) except KeyError: raise ui.UserError( - u'convert: format {0} needs "command" and "extension" fields' + u'convert: format {0} needs the "command" field' .format(fmt) ) except ConfigTypeError: - command = config['convert']['formats'][fmt].get(bytes) + command = config['convert']['formats'][fmt].get(str) extension = fmt # Convenience and backwards-compatibility shortcuts. keys = config['convert'].keys() if 'command' in keys: - command = config['convert']['command'].get(unicode) + command = config['convert']['command'].as_str() elif 'opts' in keys: # Undocumented option for backwards compatibility with < 1.3.1. command = u'ffmpeg -i $source -y {0} $dest'.format( - config['convert']['opts'].get(unicode) + config['convert']['opts'].as_str() ) if 'extension' in keys: - extension = config['convert']['extension'].get(unicode) + extension = config['convert']['extension'].as_str() - return (command.encode('utf8'), extension.encode('utf8')) + return (command.encode('utf-8'), extension.encode('utf-8')) def should_transcode(item, fmt): """Determine whether the item should be transcoded as part of conversion (i.e., its bitrate is high or it has the wrong format). """ + no_convert_queries = config['convert']['no_convert'].as_str_seq() + if no_convert_queries: + for query_string in no_convert_queries: + query, _ = parse_query_string(query_string, Item) + if query.match(item): + return False if config['convert']['never_convert_lossy_files'] and \ not (item.format.lower() in LOSSLESS_FORMATS): return False @@ -106,8 +118,8 @@ class ConvertPlugin(BeetsPlugin): u'format': u'mp3', u'formats': { u'aac': { - u'command': u'ffmpeg -i $source -y -vn -acodec libfaac ' - u'-aq 100 $dest', + u'command': u'ffmpeg -i $source -y -vn -acodec aac ' + u'-aq 1 $dest', u'extension': u'm4a', }, u'alac': { @@ -119,7 +131,7 @@ class ConvertPlugin(BeetsPlugin): u'opus': u'ffmpeg -i $source -y -vn -acodec libopus -ab 96k $dest', u'ogg': - u'ffmpeg -i $source -y -vn -acodec libvorbis -aq 2 $dest', + u'ffmpeg -i $source -y -vn -acodec libvorbis -aq 3 $dest', u'wma': u'ffmpeg -i $source -y -vn -acodec wmav2 -vn $dest', }, @@ -129,29 +141,31 @@ class ConvertPlugin(BeetsPlugin): u'quiet': False, u'embed': True, u'paths': {}, + u'no_convert': u'', u'never_convert_lossy_files': False, u'copy_album_art': False, + u'album_art_maxwidth': 0, }) - self.import_stages = [self.auto_convert] + self.early_import_stages = [self.auto_convert] self.register_listener('import_task_files', self._cleanup) def commands(self): - cmd = ui.Subcommand('convert', help='convert to external location') + cmd = ui.Subcommand('convert', help=u'convert to external location') cmd.parser.add_option('-p', '--pretend', action='store_true', - help='show actions but do nothing') + help=u'show actions but do nothing') cmd.parser.add_option('-t', '--threads', action='store', type='int', - help='change the number of threads, \ + help=u'change the number of threads, \ defaults to maximum available processors') cmd.parser.add_option('-k', '--keep-new', action='store_true', - dest='keep_new', help='keep only the converted \ + dest='keep_new', help=u'keep only the converted \ and move the old files') cmd.parser.add_option('-d', '--dest', action='store', - help='set the destination directory') + help=u'set the destination directory') cmd.parser.add_option('-f', '--format', action='store', dest='format', - help='set the target format of the tracks') + help=u'set the target format of the tracks') cmd.parser.add_option('-y', '--yes', action='store_true', dest='yes', - help='do not ask for confirmation') + help=u'do not ask for confirmation') cmd.parser.add_album_option() cmd.func = self.convert_func return [cmd] @@ -179,34 +193,55 @@ class ConvertPlugin(BeetsPlugin): if not quiet and not pretend: self._log.info(u'Encoding {0}', util.displayable_path(source)) + # On Python 3, we need to construct the command to invoke as a + # Unicode string. On Unix, this is a little unfortunate---the OS is + # expecting bytes---so we use surrogate escaping and decode with the + # argument encoding, which is the same encoding that will then be + # *reversed* to recover the same bytes before invoking the OS. On + # Windows, we want to preserve the Unicode filename "as is." + if not six.PY2: + command = command.decode(util.arg_encoding(), 'surrogateescape') + if platform.system() == 'Windows': + source = source.decode(util._fsencoding()) + dest = dest.decode(util._fsencoding()) + else: + source = source.decode(util.arg_encoding(), 'surrogateescape') + dest = dest.decode(util.arg_encoding(), 'surrogateescape') + # Substitute $source and $dest in the argument list. args = shlex.split(command) + encode_cmd = [] for i, arg in enumerate(args): args[i] = Template(arg).safe_substitute({ - b'source': source, - b'dest': dest, + 'source': source, + 'dest': dest, }) + if six.PY2: + encode_cmd.append(args[i]) + else: + encode_cmd.append(args[i].encode(util.arg_encoding())) if pretend: - self._log.info(' '.join(args)) + self._log.info(u'{0}', u' '.join(ui.decargs(args))) return try: - util.command_output(args) + util.command_output(encode_cmd) except subprocess.CalledProcessError as exc: # Something went wrong (probably Ctrl+C), remove temporary files self._log.info(u'Encoding {0} failed. Cleaning up...', util.displayable_path(source)) - self._log.debug(u'Command {0} exited with status {1}', - exc.cmd.decode('utf8', 'ignore'), - exc.returncode) + self._log.debug(u'Command {0} exited with status {1}: {2}', + args, + exc.returncode, + exc.output) util.remove(dest) util.prune_dirs(os.path.dirname(dest)) raise except OSError as exc: raise ui.UserError( - u"convert: could invoke '{0}': {1}".format( - ' '.join(args), exc + u"convert: couldn't invoke '{0}': {1}".format( + u' '.join(ui.decargs(args)), exc ) ) @@ -216,6 +251,9 @@ class ConvertPlugin(BeetsPlugin): def convert_item(self, dest_dir, keep_new, path_formats, fmt, pretend=False): + """A pipeline thread that converts `Item` objects from a + library. + """ command, ext = get_format(fmt) item, original, converted = None, None, None while True: @@ -291,6 +329,8 @@ class ConvertPlugin(BeetsPlugin): if self.config['embed']: album = item.get_album() if album and album.artpath: + self._log.debug(u'embedding album art from {}', + util.displayable_path(album.artpath)) art.embed_item(self._log, item, album.artpath, itempath=converted) @@ -302,8 +342,8 @@ class ConvertPlugin(BeetsPlugin): dest=converted, keepnew=False) def copy_album_art(self, album, dest_dir, path_formats, pretend=False): - """Copies the associated cover art of the album. Album must have at - least one track. + """Copies or converts the associated cover art of the album. Album must + have at least one track. """ if not album or not album.artpath: return @@ -333,76 +373,110 @@ class ConvertPlugin(BeetsPlugin): util.displayable_path(album.artpath)) return - if pretend: - self._log.info(u'cp {0} {1}', + # Decide whether we need to resize the cover-art image. + resize = False + maxwidth = None + if self.config['album_art_maxwidth']: + maxwidth = self.config['album_art_maxwidth'].get(int) + size = ArtResizer.shared.get_size(album.artpath) + self._log.debug('image size: {}', size) + if size: + resize = size[0] > maxwidth + else: + self._log.warning(u'Could not get size of image (please see ' + u'documentation for dependencies).') + + # Either copy or resize (while copying) the image. + if resize: + self._log.info(u'Resizing cover art from {0} to {1}', util.displayable_path(album.artpath), util.displayable_path(dest)) + if not pretend: + ArtResizer.shared.resize(maxwidth, album.artpath, dest) else: - self._log.info(u'Copying cover art to {0}', - util.displayable_path(dest)) - util.copy(album.artpath, dest) + if pretend: + self._log.info(u'cp {0} {1}', + util.displayable_path(album.artpath), + util.displayable_path(dest)) + else: + self._log.info(u'Copying cover art to {0}', + util.displayable_path(album.artpath), + util.displayable_path(dest)) + util.copy(album.artpath, dest) def convert_func(self, lib, opts, args): - if not opts.dest: - opts.dest = self.config['dest'].get() - if not opts.dest: - raise ui.UserError('no convert destination set') - opts.dest = util.bytestring_path(opts.dest) + dest = opts.dest or self.config['dest'].get() + if not dest: + raise ui.UserError(u'no convert destination set') + dest = util.bytestring_path(dest) - if not opts.threads: - opts.threads = self.config['threads'].get(int) + threads = opts.threads or self.config['threads'].get(int) - if self.config['paths']: - path_formats = ui.get_path_formats(self.config['paths']) + path_formats = ui.get_path_formats(self.config['paths'] or None) + + fmt = opts.format or self.config['format'].as_str().lower() + + if opts.pretend is not None: + pretend = opts.pretend else: - path_formats = ui.get_path_formats() - - if not opts.format: - opts.format = self.config['format'].get(unicode).lower() - - pretend = opts.pretend if opts.pretend is not None else \ - self.config['pretend'].get(bool) - - if not pretend: - ui.commands.list_items(lib, ui.decargs(args), opts.album) - - if not (opts.yes or ui.input_yn("Convert? (Y/n)")): - return + pretend = self.config['pretend'].get(bool) if opts.album: albums = lib.albums(ui.decargs(args)) - items = (i for a in albums for i in a.items()) - if self.config['copy_album_art']: - for album in albums: - self.copy_album_art(album, opts.dest, path_formats, - pretend) + items = [i for a in albums for i in a.items()] + if not pretend: + for a in albums: + ui.print_(format(a, u'')) else: - items = iter(lib.items(ui.decargs(args))) - convert = [self.convert_item(opts.dest, + items = list(lib.items(ui.decargs(args))) + if not pretend: + for i in items: + ui.print_(format(i, u'')) + + if not items: + self._log.error(u'Empty query result.') + return + if not (pretend or opts.yes or ui.input_yn(u"Convert? (Y/n)")): + return + + if opts.album and self.config['copy_album_art']: + for album in albums: + self.copy_album_art(album, dest, path_formats, pretend) + + convert = [self.convert_item(dest, opts.keep_new, path_formats, - opts.format, + fmt, pretend) - for _ in range(opts.threads)] - pipe = util.pipeline.Pipeline([items, convert]) + for _ in range(threads)] + pipe = util.pipeline.Pipeline([iter(items), convert]) pipe.run_parallel() def convert_on_import(self, lib, item): """Transcode a file automatically after it is imported into the library. """ - fmt = self.config['format'].get(unicode).lower() + fmt = self.config['format'].as_str().lower() if should_transcode(item, fmt): command, ext = get_format() + + # Create a temporary file for the conversion. tmpdir = self.config['tmpdir'].get() - fd, dest = tempfile.mkstemp('.' + ext, dir=tmpdir) - dest = util.bytestring_path(dest) + if tmpdir: + tmpdir = util.py3_path(util.bytestring_path(tmpdir)) + fd, dest = tempfile.mkstemp(util.py3_path(b'.' + ext), dir=tmpdir) os.close(fd) + dest = util.bytestring_path(dest) _temp_files.append(dest) # Delete the transcode later. + + # Convert. try: self.encode(command, item.path, dest) except subprocess.CalledProcessError: return + + # Change the newly-imported database entry to point to the + # converted file. item.path = dest item.write() item.read() # Load new audio information data. diff --git a/beetsplug/cue.py b/beetsplug/cue.py index 25205f8e8..fd564b55c 100644 --- a/beetsplug/cue.py +++ b/beetsplug/cue.py @@ -1,6 +1,9 @@ -# Copyright 2015 Bruno Cauet +# -*- coding: utf-8 -*- +# Copyright 2016 Bruno Cauet # Split an album-file in tracks thanks a cue file +from __future__ import division, absolute_import, print_function + import subprocess from os import path from glob import glob @@ -32,7 +35,7 @@ class CuePlugin(BeetsPlugin): return if len(cues) > 1: self._log.info(u"Found multiple cue files doing nothing: {0}", - map(displayable_path, cues)) + list(map(displayable_path, cues))) cue_file = cues[0] self._log.info("Found {} for {}", displayable_path(cue_file), item) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 80b7ae3df..82c79a023 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,34 +16,31 @@ """Adds Discogs album search support to the autotagger. Requires the discogs-client library. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import beets.ui -from beets import logging +from beets import config from beets.autotag.hooks import AlbumInfo, TrackInfo, Distance from beets.plugins import BeetsPlugin from beets.util import confit from discogs_client import Release, Client from discogs_client.exceptions import DiscogsAPIError from requests.exceptions import ConnectionError +from six.moves import http_client import beets import re import time import json import socket -import httplib import os +import traceback +from string import ascii_lowercase -# Silence spurious INFO log lines generated by urllib3. -urllib3_logger = logging.getLogger('requests.packages.urllib3') -urllib3_logger.setLevel(logging.CRITICAL) - -USER_AGENT = u'beets/{0} +http://beets.radbox.org/'.format(beets.__version__) +USER_AGENT = u'beets/{0} +http://beets.io/'.format(beets.__version__) # Exceptions that discogs_client should really handle but does not. -CONNECTION_ERRORS = (ConnectionError, socket.error, httplib.HTTPException, +CONNECTION_ERRORS = (ConnectionError, socket.error, http_client.HTTPException, ValueError, # JSON decoding raises a ValueError. DiscogsAPIError) @@ -56,17 +54,25 @@ class DiscogsPlugin(BeetsPlugin): 'apisecret': 'plxtUTqoCzwxZpqdPysCwGuBSmZNdZVy', 'tokenfile': 'discogs_token.json', 'source_weight': 0.5, + 'user_token': '', }) self.config['apikey'].redact = True self.config['apisecret'].redact = True + self.config['user_token'].redact = True self.discogs_client = None self.register_listener('import_begin', self.setup) def setup(self, session=None): """Create the `discogs_client` field. Authenticate if necessary. """ - c_key = self.config['apikey'].get(unicode) - c_secret = self.config['apisecret'].get(unicode) + c_key = self.config['apikey'].as_str() + c_secret = self.config['apisecret'].as_str() + + # Try using a configured user token (bypassing OAuth login). + user_token = self.config['user_token'].as_str() + if user_token: + self.discogs_client = Client(USER_AGENT, user_token=user_token) + return # Get the OAuth token from a file or log in. try: @@ -83,7 +89,7 @@ class DiscogsPlugin(BeetsPlugin): token, secret) def reset_auth(self): - """Delete toke file & redo the auth steps. + """Delete token file & redo the auth steps. """ os.remove(self._tokenfile()) self.setup() @@ -99,24 +105,24 @@ class DiscogsPlugin(BeetsPlugin): try: _, _, url = auth_client.get_authorize_url() except CONNECTION_ERRORS as e: - self._log.debug('connection error: {0}', e) - raise beets.ui.UserError('communication with Discogs failed') + self._log.debug(u'connection error: {0}', e) + raise beets.ui.UserError(u'communication with Discogs failed') - beets.ui.print_("To authenticate with Discogs, visit:") + beets.ui.print_(u"To authenticate with Discogs, visit:") beets.ui.print_(url) # Ask for the code and validate it. - code = beets.ui.input_("Enter the code:") + code = beets.ui.input_(u"Enter the code:") try: token, secret = auth_client.get_access_token(code) except DiscogsAPIError: - raise beets.ui.UserError('Discogs authorization failed') + raise beets.ui.UserError(u'Discogs authorization failed') except CONNECTION_ERRORS as e: self._log.debug(u'connection error: {0}', e) - raise beets.ui.UserError('Discogs token request failed') + raise beets.ui.UserError(u'Discogs token request failed') # Save the token for later use. - self._log.debug('Discogs token {0}, secret {1}', token, secret) + self._log.debug(u'Discogs token {0}, secret {1}', token, secret) with open(self._tokenfile(), 'w') as f: json.dump({'token': token, 'secret': secret}, f) @@ -150,8 +156,8 @@ class DiscogsPlugin(BeetsPlugin): return self.candidates(items, artist, album, va_likely) else: return [] - except CONNECTION_ERRORS as e: - self._log.debug(u'HTTP Connection Error: {0}', e) + except CONNECTION_ERRORS: + self._log.debug(u'Connection error in album search', exc_info=True) return [] def album_for_id(self, album_id): @@ -181,8 +187,8 @@ class DiscogsPlugin(BeetsPlugin): self.reset_auth() return self.album_for_id(album_id) return None - except CONNECTION_ERRORS as e: - self._log.debug(u'HTTP Connection Error: {0}', e) + except CONNECTION_ERRORS: + self._log.debug(u'Connection error in album lookup', exc_info=True) return None return self.get_album_info(result) @@ -193,25 +199,41 @@ class DiscogsPlugin(BeetsPlugin): # cause a query to return no results, even if they match the artist or # album title. Use `re.UNICODE` flag to avoid stripping non-english # word characters. - # TEMPORARY: Encode as ASCII to work around a bug: - # https://github.com/sampsyo/beets/issues/1051 + # FIXME: Encode as ASCII to work around a bug: + # https://github.com/beetbox/beets/issues/1051 # When the library is fixed, we should encode as UTF-8. query = re.sub(r'(?u)\W+', ' ', query).encode('ascii', "replace") # Strip medium information from query, Things like "CD1" and "disk 1" # can also negate an otherwise positive result. - query = re.sub(r'(?i)\b(CD|disc)\s*\d+', '', query) + query = re.sub(br'(?i)\b(CD|disc)\s*\d+', b'', query) try: releases = self.discogs_client.search(query, type='release').page(1) - except CONNECTION_ERRORS as exc: - self._log.debug("Communication error while searching for {0!r}: " - "{1}".format(query, exc)) + except CONNECTION_ERRORS: + self._log.debug(u"Communication error while searching for {0!r}", + query, exc_info=True) return [] - return [self.get_album_info(release) for release in releases[:5]] + return [album for album in map(self.get_album_info, releases[:5]) + if album] def get_album_info(self, result): """Returns an AlbumInfo object for a discogs Release object. """ + # Explicitly reload the `Release` fields, as they might not be yet + # present if the result is from a `discogs_client.search()`. + if not result.data.get('artists'): + result.refresh() + + # Sanity check for required fields. The list of required fields is + # defined at Guideline 1.3.1.a, but in practice some releases might be + # lacking some of these fields. This function expects at least: + # `artists` (>0), `title`, `id`, `tracklist` (>0) + # https://www.discogs.com/help/doc/submission-guidelines-general-rules + if not all([result.data.get(k) for k in ['artists', 'title', 'id', + 'tracklist']]): + self._log.warn(u"Release does not contain the required fields") + return None + artist, artist_id = self.get_artist([a.data for a in result.artists]) album = re.sub(r' +', ' ', result.title) album_id = result.data['id'] @@ -220,22 +242,46 @@ class DiscogsPlugin(BeetsPlugin): # information and leave us with skeleton `Artist` objects that will # each make an API call just to get the same data back. tracks = self.get_tracks(result.data['tracklist']) - albumtype = ', '.join( - result.data['formats'][0].get('descriptions', [])) or None - va = result.data['artists'][0]['name'].lower() == 'various' - year = result.data['year'] - label = result.data['labels'][0]['name'] - mediums = len(set(t.medium for t in tracks)) - catalogno = result.data['labels'][0]['catno'] - if catalogno == 'none': - catalogno = None + + # Extract information for the optional AlbumInfo fields, if possible. + va = result.data['artists'][0].get('name', '').lower() == 'various' + year = result.data.get('year') + mediums = [t.medium for t in tracks] country = result.data.get('country') - media = result.data['formats'][0]['name'] - data_url = result.data['uri'] + data_url = result.data.get('uri') + + # Extract information for the optional AlbumInfo fields that are + # contained on nested discogs fields. + albumtype = media = label = catalogno = None + if result.data.get('formats'): + albumtype = ', '.join( + result.data['formats'][0].get('descriptions', [])) or None + media = result.data['formats'][0]['name'] + if result.data.get('labels'): + label = result.data['labels'][0].get('name') + catalogno = result.data['labels'][0].get('catno') + + # Additional cleanups (various artists name, catalog number, media). + if va: + artist = config['va_name'].as_str() + if catalogno == 'none': + catalogno = None + # Explicitly set the `media` for the tracks, since it is expected by + # `autotag.apply_metadata`, and set `medium_total`. + for track in tracks: + track.media = media + track.medium_total = mediums.count(track.medium) + # Discogs does not have track IDs. Invent our own IDs as proposed + # in #2336. + track.track_id = str(album_id) + "-" + track.track_alt + + # Retrieve master release id (returns None if there isn't one) + master_id = result.data.get('master_id') + return AlbumInfo(album, album_id, artist, artist_id, tracks, asin=None, albumtype=albumtype, va=va, year=year, month=None, - day=None, label=label, mediums=mediums, - artist_sort=None, releasegroup_id=None, + day=None, label=label, mediums=len(set(mediums)), + artist_sort=None, releasegroup_id=master_id, catalognum=catalogno, script=None, language=None, country=country, albumstatus=None, media=media, albumdisambig=None, artist_credit=None, @@ -266,38 +312,71 @@ class DiscogsPlugin(BeetsPlugin): def get_tracks(self, tracklist): """Returns a list of TrackInfo objects for a discogs tracklist. """ + try: + clean_tracklist = self.coalesce_tracks(tracklist) + except Exception as exc: + # FIXME: this is an extra precaution for making sure there are no + # side effects after #2222. It should be removed after further + # testing. + self._log.debug(u'{}', traceback.format_exc()) + self._log.error(u'uncaught exception in coalesce_tracks: {}', exc) + clean_tracklist = tracklist tracks = [] index_tracks = {} index = 0 - for track in tracklist: + for track in clean_tracklist: # Only real tracks have `position`. Otherwise, it's an index track. if track['position']: index += 1 - tracks.append(self.get_track_info(track, index)) + track_info = self.get_track_info(track, index) + track_info.track_alt = track['position'] + tracks.append(track_info) else: index_tracks[index + 1] = track['title'] # Fix up medium and medium_index for each track. Discogs position is # unreliable, but tracks are in order. medium = None - medium_count, index_count = 0, 0 + medium_count, index_count, side_count = 0, 0, 0 + sides_per_medium = 1 + + # If a medium has two sides (ie. vinyl or cassette), each pair of + # consecutive sides should belong to the same medium. + if all([track.medium is not None for track in tracks]): + m = sorted(set([track.medium.lower() for track in tracks])) + # If all track.medium are single consecutive letters, assume it is + # a 2-sided medium. + if ''.join(m) in ascii_lowercase: + sides_per_medium = 2 + for track in tracks: # Handle special case where a different medium does not indicate a # new disc, when there is no medium_index and the ordinal of medium # is not sequential. For example, I, II, III, IV, V. Assume these # are the track index, not the medium. + # side_count is the number of mediums or medium sides (in the case + # of two-sided mediums) that were seen before. medium_is_index = track.medium and not track.medium_index and ( len(track.medium) != 1 or - ord(track.medium) - 64 != medium_count + 1 + # Not within standard incremental medium values (A, B, C, ...). + ord(track.medium) - 64 != side_count + 1 ) if not medium_is_index and medium != track.medium: - # Increment medium_count and reset index_count when medium - # changes. + side_count += 1 + if sides_per_medium == 2: + if side_count % sides_per_medium: + # Two-sided medium changed. Reset index_count. + index_count = 0 + medium_count += 1 + else: + # Medium changed. Reset index_count. + medium_count += 1 + index_count = 0 medium = track.medium - medium_count += 1 - index_count = 0 + index_count += 1 + medium_count = 1 if medium_count == 0 else medium_count track.medium, track.medium_index = medium_count, index_count # Get `disctitle` from Discogs index tracks. Assume that an index track @@ -312,12 +391,87 @@ class DiscogsPlugin(BeetsPlugin): return tracks + def coalesce_tracks(self, raw_tracklist): + """Pre-process a tracklist, merging subtracks into a single track. The + title for the merged track is the one from the previous index track, + if present; otherwise it is a combination of the subtracks titles. + """ + def add_merged_subtracks(tracklist, subtracks): + """Modify `tracklist` in place, merging a list of `subtracks` into + a single track into `tracklist`.""" + # Calculate position based on first subtrack, without subindex. + idx, medium_idx, sub_idx = \ + self.get_track_index(subtracks[0]['position']) + position = '%s%s' % (idx or '', medium_idx or '') + + if tracklist and not tracklist[-1]['position']: + # Assume the previous index track contains the track title. + if sub_idx: + # "Convert" the track title to a real track, discarding the + # subtracks assuming they are logical divisions of a + # physical track (12.2.9 Subtracks). + tracklist[-1]['position'] = position + else: + # Promote the subtracks to real tracks, discarding the + # index track, assuming the subtracks are physical tracks. + index_track = tracklist.pop() + # Fix artists when they are specified on the index track. + if index_track.get('artists'): + for subtrack in subtracks: + if not subtrack.get('artists'): + subtrack['artists'] = index_track['artists'] + tracklist.extend(subtracks) + else: + # Merge the subtracks, pick a title, and append the new track. + track = subtracks[0].copy() + track['title'] = ' / '.join([t['title'] for t in subtracks]) + tracklist.append(track) + + # Pre-process the tracklist, trying to identify subtracks. + subtracks = [] + tracklist = [] + prev_subindex = '' + for track in raw_tracklist: + # Regular subtrack (track with subindex). + if track['position']: + _, _, subindex = self.get_track_index(track['position']) + if subindex: + if subindex.rjust(len(raw_tracklist)) > prev_subindex: + # Subtrack still part of the current main track. + subtracks.append(track) + else: + # Subtrack part of a new group (..., 1.3, *2.1*, ...). + add_merged_subtracks(tracklist, subtracks) + subtracks = [track] + prev_subindex = subindex.rjust(len(raw_tracklist)) + continue + + # Index track with nested sub_tracks. + if not track['position'] and 'sub_tracks' in track: + # Append the index track, assuming it contains the track title. + tracklist.append(track) + add_merged_subtracks(tracklist, track['sub_tracks']) + continue + + # Regular track or index track without nested sub_tracks. + if subtracks: + add_merged_subtracks(tracklist, subtracks) + subtracks = [] + prev_subindex = '' + tracklist.append(track) + + # Merge and add the remaining subtracks, if any. + if subtracks: + add_merged_subtracks(tracklist, subtracks) + + return tracklist + def get_track_info(self, track, index): """Returns a TrackInfo object for a discogs track. """ title = track['title'] track_id = None - medium, medium_index = self.get_track_index(track['position']) + medium, medium_index, _ = self.get_track_index(track['position']) artist, artist_id = self.get_artist(track.get('artists', [])) length = self.get_track_length(track['duration']) return TrackInfo(title, track_id, artist, artist_id, length, index, @@ -325,17 +479,33 @@ class DiscogsPlugin(BeetsPlugin): disctitle=None, artist_credit=None) def get_track_index(self, position): - """Returns the medium and medium index for a discogs track position. - """ - # medium_index is a number at the end of position. medium is everything - # else. E.g. (A)(1), (Side A, Track )(1), (A)(), ()(1), etc. - match = re.match(r'^(.*?)(\d*)$', position.upper()) + """Returns the medium, medium index and subtrack index for a discogs + track position.""" + # Match the standard Discogs positions (12.2.9), which can have several + # forms (1, 1-1, A1, A1.1, A1a, ...). + match = re.match( + r'^(.*?)' # medium: everything before medium_index. + r'(\d*?)' # medium_index: a number at the end of + # `position`, except if followed by a subtrack + # index. + # subtrack_index: can only be matched if medium + # or medium_index have been matched, and can be + r'((?<=\w)\.[\w]+' # - a dot followed by a string (A.1, 2.A) + r'|(?<=\d)[A-Z]+' # - a string that follows a number (1A, B2a) + r')?' + r'$', + position.upper() + ) + if match: - medium, index = match.groups() + medium, index, subindex = match.groups() + + if subindex and subindex.startswith('.'): + subindex = subindex[1:] else: self._log.debug(u'Invalid position: {0}', position) - medium = index = None - return medium or None, index or None + medium = index = subindex = None + return medium or None, index or None, subindex or None def get_track_length(self, duration): """Returns the track length in seconds for a discogs duration. diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py index 991fec935..b316cfda6 100644 --- a/beetsplug/duplicates.py +++ b/beetsplug/duplicates.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Pedro Silva. +# Copyright 2016, Pedro Silva. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,15 +15,16 @@ """List duplicate tracks or albums. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import shlex from beets.plugins import BeetsPlugin -from beets.ui import decargs, print_, vararg_callback, Subcommand, UserError -from beets.util import command_output, displayable_path, subprocess +from beets.ui import decargs, print_, Subcommand, UserError +from beets.util import command_output, displayable_path, subprocess, \ + bytestring_path, MoveOperation from beets.library import Item, Album +import six PLUGIN = 'duplicates' @@ -53,52 +55,56 @@ class DuplicatesPlugin(BeetsPlugin): self._command = Subcommand('duplicates', help=__doc__, aliases=['dup']) - self._command.parser.add_option('-c', '--count', dest='count', - action='store_true', - help='show duplicate counts') - - self._command.parser.add_option('-C', '--checksum', dest='checksum', - action='store', metavar='PROG', - help='report duplicates based on' - ' arbitrary command') - - self._command.parser.add_option('-d', '--delete', dest='delete', - action='store_true', - help='delete items from library and ' - 'disk') - - self._command.parser.add_option('-F', '--full', dest='full', - action='store_true', - help='show all versions of duplicate' - ' tracks or albums') - - self._command.parser.add_option('-s', '--strict', dest='strict', - action='store_true', - help='report duplicates only if all' - ' attributes are set') - - self._command.parser.add_option('-k', '--keys', dest='keys', - action='callback', metavar='KEY1 KEY2', - callback=vararg_callback, - help='report duplicates based on keys') - - self._command.parser.add_option('-M', '--merge', dest='merge', - action='store_true', - help='merge duplicate items') - - self._command.parser.add_option('-m', '--move', dest='move', - action='store', metavar='DEST', - help='move items to dest') - - self._command.parser.add_option('-o', '--copy', dest='copy', - action='store', metavar='DEST', - help='copy items to dest') - - self._command.parser.add_option('-t', '--tag', dest='tag', - action='store', - help='tag matched items with \'k=v\'' - ' attribute') - + self._command.parser.add_option( + u'-c', u'--count', dest='count', + action='store_true', + help=u'show duplicate counts', + ) + self._command.parser.add_option( + u'-C', u'--checksum', dest='checksum', + action='store', metavar='PROG', + help=u'report duplicates based on arbitrary command', + ) + self._command.parser.add_option( + u'-d', u'--delete', dest='delete', + action='store_true', + help=u'delete items from library and disk', + ) + self._command.parser.add_option( + u'-F', u'--full', dest='full', + action='store_true', + help=u'show all versions of duplicate tracks or albums', + ) + self._command.parser.add_option( + u'-s', u'--strict', dest='strict', + action='store_true', + help=u'report duplicates only if all attributes are set', + ) + self._command.parser.add_option( + u'-k', u'--key', dest='keys', + action='append', metavar='KEY', + help=u'report duplicates based on keys (use multiple times)', + ) + self._command.parser.add_option( + u'-M', u'--merge', dest='merge', + action='store_true', + help=u'merge duplicate items', + ) + self._command.parser.add_option( + u'-m', u'--move', dest='move', + action='store', metavar='DEST', + help=u'move items to dest', + ) + self._command.parser.add_option( + u'-o', u'--copy', dest='copy', + action='store', metavar='DEST', + help=u'copy items to dest', + ) + self._command.parser.add_option( + u'-t', u'--tag', dest='tag', + action='store', + help=u'tag matched items with \'k=v\' attribute', + ) self._command.parser.add_all_common_options() def commands(self): @@ -107,14 +113,14 @@ class DuplicatesPlugin(BeetsPlugin): self.config.set_args(opts) album = self.config['album'].get(bool) checksum = self.config['checksum'].get(str) - copy = self.config['copy'].get(str) + copy = bytestring_path(self.config['copy'].as_str()) count = self.config['count'].get(bool) delete = self.config['delete'].get(bool) fmt = self.config['format'].get(str) full = self.config['full'].get(bool) - keys = self.config['keys'].get(list) + keys = self.config['keys'].as_str_seq() merge = self.config['merge'].get(bool) - move = self.config['move'].get(str) + move = bytestring_path(self.config['move'].as_str()) path = self.config['path'].get(bool) tiebreak = self.config['tiebreak'].get(dict) strict = self.config['strict'].get(bool) @@ -130,15 +136,15 @@ class DuplicatesPlugin(BeetsPlugin): items = lib.items(decargs(args)) if path: - fmt = '$path' + fmt = u'$path' # Default format string for count mode. if count and not fmt: if album: - fmt = '$albumartist - $album' + fmt = u'$albumartist - $album' else: - fmt = '$albumartist - $album - $title' - fmt += ': {0}' + fmt = u'$albumartist - $album - $title' + fmt += u': {0}' if checksum: for i in items: @@ -164,23 +170,25 @@ class DuplicatesPlugin(BeetsPlugin): return [self._command] def _process_item(self, item, copy=False, move=False, delete=False, - tag=False, fmt=''): + tag=False, fmt=u''): """Process Item `item`. """ print_(format(item, fmt)) if copy: - item.move(basedir=copy, copy=True) + item.move(basedir=copy, operation=MoveOperation.COPY) item.store() if move: - item.move(basedir=move, copy=False) + item.move(basedir=move) item.store() if delete: item.remove(delete=True) if tag: try: k, v = tag.split('=') - except: - raise UserError('%s: can\'t parse k=v tag: %s' % (PLUGIN, tag)) + except Exception: + raise UserError( + u"{}: can't parse k=v tag: {}".format(PLUGIN, tag) + ) setattr(item, k, v) item.store() @@ -194,7 +202,7 @@ class DuplicatesPlugin(BeetsPlugin): checksum = getattr(item, key, False) if not checksum: self._log.debug(u'key {0} on item {1} not cached:' - 'computing checksum', + u'computing checksum', key, displayable_path(item.path)) try: checksum = command_output(args) @@ -207,7 +215,7 @@ class DuplicatesPlugin(BeetsPlugin): displayable_path(item.path), e) else: self._log.debug(u'key {0} on item {1} cached:' - 'not computing checksum', + u'not computing checksum', key, displayable_path(item.path)) return key, checksum @@ -224,11 +232,11 @@ class DuplicatesPlugin(BeetsPlugin): values = [v for v in values if v not in (None, '')] if strict and len(values) < len(keys): self._log.debug(u'some keys {0} on item {1} are null or empty:' - ' skipping', + u' skipping', keys, displayable_path(obj.path)) elif (not strict and not len(values)): self._log.debug(u'all keys {0} on item {1} are null or empty:' - ' skipping', + u' skipping', keys, displayable_path(obj.path)) else: key = tuple(values) @@ -245,20 +253,19 @@ class DuplicatesPlugin(BeetsPlugin): "completeness" (objects with more non-null fields come first) and Albums are ordered by their track count. """ - if tiebreak: - kind = 'items' if all(isinstance(o, Item) - for o in objs) else 'albums' + kind = 'items' if all(isinstance(o, Item) for o in objs) else 'albums' + + if tiebreak and kind in tiebreak.keys(): key = lambda x: tuple(getattr(x, k) for k in tiebreak[kind]) else: - kind = Item if all(isinstance(o, Item) for o in objs) else Album - if kind is Item: + if kind == 'items': def truthy(v): # Avoid a Unicode warning by avoiding comparison # between a bytes object and the empty Unicode # string ''. return v is not None and \ - (v != '' if isinstance(v, unicode) else True) - fields = kind.all_keys() + (v != '' if isinstance(v, six.text_type) else True) + fields = Item.all_keys() key = lambda x: sum(1 for f in fields if truthy(getattr(x, f))) else: key = lambda x: len(x.items()) @@ -271,14 +278,14 @@ class DuplicatesPlugin(BeetsPlugin): Return same number of items, with the head item modified. """ - fields = [f for sublist in Item.get_fields() for f in sublist] + fields = Item.all_keys() for f in fields: for o in objs[1:]: if getattr(objs[0], f, None) in (None, ''): value = getattr(o, f, None) if value: self._log.debug(u'key {0} on item {1} is null ' - 'or empty: setting from item {2}', + u'or empty: setting from item {2}', f, displayable_path(objs[0].path), displayable_path(o.path)) setattr(objs[0], f, value) @@ -299,12 +306,12 @@ class DuplicatesPlugin(BeetsPlugin): missing.album_id = objs[0].id missing.add(i._db) self._log.debug(u'item {0} missing from album {1}:' - ' merging from {2} into {3}', + u' merging from {2} into {3}', missing, objs[0], displayable_path(o.path), displayable_path(missing.destination())) - missing.move(copy=True) + missing.move(operation=MoveOperation.COPY) return objs def _merge(self, objs): @@ -322,7 +329,7 @@ class DuplicatesPlugin(BeetsPlugin): """Generate triples of keys, duplicate counts, and constituent objects. """ offset = 0 if full else 1 - for k, objs in self._group_by(objs, keys, strict).iteritems(): + for k, objs in self._group_by(objs, keys, strict).items(): if len(objs) > 1: objs = self._order(objs, tiebreak) if merge: diff --git a/beetsplug/echonest.py b/beetsplug/echonest.py deleted file mode 100644 index 2c8a35c69..000000000 --- a/beetsplug/echonest.py +++ /dev/null @@ -1,499 +0,0 @@ -# This file is part of beets. -# Copyright 2015, Adrian Sampson. -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. - -"""Fetch a variety of acoustic metrics from The Echo Nest. -""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) - -import time -import socket -import os -import tempfile -from string import Template -import subprocess - -from beets import util, config, plugins, ui -from beets.dbcore import types -import pyechonest -import pyechonest.song -import pyechonest.track - -# If a request at the EchoNest fails, we want to retry the request RETRIES -# times and wait between retries for RETRY_INTERVAL seconds. -RETRIES = 10 -RETRY_INTERVAL = 10 - -DEVNULL = open(os.devnull, 'wb') -ALLOWED_FORMATS = ('MP3', 'OGG', 'AAC') -UPLOAD_MAX_SIZE = 50 * 1024 * 1024 - -# FIXME: use avconv? -CONVERT_COMMAND = u'ffmpeg -i $source -y -acodec libvorbis -vn -aq 2 $dest' -TRUNCATE_COMMAND = u'ffmpeg -t 300 -i $source'\ - u'-y -acodec libvorbis -vn -aq 2 $dest' - -# Maps attribute names from echonest to their field names in beets. -# The attributes are retrieved from a songs `audio_summary`. See: -# http://echonest.github.io/pyechonest/song.html#pyechonest.song.profile -ATTRIBUTES = { - 'energy': 'energy', - 'liveness': 'liveness', - 'speechiness': 'speechiness', - 'acousticness': 'acousticness', - 'danceability': 'danceability', - 'valence': 'valence', - 'tempo': 'bpm', -} - -# Types for the flexible fields added by `ATTRIBUTES` -FIELD_TYPES = { - 'energy': types.FLOAT, - 'liveness': types.FLOAT, - 'speechiness': types.FLOAT, - 'acousticness': types.FLOAT, - 'danceability': types.FLOAT, - 'valence': types.FLOAT, -} - -MUSICAL_SCALE = ['C', 'C#', 'D', 'D#', 'E' 'F', - 'F#', 'G', 'G#', 'A', 'A#', 'B'] - - -# We also use echonest_id (song_id) and echonest_fingerprint to speed up -# lookups. -ID_KEY = 'echonest_id' -FINGERPRINT_KEY = 'echonest_fingerprint' - - -def _splitstrip(string, delim=u','): - """Split string (at commas by default) and strip whitespace from the - pieces. - """ - return [s.strip() for s in string.split(delim)] - - -def diff(item1, item2): - """Score two Item objects according to the Echo Nest numerical - fields. - """ - result = 0.0 - for attr in ATTRIBUTES.values(): - if attr == 'bpm': - # BPM (tempo) is handled specially to normalize. - continue - - try: - result += abs( - float(item1.get(attr, None)) - - float(item2.get(attr, None)) - ) - except TypeError: - result += 1.0 - - try: - bpm1 = float(item1.get('bpm', None)) - bpm2 = float(item2.get('bpm', None)) - result += abs(bpm1 - bpm2) / max(bpm1, bpm2, 1) - except TypeError: - result += 1.0 - - return result - - -def similar(lib, src_item, threshold=0.15, fmt='${difference}: ${path}'): - for item in lib.items(): - if item.path != src_item.path: - d = diff(item, src_item) - if d < threshold: - s = fmt.replace('${difference}', '{:2.2f}'.format(d)) - ui.print_(format(item, s)) - - -class EchonestMetadataPlugin(plugins.BeetsPlugin): - - item_types = FIELD_TYPES - - def __init__(self): - super(EchonestMetadataPlugin, self).__init__() - self.config.add({ - 'auto': True, - 'apikey': u'NY2KTZHQ0QDSHBAP6', - 'upload': True, - 'convert': True, - 'truncate': True, - }) - self.config.add(ATTRIBUTES) - self.config['apikey'].redact = True - - pyechonest.config.ECHO_NEST_API_KEY = \ - self.config['apikey'].get(unicode) - - if self.config['auto']: - self.import_stages = [self.imported] - - def _echofun(self, func, **kwargs): - """Wrapper for requests to the EchoNest API. Will retry up to - RETRIES times and wait between retries for RETRY_INTERVAL - seconds. - """ - for i in range(RETRIES): - try: - result = func(**kwargs) - except pyechonest.util.EchoNestAPIError as e: - if e.code == 3: - # reached access limit per minute - self._log.debug(u'rate-limited on try {0}; waiting {1} ' - u'seconds', i + 1, RETRY_INTERVAL) - time.sleep(RETRY_INTERVAL) - elif e.code == 5: - # specified identifier does not exist - # no use in trying again. - self._log.debug(u'{0}', e) - return None - else: - self._log.error(u'{0}', e.args[0][0]) - return None - except (pyechonest.util.EchoNestIOError, socket.error) as e: - self._log.warn(u'IO error: {0}', e) - time.sleep(RETRY_INTERVAL) - except Exception as e: - # there was an error analyzing the track, status: error - self._log.debug(u'{0}', e) - return None - else: - break - else: - # If we exited the loop without breaking, then we used up all - # our allotted retries. - self._log.error(u'request failed repeatedly') - return None - return result - - def _pick_song(self, songs, item): - """Helper method to pick the best matching song from a list of songs - returned by the EchoNest. Compares artist, title and duration. If - the artist and title match and the duration difference is <= 1.0 - seconds, it's considered a match. - """ - if not songs: - self._log.debug(u'no songs found') - return - - pick = None - min_dist = item.length - for song in songs: - if song.artist_name.lower() == item.artist.lower() \ - and song.title.lower() == item.title.lower(): - dist = abs(item.length - song.audio_summary['duration']) - if dist < min_dist: - min_dist = dist - pick = song - if min_dist > 2.5: - return None - return pick - - def _flatten_song(self, song): - """Given an Echo Nest song object, return a flat dict containing - attributes we care about. If song is None, return None. - """ - if not song: - return - values = dict(song.audio_summary) - values['id'] = song.id - return values - - # "Profile" (ID-based) lookup. - - def profile(self, item): - """Do a lookup on the EchoNest by MusicBrainz ID. - """ - # Use an existing Echo Nest ID. - if ID_KEY in item: - enid = item[ID_KEY] - - # Look up the Echo Nest ID based on the MBID. - else: - if not item.mb_trackid: - self._log.debug(u'no ID available') - return - mbid = 'musicbrainz:track:{0}'.format(item.mb_trackid) - track = self._echofun(pyechonest.track.track_from_id, - identifier=mbid) - if not track: - self._log.debug(u'lookup by MBID failed') - return - enid = track.song_id - - # Use the Echo Nest ID to look up the song. - songs = self._echofun(pyechonest.song.profile, ids=enid, - buckets=['id:musicbrainz', 'audio_summary']) - return self._flatten_song(self._pick_song(songs, item)) - - # "Search" (metadata-based) lookup. - - def search(self, item): - """Search the item at the EchoNest by artist and title. - """ - songs = self._echofun(pyechonest.song.search, title=item.title, - results=100, artist=item.artist, - buckets=['id:musicbrainz', 'tracks', - 'audio_summary']) - return self._flatten_song(self._pick_song(songs, item)) - - # "Analyze" (upload the audio itself) method. - - def prepare_upload(self, item): - """Truncate and convert an item's audio file so it can be - uploaded to echonest. - - Return a ``(source, tmp)`` tuple where `source` is the path to - the file to be uploaded and `tmp` is a temporary file to be - deleted after the upload or `None`. - - If conversion or truncation fails, return `None`. - """ - source = item.path - tmp = None - if item.format not in ALLOWED_FORMATS: - if self.config['convert']: - tmp = source = self.convert(source) - if not tmp: - return - - if os.stat(source).st_size > UPLOAD_MAX_SIZE: - if self.config['truncate']: - source = self.truncate(source) - if tmp is not None: - util.remove(tmp) - tmp = source - else: - return - - if source: - return source, tmp - - def convert(self, source): - """Converts an item in an unsupported media format to ogg. Config - pending. - This is stolen from Jakob Schnitzers convert plugin. - """ - fd, dest = tempfile.mkstemp(b'.ogg') - os.close(fd) - - self._log.info(u'encoding {0} to {1}', - util.displayable_path(source), - util.displayable_path(dest)) - - opts = [] - for arg in CONVERT_COMMAND.split(): - arg = arg.encode('utf-8') - opts.append(Template(arg).substitute(source=source, dest=dest)) - - # Run the command. - try: - util.command_output(opts) - except (OSError, subprocess.CalledProcessError) as exc: - self._log.debug(u'encode failed: {0}', exc) - util.remove(dest) - return - - self._log.info(u'finished encoding {0}', util.displayable_path(source)) - return dest - - def truncate(self, source): - """Truncates an item to a size less than UPLOAD_MAX_SIZE.""" - fd, dest = tempfile.mkstemp(u'.ogg') - os.close(fd) - - self._log.info(u'truncating {0} to {1}', - util.displayable_path(source), - util.displayable_path(dest)) - - opts = [] - for arg in TRUNCATE_COMMAND.split(): - arg = arg.encode('utf-8') - opts.append(Template(arg).substitute(source=source, dest=dest)) - - # Run the command. - try: - util.command_output(opts) - except (OSError, subprocess.CalledProcessError) as exc: - self._log.debug(u'truncate failed: {0}', exc) - util.remove(dest) - return - - self._log.info(u'truncate encoding {0}', util.displayable_path(source)) - return dest - - def analyze(self, item): - """Upload the item to the EchoNest for analysis. May require to - convert the item to a supported media format. - """ - prepared = self.prepare_upload(item) - if not prepared: - self._log.debug(u'could not prepare file for upload') - return - - source, tmp = prepared - self._log.info(u'uploading file, please be patient') - track = self._echofun(pyechonest.track.track_from_filename, - filename=source) - if tmp is not None: - util.remove(tmp) - - if not track: - self._log.debug(u'failed to upload file') - return - - # Sometimes we have a track but no song. I guess this happens for - # new / unverified songs. We need to "extract" the audio_summary - # from the track object manually. I don't know why the - # pyechonest API handles tracks (merge audio_summary to __dict__) - # and songs (keep audio_summary in an extra attribute) - # differently. - # Maybe a patch for pyechonest could help? - - # First get the (limited) metadata from the track in case - # there's no associated song. - from_track = {} - for key in ATTRIBUTES: - try: - from_track[key] = getattr(track, key) - except AttributeError: - pass - from_track['duration'] = track.duration - - # Try to look up a song for the full metadata. - try: - song_id = track.song_id - except AttributeError: - return from_track - songs = self._echofun(pyechonest.song.profile, - ids=[song_id], track_ids=[track.id], - buckets=['audio_summary']) - if songs: - pick = self._pick_song(songs, item) - if pick: - return self._flatten_song(pick) - return from_track # Fall back to track metadata. - - # Shared top-level logic. - - def fetch_song(self, item): - """Try all methods to get a matching song object from the - EchoNest. If no method succeeds, return None. - """ - # There are four different ways to get a song. Each method is a - # callable that takes the Item as an argument. - methods = [self.profile, self.search] - if self.config['upload']: - methods.append(self.analyze) - - # Try each method in turn. - for method in methods: - song = method(item) - if song: - self._log.debug(u'got song through {0}: {1} [{2}]', - method.__name__, - item, - song.get('duration'), - ) - return song - - def apply_metadata(self, item, values, write=False): - """Copy the metadata from the dictionary of song information to - the item. - """ - # Update each field. - for k, v in values.iteritems(): - if k in ATTRIBUTES: - field = ATTRIBUTES[k] - self._log.debug(u'metadata: {0} = {1}', field, v) - if field == 'bpm': - item[field] = int(v) - else: - item[field] = v - if 'key' in values and 'mode' in values: - key = MUSICAL_SCALE[values['key'] - 1] - if values['mode'] == 0: # Minor key - key += 'm' - item['initial_key'] = key - if 'id' in values: - enid = values['id'] - self._log.debug(u'metadata: {0} = {1}', ID_KEY, enid) - item[ID_KEY] = enid - - # Write and save. - if write: - item.try_write() - item.store() - - # Automatic (on-import) metadata fetching. - - def imported(self, session, task): - """Import pipeline stage. - """ - for item in task.imported_items(): - song = self.fetch_song(item) - if song: - self.apply_metadata(item, song) - - # Explicit command invocation. - - def requires_update(self, item): - """Check if this item requires an update from the EchoNest (its - data is missing). - """ - for field in ATTRIBUTES.values(): - if not item.get(field): - return True - self._log.info(u'no update required') - return False - - def commands(self): - fetch_cmd = ui.Subcommand('echonest', - help='Fetch metadata from the EchoNest') - fetch_cmd.parser.add_option( - '-f', '--force', dest='force', action='store_true', default=False, - help='(re-)download information from the EchoNest' - ) - - def fetch_func(lib, opts, args): - self.config.set_args(opts) - write = config['import']['write'].get(bool) - for item in lib.items(ui.decargs(args)): - self._log.info(u'{0}', item) - if self.config['force'] or self.requires_update(item): - song = self.fetch_song(item) - if song: - self.apply_metadata(item, song, write) - - fetch_cmd.func = fetch_func - - sim_cmd = ui.Subcommand('echosim', help='show related files') - sim_cmd.parser.add_option( - '-t', '--threshold', dest='threshold', action='store', - type='float', default=0.15, help='Set difference threshold' - ) - sim_cmd.parser.add_format_option() - - def sim_func(lib, opts, args): - self.config.set_args(opts) - for item in lib.items(ui.decargs(args)): - similar(lib, item, opts.threshold, opts.format) - - sim_cmd.func = sim_func - - return [fetch_cmd, sim_cmd] diff --git a/beetsplug/edit.py b/beetsplug/edit.py new file mode 100644 index 000000000..631a1b584 --- /dev/null +++ b/beetsplug/edit.py @@ -0,0 +1,409 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016 +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Open metadata information in a text editor to let the user edit it. +""" +from __future__ import division, absolute_import, print_function + +from beets import plugins +from beets import util +from beets import ui +from beets.dbcore import types +from beets.importer import action +from beets.ui.commands import _do_query, PromptChoice +import codecs +import subprocess +import yaml +from tempfile import NamedTemporaryFile +import os +import six + + +# These "safe" types can avoid the format/parse cycle that most fields go +# through: they are safe to edit with native YAML types. +SAFE_TYPES = (types.Float, types.Integer, types.Boolean) + + +class ParseError(Exception): + """The modified file is unreadable. The user should be offered a chance to + fix the error. + """ + + +def edit(filename, log): + """Open `filename` in a text editor. + """ + cmd = util.shlex_split(util.editor_command()) + cmd.append(filename) + log.debug(u'invoking editor command: {!r}', cmd) + try: + subprocess.call(cmd) + except OSError as exc: + raise ui.UserError(u'could not run editor command {!r}: {}'.format( + cmd[0], exc + )) + + +def dump(arg): + """Dump a sequence of dictionaries as YAML for editing. + """ + return yaml.safe_dump_all( + arg, + allow_unicode=True, + default_flow_style=False, + ) + + +def load(s): + """Read a sequence of YAML documents back to a list of dictionaries + with string keys. + + Can raise a `ParseError`. + """ + try: + out = [] + for d in yaml.load_all(s): + if not isinstance(d, dict): + raise ParseError( + u'each entry must be a dictionary; found {}'.format( + type(d).__name__ + ) + ) + + # Convert all keys to strings. They started out as strings, + # but the user may have inadvertently messed this up. + out.append({six.text_type(k): v for k, v in d.items()}) + + except yaml.YAMLError as e: + raise ParseError(u'invalid YAML: {}'.format(e)) + return out + + +def _safe_value(obj, key, value): + """Check whether the `value` is safe to represent in YAML and trust as + returned from parsed YAML. + + This ensures that values do not change their type when the user edits their + YAML representation. + """ + typ = obj._type(key) + return isinstance(typ, SAFE_TYPES) and isinstance(value, typ.model_type) + + +def flatten(obj, fields): + """Represent `obj`, a `dbcore.Model` object, as a dictionary for + serialization. Only include the given `fields` if provided; + otherwise, include everything. + + The resulting dictionary's keys are strings and the values are + safely YAML-serializable types. + """ + # Format each value. + d = {} + for key in obj.keys(): + value = obj[key] + if _safe_value(obj, key, value): + # A safe value that is faithfully representable in YAML. + d[key] = value + else: + # A value that should be edited as a string. + d[key] = obj.formatted()[key] + + # Possibly filter field names. + if fields: + return {k: v for k, v in d.items() if k in fields} + else: + return d + + +def apply_(obj, data): + """Set the fields of a `dbcore.Model` object according to a + dictionary. + + This is the opposite of `flatten`. The `data` dictionary should have + strings as values. + """ + for key, value in data.items(): + if _safe_value(obj, key, value): + # A safe value *stayed* represented as a safe type. Assign it + # directly. + obj[key] = value + else: + # Either the field was stringified originally or the user changed + # it from a safe type to an unsafe one. Parse it as a string. + obj.set_parse(key, six.text_type(value)) + + +class EditPlugin(plugins.BeetsPlugin): + + def __init__(self): + super(EditPlugin, self).__init__() + + self.config.add({ + # The default fields to edit. + 'albumfields': 'album albumartist', + 'itemfields': 'track title artist album', + + # Silently ignore any changes to these fields. + 'ignore_fields': 'id path', + }) + + self.register_listener('before_choose_candidate', + self.before_choose_candidate_listener) + + def commands(self): + edit_command = ui.Subcommand( + 'edit', + help=u'interactively edit metadata' + ) + edit_command.parser.add_option( + u'-f', u'--field', + metavar='FIELD', + action='append', + help=u'edit this field also', + ) + edit_command.parser.add_option( + u'--all', + action='store_true', dest='all', + help=u'edit all fields', + ) + edit_command.parser.add_album_option() + edit_command.func = self._edit_command + return [edit_command] + + def _edit_command(self, lib, opts, args): + """The CLI command function for the `beet edit` command. + """ + # Get the objects to edit. + query = ui.decargs(args) + items, albums = _do_query(lib, query, opts.album, False) + objs = albums if opts.album else items + if not objs: + ui.print_(u'Nothing to edit.') + return + + # Get the fields to edit. + if opts.all: + fields = None + else: + fields = self._get_fields(opts.album, opts.field) + self.edit(opts.album, objs, fields) + + def _get_fields(self, album, extra): + """Get the set of fields to edit. + """ + # Start with the configured base fields. + if album: + fields = self.config['albumfields'].as_str_seq() + else: + fields = self.config['itemfields'].as_str_seq() + + # Add the requested extra fields. + if extra: + fields += extra + + # Ensure we always have the `id` field for identification. + fields.append('id') + + return set(fields) + + def edit(self, album, objs, fields): + """The core editor function. + + - `album`: A flag indicating whether we're editing Items or Albums. + - `objs`: The `Item`s or `Album`s to edit. + - `fields`: The set of field names to edit (or None to edit + everything). + """ + # Present the YAML to the user and let her change it. + success = self.edit_objects(objs, fields) + + # Save the new data. + if success: + self.save_changes(objs) + + def edit_objects(self, objs, fields): + """Dump a set of Model objects to a file as text, ask the user + to edit it, and apply any changes to the objects. + + Return a boolean indicating whether the edit succeeded. + """ + # Get the content to edit as raw data structures. + old_data = [flatten(o, fields) for o in objs] + + # Set up a temporary file with the initial data for editing. + if six.PY2: + new = NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) + else: + new = NamedTemporaryFile(mode='w', suffix='.yaml', delete=False, + encoding='utf-8') + old_str = dump(old_data) + new.write(old_str) + if six.PY2: + old_str = old_str.decode('utf-8') + new.close() + + # Loop until we have parseable data and the user confirms. + try: + while True: + # Ask the user to edit the data. + edit(new.name, self._log) + + # Read the data back after editing and check whether anything + # changed. + with codecs.open(new.name, encoding='utf-8') as f: + new_str = f.read() + if new_str == old_str: + ui.print_(u"No changes; aborting.") + return False + + # Parse the updated data. + try: + new_data = load(new_str) + except ParseError as e: + ui.print_(u"Could not read data: {}".format(e)) + if ui.input_yn(u"Edit again to fix? (Y/n)", True): + continue + else: + return False + + # Show the changes. + # If the objects are not on the DB yet, we need a copy of their + # original state for show_model_changes. + objs_old = [obj.copy() if obj.id < 0 else None + for obj in objs] + self.apply_data(objs, old_data, new_data) + changed = False + for obj, obj_old in zip(objs, objs_old): + changed |= ui.show_model_changes(obj, obj_old) + if not changed: + ui.print_(u'No changes to apply.') + return False + + # Confirm the changes. + choice = ui.input_options( + (u'continue Editing', u'apply', u'cancel') + ) + if choice == u'a': # Apply. + return True + elif choice == u'c': # Cancel. + return False + elif choice == u'e': # Keep editing. + # Reset the temporary changes to the objects. I we have a + # copy from above, use that, else reload from the database. + objs = [(old_obj or obj) + for old_obj, obj in zip(objs_old, objs)] + for obj in objs: + if not obj.id < 0: + obj.load() + continue + + # Remove the temporary file before returning. + finally: + os.remove(new.name) + + def apply_data(self, objs, old_data, new_data): + """Take potentially-updated data and apply it to a set of Model + objects. + + The objects are not written back to the database, so the changes + are temporary. + """ + if len(old_data) != len(new_data): + self._log.warning(u'number of objects changed from {} to {}', + len(old_data), len(new_data)) + + obj_by_id = {o.id: o for o in objs} + ignore_fields = self.config['ignore_fields'].as_str_seq() + for old_dict, new_dict in zip(old_data, new_data): + # Prohibit any changes to forbidden fields to avoid + # clobbering `id` and such by mistake. + forbidden = False + for key in ignore_fields: + if old_dict.get(key) != new_dict.get(key): + self._log.warning(u'ignoring object whose {} changed', key) + forbidden = True + break + if forbidden: + continue + + id_ = int(old_dict['id']) + apply_(obj_by_id[id_], new_dict) + + def save_changes(self, objs): + """Save a list of updated Model objects to the database. + """ + # Save to the database and possibly write tags. + for ob in objs: + if ob._dirty: + self._log.debug(u'saving changes to {}', ob) + ob.try_sync(ui.should_write(), ui.should_move()) + + # Methods for interactive importer execution. + + def before_choose_candidate_listener(self, session, task): + """Append an "Edit" choice and an "edit Candidates" choice (if + there are candidates) to the interactive importer prompt. + """ + choices = [PromptChoice('d', 'eDit', self.importer_edit)] + if task.candidates: + choices.append(PromptChoice('c', 'edit Candidates', + self.importer_edit_candidate)) + + return choices + + def importer_edit(self, session, task): + """Callback for invoking the functionality during an interactive + import session on the *original* item tags. + """ + # Assign negative temporary ids to Items that are not in the database + # yet. By using negative values, no clash with items in the database + # can occur. + for i, obj in enumerate(task.items, start=1): + # The importer may set the id to None when re-importing albums. + if not obj._db or obj.id is None: + obj.id = -i + + # Present the YAML to the user and let her change it. + fields = self._get_fields(album=False, extra=[]) + success = self.edit_objects(task.items, fields) + + # Remove temporary ids. + for obj in task.items: + if obj.id < 0: + obj.id = None + + # Save the new data. + if success: + # Return action.RETAG, which makes the importer write the tags + # to the files if needed without re-applying metadata. + return action.RETAG + else: + # Edit cancelled / no edits made. Revert changes. + for obj in task.items: + obj.read() + + def importer_edit_candidate(self, session, task): + """Callback for invoking the functionality during an interactive + import session on a *candidate*. The candidate's metadata is + applied to the original items. + """ + # Prompt the user for a candidate. + sel = ui.input_options([], numrange=(1, len(task.candidates))) + # Force applying the candidate on the items. + task.match = task.candidates[sel - 1] + task.apply_metadata() + + return self.importer_edit(session, task) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 10b30af0f..afe8f86fa 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -13,20 +14,41 @@ # included in all copies or substantial portions of the Software. """Allows beets to embed album art into file metadata.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import os.path from beets.plugins import BeetsPlugin from beets import ui -from beets.ui import decargs +from beets.ui import print_, decargs from beets.util import syspath, normpath, displayable_path, bytestring_path from beets.util.artresizer import ArtResizer from beets import config from beets import art +def _confirm(objs, album): + """Show the list of affected objects (items or albums) and confirm + that the user wants to modify their artwork. + + `album` is a Boolean indicating whether these are albums (as opposed + to items). + """ + noun = u'album' if album else u'file' + prompt = u'Modify artwork for {} {}{} (Y/n)?'.format( + len(objs), + noun, + u's' if len(objs) > 1 else u'' + ) + + # Show all the items or albums. + for obj in objs: + print_(format(obj)) + + # Confirm with user. + return ui.input_yn(prompt) + + class EmbedCoverArtPlugin(BeetsPlugin): """Allows albumart to be embedded into the actual files. """ @@ -55,15 +77,17 @@ class EmbedCoverArtPlugin(BeetsPlugin): def commands(self): # Embed command. embed_cmd = ui.Subcommand( - 'embedart', help='embed image files into file metadata' + 'embedart', help=u'embed image files into file metadata' ) embed_cmd.parser.add_option( - '-f', '--file', metavar='PATH', help='the image file to embed' + u'-f', u'--file', metavar='PATH', help=u'the image file to embed' + ) + embed_cmd.parser.add_option( + u"-y", u"--yes", action="store_true", help=u"skip confirmation" ) maxwidth = self.config['maxwidth'].get(int) compare_threshold = self.config['compare_threshold'].get(int) ifempty = self.config['ifempty'].get(bool) - remove_art_file = self.config['remove_art_file'].get(bool) def embed_func(lib, opts, args): if opts.file: @@ -72,36 +96,47 @@ class EmbedCoverArtPlugin(BeetsPlugin): raise ui.UserError(u'image file {0} not found'.format( displayable_path(imagepath) )) - for item in lib.items(decargs(args)): + + items = lib.items(decargs(args)) + + # Confirm with user. + if not opts.yes and not _confirm(items, not opts.file): + return + + for item in items: art.embed_item(self._log, item, imagepath, maxwidth, None, compare_threshold, ifempty) else: - for album in lib.albums(decargs(args)): + albums = lib.albums(decargs(args)) + + # Confirm with user. + if not opts.yes and not _confirm(albums, not opts.file): + return + + for album in albums: art.embed_album(self._log, album, maxwidth, False, compare_threshold, ifempty) - - if remove_art_file and album.artpath is not None: - if os.path.isfile(album.artpath): - self._log.debug(u'Removing album art file ' - u'for {0}', album) - os.remove(album.artpath) - album.artpath = None - album.store() + self.remove_artfile(album) embed_cmd.func = embed_func # Extract command. - extract_cmd = ui.Subcommand('extractart', - help='extract an image from file metadata') - extract_cmd.parser.add_option('-o', dest='outpath', - help='image output file') - extract_cmd.parser.add_option('-n', dest='filename', - help='image filename to create for all ' - 'matched albums') - extract_cmd.parser.add_option('-a', dest='associate', - action='store_true', - help='associate the extracted images ' - 'with the album') + extract_cmd = ui.Subcommand( + 'extractart', + help=u'extract an image from file metadata', + ) + extract_cmd.parser.add_option( + u'-o', dest='outpath', + help=u'image output file', + ) + extract_cmd.parser.add_option( + u'-n', dest='filename', + help=u'image filename to create for all matched albums', + ) + extract_cmd.parser.add_option( + '-a', dest='associate', action='store_true', + help='associate the extracted images with the album', + ) def extract_func(lib, opts, args): if opts.outpath: @@ -110,9 +145,9 @@ class EmbedCoverArtPlugin(BeetsPlugin): else: filename = bytestring_path(opts.filename or config['art_filename'].get()) - if os.path.dirname(filename) != '': - self._log.error(u"Only specify a name rather than a path " - u"for -n") + if os.path.dirname(filename) != b'': + self._log.error( + u"Only specify a name rather than a path for -n") return for album in lib.albums(decargs(args)): artpath = normpath(os.path.join(album.path, filename)) @@ -124,10 +159,19 @@ class EmbedCoverArtPlugin(BeetsPlugin): extract_cmd.func = extract_func # Clear command. - clear_cmd = ui.Subcommand('clearart', - help='remove images from file metadata') + clear_cmd = ui.Subcommand( + 'clearart', + help=u'remove images from file metadata', + ) + clear_cmd.parser.add_option( + u"-y", u"--yes", action="store_true", help=u"skip confirmation" + ) def clear_func(lib, opts, args): + items = lib.items(decargs(args)) + # Confirm with user. + if not opts.yes and not _confirm(items, False): + return art.clear(self._log, lib, decargs(args)) clear_cmd.func = clear_func @@ -136,8 +180,20 @@ class EmbedCoverArtPlugin(BeetsPlugin): def process_album(self, album): """Automatically embed art after art has been set """ - if self.config['auto'] and config['import']['write']: + if self.config['auto'] and ui.should_write(): max_width = self.config['maxwidth'].get(int) art.embed_album(self._log, album, max_width, True, self.config['compare_threshold'].get(int), self.config['ifempty'].get(bool)) + self.remove_artfile(album) + + def remove_artfile(self, album): + """Possibly delete the album art file for an album (if the + appropriate configuration option is enabled. + """ + if self.config['remove_art_file'] and album.artpath: + if os.path.isfile(album.artpath): + self._log.debug(u'Removing album art file for {0}', album) + os.remove(album.artpath) + album.artpath = None + album.store() diff --git a/beetsplug/embyupdate.py b/beetsplug/embyupdate.py new file mode 100644 index 000000000..5c731954b --- /dev/null +++ b/beetsplug/embyupdate.py @@ -0,0 +1,210 @@ +# -*- coding: utf-8 -*- + +"""Updates the Emby Library whenever the beets library is changed. + + emby: + host: localhost + port: 8096 + username: user + apikey: apikey + password: password +""" +from __future__ import division, absolute_import, print_function + +import hashlib +import requests + +from six.moves.urllib.parse import urlencode +from six.moves.urllib.parse import urljoin, parse_qs, urlsplit, urlunsplit + +from beets import config +from beets.plugins import BeetsPlugin + + +def api_url(host, port, endpoint): + """Returns a joined url. + + Takes host, port and endpoint and generates a valid emby API url. + + :param host: Hostname of the emby server + :param port: Portnumber of the emby server + :param endpoint: API endpoint + :type host: str + :type port: int + :type endpoint: str + :returns: Full API url + :rtype: str + """ + # check if http or https is defined as host and create hostname + hostname_list = [host] + if host.startswith('http://') or host.startswith('https://'): + hostname = ''.join(hostname_list) + else: + hostname_list.insert(0, 'http://') + hostname = ''.join(hostname_list) + + joined = urljoin( + '{hostname}:{port}'.format( + hostname=hostname, + port=port + ), + endpoint + ) + + scheme, netloc, path, query_string, fragment = urlsplit(joined) + query_params = parse_qs(query_string) + + query_params['format'] = ['json'] + new_query_string = urlencode(query_params, doseq=True) + + return urlunsplit((scheme, netloc, path, new_query_string, fragment)) + + +def password_data(username, password): + """Returns a dict with username and its encoded password. + + :param username: Emby username + :param password: Emby password + :type username: str + :type password: str + :returns: Dictionary with username and encoded password + :rtype: dict + """ + return { + 'username': username, + 'password': hashlib.sha1(password.encode('utf-8')).hexdigest(), + 'passwordMd5': hashlib.md5(password.encode('utf-8')).hexdigest() + } + + +def create_headers(user_id, token=None): + """Return header dict that is needed to talk to the Emby API. + + :param user_id: Emby user ID + :param token: Authentication token for Emby + :type user_id: str + :type token: str + :returns: Headers for requests + :rtype: dict + """ + headers = {} + + authorization = ( + 'MediaBrowser UserId="{user_id}", ' + 'Client="other", ' + 'Device="beets", ' + 'DeviceId="beets", ' + 'Version="0.0.0"' + ).format(user_id=user_id) + + headers['x-emby-authorization'] = authorization + + if token: + headers['x-mediabrowser-token'] = token + + return headers + + +def get_token(host, port, headers, auth_data): + """Return token for a user. + + :param host: Emby host + :param port: Emby port + :param headers: Headers for requests + :param auth_data: Username and encoded password for authentication + :type host: str + :type port: int + :type headers: dict + :type auth_data: dict + :returns: Access Token + :rtype: str + """ + url = api_url(host, port, '/Users/AuthenticateByName') + r = requests.post(url, headers=headers, data=auth_data) + + return r.json().get('AccessToken') + + +def get_user(host, port, username): + """Return user dict from server or None if there is no user. + + :param host: Emby host + :param port: Emby port + :username: Username + :type host: str + :type port: int + :type username: str + :returns: Matched Users + :rtype: list + """ + url = api_url(host, port, '/Users/Public') + r = requests.get(url) + user = [i for i in r.json() if i['Name'] == username] + + return user + + +class EmbyUpdate(BeetsPlugin): + def __init__(self): + super(EmbyUpdate, self).__init__() + + # Adding defaults. + config['emby'].add({ + u'host': u'http://localhost', + u'port': 8096, + u'apikey': None, + u'password': None, + }) + + self.register_listener('database_change', self.listen_for_db_change) + + def listen_for_db_change(self, lib, model): + """Listens for beets db change and register the update for the end. + """ + self.register_listener('cli_exit', self.update) + + def update(self, lib): + """When the client exists try to send refresh request to Emby. + """ + self._log.info(u'Updating Emby library...') + + host = config['emby']['host'].get() + port = config['emby']['port'].get() + username = config['emby']['username'].get() + password = config['emby']['password'].get() + token = config['emby']['apikey'].get() + + # Check if at least a apikey or password is given. + if not any([password, token]): + self._log.warning(u'Provide at least Emby password or apikey.') + return + + # Get user information from the Emby API. + user = get_user(host, port, username) + if not user: + self._log.warning(u'User {0} could not be found.'.format(username)) + return + + if not token: + # Create Authentication data and headers. + auth_data = password_data(username, password) + headers = create_headers(user[0]['Id']) + + # Get authentication token. + token = get_token(host, port, headers, auth_data) + if not token: + self._log.warning( + u'Could not get token for user {0}', username + ) + return + + # Recreate headers with a token. + headers = create_headers(user[0]['Id'], token=token) + + # Trigger the Update. + url = api_url(host, port, '/Library/Refresh') + r = requests.post(url, headers=headers) + if r.status_code != 204: + self._log.warning(u'Update could not be triggered') + else: + self._log.info(u'Update triggered.') diff --git a/beetsplug/export.py b/beetsplug/export.py new file mode 100644 index 000000000..641b9fefc --- /dev/null +++ b/beetsplug/export.py @@ -0,0 +1,151 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Exports data from beets +""" + +from __future__ import division, absolute_import, print_function + +import sys +import json +import codecs + +from datetime import datetime, date +from beets.plugins import BeetsPlugin +from beets import ui +from beets import mediafile +from beetsplug.info import make_key_filter, library_data, tag_data + + +class ExportEncoder(json.JSONEncoder): + """Deals with dates because JSON doesn't have a standard""" + def default(self, o): + if isinstance(o, datetime) or isinstance(o, date): + return o.isoformat() + return json.JSONEncoder.default(self, o) + + +class ExportPlugin(BeetsPlugin): + + def __init__(self): + super(ExportPlugin, self).__init__() + + self.config.add({ + 'default_format': 'json', + 'json': { + # json module formatting options + 'formatting': { + 'ensure_ascii': False, + 'indent': 4, + 'separators': (',', ': '), + 'sort_keys': True + } + }, + # TODO: Use something like the edit plugin + # 'item_fields': [] + }) + + def commands(self): + # TODO: Add option to use albums + + cmd = ui.Subcommand('export', help=u'export data from beets') + cmd.func = self.run + cmd.parser.add_option( + u'-l', u'--library', action='store_true', + help=u'show library fields instead of tags', + ) + cmd.parser.add_option( + u'--append', action='store_true', default=False, + help=u'if should append data to the file', + ) + cmd.parser.add_option( + u'-i', u'--include-keys', default=[], + action='append', dest='included_keys', + help=u'comma separated list of keys to show', + ) + cmd.parser.add_option( + u'-o', u'--output', + help=u'path for the output file. If not given, will print the data' + ) + return [cmd] + + def run(self, lib, opts, args): + + file_path = opts.output + file_format = self.config['default_format'].get(str) + file_mode = 'a' if opts.append else 'w' + format_options = self.config[file_format]['formatting'].get(dict) + + export_format = ExportFormat.factory( + file_format, **{ + 'file_path': file_path, + 'file_mode': file_mode + } + ) + + items = [] + data_collector = library_data if opts.library else tag_data + + included_keys = [] + for keys in opts.included_keys: + included_keys.extend(keys.split(',')) + key_filter = make_key_filter(included_keys) + + for data_emitter in data_collector(lib, ui.decargs(args)): + try: + data, item = data_emitter() + except (mediafile.UnreadableFileError, IOError) as ex: + self._log.error(u'cannot read file: {0}', ex) + continue + + data = key_filter(data) + items += [data] + + export_format.export(items, **format_options) + + +class ExportFormat(object): + """The output format type""" + + @classmethod + def factory(cls, type, **kwargs): + if type == "json": + if kwargs['file_path']: + return JsonFileFormat(**kwargs) + else: + return JsonPrintFormat() + raise NotImplementedError() + + def export(self, data, **kwargs): + raise NotImplementedError() + + +class JsonPrintFormat(ExportFormat): + """Outputs to the console""" + + def export(self, data, **kwargs): + json.dump(data, sys.stdout, cls=ExportEncoder, **kwargs) + + +class JsonFileFormat(ExportFormat): + """Saves in a json file""" + + def __init__(self, file_path, file_mode=u'w', encoding=u'utf-8'): + self.path = file_path + self.mode = file_mode + self.encoding = encoding + + def export(self, data, **kwargs): + with codecs.open(self.path, self.mode, self.encoding) as f: + json.dump(data, f, cls=ExportEncoder, **kwargs) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index b807891e0..0e106694d 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,8 +15,7 @@ """Fetches album art. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from contextlib import closing import os @@ -29,7 +29,11 @@ from beets import importer from beets import ui from beets import util from beets import config +from beets.mediafile import image_mime_type from beets.util.artresizer import ArtResizer +from beets.util import confit +from beets.util import syspath, bytestring_path, py3_path +import six try: import itunes @@ -37,9 +41,106 @@ try: except ImportError: HAVE_ITUNES = False -IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg'] -CONTENT_TYPES = ('image/jpeg', 'image/png') -DOWNLOAD_EXTENSION = '.jpg' +CONTENT_TYPES = { + 'image/jpeg': [b'jpg', b'jpeg'], + 'image/png': [b'png'] +} +IMAGE_EXTENSIONS = [ext for exts in CONTENT_TYPES.values() for ext in exts] + + +class Candidate(object): + """Holds information about a matching artwork, deals with validation of + dimension restrictions and resizing. + """ + CANDIDATE_BAD = 0 + CANDIDATE_EXACT = 1 + CANDIDATE_DOWNSCALE = 2 + + MATCH_EXACT = 0 + MATCH_FALLBACK = 1 + + def __init__(self, log, path=None, url=None, source=u'', + match=None, size=None): + self._log = log + self.path = path + self.url = url + self.source = source + self.check = None + self.match = match + self.size = size + + def _validate(self, plugin): + """Determine whether the candidate artwork is valid based on + its dimensions (width and ratio). + + Return `CANDIDATE_BAD` if the file is unusable. + Return `CANDIDATE_EXACT` if the file is usable as-is. + Return `CANDIDATE_DOWNSCALE` if the file must be resized. + """ + if not self.path: + return self.CANDIDATE_BAD + + if not (plugin.enforce_ratio or plugin.minwidth or plugin.maxwidth): + return self.CANDIDATE_EXACT + + # get_size returns None if no local imaging backend is available + if not self.size: + self.size = ArtResizer.shared.get_size(self.path) + self._log.debug(u'image size: {}', self.size) + + if not self.size: + self._log.warning(u'Could not get size of image (please see ' + u'documentation for dependencies). ' + u'The configuration options `minwidth` and ' + u'`enforce_ratio` may be violated.') + return self.CANDIDATE_EXACT + + short_edge = min(self.size) + long_edge = max(self.size) + + # Check minimum size. + if plugin.minwidth and self.size[0] < plugin.minwidth: + self._log.debug(u'image too small ({} < {})', + self.size[0], plugin.minwidth) + return self.CANDIDATE_BAD + + # Check aspect ratio. + edge_diff = long_edge - short_edge + if plugin.enforce_ratio: + if plugin.margin_px: + if edge_diff > plugin.margin_px: + self._log.debug(u'image is not close enough to being ' + u'square, ({} - {} > {})', + long_edge, short_edge, plugin.margin_px) + return self.CANDIDATE_BAD + elif plugin.margin_percent: + margin_px = plugin.margin_percent * long_edge + if edge_diff > margin_px: + self._log.debug(u'image is not close enough to being ' + u'square, ({} - {} > {})', + long_edge, short_edge, margin_px) + return self.CANDIDATE_BAD + elif edge_diff: + # also reached for margin_px == 0 and margin_percent == 0.0 + self._log.debug(u'image is not square ({} != {})', + self.size[0], self.size[1]) + return self.CANDIDATE_BAD + + # Check maximum size. + if plugin.maxwidth and self.size[0] > plugin.maxwidth: + self._log.debug(u'image needs resizing ({} > {})', + self.size[0], plugin.maxwidth) + return self.CANDIDATE_DOWNSCALE + + return self.CANDIDATE_EXACT + + def validate(self, plugin): + self.check = self._validate(plugin) + return self.check + + def resize(self, plugin): + if plugin.maxwidth and self.check == self.CANDIDATE_DOWNSCALE: + self.path = ArtResizer.shared.resize(plugin.maxwidth, self.path) def _logged_get(log, *args, **kwargs): @@ -91,46 +192,148 @@ class RequestMixin(object): # ART SOURCES ################################################################ class ArtSource(RequestMixin): - def __init__(self, log): - self._log = log + VALID_MATCHING_CRITERIA = ['default'] - def get(self, album): + def __init__(self, log, config, match_by=None): + self._log = log + self._config = config + self.match_by = match_by or self.VALID_MATCHING_CRITERIA + + def get(self, album, plugin, paths): + raise NotImplementedError() + + def _candidate(self, **kwargs): + return Candidate(source=self, log=self._log, **kwargs) + + def fetch_image(self, candidate, plugin): raise NotImplementedError() -class CoverArtArchive(ArtSource): - """Cover Art Archive""" - URL = 'http://coverartarchive.org/release/{mbid}/front' - GROUP_URL = 'http://coverartarchive.org/release-group/{mbid}/front' +class LocalArtSource(ArtSource): + IS_LOCAL = True + LOC_STR = u'local' - def get(self, album): + def fetch_image(self, candidate, plugin): + pass + + +class RemoteArtSource(ArtSource): + IS_LOCAL = False + LOC_STR = u'remote' + + def fetch_image(self, candidate, plugin): + """Downloads an image from a URL and checks whether it seems to + actually be an image. If so, returns a path to the downloaded image. + Otherwise, returns None. + """ + if plugin.maxwidth: + candidate.url = ArtResizer.shared.proxy_url(plugin.maxwidth, + candidate.url) + try: + with closing(self.request(candidate.url, stream=True, + message=u'downloading image')) as resp: + ct = resp.headers.get('Content-Type', None) + + # Download the image to a temporary file. As some servers + # (notably fanart.tv) have proven to return wrong Content-Types + # when images were uploaded with a bad file extension, do not + # rely on it. Instead validate the type using the file magic + # and only then determine the extension. + data = resp.iter_content(chunk_size=1024) + header = b'' + for chunk in data: + header += chunk + if len(header) >= 32: + # The imghdr module will only read 32 bytes, and our + # own additions in mediafile even less. + break + else: + # server didn't return enough data, i.e. corrupt image + return + + real_ct = image_mime_type(header) + if real_ct is None: + # detection by file magic failed, fall back to the + # server-supplied Content-Type + # Is our type detection failsafe enough to drop this? + real_ct = ct + + if real_ct not in CONTENT_TYPES: + self._log.debug(u'not a supported image: {}', + real_ct or u'unknown content type') + return + + ext = b'.' + CONTENT_TYPES[real_ct][0] + + if real_ct != ct: + self._log.warning(u'Server specified {}, but returned a ' + u'{} image. Correcting the extension ' + u'to {}', + ct, real_ct, ext) + + suffix = py3_path(ext) + with NamedTemporaryFile(suffix=suffix, delete=False) as fh: + # write the first already loaded part of the image + fh.write(header) + # download the remaining part of the image + for chunk in data: + fh.write(chunk) + self._log.debug(u'downloaded art to: {0}', + util.displayable_path(fh.name)) + candidate.path = util.bytestring_path(fh.name) + return + + except (IOError, requests.RequestException, TypeError) as exc: + # Handling TypeError works around a urllib3 bug: + # https://github.com/shazow/urllib3/issues/556 + self._log.debug(u'error fetching art: {}', exc) + return + + +class CoverArtArchive(RemoteArtSource): + NAME = u"Cover Art Archive" + VALID_MATCHING_CRITERIA = ['release', 'releasegroup'] + + if util.SNI_SUPPORTED: + URL = 'https://coverartarchive.org/release/{mbid}/front' + GROUP_URL = 'https://coverartarchive.org/release-group/{mbid}/front' + else: + URL = 'http://coverartarchive.org/release/{mbid}/front' + GROUP_URL = 'http://coverartarchive.org/release-group/{mbid}/front' + + def get(self, album, plugin, paths): """Return the Cover Art Archive and Cover Art Archive release group URLs using album MusicBrainz release ID and release group ID. """ - if album.mb_albumid: - yield self.URL.format(mbid=album.mb_albumid) - if album.mb_releasegroupid: - yield self.GROUP_URL.format(mbid=album.mb_releasegroupid) + if 'release' in self.match_by and album.mb_albumid: + yield self._candidate(url=self.URL.format(mbid=album.mb_albumid), + match=Candidate.MATCH_EXACT) + if 'releasegroup' in self.match_by and album.mb_releasegroupid: + yield self._candidate( + url=self.GROUP_URL.format(mbid=album.mb_releasegroupid), + match=Candidate.MATCH_FALLBACK) -class Amazon(ArtSource): +class Amazon(RemoteArtSource): + NAME = u"Amazon" URL = 'http://images.amazon.com/images/P/%s.%02i.LZZZZZZZ.jpg' INDICES = (1, 2) - def get(self, album): + def get(self, album, plugin, paths): """Generate URLs using Amazon ID (ASIN) string. """ if album.asin: for index in self.INDICES: - yield self.URL % (album.asin, index) + yield self._candidate(url=self.URL % (album.asin, index), + match=Candidate.MATCH_EXACT) -class AlbumArtOrg(ArtSource): - """AlbumArt.org scraper""" +class AlbumArtOrg(RemoteArtSource): + NAME = u"AlbumArt.org scraper" URL = 'http://www.albumart.org/index_detail.php' PAT = r'href\s*=\s*"([^>"]*)"[^>]*title\s*=\s*"View larger image"' - def get(self, album): + def get(self, album, plugin, paths): """Return art URL from AlbumArt.org using album ASIN. """ if not album.asin: @@ -147,42 +350,116 @@ class AlbumArtOrg(ArtSource): m = re.search(self.PAT, resp.text) if m: image_url = m.group(1) - yield image_url + yield self._candidate(url=image_url, match=Candidate.MATCH_EXACT) else: self._log.debug(u'no image found on page') -class GoogleImages(ArtSource): - URL = 'https://ajax.googleapis.com/ajax/services/search/images' +class GoogleImages(RemoteArtSource): + NAME = u"Google Images" + URL = u'https://www.googleapis.com/customsearch/v1' - def get(self, album): - """Return art URL from google.org given an album title and - interpreter. + def __init__(self, *args, **kwargs): + super(GoogleImages, self).__init__(*args, **kwargs) + self.key = self._config['google_key'].get(), + self.cx = self._config['google_engine'].get(), + + def get(self, album, plugin, paths): + """Return art URL from google custom search engine + given an album title and interpreter. """ if not (album.albumartist and album.album): return search_string = (album.albumartist + ',' + album.album).encode('utf-8') response = self.request(self.URL, params={ - 'v': '1.0', + 'key': self.key, + 'cx': self.cx, 'q': search_string, - 'start': '0', + 'searchType': 'image' }) # Get results using JSON. try: - results = response.json() - data = results['responseData'] - dataInfo = data['results'] - for myUrl in dataInfo: - yield myUrl['unescapedUrl'] - except: - self._log.debug(u'error scraping art page') + data = response.json() + except ValueError: + self._log.debug(u'google: error loading response: {}' + .format(response.text)) return + if 'error' in data: + reason = data['error']['errors'][0]['reason'] + self._log.debug(u'google fetchart error: {0}', reason) + return -class ITunesStore(ArtSource): - # Art from the iTunes Store. - def get(self, album): + if 'items' in data.keys(): + for item in data['items']: + yield self._candidate(url=item['link'], + match=Candidate.MATCH_EXACT) + + +class FanartTV(RemoteArtSource): + """Art from fanart.tv requested using their API""" + NAME = u"fanart.tv" + API_URL = 'https://webservice.fanart.tv/v3/' + API_ALBUMS = API_URL + 'music/albums/' + PROJECT_KEY = '61a7d0ab4e67162b7a0c7c35915cd48e' + + def __init__(self, *args, **kwargs): + super(FanartTV, self).__init__(*args, **kwargs) + self.client_key = self._config['fanarttv_key'].get() + + def get(self, album, plugin, paths): + if not album.mb_releasegroupid: + return + + response = self.request( + self.API_ALBUMS + album.mb_releasegroupid, + headers={'api-key': self.PROJECT_KEY, + 'client-key': self.client_key}) + + try: + data = response.json() + except ValueError: + self._log.debug(u'fanart.tv: error loading response: {}', + response.text) + return + + if u'status' in data and data[u'status'] == u'error': + if u'not found' in data[u'error message'].lower(): + self._log.debug(u'fanart.tv: no image found') + elif u'api key' in data[u'error message'].lower(): + self._log.warning(u'fanart.tv: Invalid API key given, please ' + u'enter a valid one in your config file.') + else: + self._log.debug(u'fanart.tv: error on request: {}', + data[u'error message']) + return + + matches = [] + # can there be more than one releasegroupid per response? + for mbid, art in data.get(u'albums', dict()).items(): + # there might be more art referenced, e.g. cdart, and an albumcover + # might not be present, even if the request was succesful + if album.mb_releasegroupid == mbid and u'albumcover' in art: + matches.extend(art[u'albumcover']) + # can this actually occur? + else: + self._log.debug(u'fanart.tv: unexpected mb_releasegroupid in ' + u'response!') + + matches.sort(key=lambda x: x[u'likes'], reverse=True) + for item in matches: + # fanart.tv has a strict size requirement for album art to be + # uploaded + yield self._candidate(url=item[u'url'], + match=Candidate.MATCH_EXACT, + size=(1000, 1000)) + + +class ITunesStore(RemoteArtSource): + NAME = u"iTunes Store" + + def get(self, album, plugin, paths): """Return art URL from iTunes Store given an album title. """ if not (album.albumartist and album.album): @@ -191,26 +468,34 @@ class ITunesStore(ArtSource): try: # Isolate bugs in the iTunes library while searching. try: - itunes_album = itunes.search_album(search_string)[0] + results = itunes.search_album(search_string) except Exception as exc: - self._log.debug('iTunes search failed: {0}', exc) + self._log.debug(u'iTunes search failed: {0}', exc) + return + + # Get the first match. + if results: + itunes_album = results[0] + else: + self._log.debug(u'iTunes search for {:r} got no results', + search_string) return if itunes_album.get_artwork()['100']: small_url = itunes_album.get_artwork()['100'] big_url = small_url.replace('100x100', '1200x1200') - yield big_url + yield self._candidate(url=big_url, match=Candidate.MATCH_EXACT) else: self._log.debug(u'album has no artwork in iTunes Store') except IndexError: self._log.debug(u'album not found in iTunes Store') -class Wikipedia(ArtSource): - # Art from Wikipedia (queried through DBpedia) - DBPEDIA_URL = 'http://dbpedia.org/sparql' - WIKIPEDIA_URL = 'http://en.wikipedia.org/w/api.php' - SPARQL_QUERY = '''PREFIX rdf: +class Wikipedia(RemoteArtSource): + NAME = u"Wikipedia (queried through DBpedia)" + DBPEDIA_URL = 'https://dbpedia.org/sparql' + WIKIPEDIA_URL = 'https://en.wikipedia.org/w/api.php' + SPARQL_QUERY = u'''PREFIX rdf: PREFIX dbpprop: PREFIX owl: PREFIX rdfs: @@ -232,7 +517,7 @@ class Wikipedia(ArtSource): }} Limit 1''' - def get(self, album): + def get(self, album, plugin, paths): if not (album.albumartist and album.album): return @@ -255,9 +540,9 @@ class Wikipedia(ArtSource): cover_filename = 'File:' + results[0]['coverFilename']['value'] page_id = results[0]['pageId']['value'] else: - self._log.debug('wikipedia: album not found on dbpedia') + self._log.debug(u'wikipedia: album not found on dbpedia') except (ValueError, KeyError, IndexError): - self._log.debug('wikipedia: error scraping dbpedia response: {}', + self._log.debug(u'wikipedia: error scraping dbpedia response: {}', dbpedia_response.text) # Ensure we have a filename before attempting to query wikipedia @@ -272,7 +557,7 @@ class Wikipedia(ArtSource): if ' .' in cover_filename and \ '.' not in cover_filename.split(' .')[-1]: self._log.debug( - 'wikipedia: dbpedia provided incomplete cover_filename' + u'wikipedia: dbpedia provided incomplete cover_filename' ) lpart, rpart = cover_filename.rsplit(' .', 1) @@ -301,7 +586,7 @@ class Wikipedia(ArtSource): break except (ValueError, KeyError): self._log.debug( - 'wikipedia: failed to retrieve a cover_filename' + u'wikipedia: failed to retrieve a cover_filename' ) return @@ -322,16 +607,18 @@ class Wikipedia(ArtSource): try: data = wikipedia_response.json() results = data['query']['pages'] - for _, result in results.iteritems(): + for _, result in results.items(): image_url = result['imageinfo'][0]['url'] - yield image_url + yield self._candidate(url=image_url, + match=Candidate.MATCH_EXACT) except (ValueError, KeyError, IndexError): - self._log.debug('wikipedia: error scraping imageinfo') + self._log.debug(u'wikipedia: error scraping imageinfo') return -class FileSystem(ArtSource): - """Art from the filesystem""" +class FileSystem(LocalArtSource): + NAME = u"Filesystem" + @staticmethod def filename_priority(filename, cover_names): """Sort order for image names. @@ -342,76 +629,126 @@ class FileSystem(ArtSource): """ return [idx for (idx, x) in enumerate(cover_names) if x in filename] - def get(self, path, cover_names, cautious): - """Look for album art files in a specified directory. + def get(self, album, plugin, paths): + """Look for album art files in the specified directories. """ - if not os.path.isdir(path): + if not paths: return + cover_names = list(map(util.bytestring_path, plugin.cover_names)) + cover_names_str = b'|'.join(cover_names) + cover_pat = br''.join([br"(\b|_)(", cover_names_str, br")(\b|_)"]) - # Find all files that look like images in the directory. - images = [] - for fn in os.listdir(path): - for ext in IMAGE_EXTENSIONS: - if fn.lower().endswith(b'.' + ext.encode('utf8')) and \ - os.path.isfile(os.path.join(path, fn)): - images.append(fn) + for path in paths: + if not os.path.isdir(syspath(path)): + continue - # Look for "preferred" filenames. - images = sorted(images, - key=lambda x: self.filename_priority(x, cover_names)) - cover_pat = br"(\b|_)({0})(\b|_)".format(b'|'.join(cover_names)) - for fn in images: - if re.search(cover_pat, os.path.splitext(fn)[0], re.I): - self._log.debug(u'using well-named art file {0}', - util.displayable_path(fn)) - return os.path.join(path, fn) + # Find all files that look like images in the directory. + images = [] + for fn in os.listdir(syspath(path)): + fn = bytestring_path(fn) + for ext in IMAGE_EXTENSIONS: + if fn.lower().endswith(b'.' + ext) and \ + os.path.isfile(syspath(os.path.join(path, fn))): + images.append(fn) - # Fall back to any image in the folder. - if images and not cautious: - self._log.debug(u'using fallback art file {0}', - util.displayable_path(images[0])) - return os.path.join(path, images[0]) + # Look for "preferred" filenames. + images = sorted(images, + key=lambda x: + self.filename_priority(x, cover_names)) + remaining = [] + for fn in images: + if re.search(cover_pat, os.path.splitext(fn)[0], re.I): + self._log.debug(u'using well-named art file {0}', + util.displayable_path(fn)) + yield self._candidate(path=os.path.join(path, fn), + match=Candidate.MATCH_EXACT) + else: + remaining.append(fn) + + # Fall back to any image in the folder. + if remaining and not plugin.cautious: + self._log.debug(u'using fallback art file {0}', + util.displayable_path(remaining[0])) + yield self._candidate(path=os.path.join(path, remaining[0]), + match=Candidate.MATCH_FALLBACK) # Try each source in turn. -SOURCES_ALL = [u'coverart', u'itunes', u'amazon', u'albumart', u'google', - u'wikipedia'] +SOURCES_ALL = [u'filesystem', + u'coverart', u'itunes', u'amazon', u'albumart', + u'wikipedia', u'google', u'fanarttv'] ART_SOURCES = { + u'filesystem': FileSystem, u'coverart': CoverArtArchive, u'itunes': ITunesStore, u'albumart': AlbumArtOrg, u'amazon': Amazon, - u'google': GoogleImages, u'wikipedia': Wikipedia, + u'google': GoogleImages, + u'fanarttv': FanartTV, } +SOURCE_NAMES = {v: k for k, v in ART_SOURCES.items()} # PLUGIN LOGIC ############################################################### class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): + PAT_PX = r"(0|[1-9][0-9]*)px" + PAT_PERCENT = r"(100(\.00?)?|[1-9]?[0-9](\.[0-9]{1,2})?)%" + def __init__(self): super(FetchArtPlugin, self).__init__() + # Holds candidates corresponding to downloaded images between + # fetching them and placing them in the filesystem. + self.art_candidates = {} + self.config.add({ 'auto': True, 'minwidth': 0, 'maxwidth': 0, 'enforce_ratio': False, - 'remote_priority': False, 'cautious': False, 'cover_names': ['cover', 'front', 'art', 'album', 'folder'], - 'sources': ['coverart', 'itunes', 'amazon', 'albumart'], + 'sources': ['filesystem', + 'coverart', 'itunes', 'amazon', 'albumart'], + 'google_key': None, + 'google_engine': u'001442825323518660753:hrh5ch1gjzm', + 'fanarttv_key': None, + 'store_source': False, }) - - # Holds paths to downloaded images between fetching them and - # placing them in the filesystem. - self.art_paths = {} + self.config['google_key'].redact = True + self.config['fanarttv_key'].redact = True self.minwidth = self.config['minwidth'].get(int) self.maxwidth = self.config['maxwidth'].get(int) - self.enforce_ratio = self.config['enforce_ratio'].get(bool) + + # allow both pixel and percentage-based margin specifications + self.enforce_ratio = self.config['enforce_ratio'].get( + confit.OneOf([bool, + confit.String(pattern=self.PAT_PX), + confit.String(pattern=self.PAT_PERCENT)])) + self.margin_px = None + self.margin_percent = None + if type(self.enforce_ratio) is six.text_type: + if self.enforce_ratio[-1] == u'%': + self.margin_percent = float(self.enforce_ratio[:-1]) / 100 + elif self.enforce_ratio[-2:] == u'px': + self.margin_px = int(self.enforce_ratio[:-2]) + else: + # shouldn't happen + raise confit.ConfigValueError() + self.enforce_ratio = True + + cover_names = self.config['cover_names'].as_str_seq() + self.cover_names = list(map(util.bytestring_path, cover_names)) + self.cautious = self.config['cautious'].get(bool) + self.store_source = self.config['store_source'].get(bool) + + self.src_removed = (config['import']['delete'].get(bool) or + config['import']['move'].get(bool)) if self.config['auto']: # Enable two import hooks when fetching is enabled. @@ -421,109 +758,100 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): available_sources = list(SOURCES_ALL) if not HAVE_ITUNES and u'itunes' in available_sources: available_sources.remove(u'itunes') - sources_name = plugins.sanitize_choices( - self.config['sources'].as_str_seq(), available_sources) - self.sources = [ART_SOURCES[s](self._log) for s in sources_name] - self.fs_source = FileSystem(self._log) + if not self.config['google_key'].get() and \ + u'google' in available_sources: + available_sources.remove(u'google') + available_sources = [(s, c) + for s in available_sources + for c in ART_SOURCES[s].VALID_MATCHING_CRITERIA] + sources = plugins.sanitize_pairs( + self.config['sources'].as_pairs(default_value='*'), + available_sources) + + if 'remote_priority' in self.config: + self._log.warning( + u'The `fetch_art.remote_priority` configuration option has ' + u'been deprecated. Instead, place `filesystem` at the end of ' + u'your `sources` list.') + if self.config['remote_priority'].get(bool): + fs = [] + others = [] + for s, c in sources: + if s == 'filesystem': + fs.append((s, c)) + else: + others.append((s, c)) + sources = others + fs + + self.sources = [ART_SOURCES[s](self._log, self.config, match_by=[c]) + for s, c in sources] # Asynchronous; after music is added to the library. def fetch_art(self, session, task): """Find art for the album being imported.""" if task.is_album: # Only fetch art for full albums. + if task.album.artpath and os.path.isfile(task.album.artpath): + # Album already has art (probably a re-import); skip it. + return if task.choice_flag == importer.action.ASIS: # For as-is imports, don't search Web sources for art. local = True - elif task.choice_flag == importer.action.APPLY: + elif task.choice_flag in (importer.action.APPLY, + importer.action.RETAG): # Search everywhere for art. local = False else: # For any other choices (e.g., TRACKS), do nothing. return - path = self.art_for_album(task.album, task.paths, local) + candidate = self.art_for_album(task.album, task.paths, local) - if path: - self.art_paths[task] = path + if candidate: + self.art_candidates[task] = candidate + + def _set_art(self, album, candidate, delete=False): + album.set_art(candidate.path, delete) + if self.store_source: + # store the source of the chosen artwork in a flexible field + self._log.debug( + u"Storing art_source for {0.albumartist} - {0.album}", + album) + album.art_source = SOURCE_NAMES[type(candidate.source)] + album.store() # Synchronous; after music files are put in place. def assign_art(self, session, task): """Place the discovered art in the filesystem.""" - if task in self.art_paths: - path = self.art_paths.pop(task) + if task in self.art_candidates: + candidate = self.art_candidates.pop(task) - album = task.album - src_removed = (config['import']['delete'].get(bool) or - config['import']['move'].get(bool)) - album.set_art(path, not src_removed) - album.store() - if src_removed: - task.prune(path) + self._set_art(task.album, candidate, not self.src_removed) + + if self.src_removed: + task.prune(candidate.path) # Manual album art fetching. def commands(self): cmd = ui.Subcommand('fetchart', help='download album art') - cmd.parser.add_option('-f', '--force', dest='force', - action='store_true', default=False, - help='re-download art when already present') + cmd.parser.add_option( + u'-f', u'--force', dest='force', + action='store_true', default=False, + help=u're-download art when already present' + ) + cmd.parser.add_option( + u'-q', u'--quiet', dest='quiet', + action='store_true', default=False, + help=u'shows only quiet art' + ) def func(lib, opts, args): - self.batch_fetch_art(lib, lib.albums(ui.decargs(args)), opts.force) + self.batch_fetch_art(lib, lib.albums(ui.decargs(args)), opts.force, + opts.quiet) cmd.func = func return [cmd] # Utilities converted from functions to methods on logging overhaul - def _fetch_image(self, url): - """Downloads an image from a URL and checks whether it seems to - actually be an image. If so, returns a path to the downloaded image. - Otherwise, returns None. - """ - try: - with closing(self.request(url, stream=True, - message='downloading image')) as resp: - if 'Content-Type' not in resp.headers \ - or resp.headers['Content-Type'] not in CONTENT_TYPES: - self._log.debug( - 'not a supported image: {}', - resp.headers.get('Content-Type') or 'no content type', - ) - return None - - # Generate a temporary file with the correct extension. - with NamedTemporaryFile(suffix=DOWNLOAD_EXTENSION, - delete=False) as fh: - for chunk in resp.iter_content(chunk_size=1024): - fh.write(chunk) - self._log.debug(u'downloaded art to: {0}', - util.displayable_path(fh.name)) - return fh.name - - except (IOError, requests.RequestException, TypeError) as exc: - # Handling TypeError works around a urllib3 bug: - # https://github.com/shazow/urllib3/issues/556 - self._log.debug('error fetching art: {}', exc) - return None - - def _is_valid_image_candidate(self, candidate): - if not candidate: - return False - - if not (self.enforce_ratio or self.minwidth): - return True - - # get_size returns None if no local imaging backend is available - size = ArtResizer.shared.get_size(candidate) - - if not size: - self._log.warning(u'could not verify size of image: please see ' - u'documentation for dependencies. ' - u'The configuration options `minwidth` and ' - u'`enforce_ratio` may be violated.') - return True - - return size and size[0] >= self.minwidth and \ - (not self.enforce_ratio or size[0] == size[1]) - def art_for_album(self, album, paths, local_only=False): """Given an Album object, returns a path to downloaded art for the album (or None if no art is found). If `maxwidth`, then images are @@ -533,72 +861,51 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): """ out = None - # Local art. - cover_names = self.config['cover_names'].as_str_seq() - cover_names = map(util.bytestring_path, cover_names) - cautious = self.config['cautious'].get(bool) - if paths: - for path in paths: - candidate = self.fs_source.get(path, cover_names, cautious) - if self._is_valid_image_candidate(candidate): - out = candidate - self._log.debug('found local image {}', out) + for source in self.sources: + if source.IS_LOCAL or not local_only: + self._log.debug( + u'trying source {0} for album {1.albumartist} - {1.album}', + SOURCE_NAMES[type(source)], + album, + ) + # URLs might be invalid at this point, or the image may not + # fulfill the requirements + for candidate in source.get(album, self, paths): + source.fetch_image(candidate, self) + if candidate.validate(self): + out = candidate + self._log.debug( + u'using {0.LOC_STR} image {1}'.format( + source, util.displayable_path(out.path))) + break + if out: break - # Web art sources. - remote_priority = self.config['remote_priority'].get(bool) - if not local_only and (remote_priority or not out): - for url in self._source_urls(album): - if self.maxwidth: - url = ArtResizer.shared.proxy_url(self.maxwidth, url) - candidate = self._fetch_image(url) - if self._is_valid_image_candidate(candidate): - out = candidate - self._log.debug('using remote image {}', out) - break - - if self.maxwidth and out: - out = ArtResizer.shared.resize(self.maxwidth, out) + if out: + out.resize(self) return out - def batch_fetch_art(self, lib, albums, force): + def batch_fetch_art(self, lib, albums, force, quiet): """Fetch album art for each of the albums. This implements the manual fetchart CLI command. """ for album in albums: - if album.artpath and not force: - message = ui.colorize('text_highlight_minor', 'has album art') + if album.artpath and not force and os.path.isfile(album.artpath): + if not quiet: + message = ui.colorize('text_highlight_minor', + u'has album art') + self._log.info(u'{0}: {1}', album, message) else: # In ordinary invocations, look for images on the # filesystem. When forcing, however, always go to the Web # sources. local_paths = None if force else [album.path] - path = self.art_for_album(album, local_paths) - if path: - album.set_art(path, False) - album.store() - message = ui.colorize('text_success', 'found album art') + candidate = self.art_for_album(album, local_paths) + if candidate: + self._set_art(album, candidate) + message = ui.colorize('text_success', u'found album art') else: - message = ui.colorize('text_error', 'no art found') - - self._log.info(u'{0}: {1}', album, message) - - def _source_urls(self, album): - """Generate possible source URLs for an album's art. The URLs are - not guaranteed to work so they each need to be attempted in turn. - This allows the main `art_for_album` function to abort iteration - through this sequence early to avoid the cost of scraping when not - necessary. - """ - source_names = {v: k for k, v in ART_SOURCES.items()} - for source in self.sources: - self._log.debug( - 'trying source {0} for album {1.albumartist} - {1.album}', - source_names[type(source)], - album, - ) - urls = source.get(album) - for url in urls: - yield url + message = ui.colorize('text_error', u'no art found') + self._log.info(u'{0}: {1}', album, message) diff --git a/beetsplug/filefilter.py b/beetsplug/filefilter.py index 432388c5a..23dac5746 100644 --- a/beetsplug/filefilter.py +++ b/beetsplug/filefilter.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Malte Ried. +# Copyright 2016, Malte Ried. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,8 +16,11 @@ """Filter imported files using a regular expression. """ +from __future__ import division, absolute_import, print_function + import re from beets import config +from beets.util import bytestring_path from beets.plugins import BeetsPlugin from beets.importer import SingletonImportTask @@ -32,14 +36,15 @@ class FileFilterPlugin(BeetsPlugin): self.path_album_regex = \ self.path_singleton_regex = \ - re.compile(self.config['path'].get()) + re.compile(bytestring_path(self.config['path'].get())) if 'album_path' in self.config: - self.path_album_regex = re.compile(self.config['album_path'].get()) + self.path_album_regex = re.compile( + bytestring_path(self.config['album_path'].get())) if 'singleton_path' in self.config: self.path_singleton_regex = re.compile( - self.config['singleton_path'].get()) + bytestring_path(self.config['singleton_path'].get())) def import_task_created_event(self, session, task): if task.items and len(task.items) > 0: @@ -66,6 +71,7 @@ class FileFilterPlugin(BeetsPlugin): of the file given in full_path. """ import_config = dict(config['import']) + full_path = bytestring_path(full_path) if 'singletons' not in import_config or not import_config[ 'singletons']: # Album diff --git a/beetsplug/freedesktop.py b/beetsplug/freedesktop.py index 675061925..a768be2d8 100644 --- a/beetsplug/freedesktop.py +++ b/beetsplug/freedesktop.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Matt Lichtenberg. +# Copyright 2016, Matt Lichtenberg. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,8 +16,7 @@ """Creates freedesktop.org-compliant .directory files on an album level. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets import ui @@ -24,13 +24,14 @@ from beets import ui class FreedesktopPlugin(BeetsPlugin): def commands(self): - deprecated = ui.Subcommand("freedesktop", help="Print a message to " - "redirect to thumbnails --dolphin") + deprecated = ui.Subcommand( + "freedesktop", + help=u"Print a message to redirect to thumbnails --dolphin") deprecated.func = self.deprecation_message return [deprecated] def deprecation_message(self, lib, opts, args): - ui.print_("This plugin is deprecated. Its functionality is superseded " - "by the 'thumbnails' plugin") - ui.print_("'thumbnails --dolphin' replaces freedesktop. See doc & " - "changelog for more information") + ui.print_(u"This plugin is deprecated. Its functionality is " + u"superseded by the 'thumbnails' plugin") + ui.print_(u"'thumbnails --dolphin' replaces freedesktop. See doc & " + u"changelog for more information") diff --git a/beetsplug/fromfilename.py b/beetsplug/fromfilename.py index dc040a0a2..56b68f756 100644 --- a/beetsplug/fromfilename.py +++ b/beetsplug/fromfilename.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Jan-Erik Dahlin +# Copyright 2016, Jan-Erik Dahlin # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,41 +16,32 @@ """If the title is empty, try to extract track and title from the filename. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from beets import plugins from beets.util import displayable_path import os import re +import six # Filename field extraction patterns. PATTERNS = [ - # "01 - Track 01" and "01": do nothing - r'^(\d+)\s*-\s*track\s*\d$', - r'^\d+$', - - # Useful patterns. - r'^(?P.+)-(?P.+)-(?P<tag>.*)$', - r'^(?P<track>\d+)\s*-(?P<artist>.+)-(?P<title>.+)-(?P<tag>.*)$', - r'^(?P<track>\d+)\s(?P<artist>.+)-(?P<title>.+)-(?P<tag>.*)$', - r'^(?P<artist>.+)-(?P<title>.+)$', - r'^(?P<track>\d+)\.\s*(?P<artist>.+)-(?P<title>.+)$', - r'^(?P<track>\d+)\s*-\s*(?P<artist>.+)-(?P<title>.+)$', - r'^(?P<track>\d+)\s*-(?P<artist>.+)-(?P<title>.+)$', - r'^(?P<track>\d+)\s(?P<artist>.+)-(?P<title>.+)$', - r'^(?P<title>.+)$', - r'^(?P<track>\d+)\.\s*(?P<title>.+)$', - r'^(?P<track>\d+)\s*-\s*(?P<title>.+)$', - r'^(?P<track>\d+)\s(?P<title>.+)$', - r'^(?P<title>.+) by (?P<artist>.+)$', + # Useful patterns. + r'^(?P<artist>.+)[\-_](?P<title>.+)[\-_](?P<tag>.*)$', + r'^(?P<track>\d+)[\s.\-_]+(?P<artist>.+)[\-_](?P<title>.+)[\-_](?P<tag>.*)$', + r'^(?P<artist>.+)[\-_](?P<title>.+)$', + r'^(?P<track>\d+)[\s.\-_]+(?P<artist>.+)[\-_](?P<title>.+)$', + r'^(?P<title>.+)$', + r'^(?P<track>\d+)[\s.\-_]+(?P<title>.+)$', + r'^(?P<track>\d+)\s+(?P<title>.+)$', + r'^(?P<title>.+) by (?P<artist>.+)$', + r'^(?P<track>\d+).*$', ] # Titles considered "empty" and in need of replacement. BAD_TITLE_PATTERNS = [ r'^$', - r'\d+?\s?-?\s*track\s*\d+', ] @@ -100,7 +92,7 @@ def apply_matches(d): """Given a mapping from items to field dicts, apply the fields to the objects. """ - some_map = d.values()[0] + some_map = list(d.values())[0] keys = some_map.keys() # Only proceed if the "tag" field is equal across all filenames. @@ -132,7 +124,7 @@ def apply_matches(d): # Apply the title and track. for item in d: if bad_title(item.title): - item.title = unicode(d[item][title_field]) + item.title = six.text_type(d[item][title_field]) if 'track' in d[item] and item.track == 0: item.track = int(d[item]['track']) diff --git a/beetsplug/ftintitle.py b/beetsplug/ftintitle.py index 8c435865c..9303f9cfc 100644 --- a/beetsplug/ftintitle.py +++ b/beetsplug/ftintitle.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Verrus, <github.com/Verrus/beets-plugin-featInTitle> +# Copyright 2016, Verrus, <github.com/Verrus/beets-plugin-featInTitle> # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,15 +15,13 @@ """Moves "featured" artists to the title from the artist field. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import re from beets import plugins from beets import ui from beets.util import displayable_path -from beets import config def split_on_feat(artist): @@ -50,29 +49,28 @@ def find_feat_part(artist, albumartist): """Attempt to find featured artists in the item's artist fields and return the results. Returns None if no featured artist found. """ - feat_part = None - # Look for the album artist in the artist field. If it's not # present, give up. albumartist_split = artist.split(albumartist, 1) if len(albumartist_split) <= 1: - return feat_part + return None # If the last element of the split (the right-hand side of the # album artist) is nonempty, then it probably contains the # featured artist. - elif albumartist_split[-1] != '': + elif albumartist_split[1] != '': # Extract the featured artist from the right-hand side. - _, feat_part = split_on_feat(albumartist_split[-1]) + _, feat_part = split_on_feat(albumartist_split[1]) + return feat_part # Otherwise, if there's nothing on the right-hand side, look for a # featuring artist on the left-hand side. else: lhs, rhs = split_on_feat(albumartist_split[0]) if lhs: - feat_part = lhs + return lhs - return feat_part + return None class FtInTitlePlugin(plugins.BeetsPlugin): @@ -87,12 +85,12 @@ class FtInTitlePlugin(plugins.BeetsPlugin): self._command = ui.Subcommand( 'ftintitle', - help='move featured artists to the title field') + help=u'move featured artists to the title field') self._command.parser.add_option( - '-d', '--drop', dest='drop', - action='store_true', default=False, - help='drop featuring from artists and ignore title update') + u'-d', u'--drop', dest='drop', + action='store_true', default=None, + help=u'drop featuring from artists and ignore title update') if self.config['auto']: self.import_stages = [self.imported] @@ -102,7 +100,7 @@ class FtInTitlePlugin(plugins.BeetsPlugin): def func(lib, opts, args): self.config.set_args(opts) drop_feat = self.config['drop'].get(bool) - write = config['import']['write'].get(bool) + write = ui.should_write() for item in lib.items(ui.decargs(args)): self.ft_in_title(item, drop_feat) @@ -138,7 +136,7 @@ class FtInTitlePlugin(plugins.BeetsPlugin): # Only update the title if it does not already contain a featured # artist and if we do not drop featuring information. if not drop_feat and not contains_feat(item.title): - feat_format = self.config['format'].get(unicode) + feat_format = self.config['format'].as_str() new_format = feat_format.format(feat_part) new_title = u"{0} {1}".format(item.title, new_format) self._log.info(u'title: {0} -> {1}', item.title, new_title) diff --git a/beetsplug/fuzzy.py b/beetsplug/fuzzy.py index d017ff0c2..a7308a525 100644 --- a/beetsplug/fuzzy.py +++ b/beetsplug/fuzzy.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Philippe Mongeau. +# Copyright 2016, Philippe Mongeau. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,8 +16,7 @@ """Provides a fuzzy matching query. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets.dbcore.query import StringFieldQuery @@ -26,13 +26,13 @@ import difflib class FuzzyQuery(StringFieldQuery): @classmethod - def string_match(self, pattern, val): + def string_match(cls, pattern, val): # smartcase if pattern.islower(): val = val.lower() - queryMatcher = difflib.SequenceMatcher(None, pattern, val) + query_matcher = difflib.SequenceMatcher(None, pattern, val) threshold = config['fuzzy']['threshold'].as_number() - return queryMatcher.quick_ratio() >= threshold + return query_matcher.quick_ratio() >= threshold class FuzzyPlugin(BeetsPlugin): @@ -44,5 +44,5 @@ class FuzzyPlugin(BeetsPlugin): }) def queries(self): - prefix = self.config['prefix'].get(basestring) + prefix = self.config['prefix'].as_str() return {prefix: FuzzyQuery} diff --git a/beetsplug/gmusic.py b/beetsplug/gmusic.py new file mode 100644 index 000000000..259d2725a --- /dev/null +++ b/beetsplug/gmusic.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2017, Tigran Kostandyan. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Upload files to Google Play Music and list songs in its library.""" + +from __future__ import absolute_import, division, print_function +import os.path + +from beets.plugins import BeetsPlugin +from beets import ui +from beets import config +from beets.ui import Subcommand +from gmusicapi import Musicmanager, Mobileclient +from gmusicapi.exceptions import NotLoggedIn +import gmusicapi.clients + + +class Gmusic(BeetsPlugin): + def __init__(self): + super(Gmusic, self).__init__() + # Checks for OAuth2 credentials, + # if they don't exist - performs authorization + self.m = Musicmanager() + if os.path.isfile(gmusicapi.clients.OAUTH_FILEPATH): + self.m.login() + else: + self.m.perform_oauth() + + def commands(self): + gupload = Subcommand('gmusic-upload', + help=u'upload your tracks to Google Play Music') + gupload.func = self.upload + + search = Subcommand('gmusic-songs', + help=u'list of songs in Google Play Music library' + ) + search.parser.add_option('-t', '--track', dest='track', + action='store_true', + help='Search by track name') + search.parser.add_option('-a', '--artist', dest='artist', + action='store_true', + help='Search by artist') + search.func = self.search + return [gupload, search] + + def upload(self, lib, opts, args): + items = lib.items(ui.decargs(args)) + files = [x.path.decode('utf-8') for x in items] + ui.print_(u'Uploading your files...') + self.m.upload(filepaths=files) + ui.print_(u'Your files were successfully added to library') + + def search(self, lib, opts, args): + password = config['gmusic']['password'] + email = config['gmusic']['email'] + password.redact = True + email.redact = True + # Since Musicmanager doesn't support library management + # we need to use mobileclient interface + mobile = Mobileclient() + try: + mobile.login(email.as_str(), password.as_str(), + Mobileclient.FROM_MAC_ADDRESS) + files = mobile.get_all_songs() + except NotLoggedIn: + ui.print_( + u'Authentication error. Please check your email and password.' + ) + return + if not args: + for i, file in enumerate(files, start=1): + print(i, ui.colorize('blue', file['artist']), + file['title'], ui.colorize('red', file['album'])) + else: + if opts.track: + self.match(files, args, 'title') + else: + self.match(files, args, 'artist') + + @staticmethod + def match(files, args, search_by): + for file in files: + if ' '.join(ui.decargs(args)) in file[search_by]: + print(file['artist'], file['title'], file['album']) diff --git a/beetsplug/hook.py b/beetsplug/hook.py new file mode 100644 index 000000000..b6270fd50 --- /dev/null +++ b/beetsplug/hook.py @@ -0,0 +1,118 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2015, Adrian Sampson. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Allows custom commands to be run when an event is emitted by beets""" +from __future__ import division, absolute_import, print_function + +import string +import subprocess +import six + +from beets.plugins import BeetsPlugin +from beets.util import shlex_split, arg_encoding + + +class CodingFormatter(string.Formatter): + """A variant of `string.Formatter` that converts everything to `unicode` + strings. + + This is necessary on Python 2, where formatting otherwise occurs on + bytestrings. It intercepts two points in the formatting process to decode + the format string and all fields using the specified encoding. If decoding + fails, the values are used as-is. + """ + + def __init__(self, coding): + """Creates a new coding formatter with the provided coding.""" + self._coding = coding + + def format(self, format_string, *args, **kwargs): + """Formats the provided string using the provided arguments and keyword + arguments. + + This method decodes the format string using the formatter's coding. + + See str.format and string.Formatter.format. + """ + try: + format_string = format_string.decode(self._coding) + except UnicodeEncodeError: + pass + + return super(CodingFormatter, self).format(format_string, *args, + **kwargs) + + def convert_field(self, value, conversion): + """Converts the provided value given a conversion type. + + This method decodes the converted value using the formatter's coding. + + See string.Formatter.convert_field. + """ + converted = super(CodingFormatter, self).convert_field(value, + conversion) + + if isinstance(converted, bytes): + return converted.decode(self._coding) + + return converted + + +class HookPlugin(BeetsPlugin): + """Allows custom commands to be run when an event is emitted by beets""" + def __init__(self): + super(HookPlugin, self).__init__() + + self.config.add({ + 'hooks': [] + }) + + hooks = self.config['hooks'].get(list) + + for hook_index in range(len(hooks)): + hook = self.config['hooks'][hook_index] + + hook_event = hook['event'].as_str() + hook_command = hook['command'].as_str() + + self.create_and_register_hook(hook_event, hook_command) + + def create_and_register_hook(self, event, command): + def hook_function(**kwargs): + if command is None or len(command) == 0: + self._log.error('invalid command "{0}"', command) + return + + # Use a string formatter that works on Unicode strings. + if six.PY2: + formatter = CodingFormatter(arg_encoding()) + else: + formatter = string.Formatter() + + command_pieces = shlex_split(command) + + for i, piece in enumerate(command_pieces): + command_pieces[i] = formatter.format(piece, event=event, + **kwargs) + + self._log.debug(u'running command "{0}" for event {1}', + u' '.join(command_pieces), event) + + try: + subprocess.Popen(command_pieces).wait() + except OSError as exc: + self._log.error(u'hook for {0} failed: {1}', event, exc) + + self.register_listener(event, hook_function) diff --git a/beetsplug/ihate.py b/beetsplug/ihate.py index b4a877fbc..6ed250fe4 100644 --- a/beetsplug/ihate.py +++ b/beetsplug/ihate.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Blemjhoo Tezoulbr <baobab@heresiarch.info>. +# Copyright 2016, Blemjhoo Tezoulbr <baobab@heresiarch.info>. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function """Warns you about things you hate (or even blocks import).""" diff --git a/beetsplug/importadded.py b/beetsplug/importadded.py index 19d4ecfe8..36407b14c 100644 --- a/beetsplug/importadded.py +++ b/beetsplug/importadded.py @@ -1,10 +1,11 @@ +# -*- coding: utf-8 -*- + """Populate an item's `added` and `mtime` fields by using the file modification time (mtime) of the item's source file before import. Reimported albums and items are skipped. """ -from __future__ import (unicode_literals, absolute_import, print_function, - division) +from __future__ import division, absolute_import, print_function import os @@ -18,6 +19,7 @@ class ImportAddedPlugin(BeetsPlugin): super(ImportAddedPlugin, self).__init__() self.config.add({ 'preserve_mtimes': False, + 'preserve_write_mtimes': False, }) # item.id for new items that were reimported @@ -28,14 +30,16 @@ class ImportAddedPlugin(BeetsPlugin): self.item_mtime = dict() register = self.register_listener - register('import_task_start', self.check_config) - register('import_task_start', self.record_if_inplace) + register('import_task_created', self.check_config) + register('import_task_created', self.record_if_inplace) register('import_task_files', self.record_reimported) register('before_item_moved', self.record_import_mtime) register('item_copied', self.record_import_mtime) register('item_linked', self.record_import_mtime) + register('item_hardlinked', self.record_import_mtime) register('album_imported', self.update_album_times) register('item_imported', self.update_item_times) + register('after_write', self.update_after_write_time) def check_config(self, task, session): self.config['preserve_mtimes'].get(bool) @@ -48,7 +52,7 @@ class ImportAddedPlugin(BeetsPlugin): def record_if_inplace(self, task, session): if not (session.config['copy'] or session.config['move'] or - session.config['link']): + session.config['link'] or session.config['hardlink']): self._log.debug(u"In place import detected, recording mtimes from " u"source paths") items = [task.item] \ @@ -59,7 +63,7 @@ class ImportAddedPlugin(BeetsPlugin): def record_reimported(self, task, session): self.reimported_item_ids = set(item.id for item, replaced_items - in task.replaced_items.iteritems() + in task.replaced_items.items() if replaced_items) self.replaced_album_paths = set(task.replaced_albums.keys()) @@ -119,3 +123,13 @@ class ImportAddedPlugin(BeetsPlugin): self._log.debug(u"Import of item '{0}', selected item.added={1}", util.displayable_path(item.path), item.added) item.store() + + def update_after_write_time(self, item): + """Update the mtime of the item's file with the item.added value + after each write of the item if `preserve_write_mtimes` is enabled. + """ + if item.added: + if self.config['preserve_write_mtimes'].get(bool): + self.write_item_mtime(item, item.added) + self._log.debug(u"Write of item '{0}', selected item.added={1}", + util.displayable_path(item.path), item.added) diff --git a/beetsplug/importfeeds.py b/beetsplug/importfeeds.py index 6b0a46778..35ae28835 100644 --- a/beetsplug/importfeeds.py +++ b/beetsplug/importfeeds.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Fabrice Laporte. +# Copyright 2016, Fabrice Laporte. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function """Write paths of imported files in various formats to ease later import in a music player. Also allow printing the new file locations to stdout in case @@ -24,26 +24,12 @@ import os import re from beets.plugins import BeetsPlugin -from beets.util import mkdirall, normpath, syspath, bytestring_path +from beets.util import mkdirall, normpath, syspath, bytestring_path, link from beets import config M3U_DEFAULT_NAME = 'imported.m3u' -def _get_feeds_dir(lib): - """Given a Library object, return the path to the feeds directory to be - used (either in the library directory or an explicitly configured - path). Ensures that the directory exists. - """ - # Inside library directory. - dirpath = lib.directory - - # Ensure directory exists. - if not os.path.exists(syspath(dirpath)): - os.makedirs(syspath(dirpath)) - return dirpath - - def _build_m3u_filename(basename): """Builds unique m3u filename by appending given basename to current date.""" @@ -61,7 +47,7 @@ def _write_m3u(m3u_path, items_paths): """Append relative paths to items into m3u file. """ mkdirall(m3u_path) - with open(syspath(m3u_path), 'a') as f: + with open(syspath(m3u_path), 'ab') as f: for path in items_paths: f.write(path + b'\n') @@ -78,30 +64,28 @@ class ImportFeedsPlugin(BeetsPlugin): 'absolute_path': False, }) - feeds_dir = self.config['dir'].get() - if feeds_dir: - feeds_dir = os.path.expanduser(bytestring_path(feeds_dir)) - self.config['dir'] = feeds_dir - if not os.path.exists(syspath(feeds_dir)): - os.makedirs(syspath(feeds_dir)) - relative_to = self.config['relative_to'].get() if relative_to: self.config['relative_to'] = normpath(relative_to) else: - self.config['relative_to'] = feeds_dir + self.config['relative_to'] = self.get_feeds_dir() - self.register_listener('library_opened', self.library_opened) self.register_listener('album_imported', self.album_imported) self.register_listener('item_imported', self.item_imported) + def get_feeds_dir(self): + feeds_dir = self.config['dir'].get() + if feeds_dir: + return os.path.expanduser(bytestring_path(feeds_dir)) + return config['directory'].as_filename() + def _record_items(self, lib, basename, items): """Records relative paths to the given items for each feed format """ - feedsdir = bytestring_path(self.config['dir'].as_filename()) + feedsdir = bytestring_path(self.get_feeds_dir()) formats = self.config['formats'].as_str_seq() relative_to = self.config['relative_to'].get() \ - or self.config['dir'].as_filename() + or self.get_feeds_dir() relative_to = bytestring_path(relative_to) paths = [] @@ -119,7 +103,7 @@ class ImportFeedsPlugin(BeetsPlugin): if 'm3u' in formats: m3u_basename = bytestring_path( - self.config['m3u_name'].get(unicode)) + self.config['m3u_name'].as_str()) m3u_path = os.path.join(feedsdir, m3u_basename) _write_m3u(m3u_path, paths) @@ -131,16 +115,12 @@ class ImportFeedsPlugin(BeetsPlugin): for path in paths: dest = os.path.join(feedsdir, os.path.basename(path)) if not os.path.exists(syspath(dest)): - os.symlink(syspath(path), syspath(dest)) + link(path, dest) if 'echo' in formats: - self._log.info("Location of imported music:") + self._log.info(u"Location of imported music:") for path in paths: - self._log.info(" {0}", path) - - def library_opened(self, lib): - if self.config['dir'].get() is None: - self.config['dir'] = _get_feeds_dir(lib) + self._log.info(u" {0}", path) def album_imported(self, lib, album): self._record_items(lib, album.album, album.items()) diff --git a/beetsplug/info.py b/beetsplug/info.py index 82bcbe965..0d40c597b 100644 --- a/beetsplug/info.py +++ b/beetsplug/info.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,8 +16,7 @@ """Shows file metadata. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import os import re @@ -24,6 +24,7 @@ import re from beets.plugins import BeetsPlugin from beets import ui from beets import mediafile +from beets.library import Item from beets.util import displayable_path, normpath, syspath @@ -50,8 +51,10 @@ def tag_data_emitter(path): for field in fields: tags[field] = getattr(mf, field) tags['art'] = mf.art is not None - tags['path'] = displayable_path(path) - return tags + # create a temporary Item to take advantage of __format__ + item = Item.from_path(syspath(path)) + + return tags, item return emitter @@ -63,13 +66,14 @@ def library_data(lib, args): def library_data_emitter(item): def emitter(): data = dict(item.formatted()) - data['path'] = displayable_path(item.path) - return data + data.pop('path', None) # path is fetched from item + + return data, item return emitter def update_summary(summary, tags): - for key, value in tags.iteritems(): + for key, value in tags.items(): if key not in summary: summary[key] = value elif summary[key] != value: @@ -77,10 +81,22 @@ def update_summary(summary, tags): return summary -def print_data(data): - path = data.pop('path', None) +def print_data(data, item=None, fmt=None): + """Print, with optional formatting, the fields of a single element. + + If no format string `fmt` is passed, the entries on `data` are printed one + in each line, with the format 'field: value'. If `fmt` is not `None`, the + `item` is printed according to `fmt`, using the `Item.__format__` + machinery. + """ + if fmt: + # use fmt specified by the user + ui.print_(format(item, fmt)) + return + + path = displayable_path(item.path) if item else None formatted = {} - for key, value in data.iteritems(): + for key, value in data.items(): if isinstance(value, list): formatted[key] = u'; '.join(value) if value is not None: @@ -102,18 +118,48 @@ def print_data(data): ui.print_(lineformat.format(field, value)) +def print_data_keys(data, item=None): + """Print only the keys (field names) for an item. + """ + path = displayable_path(item.path) if item else None + formatted = [] + for key, value in data.items(): + formatted.append(key) + + if len(formatted) == 0: + return + + line_format = u'{0}{{0}}'.format(u' ' * 4) + if path: + ui.print_(displayable_path(path)) + + for field in sorted(formatted): + ui.print_(line_format.format(field)) + + class InfoPlugin(BeetsPlugin): def commands(self): - cmd = ui.Subcommand('info', help='show file metadata') + cmd = ui.Subcommand('info', help=u'show file metadata') cmd.func = self.run - cmd.parser.add_option('-l', '--library', action='store_true', - help='show library fields instead of tags') - cmd.parser.add_option('-s', '--summarize', action='store_true', - help='summarize the tags of all files') - cmd.parser.add_option('-i', '--include-keys', default=[], - action='append', dest='included_keys', - help='comma separated list of keys to show') + cmd.parser.add_option( + u'-l', u'--library', action='store_true', + help=u'show library fields instead of tags', + ) + cmd.parser.add_option( + u'-s', u'--summarize', action='store_true', + help=u'summarize the tags of all files', + ) + cmd.parser.add_option( + u'-i', u'--include-keys', default=[], + action='append', dest='included_keys', + help=u'comma separated list of keys to show', + ) + cmd.parser.add_option( + u'-k', u'--keys-only', action='store_true', + help=u'show only the keys', + ) + cmd.parser.add_format_option(target='item') return [cmd] def run(self, lib, opts, args): @@ -144,20 +190,22 @@ class InfoPlugin(BeetsPlugin): summary = {} for data_emitter in data_collector(lib, ui.decargs(args)): try: - data = data_emitter() + data, item = data_emitter() except (mediafile.UnreadableFileError, IOError) as ex: self._log.error(u'cannot read file: {0}', ex) continue - path = data.get('path') data = key_filter(data) - data['path'] = path # always show path if opts.summarize: update_summary(summary, data) else: if not first: ui.print_() - print_data(data) + if opts.keys_only: + print_data_keys(data, item) + else: + fmt = ui.decargs([opts.format])[0] if opts.format else None + print_data(data, item, fmt) first = False if opts.summarize: @@ -180,14 +228,14 @@ def make_key_filter(include): key = key.replace(r'\*', '.*') matchers.append(re.compile(key + '$')) - def filter(data): + def filter_(data): filtered = dict() for key, value in data.items(): - if any(map(lambda m: m.match(key), matchers)): + if any([m.match(key) for m in matchers]): filtered[key] = value return filtered - return filter + return filter_ def identity(val): diff --git a/beetsplug/inline.py b/beetsplug/inline.py index fb99e729a..fd0e9fc30 100644 --- a/beetsplug/inline.py +++ b/beetsplug/inline.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,14 +15,14 @@ """Allows inline path template customization code in the config file. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import traceback import itertools from beets.plugins import BeetsPlugin from beets import config +import six FUNC_NAME = u'__INLINE_FUNC__' @@ -32,7 +33,7 @@ class InlineError(Exception): def __init__(self, code, exc): super(InlineError, self).__init__( (u"error in inline path field code:\n" - u"%s\n%s: %s") % (code, type(exc).__name__, unicode(exc)) + u"%s\n%s: %s") % (code, type(exc).__name__, six.text_type(exc)) ) @@ -64,14 +65,14 @@ class InlinePlugin(BeetsPlugin): for key, view in itertools.chain(config['item_fields'].items(), config['pathfields'].items()): self._log.debug(u'adding item field {0}', key) - func = self.compile_inline(view.get(unicode), False) + func = self.compile_inline(view.as_str(), False) if func is not None: self.template_fields[key] = func # Album fields. for key, view in config['album_fields'].items(): self._log.debug(u'adding album field {0}', key) - func = self.compile_inline(view.get(unicode), True) + func = self.compile_inline(view.as_str(), True) if func is not None: self.album_template_fields[key] = func diff --git a/beetsplug/ipfs.py b/beetsplug/ipfs.py index f785a582b..9a9d6aa50 100644 --- a/beetsplug/ipfs.py +++ b/beetsplug/ipfs.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # # Permission is hereby granted, free of charge, to any person obtaining @@ -13,6 +14,9 @@ """Adds support for ipfs. Requires go-ipfs and a running ipfs daemon """ + +from __future__ import division, absolute_import, print_function + from beets import ui, util, library, config from beets.plugins import BeetsPlugin @@ -268,9 +272,11 @@ class IPFSPlugin(BeetsPlugin): break except AttributeError: pass + item_path = os.path.basename(item.path).decode( + util._fsencoding(), 'ignore' + ) # Clear current path from item - item.path = '/ipfs/{0}/{1}'.format(album.ipfs, - os.path.basename(item.path)) + item.path = '/ipfs/{0}/{1}'.format(album.ipfs, item_path) item.id = None items.append(item) diff --git a/beetsplug/keyfinder.py b/beetsplug/keyfinder.py index e3e9a86ba..34a4abca4 100644 --- a/beetsplug/keyfinder.py +++ b/beetsplug/keyfinder.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,15 +16,13 @@ """Uses the `KeyFinder` program to add the `initial_key` field. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import subprocess from beets import ui from beets import util from beets.plugins import BeetsPlugin -from beets import config class KeyFinderPlugin(BeetsPlugin): @@ -41,41 +40,40 @@ class KeyFinderPlugin(BeetsPlugin): def commands(self): cmd = ui.Subcommand('keyfinder', - help='detect and add initial key from audio') + help=u'detect and add initial key from audio') cmd.func = self.command return [cmd] def command(self, lib, opts, args): - self.find_key(lib.items(ui.decargs(args)), - write=config['import']['write'].get(bool)) + self.find_key(lib.items(ui.decargs(args)), write=ui.should_write()) def imported(self, session, task): self.find_key(task.items) def find_key(self, items, write=False): overwrite = self.config['overwrite'].get(bool) - bin = util.bytestring_path(self.config['bin'].get(unicode)) + bin = self.config['bin'].as_str() for item in items: if item['initial_key'] and not overwrite: continue try: - output = util.command_output([bin, b'-f', + output = util.command_output([bin, '-f', util.syspath(item.path)]) except (subprocess.CalledProcessError, OSError) as exc: - self._log.error('execution failed: {0}', exc) + self._log.error(u'execution failed: {0}', exc) continue except UnicodeEncodeError: # Workaround for Python 2 Windows bug. # http://bugs.python.org/issue1759845 - self._log.error('execution failed for Unicode path: {0!r}', + self._log.error(u'execution failed for Unicode path: {0!r}', item.path) continue key_raw = output.rsplit(None, 1)[-1] try: - key = key_raw.decode('utf8') + key = util.text_string(key_raw) except UnicodeDecodeError: self._log.error(u'output is invalid UTF-8') continue diff --git a/beetsplug/kodiupdate.py b/beetsplug/kodiupdate.py new file mode 100644 index 000000000..ce5cb478c --- /dev/null +++ b/beetsplug/kodiupdate.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2017, Pauli Kettunen. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Updates a Kodi library whenever the beets library is changed. +This is based on the Plex Update plugin. + +Put something like the following in your config.yaml to configure: + kodi: + host: localhost + port: 8080 + user: user + pwd: secret +""" +from __future__ import division, absolute_import, print_function + +import requests +from beets import config +from beets.plugins import BeetsPlugin +import six + + +def update_kodi(host, port, user, password): + """Sends request to the Kodi api to start a library refresh. + """ + url = "http://{0}:{1}/jsonrpc".format(host, port) + + """Content-Type: application/json is mandatory + according to the kodi jsonrpc documentation""" + + headers = {'Content-Type': 'application/json'} + + # Create the payload. Id seems to be mandatory. + payload = {'jsonrpc': '2.0', 'method': 'AudioLibrary.Scan', 'id': 1} + r = requests.post( + url, + auth=(user, password), + json=payload, + headers=headers) + + return r + + +class KodiUpdate(BeetsPlugin): + def __init__(self): + super(KodiUpdate, self).__init__() + + # Adding defaults. + config['kodi'].add({ + u'host': u'localhost', + u'port': 8080, + u'user': u'kodi', + u'pwd': u'kodi'}) + + config['kodi']['pwd'].redact = True + self.register_listener('database_change', self.listen_for_db_change) + + def listen_for_db_change(self, lib, model): + """Listens for beets db change and register the update""" + self.register_listener('cli_exit', self.update) + + def update(self, lib): + """When the client exists try to send refresh request to Kodi server. + """ + self._log.info(u'Requesting a Kodi library update...') + + # Try to send update request. + try: + r = update_kodi( + config['kodi']['host'].get(), + config['kodi']['port'].get(), + config['kodi']['user'].get(), + config['kodi']['pwd'].get()) + r.raise_for_status() + + except requests.exceptions.RequestException as e: + self._log.warning(u'Kodi update failed: {0}', + six.text_type(e)) + return + + json = r.json() + if json.get('result') != 'OK': + self._log.warning(u'Kodi update failed: JSON response was {0!r}', + json) + return + + self._log.info(u'Kodi update triggered') diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index eab6ab440..4374310ba 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,8 +13,8 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function +import six """Gets genres for imported music based on Last.fm tags. @@ -24,14 +25,15 @@ The scraper script used is available here: https://gist.github.com/1241307 """ import pylast +import codecs import os import yaml import traceback from beets import plugins from beets import ui -from beets.util import normpath, plurality from beets import config +from beets.util import normpath, plurality from beets import library @@ -71,7 +73,7 @@ def flatten_tree(elem, path, branches): for sub in elem: flatten_tree(sub, path, branches) else: - branches.append(path + [unicode(elem)]) + branches.append(path + [six.text_type(elem)]) def find_parents(candidate, branches): @@ -107,6 +109,7 @@ class LastGenrePlugin(plugins.BeetsPlugin): 'force': True, 'auto': True, 'separator': u', ', + 'prefer_specific': False, }) self.setup() @@ -126,9 +129,9 @@ class LastGenrePlugin(plugins.BeetsPlugin): wl_filename = WHITELIST if wl_filename: wl_filename = normpath(wl_filename) - with open(wl_filename, b'r') as f: + with open(wl_filename, 'rb') as f: for line in f: - line = line.decode('utf8').strip().lower() + line = line.decode('utf-8').strip().lower() if line and not line.startswith(u'#'): self.whitelist.add(line) @@ -139,7 +142,8 @@ class LastGenrePlugin(plugins.BeetsPlugin): c14n_filename = C14N_TREE if c14n_filename: c14n_filename = normpath(c14n_filename) - genres_tree = yaml.load(open(c14n_filename, 'r')) + with codecs.open(c14n_filename, 'r', encoding='utf-8') as f: + genres_tree = yaml.load(f) flatten_tree(genres_tree, [], self.c14n_branches) @property @@ -155,6 +159,25 @@ class LastGenrePlugin(plugins.BeetsPlugin): elif source == 'artist': return 'artist', + def _get_depth(self, tag): + """Find the depth of a tag in the genres tree. + """ + depth = None + for key, value in enumerate(self.c14n_branches): + if tag in value: + depth = value.index(tag) + break + return depth + + def _sort_by_depth(self, tags): + """Given a list of tags, sort the tags by their depths in the + genre tree. + """ + depth_tag_pairs = [(self._get_depth(t), t) for t in tags] + depth_tag_pairs = [e for e in depth_tag_pairs if e[0] is not None] + depth_tag_pairs.sort(reverse=True) + return [p[1] for p in depth_tag_pairs] + def _resolve_genres(self, tags): """Given a list of strings, return a genre by joining them into a single string and (optionally) canonicalizing each. @@ -176,17 +199,24 @@ class LastGenrePlugin(plugins.BeetsPlugin): parents = [find_parents(tag, self.c14n_branches)[-1]] tags_all += parents - if len(tags_all) >= count: + # Stop if we have enough tags already, unless we need to find + # the most specific tag (instead of the most popular). + if (not self.config['prefer_specific'] and + len(tags_all) >= count): break tags = tags_all tags = deduplicate(tags) + # Sort the tags by specificity. + if self.config['prefer_specific']: + tags = self._sort_by_depth(tags) + # c14n only adds allowed genres but we may have had forbidden genres in # the original tags list tags = [x.title() for x in tags if self._is_allowed(x)] - return self.config['separator'].get(unicode).join( + return self.config['separator'].as_str().join( tags[:self.config['count'].get(int)] ) @@ -221,7 +251,8 @@ class LastGenrePlugin(plugins.BeetsPlugin): if any(not s for s in args): return None - key = u'{0}.{1}'.format(entity, u'-'.join(unicode(a) for a in args)) + key = u'{0}.{1}'.format(entity, + u'-'.join(six.text_type(a) for a in args)) if key in self._genre_cache: return self._genre_cache[key] else: @@ -238,25 +269,30 @@ class LastGenrePlugin(plugins.BeetsPlugin): def fetch_album_genre(self, obj): """Return the album genre for this Item or Album. """ - return self._last_lookup(u'album', LASTFM.get_album, obj.albumartist, - obj.album) + return self._last_lookup( + u'album', LASTFM.get_album, obj.albumartist, obj.album + ) def fetch_album_artist_genre(self, obj): """Return the album artist genre for this Item or Album. """ - return self._last_lookup(u'artist', LASTFM.get_artist, - obj.albumartist) + return self._last_lookup( + u'artist', LASTFM.get_artist, obj.albumartist + ) def fetch_artist_genre(self, item): """Returns the track artist genre for this Item. """ - return self._last_lookup(u'artist', LASTFM.get_artist, item.artist) + return self._last_lookup( + u'artist', LASTFM.get_artist, item.artist + ) def fetch_track_genre(self, obj): """Returns the track genre for this Item. """ - return self._last_lookup(u'track', LASTFM.get_track, obj.artist, - obj.title) + return self._last_lookup( + u'track', LASTFM.get_track, obj.artist, obj.title + ) def _get_genre(self, obj): """Get the genre string for an Album or Item object based on @@ -292,7 +328,7 @@ class LastGenrePlugin(plugins.BeetsPlugin): result = None if isinstance(obj, library.Item): result = self.fetch_artist_genre(obj) - elif obj.albumartist != 'Various Artists': + elif obj.albumartist != config['va_name'].as_str(): result = self.fetch_album_artist_genre(obj) else: # For "Various Artists", pick the most popular track genre. @@ -325,18 +361,19 @@ class LastGenrePlugin(plugins.BeetsPlugin): return None, None def commands(self): - lastgenre_cmd = ui.Subcommand('lastgenre', help='fetch genres') + lastgenre_cmd = ui.Subcommand('lastgenre', help=u'fetch genres') lastgenre_cmd.parser.add_option( - '-f', '--force', dest='force', action='store_true', default=False, - help='re-download genre when already present' + u'-f', u'--force', dest='force', + action='store_true', default=False, + help=u're-download genre when already present' ) lastgenre_cmd.parser.add_option( - '-s', '--source', dest='source', type='string', - help='genre source: artist, album, or track' + u'-s', u'--source', dest='source', type='string', + help=u'genre source: artist, album, or track' ) def lastgenre_func(lib, opts, args): - write = config['import']['write'].get(bool) + write = ui.should_write() self.config.set_args(opts) for album in lib.albums(ui.decargs(args)): @@ -394,7 +431,7 @@ class LastGenrePlugin(plugins.BeetsPlugin): """ # Work around an inconsistency in pylast where # Album.get_top_tags() does not return TopItem instances. - # https://code.google.com/p/pylast/issues/detail?id=85 + # https://github.com/pylast/pylast/issues/86 if isinstance(obj, pylast.Album): obj = super(pylast.Album, obj) @@ -405,8 +442,8 @@ class LastGenrePlugin(plugins.BeetsPlugin): return [] except Exception as exc: # Isolate bugs in pylast. - self._log.debug('{}', traceback.format_exc()) - self._log.error('error in pylast library: {0}', exc) + self._log.debug(u'{}', traceback.format_exc()) + self._log.error(u'error in pylast library: {0}', exc) return [] # Filter by weight (optionally). diff --git a/beetsplug/lastgenre/genres-tree.yaml b/beetsplug/lastgenre/genres-tree.yaml index 8e9eb12eb..a09f7e6b3 100644 --- a/beetsplug/lastgenre/genres-tree.yaml +++ b/beetsplug/lastgenre/genres-tree.yaml @@ -133,7 +133,6 @@ - chutney - chutney soca - compas - - dance hall - mambo - merengue - méringue @@ -148,7 +147,6 @@ - punta - punta rock - rasin - - reggae - reggaeton - salsa - soca @@ -291,7 +289,7 @@ - neurofunk - oldschool jungle: - darkside jungle - - ragga-jungle + - ragga jungle - raggacore - sambass - techstep @@ -494,8 +492,8 @@ - lyrical hip hop - merenrap - midwest hip hop: - - chicago hip hop: - - detroit hip hop: + - chicago hip hop + - detroit hip hop - horrorcore - st. louis hip hop - twin cities hip hop @@ -505,12 +503,10 @@ - new school hip hop - old school hip hop - political hip hop - - ragga - rap opera - rap rock: - rap metal - rapcore - - reggae español/spanish reggae - songo-salsa - southern hip hop: - atlanta hip hop: @@ -652,7 +648,7 @@ - glam rock - hard rock - heavy metal: - - alternative metal: + - alternative metal - black metal: - viking metal - christian metal @@ -735,12 +731,19 @@ - surf rock - visual kei: - nagoya kei -- ska: - - 2 tone - - dancehall - - dub - - lovers rock - - ragga jungle - - polish reggae +- reggae: + - roots reggae - reggae fusion - - rocksteady + - reggae en español: + - spanish reggae + - reggae 110 + - reggae bultrón + - romantic flow + - lovers rock + - raggamuffin: + - ragga + - dancehall + - ska: + - 2 tone + - dub + - rocksteady diff --git a/beetsplug/lastgenre/genres.txt b/beetsplug/lastgenre/genres.txt index 64e583bfa..914ee1290 100644 --- a/beetsplug/lastgenre/genres.txt +++ b/beetsplug/lastgenre/genres.txt @@ -1224,6 +1224,9 @@ rebetiko red dirt reel reggae +reggae 110 +reggae bultrón +reggae en español reggae fusion reggae highlife reggaefusion @@ -1247,6 +1250,7 @@ rock opera rockabilly rocksteady rococo +romantic flow romantic period in music rondeaux ronggeng diff --git a/beetsplug/lastimport.py b/beetsplug/lastimport.py index c2ba976fa..d7b84b0aa 100644 --- a/beetsplug/lastimport.py +++ b/beetsplug/lastimport.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Rafael Bodill http://github.com/rafi +# Copyright 2016, Rafael Bodill http://github.com/rafi # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,17 +13,17 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function -import requests +import pylast +from pylast import TopItem, _extract, _number from beets import ui from beets import dbcore from beets import config from beets import plugins from beets.dbcore import types -API_URL = 'http://ws.audioscrobbler.com/2.0/' +API_URL = 'https://ws.audioscrobbler.com/2.0/' class LastImportPlugin(plugins.BeetsPlugin): @@ -30,7 +31,7 @@ class LastImportPlugin(plugins.BeetsPlugin): super(LastImportPlugin, self).__init__() config['lastfm'].add({ 'user': '', - 'api_key': '', + 'api_key': plugins.LASTFM_KEY, }) config['lastfm']['api_key'].redact = True self.config.add({ @@ -42,7 +43,7 @@ class LastImportPlugin(plugins.BeetsPlugin): } def commands(self): - cmd = ui.Subcommand('lastimport', help='import last.fm play-count') + cmd = ui.Subcommand('lastimport', help=u'import last.fm play-count') def func(lib, opts, args): import_lastfm(lib, self._log) @@ -51,14 +52,71 @@ class LastImportPlugin(plugins.BeetsPlugin): return [cmd] +class CustomUser(pylast.User): + """ Custom user class derived from pylast.User, and overriding the + _get_things method to return MBID and album. Also introduces new + get_top_tracks_by_page method to allow access to more than one page of top + tracks. + """ + def __init__(self, *args, **kwargs): + super(CustomUser, self).__init__(*args, **kwargs) + + def _get_things(self, method, thing, thing_type, params=None, + cacheable=True): + """Returns a list of the most played thing_types by this thing, in a + tuple with the total number of pages of results. Includes an MBID, if + found. + """ + doc = self._request( + self.ws_prefix + "." + method, cacheable, params) + + toptracks_node = doc.getElementsByTagName('toptracks')[0] + total_pages = int(toptracks_node.getAttribute('totalPages')) + + seq = [] + for node in doc.getElementsByTagName(thing): + title = _extract(node, "name") + artist = _extract(node, "name", 1) + mbid = _extract(node, "mbid") + playcount = _number(_extract(node, "playcount")) + + thing = thing_type(artist, title, self.network) + thing.mbid = mbid + seq.append(TopItem(thing, playcount)) + + return seq, total_pages + + def get_top_tracks_by_page(self, period=pylast.PERIOD_OVERALL, limit=None, + page=1, cacheable=True): + """Returns the top tracks played by a user, in a tuple with the total + number of pages of results. + * period: The period of time. Possible values: + o PERIOD_OVERALL + o PERIOD_7DAYS + o PERIOD_1MONTH + o PERIOD_3MONTHS + o PERIOD_6MONTHS + o PERIOD_12MONTHS + """ + + params = self._get_params() + params['period'] = period + params['page'] = page + if limit: + params['limit'] = limit + + return self._get_things( + "getTopTracks", "track", pylast.Track, params, cacheable) + + def import_lastfm(lib, log): - user = config['lastfm']['user'].get(unicode) + user = config['lastfm']['user'].as_str() per_page = config['lastimport']['per_page'].get(int) if not user: - raise ui.UserError('You must specify a user name for lastimport') + raise ui.UserError(u'You must specify a user name for lastimport') - log.info('Fetching last.fm library for @{0}', user) + log.info(u'Fetching last.fm library for @{0}', user) page_total = 1 page_current = 0 @@ -67,63 +125,75 @@ def import_lastfm(lib, log): retry_limit = config['lastimport']['retry_limit'].get(int) # Iterate through a yet to be known page total count while page_current < page_total: - log.info('Querying page #{0}{1}...', + log.info(u'Querying page #{0}{1}...', page_current + 1, '/{}'.format(page_total) if page_total > 1 else '') for retry in range(0, retry_limit): - page = fetch_tracks(user, page_current + 1, per_page) - if 'tracks' in page: - # Let us the reveal the holy total pages! - page_total = int(page['tracks']['@attr']['totalPages']) - if page_total < 1: - # It means nothing to us! - raise ui.UserError('Last.fm reported no data.') + tracks, page_total = fetch_tracks(user, page_current + 1, per_page) + if page_total < 1: + # It means nothing to us! + raise ui.UserError(u'Last.fm reported no data.') - track = page['tracks']['track'] - found, unknown = process_tracks(lib, track, log) + if tracks: + found, unknown = process_tracks(lib, tracks, log) found_total += found unknown_total += unknown break else: - log.error('ERROR: unable to read page #{0}', + log.error(u'ERROR: unable to read page #{0}', page_current + 1) - log.debug('API response: {}', page) if retry < retry_limit: log.info( - 'Retrying page #{0}... ({1}/{2} retry)', + u'Retrying page #{0}... ({1}/{2} retry)', page_current + 1, retry + 1, retry_limit ) else: - log.error('FAIL: unable to fetch page #{0}, ', - 'tried {1} times', page_current, retry + 1) + log.error(u'FAIL: unable to fetch page #{0}, ', + u'tried {1} times', page_current, retry + 1) page_current += 1 - log.info('... done!') - log.info('finished processing {0} song pages', page_total) - log.info('{0} unknown play-counts', unknown_total) - log.info('{0} play-counts imported', found_total) + log.info(u'... done!') + log.info(u'finished processing {0} song pages', page_total) + log.info(u'{0} unknown play-counts', unknown_total) + log.info(u'{0} play-counts imported', found_total) def fetch_tracks(user, page, limit): - return requests.get(API_URL, params={ - 'method': 'library.gettracks', - 'user': user, - 'api_key': plugins.LASTFM_KEY, - 'page': bytes(page), - 'limit': bytes(limit), - 'format': 'json', - }).json() + """ JSON format: + [ + { + "mbid": "...", + "artist": "...", + "title": "...", + "playcount": "..." + } + ] + """ + network = pylast.LastFMNetwork(api_key=config['lastfm']['api_key']) + user_obj = CustomUser(user, network) + results, total_pages =\ + user_obj.get_top_tracks_by_page(limit=limit, page=page) + return [ + { + "mbid": track.item.mbid if track.item.mbid else '', + "artist": { + "name": track.item.artist.name + }, + "name": track.item.title, + "playcount": track.weight + } for track in results + ], total_pages def process_tracks(lib, tracks, log): total = len(tracks) total_found = 0 total_fails = 0 - log.info('Received {0} tracks in this page, processing...', total) + log.info(u'Received {0} tracks in this page, processing...', total) - for num in xrange(0, total): - song = '' + for num in range(0, total): + song = None trackid = tracks[num]['mbid'].strip() artist = tracks[num]['artist'].get('name', '').strip() title = tracks[num]['name'].strip() @@ -139,19 +209,8 @@ def process_tracks(lib, tracks, log): dbcore.query.MatchQuery('mb_trackid', trackid) ).get() - # Otherwise try artist/title/album - if not song: - log.debug(u'no match for mb_trackid {0}, trying by ' - u'artist/title/album', trackid) - query = dbcore.AndQuery([ - dbcore.query.SubstringQuery('artist', artist), - dbcore.query.SubstringQuery('title', title), - dbcore.query.SubstringQuery('album', album) - ]) - song = lib.items(query).get() - # If not, try just artist/title - if not song: + if song is None: log.debug(u'no album match, trying by artist/title') query = dbcore.AndQuery([ dbcore.query.SubstringQuery('artist', artist), @@ -160,7 +219,7 @@ def process_tracks(lib, tracks, log): song = lib.items(query).get() # Last resort, try just replacing to utf-8 quote - if not song: + if song is None: title = title.replace("'", u'\u2019') log.debug(u'no title match, trying utf-8 single quote') query = dbcore.AndQuery([ @@ -169,7 +228,7 @@ def process_tracks(lib, tracks, log): ]) song = lib.items(query).get() - if song: + if song is not None: count = int(song.get('play_count', 0)) new_count = int(tracks[num]['playcount']) log.debug(u'match: {0} - {1} ({2}) ' @@ -184,7 +243,7 @@ def process_tracks(lib, tracks, log): artist, title, album) if total_fails > 0: - log.info('Acquired {0}/{1} play-counts ({2} unknown)', + log.info(u'Acquired {0}/{1} play-counts ({2} unknown)', total_found, total, total_fails) return total_found, total_fails diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 59937d480..d9db8eadc 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,22 +16,46 @@ """Fetches, embeds, and displays lyrics. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import absolute_import, division, print_function +import difflib +import errno +import itertools +import json +import struct +import os.path import re import requests -import json import unicodedata -import urllib -import difflib -import itertools +from unidecode import unidecode import warnings -from HTMLParser import HTMLParseError +import six +from six.moves import urllib + +try: + from bs4 import SoupStrainer, BeautifulSoup + HAS_BEAUTIFUL_SOUP = True +except ImportError: + HAS_BEAUTIFUL_SOUP = False + +try: + import langdetect + HAS_LANGDETECT = True +except ImportError: + HAS_LANGDETECT = False + +try: + # PY3: HTMLParseError was removed in 3.5 as strict mode + # was deprecated in 3.3. + # https://docs.python.org/3.3/library/html.parser.html + from six.moves.html_parser import HTMLParseError +except ImportError: + class HTMLParseError(Exception): + pass from beets import plugins -from beets import config, ui - +from beets import ui +import beets DIV_RE = re.compile(r'<(/?)div>?', re.I) COMMENT_RE = re.compile(r'<!--.*-->', re.S) @@ -50,20 +75,62 @@ URL_CHARACTERS = { u'\u2016': u'-', u'\u2026': u'...', } +USER_AGENT = 'beets/{}'.format(beets.__version__) + +# The content for the base index.rst generated in ReST mode. +REST_INDEX_TEMPLATE = u'''Lyrics +====== + +* :ref:`Song index <genindex>` +* :ref:`search` + +Artist index: + +.. toctree:: + :maxdepth: 1 + :glob: + + artists/* +''' + +# The content for the base conf.py generated. +REST_CONF_TEMPLATE = u'''# -*- coding: utf-8 -*- +master_doc = 'index' +project = u'Lyrics' +copyright = u'none' +author = u'Various Authors' +latex_documents = [ + (master_doc, 'Lyrics.tex', project, + author, 'manual'), +] +epub_title = project +epub_author = author +epub_publisher = author +epub_copyright = copyright +epub_exclude_files = ['search.html'] +epub_tocdepth = 1 +epub_tocdup = False +''' # Utilities. +def unichar(i): + try: + return six.unichr(i) + except ValueError: + return struct.pack('i', i).decode('utf-32') + def unescape(text): - """Resolves &#xxx; HTML entities (and some others).""" + """Resolve &#xxx; HTML entities (and some others).""" if isinstance(text, bytes): - text = text.decode('utf8', 'ignore') + text = text.decode('utf-8', 'ignore') out = text.replace(u' ', u' ') def replchar(m): num = m.group(1) - return unichr(int(num)) + return unichar(int(num)) out = re.sub(u"&#(\d+);", replchar, out) return out @@ -81,7 +148,6 @@ def extract_text_in(html, starttag): """Extract the text from a <DIV> tag in the HTML starting with ``starttag``. Returns None if parsing fails. """ - # Strip off the leading text before opening tag. try: _, html = html.split(starttag, 1) @@ -106,7 +172,7 @@ def extract_text_in(html, starttag): parts.append(html[pos:match.start()]) break else: - print('no closing tag found!') + print(u'no closing tag found!') return return u''.join(parts) @@ -122,30 +188,33 @@ def search_pairs(item): and featured artists from the strings and add them as candidates. The method also tries to split multiple titles separated with `/`. """ + def generate_alternatives(string, patterns): + """Generate string alternatives by extracting first matching group for + each given pattern. + """ + alternatives = [string] + for pattern in patterns: + match = re.search(pattern, string, re.IGNORECASE) + if match: + alternatives.append(match.group(1)) + return alternatives title, artist = item.title, item.artist - titles = [title] - artists = [artist] - # Remove any featuring artists from the artists name - pattern = r"(.*?) {0}".format(plugins.feat_tokens()) - match = re.search(pattern, artist, re.IGNORECASE) - if match: - artists.append(match.group(1)) + patterns = [ + # Remove any featuring artists from the artists name + r"(.*?) {0}".format(plugins.feat_tokens())] + artists = generate_alternatives(artist, patterns) - # Remove a parenthesized suffix from a title string. Common - # examples include (live), (remix), and (acoustic). - pattern = r"(.+?)\s+[(].*[)]$" - match = re.search(pattern, title, re.IGNORECASE) - if match: - titles.append(match.group(1)) - - # Remove any featuring artists from the title - pattern = r"(.*?) {0}".format(plugins.feat_tokens(for_artist=False)) - for title in titles[:]: - match = re.search(pattern, title, re.IGNORECASE) - if match: - titles.append(match.group(1)) + patterns = [ + # Remove a parenthesized suffix from a title string. Common + # examples include (live), (remix), and (acoustic). + r"(.+?)\s+[(].*[)]$", + # Remove any featuring artists from the title + r"(.*?) {0}".format(plugins.feat_tokens(for_artist=False)), + # Remove part of title after colon ':' for songs with subtitles + r"(.+?)\s*:.*"] + titles = generate_alternatives(title, patterns) # Check for a dual song (e.g. Pink Floyd - Speak to Me / Breathe) # and each of them. @@ -158,6 +227,24 @@ def search_pairs(item): return itertools.product(artists, multi_titles) +def slug(text): + """Make a URL-safe, human-readable version of the given text + + This will do the following: + + 1. decode unicode characters into ASCII + 2. shift everything to lowercase + 3. strip whitespace + 4. replace other non-word characters with dashes + 5. strip extra dashes + + This somewhat duplicates the :func:`Google.slugify` function but + slugify is not as generic as this one, which can be reused + elsewhere. + """ + return re.sub(r'\W+', '-', unidecode(text).lower().strip()).strip('-') + + class Backend(object): def __init__(self, config, log): self._log = log @@ -165,11 +252,11 @@ class Backend(object): @staticmethod def _encode(s): """Encode the string for inclusion in a URL""" - if isinstance(s, unicode): + if isinstance(s, six.text_type): for char, repl in URL_CHARACTERS.items(): s = s.replace(char, repl) - s = s.encode('utf8', 'ignore') - return urllib.quote(s) + s = s.encode('utf-8', 'ignore') + return urllib.parse.quote(s) def build_url(self, artist, title): return self.URL_PATTERN % (self._encode(artist.title()), @@ -186,7 +273,9 @@ class Backend(object): # We're not overly worried about the NSA MITMing our lyrics scraper with warnings.catch_warnings(): warnings.simplefilter('ignore') - r = requests.get(url, verify=False) + r = requests.get(url, verify=False, headers={ + 'User-Agent': USER_AGENT, + }) except requests.RequestException as exc: self._log.debug(u'lyrics request failed: {0}', exc) return @@ -200,32 +289,123 @@ class Backend(object): class SymbolsReplaced(Backend): + REPLACEMENTS = { + r'\s+': '_', + '<': 'Less_Than', + '>': 'Greater_Than', + '#': 'Number_', + r'[\[\{]': '(', + r'[\]\}]': ')', + } + @classmethod def _encode(cls, s): - s = re.sub(r'\s+', '_', s) - s = s.replace("<", "Less_Than") - s = s.replace(">", "Greater_Than") - s = s.replace("#", "Number_") - s = re.sub(r'[\[\{]', '(', s) - s = re.sub(r'[\]\}]', ')', s) + for old, new in cls.REPLACEMENTS.items(): + s = re.sub(old, new, s) + return super(SymbolsReplaced, cls)._encode(s) class MusiXmatch(SymbolsReplaced): + REPLACEMENTS = dict(SymbolsReplaced.REPLACEMENTS, **{ + r'\s+': '-' + }) + URL_PATTERN = 'https://www.musixmatch.com/lyrics/%s/%s' def fetch(self, artist, title): url = self.build_url(artist, title) + html = self.fetch_url(url) if not html: return - lyrics = extract_text_between(html, - '"lyrics_body":', '"lyrics_language":') - return lyrics.strip(',"').replace('\\n', '\n') + if "We detected that your IP is blocked" in html: + self._log.warning(u'we are blocked at MusixMatch: url %s failed' + % url) + return + html_part = html.split('<p class="mxm-lyrics__content')[-1] + lyrics = extract_text_between(html_part, '>', '</p>') + lyrics = lyrics.strip(',"').replace('\\n', '\n') + # another odd case: sometimes only that string remains, for + # missing songs. this seems to happen after being blocked + # above, when filling in the CAPTCHA. + if "Instant lyrics for all your music." in lyrics: + return + return lyrics + + +class Genius(Backend): + """Fetch lyrics from Genius via genius-api. + + Simply adapted from + bigishdata.com/2016/09/27/getting-song-lyrics-from-geniuss-api-scraping/ + """ + + base_url = "https://api.genius.com" + + def __init__(self, config, log): + super(Genius, self).__init__(config, log) + self.api_key = config['genius_api_key'].as_str() + self.headers = { + 'Authorization': "Bearer %s" % self.api_key, + 'User-Agent': USER_AGENT, + } + + def lyrics_from_song_api_path(self, song_api_path): + song_url = self.base_url + song_api_path + response = requests.get(song_url, headers=self.headers) + json = response.json() + path = json["response"]["song"]["path"] + + # Gotta go regular html scraping... come on Genius. + page_url = "https://genius.com" + path + try: + page = requests.get(page_url) + except requests.RequestException as exc: + self._log.debug(u'Genius page request for {0} failed: {1}', + page_url, exc) + return None + html = BeautifulSoup(page.text, "html.parser") + + # Remove script tags that they put in the middle of the lyrics. + [h.extract() for h in html('script')] + + # At least Genius is nice and has a tag called 'lyrics'! + # Updated css where the lyrics are based in HTML. + lyrics = html.find("div", class_="lyrics").get_text() + + return lyrics + + def fetch(self, artist, title): + search_url = self.base_url + "/search" + data = {'q': title} + try: + response = requests.get(search_url, data=data, + headers=self.headers) + except requests.RequestException as exc: + self._log.debug(u'Genius API request failed: {0}', exc) + return None + + try: + json = response.json() + except ValueError: + self._log.debug(u'Genius API request returned invalid JSON') + return None + + song_info = None + for hit in json["response"]["hits"]: + if hit["result"]["primary_artist"]["name"] == artist: + song_info = hit + break + + if song_info: + song_api_path = song_info["result"]["api_path"] + return self.lyrics_from_song_api_path(song_api_path) class LyricsWiki(SymbolsReplaced): """Fetch lyrics from LyricsWiki.""" + URL_PATTERN = 'http://lyrics.wikia.com/%s:%s' def fetch(self, artist, title): @@ -233,41 +413,15 @@ class LyricsWiki(SymbolsReplaced): html = self.fetch_url(url) if not html: return - lyrics = extract_text_in(html, u"<div class='lyricbox'>") - if lyrics and 'Unfortunately, we are not licensed' not in lyrics: - return lyrics + # Get the HTML fragment inside the appropriate HTML element and then + # extract the text from it. + html_frag = extract_text_in(html, u"<div class='lyricbox'>") + if html_frag: + lyrics = _scrape_strip_cruft(html_frag, True) -class LyricsCom(Backend): - """Fetch lyrics from Lyrics.com.""" - URL_PATTERN = 'http://www.lyrics.com/%s-lyrics-%s.html' - NOT_FOUND = ( - 'Sorry, we do not have the lyric', - 'Submit Lyrics', - ) - - @classmethod - def _encode(cls, s): - s = re.sub(r'[^\w\s-]', '', s) - s = re.sub(r'\s+', '-', s) - return super(LyricsCom, cls)._encode(s).lower() - - def fetch(self, artist, title): - url = self.build_url(artist, title) - html = self.fetch_url(url) - if not html: - return - lyrics = extract_text_between(html, '<div id="lyrics" class="SCREENO' - 'NLY" itemprop="description">', '</div>') - if not lyrics: - return - for not_found_str in self.NOT_FOUND: - if not_found_str in lyrics: - return - - parts = lyrics.split('\n---\nLyrics powered by', 1) - if parts: - return parts[0] + if lyrics and 'Unfortunately, we are not licensed' not in lyrics: + return lyrics def remove_credits(text): @@ -312,7 +466,8 @@ def scrape_lyrics_from_html(html): """Scrape lyrics from a URL. If no lyrics can be found, return None instead. """ - from bs4 import SoupStrainer, BeautifulSoup + if not HAS_BEAUTIFUL_SOUP: + return None if not html: return None @@ -331,45 +486,51 @@ def scrape_lyrics_from_html(html): parse_only=SoupStrainer(text=is_text_notcode)) except HTMLParseError: return None - soup = sorted(soup.stripped_strings, key=len)[-1] - return soup + + # Get the longest text element (if any). + strings = sorted(soup.stripped_strings, key=len, reverse=True) + if strings: + return strings[0] + else: + return None class Google(Backend): """Fetch lyrics from Google search results.""" + def __init__(self, config, log): super(Google, self).__init__(config, log) - self.api_key = config['google_API_key'].get(unicode) - self.engine_id = config['google_engine_ID'].get(unicode) + self.api_key = config['google_API_key'].as_str() + self.engine_id = config['google_engine_ID'].as_str() def is_lyrics(self, text, artist=None): """Determine whether the text seems to be valid lyrics. """ if not text: return False - badTriggersOcc = [] - nbLines = text.count('\n') - if nbLines <= 1: + bad_triggers_occ = [] + nb_lines = text.count('\n') + if nb_lines <= 1: self._log.debug(u"Ignoring too short lyrics '{0}'", text) return False - elif nbLines < 5: - badTriggersOcc.append('too_short') + elif nb_lines < 5: + bad_triggers_occ.append('too_short') else: # Lyrics look legit, remove credits to avoid being penalized # further down text = remove_credits(text) - badTriggers = ['lyrics', 'copyright', 'property', 'links'] + bad_triggers = ['lyrics', 'copyright', 'property', 'links'] if artist: - badTriggersOcc += [artist] + bad_triggers_occ += [artist] - for item in badTriggers: - badTriggersOcc += [item] * len(re.findall(r'\W%s\W' % item, - text, re.I)) + for item in bad_triggers: + bad_triggers_occ += [item] * len(re.findall(r'\W%s\W' % item, + text, re.I)) - if badTriggersOcc: - self._log.debug(u'Bad triggers detected: {0}', badTriggersOcc) - return len(badTriggersOcc) < 2 + if bad_triggers_occ: + self._log.debug(u'Bad triggers detected: {0}', bad_triggers_occ) + return len(bad_triggers_occ) < 2 def slugify(self, text): """Normalize a string and remove non-alphanumeric characters. @@ -381,7 +542,7 @@ class Google(Backend): try: text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore') - text = unicode(re.sub('[-\s]+', ' ', text)) + text = six.text_type(re.sub('[-\s]+', ' ', text.decode('utf-8'))) except UnicodeDecodeError: self._log.exception(u"Failing to normalize '{0}'", text) return text @@ -389,50 +550,60 @@ class Google(Backend): BY_TRANS = ['by', 'par', 'de', 'von'] LYRICS_TRANS = ['lyrics', 'paroles', 'letras', 'liedtexte'] - def is_page_candidate(self, urlLink, urlTitle, title, artist): + def is_page_candidate(self, url_link, url_title, title, artist): """Return True if the URL title makes it a good candidate to be a page that contains lyrics of title by artist. """ title = self.slugify(title.lower()) artist = self.slugify(artist.lower()) sitename = re.search(u"//([^/]+)/.*", - self.slugify(urlLink.lower())).group(1) - urlTitle = self.slugify(urlTitle.lower()) + self.slugify(url_link.lower())).group(1) + url_title = self.slugify(url_title.lower()) + # Check if URL title contains song title (exact match) - if urlTitle.find(title) != -1: + if url_title.find(title) != -1: return True + # or try extracting song title from URL title and check if # they are close enough tokens = [by + '_' + artist for by in self.BY_TRANS] + \ [artist, sitename, sitename.replace('www.', '')] + \ self.LYRICS_TRANS - songTitle = re.sub(u'(%s)' % u'|'.join(tokens), u'', urlTitle) - songTitle = songTitle.strip('_|') - typoRatio = .9 - ratio = difflib.SequenceMatcher(None, songTitle, title).ratio() - return ratio >= typoRatio + tokens = [re.escape(t) for t in tokens] + song_title = re.sub(u'(%s)' % u'|'.join(tokens), u'', url_title) + + song_title = song_title.strip('_|') + typo_ratio = .9 + ratio = difflib.SequenceMatcher(None, song_title, title).ratio() + return ratio >= typo_ratio def fetch(self, artist, title): query = u"%s %s" % (artist, title) url = u'https://www.googleapis.com/customsearch/v1?key=%s&cx=%s&q=%s' \ % (self.api_key, self.engine_id, - urllib.quote(query.encode('utf8'))) + urllib.parse.quote(query.encode('utf-8'))) - data = urllib.urlopen(url) - data = json.load(data) + data = self.fetch_url(url) + if not data: + self._log.debug(u'google backend returned no data') + return None + try: + data = json.loads(data) + except ValueError as exc: + self._log.debug(u'google backend returned malformed JSON: {}', exc) if 'error' in data: reason = data['error']['errors'][0]['reason'] - self._log.debug(u'google lyrics backend error: {0}', reason) - return + self._log.debug(u'google backend error: {0}', reason) + return None if 'items' in data.keys(): for item in data['items']: - urlLink = item['link'] - urlTitle = item.get('title', u'') - if not self.is_page_candidate(urlLink, urlTitle, + url_link = item['link'] + url_title = item.get('title', u'') + if not self.is_page_candidate(url_link, url_title, title, artist): continue - html = self.fetch_url(urlLink) + html = self.fetch_url(url_link) lyrics = scrape_lyrics_from_html(html) if not lyrics: continue @@ -444,12 +615,12 @@ class Google(Backend): class LyricsPlugin(plugins.BeetsPlugin): - SOURCES = ['google', 'lyricwiki', 'lyrics.com', 'musixmatch'] + SOURCES = ['google', 'lyricwiki', 'musixmatch', 'genius'] SOURCE_BACKENDS = { 'google': Google, 'lyricwiki': LyricsWiki, - 'lyrics.com': LyricsCom, 'musixmatch': MusiXmatch, + 'genius': Genius, } def __init__(self): @@ -457,49 +628,196 @@ class LyricsPlugin(plugins.BeetsPlugin): self.import_stages = [self.imported] self.config.add({ 'auto': True, + 'bing_client_secret': None, + 'bing_lang_from': [], + 'bing_lang_to': None, 'google_API_key': None, 'google_engine_ID': u'009217259823014548361:lndtuqkycfu', + 'genius_api_key': + "Ryq93pUGm8bM6eUWwD_M3NOFFDAtp2yEE7W" + "76V-uFL5jks5dNvcGCdarqFjDhP9c", 'fallback': None, 'force': False, + 'local': False, 'sources': self.SOURCES, }) + self.config['bing_client_secret'].redact = True self.config['google_API_key'].redact = True self.config['google_engine_ID'].redact = True + self.config['genius_api_key'].redact = True + + # State information for the ReST writer. + # First, the current artist we're writing. + self.artist = u'Unknown artist' + # The current album: False means no album yet. + self.album = False + # The current rest file content. None means the file is not + # open yet. + self.rest = None available_sources = list(self.SOURCES) - if not self.config['google_API_key'].get() and \ - 'google' in self.SOURCES: - available_sources.remove('google') - self.config['sources'] = plugins.sanitize_choices( + sources = plugins.sanitize_choices( self.config['sources'].as_str_seq(), available_sources) - self.backends = [self.SOURCE_BACKENDS[key](self.config, self._log) - for key in self.config['sources'].as_str_seq()] + if 'google' in sources: + if not self.config['google_API_key'].get(): + # We log a *debug* message here because the default + # configuration includes `google`. This way, the source + # is silent by default but can be enabled just by + # setting an API key. + self._log.debug(u'Disabling google source: ' + u'no API key configured.') + sources.remove('google') + elif not HAS_BEAUTIFUL_SOUP: + self._log.warning(u'To use the google lyrics source, you must ' + u'install the beautifulsoup4 module. See ' + u'the documentation for further details.') + sources.remove('google') + + if 'genius' in sources and not HAS_BEAUTIFUL_SOUP: + self._log.debug( + u'The Genius backend requires BeautifulSoup, which is not ' + u'installed, so the source is disabled.' + ) + sources.remove('google') + + self.config['bing_lang_from'] = [ + x.lower() for x in self.config['bing_lang_from'].as_str_seq()] + self.bing_auth_token = None + + if not HAS_LANGDETECT and self.config['bing_client_secret'].get(): + self._log.warning(u'To use bing translations, you need to ' + u'install the langdetect module. See the ' + u'documentation for further details.') + + self.backends = [self.SOURCE_BACKENDS[source](self.config, self._log) + for source in sources] + + def get_bing_access_token(self): + params = { + 'client_id': 'beets', + 'client_secret': self.config['bing_client_secret'], + 'scope': "https://api.microsofttranslator.com", + 'grant_type': 'client_credentials', + } + + oauth_url = 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13' + oauth_token = json.loads(requests.post( + oauth_url, + data=urllib.parse.urlencode(params)).content) + if 'access_token' in oauth_token: + return "Bearer " + oauth_token['access_token'] + else: + self._log.warning(u'Could not get Bing Translate API access token.' + u' Check your "bing_client_secret" password') def commands(self): cmd = ui.Subcommand('lyrics', help='fetch song lyrics') - cmd.parser.add_option('-p', '--print', dest='printlyr', - action='store_true', default=False, - help='print lyrics to console') - cmd.parser.add_option('-f', '--force', dest='force_refetch', - action='store_true', default=False, - help='always re-download lyrics') + cmd.parser.add_option( + u'-p', u'--print', dest='printlyr', + action='store_true', default=False, + help=u'print lyrics to console', + ) + cmd.parser.add_option( + u'-r', u'--write-rest', dest='writerest', + action='store', default=None, metavar='dir', + help=u'write lyrics to given directory as ReST files', + ) + cmd.parser.add_option( + u'-f', u'--force', dest='force_refetch', + action='store_true', default=False, + help=u'always re-download lyrics', + ) + cmd.parser.add_option( + u'-l', u'--local', dest='local_only', + action='store_true', default=False, + help=u'do not fetch missing lyrics', + ) def func(lib, opts, args): # The "write to files" option corresponds to the # import_write config value. - write = config['import']['write'].get(bool) + write = ui.should_write() + if opts.writerest: + self.writerest_indexes(opts.writerest) for item in lib.items(ui.decargs(args)): - self.fetch_item_lyrics( - lib, item, write, - opts.force_refetch or self.config['force'], - ) - if opts.printlyr and item.lyrics: - ui.print_(item.lyrics) - + if not opts.local_only and not self.config['local']: + self.fetch_item_lyrics( + lib, item, write, + opts.force_refetch or self.config['force'], + ) + if item.lyrics: + if opts.printlyr: + ui.print_(item.lyrics) + if opts.writerest: + self.writerest(opts.writerest, item) + if opts.writerest: + # flush last artist + self.writerest(opts.writerest, None) + ui.print_(u'ReST files generated. to build, use one of:') + ui.print_(u' sphinx-build -b html %s _build/html' + % opts.writerest) + ui.print_(u' sphinx-build -b epub %s _build/epub' + % opts.writerest) + ui.print_((u' sphinx-build -b latex %s _build/latex ' + u'&& make -C _build/latex all-pdf') + % opts.writerest) cmd.func = func return [cmd] + def writerest(self, directory, item): + """Write the item to an ReST file + + This will keep state (in the `rest` variable) in order to avoid + writing continuously to the same files. + """ + + if item is None or slug(self.artist) != slug(item.artist): + if self.rest is not None: + path = os.path.join(directory, 'artists', + slug(self.artist) + u'.rst') + with open(path, 'wb') as output: + output.write(self.rest.encode('utf-8')) + self.rest = None + if item is None: + return + self.artist = item.artist.strip() + self.rest = u"%s\n%s\n\n.. contents::\n :local:\n\n" \ + % (self.artist, + u'=' * len(self.artist)) + if self.album != item.album: + tmpalbum = self.album = item.album.strip() + if self.album == '': + tmpalbum = u'Unknown album' + self.rest += u"%s\n%s\n\n" % (tmpalbum, u'-' * len(tmpalbum)) + title_str = u":index:`%s`" % item.title.strip() + block = u'| ' + item.lyrics.replace(u'\n', u'\n| ') + self.rest += u"%s\n%s\n\n%s\n\n" % (title_str, + u'~' * len(title_str), + block) + + def writerest_indexes(self, directory): + """Write conf.py and index.rst files necessary for Sphinx + + We write minimal configurations that are necessary for Sphinx + to operate. We do not overwrite existing files so that + customizations are respected.""" + try: + os.makedirs(os.path.join(directory, 'artists')) + except OSError as e: + if e.errno == errno.EEXIST: + pass + else: + raise + indexfile = os.path.join(directory, 'index.rst') + if not os.path.exists(indexfile): + with open(indexfile, 'w') as output: + output.write(REST_INDEX_TEMPLATE) + conffile = os.path.join(directory, 'conf.py') + if not os.path.exists(conffile): + with open(conffile, 'w') as output: + output.write(REST_CONF_TEMPLATE) + def imported(self, session, task): """Import hook for fetching lyrics automatically. """ @@ -510,7 +828,8 @@ class LyricsPlugin(plugins.BeetsPlugin): def fetch_item_lyrics(self, lib, item, write, force): """Fetch and store lyrics for a single item. If ``write``, then the - lyrics will also be written to the file itself.""" + lyrics will also be written to the file itself. + """ # Skip if the item already has lyrics. if not force and item.lyrics: self._log.info(u'lyrics already present: {0}', item) @@ -526,6 +845,14 @@ class LyricsPlugin(plugins.BeetsPlugin): if lyrics: self._log.info(u'fetched lyrics: {0}', item) + if HAS_LANGDETECT and self.config['bing_client_secret'].get(): + lang_from = langdetect.detect(lyrics) + if self.config['bing_lang_to'].get() != lang_from and ( + not self.config['bing_lang_from'] or ( + lang_from in self.config[ + 'bing_lang_from'].as_str_seq())): + lyrics = self.append_translation( + lyrics, self.config['bing_lang_to']) else: self._log.info(u'lyrics not found: {0}', item) fallback = self.config['fallback'].get() @@ -533,9 +860,7 @@ class LyricsPlugin(plugins.BeetsPlugin): lyrics = fallback else: return - item.lyrics = lyrics - if write: item.try_write() item.store() @@ -550,3 +875,30 @@ class LyricsPlugin(plugins.BeetsPlugin): self._log.debug(u'got lyrics from backend: {0}', backend.__class__.__name__) return _scrape_strip_cruft(lyrics, True) + + def append_translation(self, text, to_lang): + import xml.etree.ElementTree as ET + + if not self.bing_auth_token: + self.bing_auth_token = self.get_bing_access_token() + if self.bing_auth_token: + # Extract unique lines to limit API request size per song + text_lines = set(text.split('\n')) + url = ('https://api.microsofttranslator.com/v2/Http.svc/' + 'Translate?text=%s&to=%s' % ('|'.join(text_lines), to_lang)) + r = requests.get(url, + headers={"Authorization ": self.bing_auth_token}) + if r.status_code != 200: + self._log.debug('translation API error {}: {}', r.status_code, + r.text) + if 'token has expired' in r.text: + self.bing_auth_token = None + return self.append_translation(text, to_lang) + return text + lines_translated = ET.fromstring(r.text.encode('utf-8')).text + # Use a translation mapping dict to build resulting lyrics + translations = dict(zip(text_lines, lines_translated.split('|'))) + result = '' + for line in text.split('\n'): + result += '%s / %s\n' % (line, translations[line]) + return result diff --git a/beetsplug/mbcollection.py b/beetsplug/mbcollection.py index 6dc724636..d99c386c9 100644 --- a/beetsplug/mbcollection.py +++ b/beetsplug/mbcollection.py @@ -1,19 +1,19 @@ -# Copyright (c) 2011, Jeffrey Aylesworth <jeffrey@aylesworth.ca> +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright (c) 2011, Jeffrey Aylesworth <mail@jeffrey.red> # -# Permission to use, copy, modify, and/or distribute this software for any -# purpose with or without fee is hereby granted, provided that the above -# copyright notice and this permission notice appear in all copies. +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: # -# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets.ui import Subcommand @@ -24,6 +24,7 @@ import musicbrainzngs import re SUBMISSION_CHUNK_SIZE = 200 +FETCH_CHUNK_SIZE = 100 UUID_REGEX = r'^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$' @@ -33,11 +34,11 @@ def mb_call(func, *args, **kwargs): try: return func(*args, **kwargs) except musicbrainzngs.AuthenticationError: - raise ui.UserError('authentication with MusicBrainz failed') + raise ui.UserError(u'authentication with MusicBrainz failed') except (musicbrainzngs.ResponseError, musicbrainzngs.NetworkError) as exc: - raise ui.UserError('MusicBrainz API error: {0}'.format(exc)) + raise ui.UserError(u'MusicBrainz API error: {0}'.format(exc)) except musicbrainzngs.UsageError: - raise ui.UserError('MusicBrainz credentials missing') + raise ui.UserError(u'MusicBrainz credentials missing') def submit_albums(collection_id, release_ids): @@ -55,44 +56,95 @@ def submit_albums(collection_id, release_ids): class MusicBrainzCollectionPlugin(BeetsPlugin): def __init__(self): super(MusicBrainzCollectionPlugin, self).__init__() + config['musicbrainz']['pass'].redact = True musicbrainzngs.auth( - config['musicbrainz']['user'].get(unicode), - config['musicbrainz']['pass'].get(unicode), + config['musicbrainz']['user'].as_str(), + config['musicbrainz']['pass'].as_str(), ) - self.config.add({'auto': False}) + self.config.add({ + 'auto': False, + 'collection': u'', + 'remove': False, + }) if self.config['auto']: self.import_stages = [self.imported] + def _get_collection(self): + collections = mb_call(musicbrainzngs.get_collections) + if not collections['collection-list']: + raise ui.UserError(u'no collections exist for user') + + # Get all collection IDs, avoiding event collections + collection_ids = [x['id'] for x in collections['collection-list']] + if not collection_ids: + raise ui.UserError(u'No collection found.') + + # Check that the collection exists so we can present a nice error + collection = self.config['collection'].as_str() + if collection: + if collection not in collection_ids: + raise ui.UserError(u'invalid collection ID: {}' + .format(collection)) + return collection + + # No specified collection. Just return the first collection ID + return collection_ids[0] + + def _get_albums_in_collection(self, id): + def _fetch(offset): + res = mb_call( + musicbrainzngs.get_releases_in_collection, + id, + limit=FETCH_CHUNK_SIZE, + offset=offset + )['collection'] + return [x['id'] for x in res['release-list']], res['release-count'] + + offset = 0 + albums_in_collection, release_count = _fetch(offset) + for i in range(0, release_count, FETCH_CHUNK_SIZE): + albums_in_collection += _fetch(offset)[0] + offset += FETCH_CHUNK_SIZE + + return albums_in_collection + def commands(self): - mbupdate = Subcommand('mbupdate', help='Update MusicBrainz collection') + mbupdate = Subcommand('mbupdate', + help=u'Update MusicBrainz collection') + mbupdate.parser.add_option('-r', '--remove', + action='store_true', + default=None, + dest='remove', + help='Remove albums not in beets library') mbupdate.func = self.update_collection return [mbupdate] + def remove_missing(self, collection_id, lib_albums): + lib_ids = set([x.mb_albumid for x in lib_albums]) + albums_in_collection = self._get_albums_in_collection(collection_id) + remove_me = list(set(albums_in_collection) - lib_ids) + for i in range(0, len(remove_me), FETCH_CHUNK_SIZE): + chunk = remove_me[i:i + FETCH_CHUNK_SIZE] + mb_call( + musicbrainzngs.remove_releases_from_collection, + collection_id, chunk + ) + def update_collection(self, lib, opts, args): - self.update_album_list(lib.albums()) + self.config.set_args(opts) + remove_missing = self.config['remove'].get(bool) + self.update_album_list(lib, lib.albums(), remove_missing) def imported(self, session, task): """Add each imported album to the collection. """ if task.is_album: - self.update_album_list([task.album]) + self.update_album_list(session.lib, [task.album]) - def update_album_list(self, album_list): - """Update the MusicBrainz colleciton from a list of Beets albums + def update_album_list(self, lib, album_list, remove_missing=False): + """Update the MusicBrainz collection from a list of Beets albums """ - # Get the available collections. - collections = mb_call(musicbrainzngs.get_collections) - if not collections['collection-list']: - raise ui.UserError('no collections exist for user') - - # Get the first release collection. MusicBrainz also has event - # collections, so we need to avoid adding to those. - for collection in collections['collection-list']: - if 'release-count' in collection: - collection_id = collection['id'] - break - else: - raise ui.UserError('No collection found.') + collection_id = self._get_collection() # Get a list of all the album IDs. album_ids = [] @@ -105,6 +157,10 @@ class MusicBrainzCollectionPlugin(BeetsPlugin): self._log.info(u'skipping invalid MBID: {0}', aid) # Submit to MusicBrainz. - self._log.info('Updating MusicBrainz collection {0}...', collection_id) + self._log.info( + u'Updating MusicBrainz collection {0}...', collection_id + ) submit_albums(collection_id, album_ids) - self._log.info('...MusicBrainz collection updated.') + if remove_missing: + self.remove_missing(collection_id, lib.albums()) + self._log.info(u'...MusicBrainz collection updated.') diff --git a/beetsplug/mbsubmit.py b/beetsplug/mbsubmit.py new file mode 100644 index 000000000..02bd5f697 --- /dev/null +++ b/beetsplug/mbsubmit.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Adrian Sampson and Diego Moreda. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Aid in submitting information to MusicBrainz. + +This plugin allows the user to print track information in a format that is +parseable by the MusicBrainz track parser [1]. Programmatic submitting is not +implemented by MusicBrainz yet. + +[1] http://wiki.musicbrainz.org/History:How_To_Parse_Track_Listings +""" + +from __future__ import division, absolute_import, print_function + + +from beets.autotag import Recommendation +from beets.plugins import BeetsPlugin +from beets.ui.commands import PromptChoice +from beetsplug.info import print_data + + +class MBSubmitPlugin(BeetsPlugin): + def __init__(self): + super(MBSubmitPlugin, self).__init__() + + self.config.add({ + 'format': u'$track. $title - $artist ($length)', + 'threshold': 'medium', + }) + + # Validate and store threshold. + self.threshold = self.config['threshold'].as_choice({ + 'none': Recommendation.none, + 'low': Recommendation.low, + 'medium': Recommendation.medium, + 'strong': Recommendation.strong + }) + + self.register_listener('before_choose_candidate', + self.before_choose_candidate_event) + + def before_choose_candidate_event(self, session, task): + if task.rec <= self.threshold: + return [PromptChoice(u'p', u'Print tracks', self.print_tracks)] + + def print_tracks(self, session, task): + for i in sorted(task.items, key=lambda i: i.track): + print_data(None, i, self.config['format'].as_str()) diff --git a/beetsplug/mbsync.py b/beetsplug/mbsync.py index 974f7e894..cf58c82d5 100644 --- a/beetsplug/mbsync.py +++ b/beetsplug/mbsync.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Jakob Schnitzer. +# Copyright 2016, Jakob Schnitzer. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,13 +15,11 @@ """Update library's tags using MusicBrainz. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets import autotag, library, ui, util from beets.autotag import hooks -from beets import config from collections import defaultdict @@ -43,15 +42,20 @@ class MBSyncPlugin(BeetsPlugin): def commands(self): cmd = ui.Subcommand('mbsync', - help='update metadata from musicbrainz') - cmd.parser.add_option('-p', '--pretend', action='store_true', - help='show all changes but do nothing') - cmd.parser.add_option('-M', '--nomove', action='store_false', - default=True, dest='move', - help="don't move files in library") - cmd.parser.add_option('-W', '--nowrite', action='store_false', - default=config['import']['write'], dest='write', - help="don't write updated metadata to files") + help=u'update metadata from musicbrainz') + cmd.parser.add_option( + u'-p', u'--pretend', action='store_true', + help=u'show all changes but do nothing') + cmd.parser.add_option( + u'-m', u'--move', action='store_true', dest='move', + help=u"move files in the library directory") + cmd.parser.add_option( + u'-M', u'--nomove', action='store_false', dest='move', + help=u"don't move files in library") + cmd.parser.add_option( + u'-W', u'--nowrite', action='store_false', + default=None, dest='write', + help=u"don't write updated metadata to files") cmd.parser.add_format_option() cmd.func = self.func return [cmd] @@ -59,9 +63,9 @@ class MBSyncPlugin(BeetsPlugin): def func(self, lib, opts, args): """Command handler for the mbsync function. """ - move = opts.move + move = ui.should_move(opts.move) pretend = opts.pretend - write = opts.write + write = ui.should_write(opts.write) query = ui.decargs(args) self.singletons(lib, query, move, pretend, write) @@ -71,7 +75,7 @@ class MBSyncPlugin(BeetsPlugin): """Retrieve and apply info from the autotagger for items matched by query. """ - for item in lib.items(query + ['singleton:true']): + for item in lib.items(query + [u'singleton:true']): item_formatted = format(item) if not item.mb_trackid: self._log.info(u'Skipping singleton with no mb_trackid: {0}', @@ -137,6 +141,7 @@ class MBSyncPlugin(BeetsPlugin): break # Apply. + self._log.debug(u'applying changes to {}', album_formatted) with lib.transaction(): autotag.apply_metadata(album_info, mapping) changed = False diff --git a/beetsplug/metasync/__init__.py b/beetsplug/metasync/__init__.py index 380c72707..02f0b0f9b 100644 --- a/beetsplug/metasync/__init__.py +++ b/beetsplug/metasync/__init__.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Heinz Wiesinger. +# Copyright 2016, Heinz Wiesinger. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,12 +15,16 @@ """Synchronize information from music player libraries """ + +from __future__ import division, absolute_import, print_function + from abc import abstractmethod, ABCMeta from importlib import import_module from beets.util.confit import ConfigValueError from beets import ui from beets.plugins import BeetsPlugin +import six METASYNC_MODULE = 'beetsplug.metasync' @@ -31,9 +36,7 @@ SOURCES = { } -class MetaSource(object): - __metaclass__ = ABCMeta - +class MetaSource(six.with_metaclass(ABCMeta, object)): def __init__(self, config, log): self.item_types = {} self.config = config @@ -111,11 +114,13 @@ class MetaSyncPlugin(BeetsPlugin): # Instantiate the meta sources for player in sources: try: - meta_source_instances[player] = \ - META_SOURCES[player](self.config, self._log) + cls = META_SOURCES[player] except KeyError: self._log.error(u'Unknown metadata source \'{0}\''.format( player)) + + try: + meta_source_instances[player] = cls(self.config, self._log) except (ImportError, ConfigValueError) as e: self._log.error(u'Failed to instantiate metadata source ' u'\'{0}\': {1}'.format(player, e)) diff --git a/beetsplug/metasync/amarok.py b/beetsplug/metasync/amarok.py index b544c22ec..0622fc17a 100644 --- a/beetsplug/metasync/amarok.py +++ b/beetsplug/metasync/amarok.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Heinz Wiesinger. +# Copyright 2016, Heinz Wiesinger. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,10 +16,12 @@ """Synchronize information from amarok's library via dbus """ +from __future__ import division, absolute_import, print_function + from os.path import basename from datetime import datetime from time import mktime -from xml.sax.saxutils import escape +from xml.sax.saxutils import quoteattr from beets.util import displayable_path from beets.dbcore import types @@ -48,7 +51,7 @@ class Amarok(MetaSource): queryXML = u'<query version="1.0"> \ <filters> \ - <and><include field="filename" value="%s" /></and> \ + <and><include field="filename" value=%s /></and> \ </filters> \ </query>' @@ -68,7 +71,9 @@ class Amarok(MetaSource): # for the patch relative to the mount point. But the full path is part # of the result set. So query for the filename and then try to match # the correct item from the results we get back - results = self.collection.Query(self.queryXML % escape(basename(path))) + results = self.collection.Query( + self.queryXML % quoteattr(basename(path)) + ) for result in results: if result['xesam:url'] != path: continue diff --git a/beetsplug/metasync/itunes.py b/beetsplug/metasync/itunes.py index b2795f9a4..17ab1637f 100644 --- a/beetsplug/metasync/itunes.py +++ b/beetsplug/metasync/itunes.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Tom Jaspers. +# Copyright 2016, Tom Jaspers. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,13 +15,16 @@ """Synchronize information from iTunes's library """ + +from __future__ import division, absolute_import, print_function + from contextlib import contextmanager import os import shutil import tempfile import plistlib -import urllib -from urlparse import urlparse + +from six.moves.urllib.parse import urlparse, unquote from time import mktime from beets import util @@ -53,7 +57,7 @@ def _norm_itunes_path(path): # E.g., '\\G:\\Music\\bar' needs to be stripped to 'G:\\Music\\bar' return util.bytestring_path(os.path.normpath( - urllib.unquote(urlparse(path).path)).lstrip('\\')).lower() + unquote(urlparse(path).path)).lstrip('\\')).lower() class Itunes(MetaSource): @@ -94,7 +98,8 @@ class Itunes(MetaSource): # Make the iTunes library queryable using the path self.collection = {_norm_itunes_path(track['Location']): track - for track in raw_library['Tracks'].values()} + for track in raw_library['Tracks'].values() + if 'Location' in track} def sync_from_source(self, item): result = self.collection.get(util.bytestring_path(item.path).lower()) diff --git a/beetsplug/missing.py b/beetsplug/missing.py index 75b3e58e8..8f0790f2b 100644 --- a/beetsplug/missing.py +++ b/beetsplug/missing.py @@ -1,5 +1,7 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Pedro Silva. +# Copyright 2016, Pedro Silva. +# Copyright 2017, Quentin Young. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,14 +16,18 @@ """List missing tracks. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function +import musicbrainzngs + +from musicbrainzngs.musicbrainz import MusicBrainzError +from collections import defaultdict from beets.autotag import hooks from beets.library import Item from beets.plugins import BeetsPlugin from beets.ui import decargs, print_, Subcommand from beets import config +from beets.dbcore import types def _missing_count(album): @@ -81,12 +87,18 @@ def _item(track_info, album_info, album_id): class MissingPlugin(BeetsPlugin): """List missing tracks """ + + album_types = { + 'missing': types.INTEGER, + } + def __init__(self): super(MissingPlugin, self).__init__() self.config.add({ 'count': False, 'total': False, + 'album': False, }) self.album_template_fields['missing'] = _missing_count @@ -94,46 +106,116 @@ class MissingPlugin(BeetsPlugin): self._command = Subcommand('missing', help=__doc__, aliases=['miss']) - self._command.parser.add_option('-c', '--count', dest='count', - action='store_true', - help='count missing tracks per album') - self._command.parser.add_option('-t', '--total', dest='total', - action='store_true', - help='count total of missing tracks') + self._command.parser.add_option( + u'-c', u'--count', dest='count', action='store_true', + help=u'count missing tracks per album') + self._command.parser.add_option( + u'-t', u'--total', dest='total', action='store_true', + help=u'count total of missing tracks') + self._command.parser.add_option( + u'-a', u'--album', dest='album', action='store_true', + help=u'show missing albums for artist instead of tracks') self._command.parser.add_format_option() def commands(self): def _miss(lib, opts, args): self.config.set_args(opts) - count = self.config['count'].get() - total = self.config['total'].get() - fmt = config['format_album' if count else 'format_item'].get() + albms = self.config['album'].get() - albums = lib.albums(decargs(args)) - if total: - print(sum([_missing_count(a) for a in albums])) - return - - # Default format string for count mode. - if count: - fmt += ': $missing' - - for album in albums: - if count: - if _missing_count(album): - print_(format(album, fmt)) - - else: - for item in self._missing(album): - print_(format(item, fmt)) + helper = self._missing_albums if albms else self._missing_tracks + helper(lib, decargs(args)) self._command.func = _miss return [self._command] + def _missing_tracks(self, lib, query): + """Print a listing of tracks missing from each album in the library + matching query. + """ + albums = lib.albums(query) + + count = self.config['count'].get() + total = self.config['total'].get() + fmt = config['format_album' if count else 'format_item'].get() + + if total: + print(sum([_missing_count(a) for a in albums])) + return + + # Default format string for count mode. + if count: + fmt += ': $missing' + + for album in albums: + if count: + if _missing_count(album): + print_(format(album, fmt)) + + else: + for item in self._missing(album): + print_(format(item, fmt)) + + def _missing_albums(self, lib, query): + """Print a listing of albums missing from each artist in the library + matching query. + """ + total = self.config['total'].get() + + albums = lib.albums(query) + # build dict mapping artist to list of their albums in library + albums_by_artist = defaultdict(list) + for alb in albums: + artist = (alb['albumartist'], alb['mb_albumartistid']) + albums_by_artist[artist].append(alb) + + total_missing = 0 + + # build dict mapping artist to list of all albums + for artist, albums in albums_by_artist.items(): + if artist[1] is None or artist[1] == "": + albs_no_mbid = [u"'" + a['album'] + u"'" for a in albums] + self._log.info( + u"No musicbrainz ID for artist '{}' found in album(s) {}; " + "skipping", artist[0], u", ".join(albs_no_mbid) + ) + continue + + try: + resp = musicbrainzngs.browse_release_groups(artist=artist[1]) + release_groups = resp['release-group-list'] + except MusicBrainzError as err: + self._log.info( + u"Couldn't fetch info for artist '{}' ({}) - '{}'", + artist[0], artist[1], err + ) + continue + + missing = [] + present = [] + for rg in release_groups: + missing.append(rg) + for alb in albums: + if alb['mb_releasegroupid'] == rg['id']: + missing.remove(rg) + present.append(rg) + break + + total_missing += len(missing) + if total: + continue + + missing_titles = {rg['title'] for rg in missing} + + for release_title in missing_titles: + print_(u"{} - {}".format(artist[0], release_title)) + + if total: + print(total_missing) + def _missing(self, album): """Query MusicBrainz to determine items missing from `album`. """ - item_mbids = map(lambda x: x.mb_trackid, album.items()) + item_mbids = [x.mb_trackid for x in album.items()] if len([i for i in album.items()]) < album.albumtotal: # fetch missing items # TODO: Implement caching that without breaking other stuff diff --git a/beetsplug/mpdstats.py b/beetsplug/mpdstats.py index fce04440a..e5e82d480 100644 --- a/beetsplug/mpdstats.py +++ b/beetsplug/mpdstats.py @@ -1,6 +1,6 @@ -# coding=utf-8 +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Peter Schnebel and Johann Klähn. +# Copyright 2016, Peter Schnebel and Johann Klähn. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import mpd import socket @@ -41,36 +40,24 @@ mpd_config = config['mpd'] def is_url(path): """Try to determine if the path is an URL. """ + if isinstance(path, bytes): # if it's bytes, then it's a path + return False return path.split('://', 1)[0] in ['http', 'https'] -# Use the MPDClient internals to get unicode. -# see http://www.tarmack.eu/code/mpdunicode.py for the general idea -class MPDClient(mpd.MPDClient): - def _write_command(self, command, args=[]): - args = [unicode(arg).encode('utf-8') for arg in args] - super(MPDClient, self)._write_command(command, args) - - def _read_line(self): - line = super(MPDClient, self)._read_line() - if line is not None: - return line.decode('utf-8') - return None - - class MPDClientWrapper(object): def __init__(self, log): self._log = log self.music_directory = ( - mpd_config['music_directory'].get(unicode)) + mpd_config['music_directory'].as_str()) - self.client = MPDClient() + self.client = mpd.MPDClient(use_unicode=True) def connect(self): """Connect to the MPD. """ - host = mpd_config['host'].get(unicode) + host = mpd_config['host'].as_str() port = mpd_config['port'].get(int) if host[0] in ['/', '~']: @@ -80,15 +67,15 @@ class MPDClientWrapper(object): try: self.client.connect(host, port) except socket.error as e: - raise ui.UserError('could not connect to MPD: {0}'.format(e)) + raise ui.UserError(u'could not connect to MPD: {0}'.format(e)) - password = mpd_config['password'].get(unicode) + password = mpd_config['password'].as_str() if password: try: self.client.password(password) except mpd.CommandError as e: raise ui.UserError( - 'could not authenticate to MPD: {0}'.format(e) + u'could not authenticate to MPD: {0}'.format(e) ) def disconnect(self): @@ -269,32 +256,41 @@ class MPDStats(object): if not path: return - if is_url(path): - self._log.info(u'playing stream {0}', displayable_path(path)) - return - played, duration = map(int, status['time'].split(':', 1)) remaining = duration - played - if self.now_playing and self.now_playing['path'] != path: - skipped = self.handle_song_change(self.now_playing) - # mpd responds twice on a natural new song start - going_to_happen_twice = not skipped - else: - going_to_happen_twice = False + if self.now_playing: + if self.now_playing['path'] != path: + self.handle_song_change(self.now_playing) + else: + # In case we got mpd play event with same song playing + # multiple times, + # assume low diff means redundant second play event + # after natural song start. + diff = abs(time.time() - self.now_playing['started']) - if not going_to_happen_twice: - self._log.info(u'playing {0}', displayable_path(path)) + if diff <= self.time_threshold: + return - self.now_playing = { - 'started': time.time(), - 'remaining': remaining, - 'path': path, - 'beets_item': self.get_item(path), - } + if self.now_playing['path'] == path and played == 0: + self.handle_song_change(self.now_playing) - self.update_item(self.now_playing['beets_item'], - 'last_played', value=int(time.time())) + if is_url(path): + self._log.info(u'playing stream {0}', displayable_path(path)) + self.now_playing = None + return + + self._log.info(u'playing {0}', displayable_path(path)) + + self.now_playing = { + 'started': time.time(), + 'remaining': remaining, + 'path': path, + 'beets_item': self.get_item(path), + } + + self.update_item(self.now_playing['beets_item'], + 'last_played', value=int(time.time())) def run(self): self.mpd.connect() @@ -329,7 +325,7 @@ class MPDStatsPlugin(plugins.BeetsPlugin): 'music_directory': config['directory'].as_filename(), 'rating': True, 'rating_mix': 0.75, - 'host': u'localhost', + 'host': os.environ.get('MPD_HOST', u'localhost'), 'port': 6600, 'password': u'', }) @@ -338,27 +334,27 @@ class MPDStatsPlugin(plugins.BeetsPlugin): def commands(self): cmd = ui.Subcommand( 'mpdstats', - help='run a MPD client to gather play statistics') + help=u'run a MPD client to gather play statistics') cmd.parser.add_option( - '--host', dest='host', type='string', - help='set the hostname of the server to connect to') + u'--host', dest='host', type='string', + help=u'set the hostname of the server to connect to') cmd.parser.add_option( - '--port', dest='port', type='int', - help='set the port of the MPD server to connect to') + u'--port', dest='port', type='int', + help=u'set the port of the MPD server to connect to') cmd.parser.add_option( - '--password', dest='password', type='string', - help='set the password of the MPD server to connect to') + u'--password', dest='password', type='string', + help=u'set the password of the MPD server to connect to') def func(lib, opts, args): mpd_config.set_args(opts) # Overrides for MPD settings. if opts.host: - mpd_config['host'] = opts.host.decode('utf8') + mpd_config['host'] = opts.host.decode('utf-8') if opts.port: mpd_config['host'] = int(opts.port) if opts.password: - mpd_config['password'] = opts.password.decode('utf8') + mpd_config['password'] = opts.password.decode('utf-8') try: MPDStats(lib, self._log).run() diff --git a/beetsplug/mpdupdate.py b/beetsplug/mpdupdate.py index a6e14e48e..6ecc92131 100644 --- a/beetsplug/mpdupdate.py +++ b/beetsplug/mpdupdate.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -20,13 +21,13 @@ Put something like the following in your config.yaml to configure: port: 6600 password: seekrit """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin import os import socket from beets import config +import six # No need to introduce a dependency on an MPD library for such a @@ -34,14 +35,14 @@ from beets import config # easier. class BufferedSocket(object): """Socket abstraction that allows reading by line.""" - def __init__(self, host, port, sep='\n'): + def __init__(self, host, port, sep=b'\n'): if host[0] in ['/', '~']: self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.sock.connect(os.path.expanduser(host)) else: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, port)) - self.buf = '' + self.buf = b'' self.sep = sep def readline(self): @@ -50,11 +51,11 @@ class BufferedSocket(object): if not data: break self.buf += data - if '\n' in self.buf: + if self.sep in self.buf: res, self.buf = self.buf.split(self.sep, 1) return res + self.sep else: - return '' + return b'' def send(self, data): self.sock.send(data) @@ -67,7 +68,7 @@ class MPDUpdatePlugin(BeetsPlugin): def __init__(self): super(MPDUpdatePlugin, self).__init__() config['mpd'].add({ - 'host': u'localhost', + 'host': os.environ.get('MPD_HOST', u'localhost'), 'port': 6600, 'password': u'', }) @@ -86,9 +87,9 @@ class MPDUpdatePlugin(BeetsPlugin): def update(self, lib): self.update_mpd( - config['mpd']['host'].get(unicode), + config['mpd']['host'].as_str(), config['mpd']['port'].get(int), - config['mpd']['password'].get(unicode), + config['mpd']['password'].as_str(), ) def update_mpd(self, host='localhost', port=6600, password=None): @@ -101,28 +102,28 @@ class MPDUpdatePlugin(BeetsPlugin): s = BufferedSocket(host, port) except socket.error as e: self._log.warning(u'MPD connection failed: {0}', - unicode(e.strerror)) + six.text_type(e.strerror)) return resp = s.readline() - if 'OK MPD' not in resp: + if b'OK MPD' not in resp: self._log.warning(u'MPD connection failed: {0!r}', resp) return if password: - s.send('password "%s"\n' % password) + s.send(b'password "%s"\n' % password.encode('utf8')) resp = s.readline() - if 'OK' not in resp: + if b'OK' not in resp: self._log.warning(u'Authentication failed: {0!r}', resp) - s.send('close\n') + s.send(b'close\n') s.close() return - s.send('update\n') + s.send(b'update\n') resp = s.readline() - if 'updating_db' not in resp: + if b'updating_db' not in resp: self._log.warning(u'Update failed: {0!r}', resp) - s.send('close\n') + s.send(b'close\n') s.close() - self._log.info('Database updated.') + self._log.info(u'Database updated.') diff --git a/beetsplug/permissions.py b/beetsplug/permissions.py index 44757be5b..dd9e09843 100644 --- a/beetsplug/permissions.py +++ b/beetsplug/permissions.py @@ -1,5 +1,6 @@ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +# -*- coding: utf-8 -*- + +from __future__ import division, absolute_import, print_function """Fixes file permissions after the file gets written on import. Put something like the following in your config.yaml to configure: @@ -12,24 +13,43 @@ import os from beets import config, util from beets.plugins import BeetsPlugin from beets.util import ancestry +import six def convert_perm(perm): - """If the perm is a int it will first convert it to a string and back - to an oct int. Else it just converts it to oct. + """Convert a string to an integer, interpreting the text as octal. + Or, if `perm` is an integer, reinterpret it as an octal number that + has been "misinterpreted" as decimal. """ - if isinstance(perm, int): - return int(bytes(perm), 8) - else: - return int(perm, 8) + if isinstance(perm, six.integer_types): + perm = six.text_type(perm) + return int(perm, 8) def check_permissions(path, permission): - """Checks the permissions of a path. + """Check whether the file's permissions equal the given vector. + Return a boolean. """ return oct(os.stat(path).st_mode & 0o777) == oct(permission) +def assert_permissions(path, permission, log): + """Check whether the file's permissions are as expected, otherwise, + log a warning message. Return a boolean indicating the match, like + `check_permissions`. + """ + if not check_permissions(util.syspath(path), permission): + log.warning( + u'could not set permissions on {}', + util.displayable_path(path), + ) + log.debug( + u'set permissions to {}, but permissions are now {}', + permission, + os.stat(util.syspath(path)).st_mode & 0o777, + ) + + def dirs_in_library(library, item): """Creates a list of ancestor directories in the beets library path. """ @@ -44,58 +64,60 @@ class Permissions(BeetsPlugin): # Adding defaults. self.config.add({ - u'file': 644, - u'dir': 755 + u'file': '644', + u'dir': '755', }) - self.register_listener('item_imported', permissions) - self.register_listener('album_imported', permissions) + self.register_listener('item_imported', self.fix) + self.register_listener('album_imported', self.fix) + def fix(self, lib, item=None, album=None): + """Fix the permissions for an imported Item or Album. + """ + # Get the configured permissions. The user can specify this either a + # string (in YAML quotes) or, for convenience, as an integer so the + # quotes can be omitted. In the latter case, we need to reinterpret the + # integer as octal, not decimal. + file_perm = config['permissions']['file'].get() + dir_perm = config['permissions']['dir'].get() + file_perm = convert_perm(file_perm) + dir_perm = convert_perm(dir_perm) -def permissions(lib, item=None, album=None): - """Running the permission fixer. - """ - # Getting the config. - file_perm = config['permissions']['file'].get() - dir_perm = config['permissions']['dir'].get() + # Create chmod_queue. + file_chmod_queue = [] + if item: + file_chmod_queue.append(item.path) + elif album: + for album_item in album.items(): + file_chmod_queue.append(album_item.path) - # Converts permissions to oct. - file_perm = convert_perm(file_perm) - dir_perm = convert_perm(dir_perm) + # A set of directories to change permissions for. + dir_chmod_queue = set() - # Create chmod_queue. - file_chmod_queue = [] - if item: - file_chmod_queue.append(item.path) - elif album: - for album_item in album.items(): - file_chmod_queue.append(album_item.path) + for path in file_chmod_queue: + # Changing permissions on the destination file. + self._log.debug( + u'setting file permissions on {}', + util.displayable_path(path), + ) + os.chmod(util.syspath(path), file_perm) - # A set of directories to change permissions for. - dir_chmod_queue = set() + # Checks if the destination path has the permissions configured. + assert_permissions(path, file_perm, self._log) - for path in file_chmod_queue: - # Changing permissions on the destination file. - os.chmod(util.bytestring_path(path), file_perm) + # Adding directories to the directory chmod queue. + dir_chmod_queue.update( + dirs_in_library(lib.directory, + path)) - # Checks if the destination path has the permissions configured. - if not check_permissions(util.bytestring_path(path), file_perm): - message = 'There was a problem setting permission on {}'.format( - path) - print(message) + # Change permissions for the directories. + for path in dir_chmod_queue: + # Chaning permissions on the destination directory. + self._log.debug( + u'setting directory permissions on {}', + util.displayable_path(path), + ) + os.chmod(util.syspath(path), dir_perm) - # Adding directories to the directory chmod queue. - dir_chmod_queue.update( - dirs_in_library(lib.directory, - path)) - - # Change permissions for the directories. - for path in dir_chmod_queue: - # Chaning permissions on the destination directory. - os.chmod(util.bytestring_path(path), dir_perm) - - # Checks if the destination path has the permissions configured. - if not check_permissions(util.bytestring_path(path), dir_perm): - message = 'There was a problem setting permission on {}'.format( - path) - print(message) + # Checks if the destination path has the permissions configured. + assert_permissions(path, dir_perm, self._log) diff --git a/beetsplug/play.py b/beetsplug/play.py index eb04faeaa..4d32a3576 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, David Hamp-Gonsalves +# Copyright 2016, David Hamp-Gonsalves # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,22 +15,45 @@ """Send the results of a query to the configured music player as a playlist. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets.ui import Subcommand +from beets.ui.commands import PromptChoice from beets import config from beets import ui from beets import util from os.path import relpath from tempfile import NamedTemporaryFile +import subprocess # Indicate where arguments should be inserted into the command string. # If this is missing, they're placed at the end. ARGS_MARKER = '$args' +def play(command_str, selection, paths, open_args, log, item_type='track', + keep_open=False): + """Play items in paths with command_str and optional arguments. If + keep_open, return to beets, otherwise exit once command runs. + """ + # Print number of tracks or albums to be played, log command to be run. + item_type += 's' if len(selection) > 1 else '' + ui.print_(u'Playing {0} {1}.'.format(len(selection), item_type)) + log.debug(u'executing command: {} {!r}', command_str, open_args) + + try: + if keep_open: + command = util.shlex_split(command_str) + command = command + open_args + subprocess.call(command) + else: + util.interactive_open(open_args, command_str) + except OSError as exc: + raise ui.UserError( + "Could not play the query: {0}".format(exc)) + + class PlayPlugin(BeetsPlugin): def __init__(self): @@ -40,42 +64,39 @@ class PlayPlugin(BeetsPlugin): 'use_folders': False, 'relative_to': None, 'raw': False, - 'warning_treshold': 100, + 'warning_threshold': 100, }) + self.register_listener('before_choose_candidate', + self.before_choose_candidate_listener) + def commands(self): play_command = Subcommand( 'play', - help='send music to a player as a playlist' + help=u'send music to a player as a playlist' ) play_command.parser.add_album_option() play_command.parser.add_option( - '-A', '--args', + u'-A', u'--args', action='store', - help='add additional arguments to the command', + help=u'add additional arguments to the command', ) - play_command.func = self.play_music + play_command.parser.add_option( + u'-y', u'--yes', + action="store_true", + help=u'skip the warning threshold', + ) + play_command.func = self._play_command return [play_command] - def play_music(self, lib, opts, args): - """Execute query, create temporary playlist and execute player - command passing that playlist, at request insert optional arguments. + def _play_command(self, lib, opts, args): + """The CLI command function for `beet play`. Create a list of paths + from query, determine if tracks or albums are to be played. """ - command_str = config['play']['command'].get() use_folders = config['play']['use_folders'].get(bool) relative_to = config['play']['relative_to'].get() - raw = config['play']['raw'].get(bool) - warning_treshold = config['play']['warning_treshold'].get(int) if relative_to: relative_to = util.normpath(relative_to) - - # Add optional arguments to the player command. - if opts.args: - if ARGS_MARKER in command_str: - command_str = command_str.replace(ARGS_MARKER, opts.args) - else: - command_str = "{} {}".format(command_str, opts.args) - # Perform search by album and add folders rather than tracks to # playlist. if opts.album: @@ -95,52 +116,95 @@ class PlayPlugin(BeetsPlugin): else: selection = lib.items(ui.decargs(args)) paths = [item.path for item in selection] - if relative_to: - paths = [relpath(path, relative_to) for path in paths] item_type = 'track' - item_type += 's' if len(selection) > 1 else '' + if relative_to: + paths = [relpath(path, relative_to) for path in paths] if not selection: ui.print_(ui.colorize('text_warning', - 'No {0} to play.'.format(item_type))) + u'No {0} to play.'.format(item_type))) return + open_args = self._playlist_or_paths(paths) + command_str = self._command_str(opts.args) + + # Check if the selection exceeds configured threshold. If True, + # cancel, otherwise proceed with play command. + if opts.yes or not self._exceeds_threshold( + selection, command_str, open_args, item_type): + play(command_str, selection, paths, open_args, self._log, + item_type) + + def _command_str(self, args=None): + """Create a command string from the config command and optional args. + """ + command_str = config['play']['command'].get() + if not command_str: + return util.open_anything() + # Add optional arguments to the player command. + if args: + if ARGS_MARKER in command_str: + return command_str.replace(ARGS_MARKER, args) + else: + return u"{} {}".format(command_str, args) + else: + # Don't include the marker in the command. + return command_str.replace(" " + ARGS_MARKER, "") + + def _playlist_or_paths(self, paths): + """Return either the raw paths of items or a playlist of the items. + """ + if config['play']['raw']: + return paths + else: + return [self._create_tmp_playlist(paths)] + + def _exceeds_threshold(self, selection, command_str, open_args, + item_type='track'): + """Prompt user whether to abort if playlist exceeds threshold. If + True, cancel playback. If False, execute play command. + """ + warning_threshold = config['play']['warning_threshold'].get(int) + # Warn user before playing any huge playlists. - if warning_treshold and len(selection) > warning_treshold: + if warning_threshold and len(selection) > warning_threshold: + if len(selection) > 1: + item_type += 's' + ui.print_(ui.colorize( 'text_warning', - 'You are about to queue {0} {1}.'.format(len(selection), - item_type) - )) + u'You are about to queue {0} {1}.'.format( + len(selection), item_type))) - if ui.input_options(('Continue', 'Abort')) == 'a': - return + if ui.input_options((u'Continue', u'Abort')) == 'a': + return True - ui.print_(u'Playing {0} {1}.'.format(len(selection), item_type)) - if raw: - open_args = paths - else: - open_args = [self._create_tmp_playlist(paths)] - - self._log.debug('executing command: {} {}', command_str, - b' '.join(open_args)) - try: - util.interactive_open(open_args, command_str) - except OSError as exc: - raise ui.UserError("Could not play the music playlist: " - "{0}".format(exc)) - finally: - if not raw: - self._log.debug('Removing temporary playlist: {}', - open_args[0]) - util.remove(open_args[0]) + return False def _create_tmp_playlist(self, paths_list): """Create a temporary .m3u file. Return the filename. """ - m3u = NamedTemporaryFile('w', suffix='.m3u', delete=False) + m3u = NamedTemporaryFile('wb', suffix='.m3u', delete=False) for item in paths_list: m3u.write(item + b'\n') m3u.close() return m3u.name + + def before_choose_candidate_listener(self, session, task): + """Append a "Play" choice to the interactive importer prompt. + """ + return [PromptChoice('y', 'plaY', self.importer_play)] + + def importer_play(self, session, task): + """Get items from current import task and send to play function. + """ + selection = task.items + paths = [item.path for item in selection] + + open_args = self._playlist_or_paths(paths) + command_str = self._command_str() + + if not self._exceeds_threshold(selection, command_str, open_args): + play(command_str, selection, paths, open_args, self._log, + keep_open=True) diff --git a/beetsplug/plexupdate.py b/beetsplug/plexupdate.py index 340bcdf4d..17fd8208d 100644 --- a/beetsplug/plexupdate.py +++ b/beetsplug/plexupdate.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + """Updates an Plex library whenever the beets library is changed. Plex Home users enter the Plex Token to enable updating. @@ -7,13 +9,11 @@ Put something like the following in your config.yaml to configure: port: 32400 token: token """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import requests -from urlparse import urljoin -from urllib import urlencode import xml.etree.ElementTree as ET +from six.moves.urllib.parse import urljoin, urlencode from beets import config from beets.plugins import BeetsPlugin @@ -28,7 +28,7 @@ def get_music_section(host, port, token, library_name): r = requests.get(url) # Parse xml tree and extract music section key. - tree = ET.fromstring(r.text) + tree = ET.fromstring(r.content) for child in tree.findall('Directory'): if child.get('title') == library_name: return child.get('key') @@ -67,6 +67,7 @@ class PlexUpdate(BeetsPlugin): u'token': u'', u'library_name': u'Music'}) + config['plex']['token'].redact = True self.register_listener('database_change', self.listen_for_db_change) def listen_for_db_change(self, lib, model): @@ -76,7 +77,7 @@ class PlexUpdate(BeetsPlugin): def update(self, lib): """When the client exists try to send refresh request to Plex server. """ - self._log.info('Updating Plex library...') + self._log.info(u'Updating Plex library...') # Try to send update request. try: @@ -85,7 +86,7 @@ class PlexUpdate(BeetsPlugin): config['plex']['port'].get(), config['plex']['token'].get(), config['plex']['library_name'].get()) - self._log.info('... started.') + self._log.info(u'... started.') except requests.exceptions.RequestException: - self._log.warning('Update failed.') + self._log.warning(u'Update failed.') diff --git a/beetsplug/random.py b/beetsplug/random.py index 43fb7957c..65caaf908 100644 --- a/beetsplug/random.py +++ b/beetsplug/random.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Philippe Mongeau. +# Copyright 2016, Philippe Mongeau. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,8 +15,7 @@ """Get a random song or album from the library. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets.ui import Subcommand, decargs, print_ @@ -24,54 +24,124 @@ from operator import attrgetter from itertools import groupby -def random_item(lib, opts, args): - query = decargs(args) +def _length(obj, album): + """Get the duration of an item or album. + """ + if album: + return sum(i.length for i in obj.items()) + else: + return obj.length + +def _equal_chance_permutation(objs, field='albumartist'): + """Generate (lazily) a permutation of the objects where every group + with equal values for `field` have an equal chance of appearing in + any given position. + """ + # Group the objects by artist so we can sample from them. + key = attrgetter(field) + objs.sort(key=key) + objs_by_artists = {} + for artist, v in groupby(objs, key): + objs_by_artists[artist] = list(v) + + # While we still have artists with music to choose from, pick one + # randomly and pick a track from that artist. + while objs_by_artists: + # Choose an artist and an object for that artist, removing + # this choice from the pool. + artist = random.choice(list(objs_by_artists.keys())) + objs_from_artist = objs_by_artists[artist] + i = random.randint(0, len(objs_from_artist) - 1) + yield objs_from_artist.pop(i) + + # Remove the artist if we've used up all of its objects. + if not objs_from_artist: + del objs_by_artists[artist] + + +def _take(iter, num): + """Return a list containing the first `num` values in `iter` (or + fewer, if the iterable ends early). + """ + out = [] + for val in iter: + out.append(val) + num -= 1 + if num <= 0: + break + return out + + +def _take_time(iter, secs, album): + """Return a list containing the first values in `iter`, which should + be Item or Album objects, that add up to the given amount of time in + seconds. + """ + out = [] + total_time = 0.0 + for obj in iter: + length = _length(obj, album) + if total_time + length <= secs: + out.append(obj) + total_time += length + return out + + +def random_objs(objs, album, number=1, time=None, equal_chance=False): + """Get a random subset of the provided `objs`. + + If `number` is provided, produce that many matches. Otherwise, if + `time` is provided, instead select a list whose total time is close + to that number of minutes. If `equal_chance` is true, give each + artist an equal chance of being included so that artists with more + songs are not represented disproportionately. + """ + # Permute the objects either in a straightforward way or an + # artist-balanced way. + if equal_chance: + perm = _equal_chance_permutation(objs) + else: + perm = objs + random.shuffle(perm) # N.B. This shuffles the original list. + + # Select objects by time our count. + if time: + return _take_time(perm, time * 60, album) + else: + return _take(perm, number) + + +def random_func(lib, opts, args): + """Select some random items or albums and print the results. + """ + # Fetch all the objects matching the query into a list. + query = decargs(args) if opts.album: objs = list(lib.albums(query)) else: objs = list(lib.items(query)) - if opts.equal_chance: - # Group the objects by artist so we can sample from them. - key = attrgetter('albumartist') - objs.sort(key=key) - objs_by_artists = {} - for artist, v in groupby(objs, key): - objs_by_artists[artist] = list(v) + # Print a random subset. + objs = random_objs(objs, opts.album, opts.number, opts.time, + opts.equal_chance) + for obj in objs: + print_(format(obj)) - objs = [] - for _ in range(opts.number): - # Terminate early if we're out of objects to select. - if not objs_by_artists: - break - - # Choose an artist and an object for that artist, removing - # this choice from the pool. - artist = random.choice(objs_by_artists.keys()) - objs_from_artist = objs_by_artists[artist] - i = random.randint(0, len(objs_from_artist) - 1) - objs.append(objs_from_artist.pop(i)) - - # Remove the artist if we've used up all of its objects. - if not objs_from_artist: - del objs_by_artists[artist] - - else: - number = min(len(objs), opts.number) - objs = random.sample(objs, number) - - for item in objs: - print_(format(item)) random_cmd = Subcommand('random', - help='chose a random track or album') -random_cmd.parser.add_option('-n', '--number', action='store', type="int", - help='number of objects to choose', default=1) -random_cmd.parser.add_option('-e', '--equal-chance', action='store_true', - help='each artist has the same chance') + help=u'choose a random track or album') +random_cmd.parser.add_option( + u'-n', u'--number', action='store', type="int", + help=u'number of objects to choose', default=1) +random_cmd.parser.add_option( + u'-e', u'--equal-chance', action='store_true', + help=u'each artist has the same chance') +random_cmd.parser.add_option( + u'-t', u'--time', action='store', type="float", + help=u'total length in minutes of objects to choose') random_cmd.parser.add_all_common_options() -random_cmd.func = random_item +random_cmd.func = random_func class Random(BeetsPlugin): diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index 8186b42f4..a7eb81b5c 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Fabrice Laporte, Yevgeny Bezman, and Adrian Sampson. +# Copyright 2016, Fabrice Laporte, Yevgeny Bezman, and Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,22 +13,20 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import subprocess import os import collections -import itertools import sys import warnings -import re +import xml.parsers.expat +from six.moves import zip -from beets import logging from beets import ui from beets.plugins import BeetsPlugin -from beets.util import syspath, command_output, displayable_path -from beets import config +from beets.util import (syspath, command_output, bytestring_path, + displayable_path, py3_path) # Utilities. @@ -43,6 +42,11 @@ class FatalReplayGainError(Exception): """ +class FatalGstreamerPluginReplayGainError(FatalReplayGainError): + """Raised when a fatal error occurs in the GStreamerBackend when + loading the required plugins.""" + + def call(args): """Execute the command and return its output or raise a ReplayGainError on failure. @@ -51,13 +55,13 @@ def call(args): return command_output(args) except subprocess.CalledProcessError as e: raise ReplayGainError( - "{0} exited with status {1}".format(args[0], e.returncode) + u"{0} exited with status {1}".format(args[0], e.returncode) ) except UnicodeEncodeError: # Due to a bug in Python 2's subprocess on Windows, Unicode # filenames can fail to encode on that platform. See: - # http://code.google.com/p/beets/issues/detail?id=499 - raise ReplayGainError("argument encoding failed") + # https://github.com/google-code-export/beets/issues/499 + raise ReplayGainError(u"argument encoding failed") # Backend base and plumbing classes. @@ -98,19 +102,19 @@ class Bs1770gainBackend(Backend): 'method': 'replaygain', }) self.chunk_at = config['chunk_at'].as_number() - self.method = b'--' + bytes(config['method'].get(unicode)) + self.method = '--' + config['method'].as_str() - cmd = b'bs1770gain' + cmd = 'bs1770gain' try: call([cmd, self.method]) self.command = cmd except OSError: raise FatalReplayGainError( - 'Is bs1770gain installed? Is your method in config correct?' + u'Is bs1770gain installed? Is your method in config correct?' ) if not self.command: raise FatalReplayGainError( - 'no replaygain command found: install bs1770gain' + u'no replaygain command found: install bs1770gain' ) def compute_track_gain(self, items): @@ -132,7 +136,7 @@ class Bs1770gainBackend(Backend): output = self.compute_gain(supported_items, True) if not output: - raise ReplayGainError('no output from bs1770gain') + raise ReplayGainError(u'no output from bs1770gain') return AlbumGain(output[-1], output[:-1]) def isplitter(self, items, chunk_at): @@ -190,53 +194,81 @@ class Bs1770gainBackend(Backend): """ # Construct shell command. cmd = [self.command] - cmd = cmd + [self.method] - cmd = cmd + [b'-it'] + cmd += [self.method] + cmd += ['--xml', '-p'] # Workaround for Windows: the underlying tool fails on paths # with the \\?\ prefix, so we don't use it here. This # prevents the backend from working with long paths. args = cmd + [syspath(i.path, prefix=False) for i in items] + path_list = [i.path for i in items] # Invoke the command. - self._log.debug("executing {0}", " ".join(map(displayable_path, args))) + self._log.debug( + u'executing {0}', u' '.join(map(displayable_path, args)) + ) output = call(args) self._log.debug(u'analysis finished: {0}', output) - results = self.parse_tool_output(output, - len(items) + is_album) + results = self.parse_tool_output(output, path_list, is_album) self._log.debug(u'{0} items, {1} results', len(items), len(results)) return results - def parse_tool_output(self, text, num_lines): + def parse_tool_output(self, text, path_list, is_album): """Given the output from bs1770gain, parse the text and return a list of dictionaries containing information about each analyzed file. """ - out = [] - data = text.decode('utf8', errors='ignore') - regex = re.compile( - ur'(\s{2,2}\[\d+\/\d+\].*?|\[ALBUM\].*?)' - '(?=\s{2,2}\[\d+\/\d+\]|\s{2,2}\[ALBUM\]' - ':|done\.\s)', re.DOTALL | re.UNICODE) - results = re.findall(regex, data) - for parts in results[0:num_lines]: - part = parts.split(b'\n') - if len(part) == 0: - self._log.debug('bad tool output: {0!r}', text) - raise ReplayGainError('bs1770gain failed') + per_file_gain = {} + album_gain = {} # mutable variable so it can be set from handlers + parser = xml.parsers.expat.ParserCreate(encoding='utf-8') + state = {'file': None, 'gain': None, 'peak': None} - try: - song = { - 'file': part[0], - 'gain': float((part[1].split('/'))[1].split('LU')[0]), - 'peak': float(part[2].split('/')[1]), - } - except IndexError: - self._log.info('bs1770gain reports (faulty file?): {}', parts) - continue + def start_element_handler(name, attrs): + if name == u'track': + state['file'] = bytestring_path(attrs[u'file']) + if state['file'] in per_file_gain: + raise ReplayGainError( + u'duplicate filename in bs1770gain output') + elif name == u'integrated': + state['gain'] = float(attrs[u'lu']) + elif name == u'sample-peak': + state['peak'] = float(attrs[u'factor']) - out.append(Gain(song['gain'], song['peak'])) + def end_element_handler(name): + if name == u'track': + if state['gain'] is None or state['peak'] is None: + raise ReplayGainError(u'could not parse gain or peak from ' + 'the output of bs1770gain') + per_file_gain[state['file']] = Gain(state['gain'], + state['peak']) + state['gain'] = state['peak'] = None + elif name == u'summary': + if state['gain'] is None or state['peak'] is None: + raise ReplayGainError(u'could not parse gain or peak from ' + 'the output of bs1770gain') + album_gain["album"] = Gain(state['gain'], state['peak']) + state['gain'] = state['peak'] = None + parser.StartElementHandler = start_element_handler + parser.EndElementHandler = end_element_handler + parser.Parse(text, True) + + if len(per_file_gain) != len(path_list): + raise ReplayGainError( + u'the number of results returned by bs1770gain does not match ' + 'the number of files passed to it') + + # bs1770gain does not return the analysis results in the order that + # files are passed on the command line, because it is sorting the files + # internally. We must recover the order from the filenames themselves. + try: + out = [per_file_gain[os.path.basename(p)] for p in path_list] + except KeyError: + raise ReplayGainError( + u'unrecognized filename in bs1770gain output ' + '(bs1770gain can only deal with utf-8 file names)') + if is_album: + out.append(album_gain["album"]) return out @@ -250,27 +282,26 @@ class CommandBackend(Backend): 'noclip': True, }) - self.command = config["command"].get(unicode) + self.command = config["command"].as_str() if self.command: # Explicit executable path. if not os.path.isfile(self.command): raise FatalReplayGainError( - 'replaygain command does not exist: {0}'.format( - self.command - ) + u'replaygain command does not exist: {0}'.format( + self.command) ) else: # Check whether the program is in $PATH. - for cmd in (b'mp3gain', b'aacgain'): + for cmd in ('mp3gain', 'aacgain'): try: - call([cmd, b'-v']) + call([cmd, '-v']) self.command = cmd except OSError: pass if not self.command: raise FatalReplayGainError( - 'no replaygain command found: install mp3gain or aacgain' + u'no replaygain command found: install mp3gain or aacgain' ) self.noclip = config['noclip'].get(bool) @@ -281,7 +312,7 @@ class CommandBackend(Backend): """Computes the track gain of the given tracks, returns a list of TrackGain objects. """ - supported_items = filter(self.format_supported, items) + supported_items = list(filter(self.format_supported, items)) output = self.compute_gain(supported_items, False) return output @@ -292,7 +323,7 @@ class CommandBackend(Backend): # TODO: What should be done when not all tracks in the album are # supported? - supported_items = filter(self.format_supported, album.items()) + supported_items = list(filter(self.format_supported, album.items())) if len(supported_items) != len(album.items()): self._log.debug(u'tracks are of unsupported format') return AlbumGain(None, []) @@ -317,6 +348,7 @@ class CommandBackend(Backend): the album gain """ if len(items) == 0: + self._log.debug(u'no supported tracks to analyze') return [] """Compute ReplayGain values and return a list of results @@ -328,14 +360,14 @@ class CommandBackend(Backend): # tag-writing; this turns the mp3gain/aacgain tool into a gain # calculator rather than a tag manipulator because we take care # of changing tags ourselves. - cmd = [self.command, b'-o', b'-s', b's'] + cmd = [self.command, '-o', '-s', 's'] if self.noclip: # Adjust to avoid clipping. - cmd = cmd + [b'-k'] + cmd = cmd + ['-k'] else: # Disable clipping warning. - cmd = cmd + [b'-c'] - cmd = cmd + [b'-d', bytes(self.gain_offset)] + cmd = cmd + ['-c'] + cmd = cmd + ['-d', str(self.gain_offset)] cmd = cmd + [syspath(i.path) for i in items] self._log.debug(u'analyzing {0} files', len(items)) @@ -355,7 +387,7 @@ class CommandBackend(Backend): parts = line.split(b'\t') if len(parts) != 6 or parts[0] == b'File': self._log.debug(u'bad tool output: {0}', text) - raise ReplayGainError('mp3gain failed') + raise ReplayGainError(u'mp3gain failed') d = { 'file': parts[0], 'mp3gain': int(parts[1]), @@ -390,8 +422,8 @@ class GStreamerBackend(Backend): if self._src is None or self._decbin is None or self._conv is None \ or self._res is None or self._rg is None: - raise FatalReplayGainError( - "Failed to load required GStreamer plugins" + raise FatalGstreamerPluginReplayGainError( + u"Failed to load required GStreamer plugins" ) # We check which files need gain ourselves, so all files given @@ -438,14 +470,14 @@ class GStreamerBackend(Backend): import gi except ImportError: raise FatalReplayGainError( - "Failed to load GStreamer: python-gi not found" + u"Failed to load GStreamer: python-gi not found" ) try: gi.require_version('Gst', '1.0') except ValueError as e: raise FatalReplayGainError( - "Failed to load GStreamer 1.0: {0}".format(e) + u"Failed to load GStreamer 1.0: {0}".format(e) ) from gi.repository import GObject, Gst, GLib @@ -480,7 +512,7 @@ class GStreamerBackend(Backend): def compute_track_gain(self, items): self.compute(items, False) if len(self._file_tags) != len(items): - raise ReplayGainError("Some tracks did not receive tags") + raise ReplayGainError(u"Some tracks did not receive tags") ret = [] for item in items: @@ -493,16 +525,27 @@ class GStreamerBackend(Backend): items = list(album.items()) self.compute(items, True) if len(self._file_tags) != len(items): - raise ReplayGainError("Some items in album did not receive tags") + raise ReplayGainError(u"Some items in album did not receive tags") - ret = [] + # Collect track gains. + track_gains = [] for item in items: - ret.append(Gain(self._file_tags[item]["TRACK_GAIN"], - self._file_tags[item]["TRACK_PEAK"])) + try: + gain = self._file_tags[item]["TRACK_GAIN"] + peak = self._file_tags[item]["TRACK_PEAK"] + except KeyError: + raise ReplayGainError(u"results missing for track") + track_gains.append(Gain(gain, peak)) + # Get album gain information from the last track. last_tags = self._file_tags[items[-1]] - return AlbumGain(Gain(last_tags["ALBUM_GAIN"], - last_tags["ALBUM_PEAK"]), ret) + try: + gain = last_tags["ALBUM_GAIN"] + peak = last_tags["ALBUM_PEAK"] + except KeyError: + raise ReplayGainError(u"results missing for album") + + return AlbumGain(Gain(gain, peak), track_gains) def close(self): self._bus.remove_signal_watch() @@ -521,10 +564,9 @@ class GStreamerBackend(Backend): err, debug = message.parse_error() f = self._src.get_property("location") # A GStreamer error, either an unsupported format or a bug. - self._error = \ - ReplayGainError(u"Error {0} - {1} on file {2}".format(err, - debug, - f)) + self._error = ReplayGainError( + u"Error {0!r} - {1!r} on file {2!r}".format(err, debug, f) + ) def _on_tag(self, bus, message): tags = message.parse_tag() @@ -558,7 +600,7 @@ class GStreamerBackend(Backend): self._file = self._files.pop(0) self._pipe.set_state(self.Gst.State.NULL) - self._src.set_property("location", syspath(self._file.path)) + self._src.set_property("location", py3_path(syspath(self._file.path))) self._pipe.set_state(self.Gst.State.PLAYING) return True @@ -571,16 +613,6 @@ class GStreamerBackend(Backend): self._file = self._files.pop(0) - # Disconnect the decodebin element from the pipeline, set its - # state to READY to to clear it. - self._decbin.unlink(self._conv) - self._decbin.set_state(self.Gst.State.READY) - - # Set a new file on the filesrc element, can only be done in the - # READY state - self._src.set_state(self.Gst.State.READY) - self._src.set_property("location", syspath(self._file.path)) - # Ensure the filesrc element received the paused state of the # pipeline in a blocking manner self._src.sync_state_with_parent() @@ -591,6 +623,19 @@ class GStreamerBackend(Backend): self._decbin.sync_state_with_parent() self._decbin.get_state(self.Gst.CLOCK_TIME_NONE) + # Disconnect the decodebin element from the pipeline, set its + # state to READY to to clear it. + self._decbin.unlink(self._conv) + self._decbin.set_state(self.Gst.State.READY) + + # Set a new file on the filesrc element, can only be done in the + # READY state + self._src.set_state(self.Gst.State.READY) + self._src.set_property("location", py3_path(syspath(self._file.path))) + + self._decbin.link(self._conv) + self._pipe.set_state(self.Gst.State.READY) + return True def _set_next_file(self): @@ -647,7 +692,7 @@ class AudioToolsBackend(Backend): import audiotools.replaygain except ImportError: raise FatalReplayGainError( - "Failed to load audiotools: audiotools not found" + u"Failed to load audiotools: audiotools not found" ) self._mod_audiotools = audiotools self._mod_replaygain = audiotools.replaygain @@ -665,11 +710,11 @@ class AudioToolsBackend(Backend): audiofile = self._mod_audiotools.open(item.path) except IOError: raise ReplayGainError( - "File {} was not found".format(item.path) + u"File {} was not found".format(item.path) ) except self._mod_audiotools.UnsupportedFile: raise ReplayGainError( - "Unsupported file type {}".format(item.format) + u"Unsupported file type {}".format(item.format) ) return audiofile @@ -688,8 +733,7 @@ class AudioToolsBackend(Backend): rg = self._mod_replaygain.ReplayGain(audiofile.sample_rate()) except ValueError: raise ReplayGainError( - "Unsupported sample rate {}".format(item.samplerate) - ) + u"Unsupported sample rate {}".format(item.samplerate)) return return rg @@ -714,8 +758,8 @@ class AudioToolsBackend(Backend): except ValueError as exc: # `audiotools.replaygain` can raise a `ValueError` if the sample # rate is incorrect. - self._log.debug('error in rg.title_gain() call: {}', exc) - raise ReplayGainError('audiotools audio data error') + self._log.debug(u'error in rg.title_gain() call: {}', exc) + raise ReplayGainError(u'audiotools audio data error') def _compute_track_gain(self, item): """Compute ReplayGain value for the requested item. @@ -727,7 +771,7 @@ class AudioToolsBackend(Backend): # Each call to title_gain on a ReplayGain object returns peak and gain # of the track. - rg_track_gain, rg_track_peak = rg._title_gain(rg, audiofile) + rg_track_gain, rg_track_peak = self._title_gain(rg, audiofile) self._log.debug(u'ReplayGain for track {0} - {1}: {2:.2f}, {3:.2f}', item.artist, item.title, rg_track_gain, rg_track_peak) @@ -779,7 +823,7 @@ class ReplayGainPlugin(BeetsPlugin): "command": CommandBackend, "gstreamer": GStreamerBackend, "audiotools": AudioToolsBackend, - "bs1770gain": Bs1770gainBackend + "bs1770gain": Bs1770gainBackend, } def __init__(self): @@ -791,10 +835,11 @@ class ReplayGainPlugin(BeetsPlugin): 'auto': True, 'backend': u'command', 'targetlevel': 89, + 'r128': ['Opus'], }) self.overwrite = self.config['overwrite'].get(bool) - backend_name = self.config['backend'].get(unicode) + backend_name = self.config['backend'].as_str() if backend_name not in self.backends: raise ui.UserError( u"Selected ReplayGain backend {0} is not supported. " @@ -808,18 +853,30 @@ class ReplayGainPlugin(BeetsPlugin): if self.config['auto']: self.import_stages = [self.imported] + # Formats to use R128. + self.r128_whitelist = self.config['r128'].as_str_seq() + try: self.backend_instance = self.backends[backend_name]( self.config, self._log ) except (ReplayGainError, FatalReplayGainError) as e: raise ui.UserError( - 'replaygain initialization failed: {0}'.format(e) - ) + u'replaygain initialization failed: {0}'.format(e)) + + self.r128_backend_instance = '' + + def should_use_r128(self, item): + """Checks the plugin setting to decide whether the calculation + should be done using the EBU R128 standard and use R128_ tags instead. + """ + return item.format in self.r128_whitelist def track_requires_gain(self, item): return self.overwrite or \ - (not item.rg_track_gain or not item.rg_track_peak) + (self.should_use_r128(item) and not item.r128_track_gain) or \ + (not self.should_use_r128(item) and + (not item.rg_track_gain or not item.rg_track_peak)) def album_requires_gain(self, album): # Skip calculating gain only when *all* files don't need @@ -827,8 +884,12 @@ class ReplayGainPlugin(BeetsPlugin): # needs recalculation, we still get an accurate album gain # value. return self.overwrite or \ - any([not item.rg_album_gain or not item.rg_album_peak - for item in album.items()]) + any([self.should_use_r128(item) and + (not item.r128_track_gain or not item.r128_album_gain) + for item in album.items()]) or \ + any([not self.should_use_r128(item) and + (not item.rg_album_gain or not item.rg_album_peak) + for item in album.items()]) def store_track_gain(self, item, track_gain): item.rg_track_gain = track_gain.gain @@ -838,6 +899,12 @@ class ReplayGainPlugin(BeetsPlugin): self._log.debug(u'applied track gain {0}, peak {1}', item.rg_track_gain, item.rg_track_peak) + def store_track_r128_gain(self, item, track_gain): + item.r128_track_gain = int(round(track_gain.gain * pow(2, 8))) + item.store() + + self._log.debug(u'applied track gain {0}', item.r128_track_gain) + def store_album_gain(self, album, album_gain): album.rg_album_gain = album_gain.gain album.rg_album_peak = album_gain.peak @@ -846,7 +913,13 @@ class ReplayGainPlugin(BeetsPlugin): self._log.debug(u'applied album gain {0}, peak {1}', album.rg_album_gain, album.rg_album_peak) - def handle_album(self, album, write): + def store_album_r128_gain(self, album, album_gain): + album.r128_album_gain = int(round(album_gain.gain * pow(2, 8))) + album.store() + + self._log.debug(u'applied album gain {0}', album.r128_album_gain) + + def handle_album(self, album, write, force=False): """Compute album and track replay gain store it in all of the album's items. @@ -854,62 +927,99 @@ class ReplayGainPlugin(BeetsPlugin): item. If replay gain information is already present in all items, nothing is done. """ - if not self.album_requires_gain(album): + if not force and not self.album_requires_gain(album): self._log.info(u'Skipping album {0}', album) return self._log.info(u'analyzing {0}', album) + if (any([self.should_use_r128(item) for item in album.items()]) and not + all(([self.should_use_r128(item) for item in album.items()]))): + raise ReplayGainError( + u"Mix of ReplayGain and EBU R128 detected" + u" for some tracks in album {0}".format(album) + ) + + if any([self.should_use_r128(item) for item in album.items()]): + if self.r128_backend_instance == '': + self.init_r128_backend() + backend_instance = self.r128_backend_instance + store_track_gain = self.store_track_r128_gain + store_album_gain = self.store_album_r128_gain + else: + backend_instance = self.backend_instance + store_track_gain = self.store_track_gain + store_album_gain = self.store_album_gain + try: - album_gain = self.backend_instance.compute_album_gain(album) + album_gain = backend_instance.compute_album_gain(album) if len(album_gain.track_gains) != len(album.items()): raise ReplayGainError( u"ReplayGain backend failed " u"for some tracks in album {0}".format(album) ) - self.store_album_gain(album, album_gain.album_gain) - for item, track_gain in itertools.izip(album.items(), - album_gain.track_gains): - self.store_track_gain(item, track_gain) + store_album_gain(album, album_gain.album_gain) + for item, track_gain in zip(album.items(), album_gain.track_gains): + store_track_gain(item, track_gain) if write: item.try_write() except ReplayGainError as e: self._log.info(u"ReplayGain error: {0}", e) except FatalReplayGainError as e: raise ui.UserError( - u"Fatal replay gain error: {0}".format(e) - ) + u"Fatal replay gain error: {0}".format(e)) - def handle_track(self, item, write): + def handle_track(self, item, write, force=False): """Compute track replay gain and store it in the item. If ``write`` is truthy then ``item.write()`` is called to write the data to disk. If replay gain information is already present in the item, nothing is done. """ - if not self.track_requires_gain(item): + if not force and not self.track_requires_gain(item): self._log.info(u'Skipping track {0}', item) return self._log.info(u'analyzing {0}', item) + if self.should_use_r128(item): + if self.r128_backend_instance == '': + self.init_r128_backend() + backend_instance = self.r128_backend_instance + store_track_gain = self.store_track_r128_gain + else: + backend_instance = self.backend_instance + store_track_gain = self.store_track_gain + try: - track_gains = self.backend_instance.compute_track_gain([item]) + track_gains = backend_instance.compute_track_gain([item]) if len(track_gains) != 1: raise ReplayGainError( u"ReplayGain backend failed for track {0}".format(item) ) - self.store_track_gain(item, track_gains[0]) + store_track_gain(item, track_gains[0]) if write: item.try_write() except ReplayGainError as e: self._log.info(u"ReplayGain error: {0}", e) except FatalReplayGainError as e: raise ui.UserError( - u"Fatal replay gain error: {0}".format(e) + u"Fatal replay gain error: {0}".format(e)) + + def init_r128_backend(self): + backend_name = 'bs1770gain' + + try: + self.r128_backend_instance = self.backends[backend_name]( + self.config, self._log ) + except (ReplayGainError, FatalReplayGainError) as e: + raise ui.UserError( + u'replaygain initialization failed: {0}'.format(e)) + + self.r128_backend_instance.method = '--ebu' def imported(self, session, task): """Add replay gain info to items or albums of ``task``. @@ -923,19 +1033,28 @@ class ReplayGainPlugin(BeetsPlugin): """Return the "replaygain" ui subcommand. """ def func(lib, opts, args): - self._log.setLevel(logging.INFO) - - write = config['import']['write'].get(bool) + write = ui.should_write(opts.write) + force = opts.force if opts.album: for album in lib.albums(ui.decargs(args)): - self.handle_album(album, write) + self.handle_album(album, write, force) else: for item in lib.items(ui.decargs(args)): - self.handle_track(item, write) + self.handle_track(item, write, force) - cmd = ui.Subcommand('replaygain', help='analyze for ReplayGain') + cmd = ui.Subcommand('replaygain', help=u'analyze for ReplayGain') cmd.parser.add_album_option() + cmd.parser.add_option( + "-f", "--force", dest="force", action="store_true", default=False, + help=u"analyze all files, including those that " + "already have ReplayGain metadata") + cmd.parser.add_option( + "-w", "--write", default=None, action="store_true", + help=u"write new metadata to files' tags") + cmd.parser.add_option( + "-W", "--nowrite", dest="write", action="store_false", + help=u"don't write metadata (opposite of -w)") cmd.func = func return [cmd] diff --git a/beetsplug/rewrite.py b/beetsplug/rewrite.py index fd6346f9b..eadb14252 100644 --- a/beetsplug/rewrite.py +++ b/beetsplug/rewrite.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,8 +16,7 @@ """Uses user-specified rewriting rules to canonicalize names for path formats. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import re from collections import defaultdict @@ -51,13 +51,13 @@ class RewritePlugin(BeetsPlugin): # Gather all the rewrite rules for each field. rules = defaultdict(list) for key, view in self.config.items(): - value = view.get(unicode) + value = view.as_str() try: fieldname, pattern = key.split(None, 1) except ValueError: - raise ui.UserError("invalid rewrite specification") + raise ui.UserError(u"invalid rewrite specification") if fieldname not in library.Item._fields: - raise ui.UserError("invalid field name (%s) in rewriter" % + raise ui.UserError(u"invalid field name (%s) in rewriter" % fieldname) self._log.debug(u'adding template field {0}', key) pattern = re.compile(pattern.lower()) @@ -68,7 +68,7 @@ class RewritePlugin(BeetsPlugin): rules['albumartist'].append((pattern, value)) # Replace each template field with the new rewriter function. - for fieldname, fieldrules in rules.iteritems(): + for fieldname, fieldrules in rules.items(): getter = rewriter(fieldname, fieldrules) self.template_fields[fieldname] = getter if fieldname in library.Album._fields: diff --git a/beetsplug/scrub.py b/beetsplug/scrub.py index ac0017474..be6e7fd1f 100644 --- a/beetsplug/scrub.py +++ b/beetsplug/scrub.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -16,37 +17,34 @@ automatically whenever tags are written. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets import ui from beets import util from beets import config from beets import mediafile +import mutagen _MUTAGEN_FORMATS = { - b'asf': b'ASF', - b'apev2': b'APEv2File', - b'flac': b'FLAC', - b'id3': b'ID3FileType', - b'mp3': b'MP3', - b'mp4': b'MP4', - b'oggflac': b'OggFLAC', - b'oggspeex': b'OggSpeex', - b'oggtheora': b'OggTheora', - b'oggvorbis': b'OggVorbis', - b'oggopus': b'OggOpus', - b'trueaudio': b'TrueAudio', - b'wavpack': b'WavPack', - b'monkeysaudio': b'MonkeysAudio', - b'optimfrog': b'OptimFROG', + 'asf': 'ASF', + 'apev2': 'APEv2File', + 'flac': 'FLAC', + 'id3': 'ID3FileType', + 'mp3': 'MP3', + 'mp4': 'MP4', + 'oggflac': 'OggFLAC', + 'oggspeex': 'OggSpeex', + 'oggtheora': 'OggTheora', + 'oggvorbis': 'OggVorbis', + 'oggopus': 'OggOpus', + 'trueaudio': 'TrueAudio', + 'wavpack': 'WavPack', + 'monkeysaudio': 'MonkeysAudio', + 'optimfrog': 'OptimFROG', } -scrubbing = False - - class ScrubPlugin(BeetsPlugin): """Removes extraneous metadata from files' tags.""" def __init__(self): @@ -54,49 +52,23 @@ class ScrubPlugin(BeetsPlugin): self.config.add({ 'auto': True, }) - self.register_listener("write", self.write_item) + + if self.config['auto']: + self.register_listener("import_task_files", self.import_task_files) def commands(self): def scrub_func(lib, opts, args): - # This is a little bit hacky, but we set a global flag to - # avoid autoscrubbing when we're also explicitly scrubbing. - global scrubbing - scrubbing = True - # Walk through matching files and remove tags. for item in lib.items(ui.decargs(args)): self._log.info(u'scrubbing: {0}', util.displayable_path(item.path)) + self._scrub_item(item, opts.write) - # Get album art if we need to restore it. - if opts.write: - try: - mf = mediafile.MediaFile(util.syspath(item.path), - config['id3v23'].get(bool)) - except IOError as exc: - self._log.error(u'could not open file to scrub: {0}', - exc) - art = mf.art - - # Remove all tags. - self._scrub(item.path) - - # Restore tags, if enabled. - if opts.write: - self._log.debug(u'writing new tags after scrub') - item.try_write() - if art: - self._log.info(u'restoring art') - mf = mediafile.MediaFile(util.syspath(item.path)) - mf.art = art - mf.save() - - scrubbing = False - - scrub_cmd = ui.Subcommand('scrub', help='clean audio tags') - scrub_cmd.parser.add_option('-W', '--nowrite', dest='write', - action='store_false', default=True, - help='leave tags empty') + scrub_cmd = ui.Subcommand('scrub', help=u'clean audio tags') + scrub_cmd.parser.add_option( + u'-W', u'--nowrite', dest='write', + action='store_false', default=True, + help=u'leave tags empty') scrub_cmd.func = scrub_func return [scrub_cmd] @@ -107,7 +79,7 @@ class ScrubPlugin(BeetsPlugin): """ classes = [] for modname, clsname in _MUTAGEN_FORMATS.items(): - mod = __import__(b'mutagen.{0}'.format(modname), + mod = __import__('mutagen.{0}'.format(modname), fromlist=[clsname]) classes.append(getattr(mod, clsname)) return classes @@ -135,12 +107,45 @@ class ScrubPlugin(BeetsPlugin): for tag in f.keys(): del f[tag] f.save() - except IOError as exc: + except (IOError, mutagen.MutagenError) as exc: self._log.error(u'could not scrub {0}: {1}', util.displayable_path(path), exc) - def write_item(self, item, path, tags): - """Automatically embed art into imported albums.""" - if not scrubbing and self.config['auto']: - self._log.debug(u'auto-scrubbing {0}', util.displayable_path(path)) - self._scrub(path) + def _scrub_item(self, item, restore=True): + """Remove tags from an Item's associated file and, if `restore` + is enabled, write the database's tags back to the file. + """ + # Get album art if we need to restore it. + if restore: + try: + mf = mediafile.MediaFile(util.syspath(item.path), + config['id3v23'].get(bool)) + except mediafile.UnreadableFileError as exc: + self._log.error(u'could not open file to scrub: {0}', + exc) + return + images = mf.images + + # Remove all tags. + self._scrub(item.path) + + # Restore tags, if enabled. + if restore: + self._log.debug(u'writing new tags after scrub') + item.try_write() + if images: + self._log.debug(u'restoring art') + try: + mf = mediafile.MediaFile(util.syspath(item.path), + config['id3v23'].get(bool)) + mf.images = images + mf.save() + except mediafile.UnreadableFileError as exc: + self._log.error(u'could not write tags: {0}', exc) + + def import_task_files(self, session, task): + """Automatically scrub imported files.""" + for item in task.imported_items(): + self._log.debug(u'auto-scrubbing {0}', + util.displayable_path(item.path)) + self._scrub_item(item) diff --git a/beetsplug/smartplaylist.py b/beetsplug/smartplaylist.py index 8889a2534..009512c5c 100644 --- a/beetsplug/smartplaylist.py +++ b/beetsplug/smartplaylist.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Dang Mai <contact@dangmai.net>. +# Copyright 2016, Dang Mai <contact@dangmai.net>. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,16 +16,17 @@ """Generates smart playlists based on beets queries. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets import ui -from beets.util import mkdirall, normpath, syspath +from beets.util import (mkdirall, normpath, sanitize_path, syspath, + bytestring_path) from beets.library import Item, Album, parse_query_string from beets.dbcore import OrQuery -from beets.dbcore.query import MultipleSort +from beets.dbcore.query import MultipleSort, ParsingError import os +import six class SmartPlaylistPlugin(BeetsPlugin): @@ -45,9 +47,11 @@ class SmartPlaylistPlugin(BeetsPlugin): self.register_listener('database_change', self.db_change) def commands(self): - spl_update = ui.Subcommand('splupdate', - help='update the smart playlists. Playlist ' - 'names may be passed as arguments.') + spl_update = ui.Subcommand( + 'splupdate', + help=u'update the smart playlists. Playlist names may be ' + u'passed as arguments.' + ) spl_update.func = self.update_cmd return [spl_update] @@ -63,9 +67,10 @@ class SmartPlaylistPlugin(BeetsPlugin): for name, q, a_q in self._unmatched_playlists if name in args) if not playlists: - raise ui.UserError('No playlist matching any of {0} ' - 'found'.format([name for name, _, _ in - self._unmatched_playlists])) + raise ui.UserError( + u'No playlist matching any of {0} found'.format( + [name for name, _, _ in self._unmatched_playlists]) + ) self._matched_playlists = playlists self._unmatched_playlists -= playlists @@ -93,36 +98,46 @@ class SmartPlaylistPlugin(BeetsPlugin): self._matched_playlists = set() for playlist in self.config['playlists'].get(list): - playlist_data = (playlist['name'],) - for key, Model in (('query', Item), ('album_query', Album)): - qs = playlist.get(key) - if qs is None: - query_and_sort = None, None - elif isinstance(qs, basestring): - query_and_sort = parse_query_string(qs, Model) - elif len(qs) == 1: - query_and_sort = parse_query_string(qs[0], Model) - else: - # multiple queries and sorts - queries, sorts = zip(*(parse_query_string(q, Model) - for q in qs)) - query = OrQuery(queries) - final_sorts = [] - for s in sorts: - if s: - if isinstance(s, MultipleSort): - final_sorts += s.sorts - else: - final_sorts.append(s) - if not final_sorts: - sort = None - elif len(final_sorts) == 1: - sort, = final_sorts - else: - sort = MultipleSort(final_sorts) - query_and_sort = query, sort + if 'name' not in playlist: + self._log.warning(u"playlist configuration is missing name") + continue - playlist_data += (query_and_sort,) + playlist_data = (playlist['name'],) + try: + for key, Model in (('query', Item), ('album_query', Album)): + qs = playlist.get(key) + if qs is None: + query_and_sort = None, None + elif isinstance(qs, six.string_types): + query_and_sort = parse_query_string(qs, Model) + elif len(qs) == 1: + query_and_sort = parse_query_string(qs[0], Model) + else: + # multiple queries and sorts + queries, sorts = zip(*(parse_query_string(q, Model) + for q in qs)) + query = OrQuery(queries) + final_sorts = [] + for s in sorts: + if s: + if isinstance(s, MultipleSort): + final_sorts += s.sorts + else: + final_sorts.append(s) + if not final_sorts: + sort = None + elif len(final_sorts) == 1: + sort, = final_sorts + else: + sort = MultipleSort(final_sorts) + query_and_sort = query, sort + + playlist_data += (query_and_sort,) + + except ParsingError as exc: + self._log.warning(u"invalid query in playlist {}: {}", + playlist['name'], exc) + continue self._unmatched_playlists.add(playlist_data) @@ -140,21 +155,26 @@ class SmartPlaylistPlugin(BeetsPlugin): for playlist in self._unmatched_playlists: n, (q, _), (a_q, _) = playlist if self.matches(model, q, a_q): - self._log.debug("{0} will be updated because of {1}", n, model) + self._log.debug( + u"{0} will be updated because of {1}", n, model) self._matched_playlists.add(playlist) self.register_listener('cli_exit', self.update_playlists) self._unmatched_playlists -= self._matched_playlists def update_playlists(self, lib): - self._log.info("Updating {0} smart playlists...", + self._log.info(u"Updating {0} smart playlists...", len(self._matched_playlists)) playlist_dir = self.config['playlist_dir'].as_filename() + playlist_dir = bytestring_path(playlist_dir) relative_to = self.config['relative_to'].get() if relative_to: relative_to = normpath(relative_to) + # Maps playlist filenames to lists of track filenames. + m3us = {} + for playlist in self._matched_playlists: name, (query, q_sort), (album_query, a_q_sort) = playlist self._log.debug(u"Creating playlist {0}", name) @@ -166,11 +186,11 @@ class SmartPlaylistPlugin(BeetsPlugin): for album in lib.albums(album_query, a_q_sort): items.extend(album.items()) - m3us = {} # As we allow tags in the m3u names, we'll need to iterate through # the items and generate the correct m3u file names. for item in items: m3u_name = item.evaluate_template(name, True) + m3u_name = sanitize_path(m3u_name, lib.replacements) if m3u_name not in m3us: m3us[m3u_name] = [] item_path = item.path @@ -178,11 +198,14 @@ class SmartPlaylistPlugin(BeetsPlugin): item_path = os.path.relpath(item.path, relative_to) if item_path not in m3us[m3u_name]: m3us[m3u_name].append(item_path) - # Now iterate through the m3us that we need to generate - for m3u in m3us: - m3u_path = normpath(os.path.join(playlist_dir, m3u)) - mkdirall(m3u_path) - with open(syspath(m3u_path), 'w') as f: - for path in m3us[m3u]: - f.write(path + b'\n') - self._log.info("{0} playlists updated", len(self._matched_playlists)) + + # Write all of the accumulated track lists to files. + for m3u in m3us: + m3u_path = normpath(os.path.join(playlist_dir, + bytestring_path(m3u))) + mkdirall(m3u_path) + with open(syspath(m3u_path), 'wb') as f: + for path in m3us[m3u]: + f.write(path + b'\n') + + self._log.info(u"{0} playlists updated", len(self._matched_playlists)) diff --git a/beetsplug/sonosupdate.py b/beetsplug/sonosupdate.py new file mode 100644 index 000000000..56a315a15 --- /dev/null +++ b/beetsplug/sonosupdate.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2018, Tobias Sauerwein. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Updates a Sonos library whenever the beets library is changed. +This is based on the Kodi Update plugin. +""" +from __future__ import division, absolute_import, print_function + +from beets.plugins import BeetsPlugin +import soco + + +class SonosUpdate(BeetsPlugin): + def __init__(self): + super(SonosUpdate, self).__init__() + self.register_listener('database_change', self.listen_for_db_change) + + def listen_for_db_change(self, lib, model): + """Listens for beets db change and register the update""" + self.register_listener('cli_exit', self.update) + + def update(self, lib): + """When the client exists try to send refresh request to a Sonos + controler. + """ + self._log.info(u'Requesting a Sonos library update...') + + device = soco.discovery.any_soco() + + if device: + device.music_library.start_library_update() + else: + self._log.warning(u'Could not find a Sonos device.') + return + + self._log.info(u'Sonos update triggered') diff --git a/beetsplug/spotify.py b/beetsplug/spotify.py index 42683d4cb..36231f297 100644 --- a/beetsplug/spotify.py +++ b/beetsplug/spotify.py @@ -1,5 +1,6 @@ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +# -*- coding: utf-8 -*- + +from __future__ import division, absolute_import, print_function import re import webbrowser @@ -39,17 +40,17 @@ class SpotifyPlugin(BeetsPlugin): self.output_results(results) spotify_cmd = ui.Subcommand( 'spotify', - help='build a Spotify playlist' + help=u'build a Spotify playlist' ) spotify_cmd.parser.add_option( - '-m', '--mode', action='store', - help='"open" to open Spotify with playlist, ' - '"list" to print (default)' + u'-m', u'--mode', action='store', + help=u'"open" to open Spotify with playlist, ' + u'"list" to print (default)' ) spotify_cmd.parser.add_option( - '-f', '--show-failures', action='store_true', - help='list tracks that did not match a Spotify ID', - dest='show_failures', + u'-f', u'--show-failures', + action='store_true', dest='show_failures', + help=u'list tracks that did not match a Spotify ID' ) spotify_cmd.func = queries return [spotify_cmd] @@ -62,8 +63,8 @@ class SpotifyPlugin(BeetsPlugin): self.config['show_failures'].set(True) if self.config['mode'].get() not in ['list', 'open']: - self._log.warn(u'{0} is not a valid mode', - self.config['mode'].get()) + self._log.warning(u'{0} is not a valid mode', + self.config['mode'].get()) return False self.opts = opts @@ -123,9 +124,8 @@ class SpotifyPlugin(BeetsPlugin): # Apply market filter if requested region_filter = self.config['region_filter'].get() if region_filter: - r_data = filter( - lambda x: region_filter in x['available_markets'], r_data - ) + r_data = [x for x in r_data if region_filter + in x['available_markets']] # Simplest, take the first result chosen_result = None @@ -154,15 +154,15 @@ class SpotifyPlugin(BeetsPlugin): self._log.info(u'track: {0}', track) self._log.info(u'') else: - self._log.warn(u'{0} track(s) did not match a Spotify ID;\n' - u'use --show-failures to display', - failure_count) + self._log.warning(u'{0} track(s) did not match a Spotify ID;\n' + u'use --show-failures to display', + failure_count) return results def output_results(self, results): if results: - ids = map(lambda x: x['id'], results) + ids = [x['id'] for x in results] if self.config['mode'].get() == "open": self._log.info(u'Attempting to open Spotify with playlist') spotify_url = self.playlist_partial + ",".join(ids) @@ -170,6 +170,6 @@ class SpotifyPlugin(BeetsPlugin): else: for item in ids: - print(unicode.encode(self.open_url + item)) + print(self.open_url + item) else: - self._log.warn(u'No Spotify tracks found from beets query') + self._log.warning(u'No Spotify tracks found from beets query') diff --git a/beetsplug/the.py b/beetsplug/the.py index 538b81245..cfb583ced 100644 --- a/beetsplug/the.py +++ b/beetsplug/the.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Blemjhoo Tezoulbr <baobab@heresiarch.info>. +# Copyright 2016, Blemjhoo Tezoulbr <baobab@heresiarch.info>. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,8 +15,7 @@ """Moves patterns in path formats (suitable for moving articles).""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import re from beets.plugins import BeetsPlugin @@ -54,14 +54,14 @@ class ThePlugin(BeetsPlugin): self._log.error(u'invalid pattern: {0}', p) else: if not (p.startswith('^') or p.endswith('$')): - self._log.warn(u'warning: \"{0}\" will not ' - u'match string start/end', p) + self._log.warning(u'warning: \"{0}\" will not ' + u'match string start/end', p) if self.config['a']: self.patterns = [PATTERN_A] + self.patterns if self.config['the']: self.patterns = [PATTERN_THE] + self.patterns if not self.patterns: - self._log.warn(u'no patterns defined!') + self._log.warning(u'no patterns defined!') def unthe(self, text, pattern): """Moves pattern in the path format string or strips it @@ -81,7 +81,7 @@ class ThePlugin(BeetsPlugin): if self.config['strip']: return r else: - fmt = self.config['format'].get(unicode) + fmt = self.config['format'].as_str() return fmt.format(r, t.strip()).strip() else: return u'' diff --git a/beetsplug/thumbnails.py b/beetsplug/thumbnails.py index ce3382fc8..04845e880 100644 --- a/beetsplug/thumbnails.py +++ b/beetsplug/thumbnails.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Bruno Cauet +# Copyright 2016, Bruno Cauet # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -19,8 +19,7 @@ This plugin is POSIX-only. Spec: standards.freedesktop.org/thumbnail-spec/latest/index.html """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from hashlib import md5 import os @@ -35,12 +34,13 @@ from xdg import BaseDirectory from beets.plugins import BeetsPlugin from beets.ui import Subcommand, decargs from beets import util -from beets.util.artresizer import ArtResizer, has_IM, has_PIL +from beets.util.artresizer import ArtResizer, get_im_version, get_pil_version +import six BASE_DIR = os.path.join(BaseDirectory.xdg_cache_home, "thumbnails") -NORMAL_DIR = os.path.join(BASE_DIR, "normal") -LARGE_DIR = os.path.join(BASE_DIR, "large") +NORMAL_DIR = util.bytestring_path(os.path.join(BASE_DIR, "normal")) +LARGE_DIR = util.bytestring_path(os.path.join(BASE_DIR, "large")) class ThumbnailsPlugin(BeetsPlugin): @@ -58,14 +58,15 @@ class ThumbnailsPlugin(BeetsPlugin): def commands(self): thumbnails_command = Subcommand("thumbnails", - help="Create album thumbnails") + help=u"Create album thumbnails") thumbnails_command.parser.add_option( - '-f', '--force', dest='force', action='store_true', default=False, - help='force regeneration of thumbnails deemed fine (existing & ' - 'recent enough)') + u'-f', u'--force', + dest='force', action='store_true', default=False, + help=u'force regeneration of thumbnails deemed fine (existing & ' + u'recent enough)') thumbnails_command.parser.add_option( - '--dolphin', dest='dolphin', action='store_true', default=False, - help="create Dolphin-compatible thumbnail information (for KDE)") + u'--dolphin', dest='dolphin', action='store_true', default=False, + help=u"create Dolphin-compatible thumbnail information (for KDE)") thumbnails_command.func = self.process_query return [thumbnails_command] @@ -84,27 +85,27 @@ class ThumbnailsPlugin(BeetsPlugin): - detect whether we'll use GIO or Python to get URIs """ if not ArtResizer.shared.local: - self._log.warning("No local image resizing capabilities, " - "cannot generate thumbnails") + self._log.warning(u"No local image resizing capabilities, " + u"cannot generate thumbnails") return False for dir in (NORMAL_DIR, LARGE_DIR): if not os.path.exists(dir): os.makedirs(dir) - if has_IM(): + if get_im_version(): self.write_metadata = write_metadata_im tool = "IM" else: - assert has_PIL() # since we're local + assert get_pil_version() # since we're local self.write_metadata = write_metadata_pil tool = "PIL" - self._log.debug("using {0} to write metadata", tool) + self._log.debug(u"using {0} to write metadata", tool) uri_getter = GioURI() if not uri_getter.available: uri_getter = PathlibURI() - self._log.debug("using {0.name} to compute URIs", uri_getter) + self._log.debug(u"using {0.name} to compute URIs", uri_getter) self.get_uri = uri_getter.uri return True @@ -122,7 +123,7 @@ class ThumbnailsPlugin(BeetsPlugin): size = ArtResizer.shared.get_size(album.artpath) if not size: - self._log.warning('problem getting the picture size for {0}', + self._log.warning(u'problem getting the picture size for {0}', album.artpath) return @@ -132,9 +133,9 @@ class ThumbnailsPlugin(BeetsPlugin): wrote &= self.make_cover_thumbnail(album, 128, NORMAL_DIR) if wrote: - self._log.info('wrote thumbnail for {0}', album) + self._log.info(u'wrote thumbnail for {0}', album) else: - self._log.info('nothing to do for {0}', album) + self._log.info(u'nothing to do for {0}', album) def make_cover_thumbnail(self, album, size, target_dir): """Make a thumbnail of given size for `album` and put it in @@ -145,11 +146,11 @@ class ThumbnailsPlugin(BeetsPlugin): if os.path.exists(target) and \ os.stat(target).st_mtime > os.stat(album.artpath).st_mtime: if self.config['force']: - self._log.debug("found a suitable {1}x{1} thumbnail for {0}, " - "forcing regeneration", album, size) + self._log.debug(u"found a suitable {1}x{1} thumbnail for {0}, " + u"forcing regeneration", album, size) else: - self._log.debug("{1}x{1} thumbnail for {0} exists and is " - "recent enough", album, size) + self._log.debug(u"{1}x{1} thumbnail for {0} exists and is " + u"recent enough", album, size) return False resized = ArtResizer.shared.resize(size, album.artpath, util.syspath(target)) @@ -162,19 +163,20 @@ class ThumbnailsPlugin(BeetsPlugin): See http://standards.freedesktop.org/thumbnail-spec/latest/x227.html """ uri = self.get_uri(path) - hash = md5(uri).hexdigest() - return b"{0}.png".format(hash) + hash = md5(uri.encode('utf-8')).hexdigest() + return util.bytestring_path("{0}.png".format(hash)) def add_tags(self, album, image_path): """Write required metadata to the thumbnail See http://standards.freedesktop.org/thumbnail-spec/latest/x142.html """ + mtime = os.stat(album.artpath).st_mtime metadata = {"Thumb::URI": self.get_uri(album.artpath), - "Thumb::MTime": unicode(os.stat(album.artpath).st_mtime)} + "Thumb::MTime": six.text_type(mtime)} try: self.write_metadata(image_path, metadata) except Exception: - self._log.exception("could not write metadata to {0}", + self._log.exception(u"could not write metadata to {0}", util.displayable_path(image_path)) def make_dolphin_cover_thumbnail(self, album): @@ -183,9 +185,10 @@ class ThumbnailsPlugin(BeetsPlugin): return artfile = os.path.split(album.artpath)[1] with open(outfilename, 'w') as f: - f.write(b"[Desktop Entry]\nIcon=./{0}".format(artfile)) + f.write('[Desktop Entry]\n') + f.write('Icon=./{0}'.format(artfile.decode('utf-8'))) f.close() - self._log.debug("Wrote file {0}", util.displayable_path(outfilename)) + self._log.debug(u"Wrote file {0}", util.displayable_path(outfilename)) def write_metadata_im(file, metadata): @@ -224,6 +227,17 @@ class PathlibURI(URIGetter): return PurePosixPath(path).as_uri() +def copy_c_string(c_string): + """Copy a `ctypes.POINTER(ctypes.c_char)` value into a new Python + string and return it. The old memory is then safe to free. + """ + # This is a pretty dumb way to get a string copy, but it seems to + # work. A more surefire way would be to allocate a ctypes buffer and copy + # the data with `memcpy` or somesuch. + s = ctypes.cast(c_string, ctypes.c_char_p).value + return b'' + s + + class GioURI(URIGetter): """Use gio URI function g_file_get_uri. Paths must be utf-8 encoded. """ @@ -234,8 +248,13 @@ class GioURI(URIGetter): self.available = bool(self.libgio) if self.available: self.libgio.g_type_init() # for glib < 2.36 + + self.libgio.g_file_get_uri.argtypes = [ctypes.c_char_p] self.libgio.g_file_new_for_path.restype = ctypes.c_void_p + self.libgio.g_file_get_uri.argtypes = [ctypes.c_void_p] + self.libgio.g_file_get_uri.restype = ctypes.POINTER(ctypes.c_char) + self.libgio.g_object_unref.argtypes = [ctypes.c_void_p] def get_library(self): @@ -250,24 +269,26 @@ class GioURI(URIGetter): def uri(self, path): g_file_ptr = self.libgio.g_file_new_for_path(path) if not g_file_ptr: - raise RuntimeError("No gfile pointer received for {0}".format( + raise RuntimeError(u"No gfile pointer received for {0}".format( util.displayable_path(path))) try: uri_ptr = self.libgio.g_file_get_uri(g_file_ptr) - except: - raise finally: self.libgio.g_object_unref(g_file_ptr) if not uri_ptr: self.libgio.g_free(uri_ptr) - raise RuntimeError("No URI received from the gfile pointer for " - "{0}".format(util.displayable_path(path))) + raise RuntimeError(u"No URI received from the gfile pointer for " + u"{0}".format(util.displayable_path(path))) try: - uri = ctypes.c_char_p(uri_ptr).value - except: - raise + uri = copy_c_string(uri_ptr) finally: self.libgio.g_free(uri_ptr) - return uri + + try: + return uri.decode(util._fsencoding()) + except UnicodeDecodeError: + raise RuntimeError( + "Could not decode filename from GIO: {!r}".format(uri) + ) diff --git a/beetsplug/types.py b/beetsplug/types.py index dad892bc9..0c078881c 100644 --- a/beetsplug/types.py +++ b/beetsplug/types.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets.dbcore import types diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 18750ebb3..3cf43ed56 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -13,8 +14,7 @@ # included in all copies or substantial portions of the Software. """A Web interface to beets.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets import ui @@ -24,7 +24,9 @@ import flask from flask import g from werkzeug.routing import BaseConverter, PathConverter import os +from unidecode import unidecode import json +import base64 # Utilities. @@ -37,7 +39,15 @@ def _rep(obj, expand=False): out = dict(obj) if isinstance(obj, beets.library.Item): - del out['path'] + if app.config.get('INCLUDE_PATHS', False): + out['path'] = util.displayable_path(out['path']) + else: + del out['path'] + + # Filter all bytes attributes and convert them to strings. + for key, value in out.items(): + if isinstance(out[key], bytes): + out[key] = base64.b64encode(value).decode('ascii') # Get the size (in bytes) of the backing file. This is useful # for the Tomahawk resolver API. @@ -55,11 +65,13 @@ def _rep(obj, expand=False): return out -def json_generator(items, root): +def json_generator(items, root, expand=False): """Generator that dumps list of beets Items or Albums as JSON :param root: root key for JSON :param items: list of :class:`Item` or :class:`Album` to dump + :param expand: If true every :class:`Album` contains its items in the json + representation :returns: generator that yields strings """ yield '{"%s":[' % root @@ -69,10 +81,16 @@ def json_generator(items, root): first = False else: yield ',' - yield json.dumps(_rep(item)) + yield json.dumps(_rep(item, expand=expand)) yield ']}' +def is_expand(): + """Returns whether the current request is for an expanded response.""" + + return flask.request.args.get('expand') is not None + + def resource(name): """Decorates a function to handle RESTful HTTP requests for a resource. """ @@ -82,7 +100,7 @@ def resource(name): entities = [entity for entity in entities if entity] if len(entities) == 1: - return flask.jsonify(_rep(entities[0])) + return flask.jsonify(_rep(entities[0], expand=is_expand())) elif entities: return app.response_class( json_generator(entities, root=name), @@ -90,7 +108,7 @@ def resource(name): ) else: return flask.abort(404) - responder.__name__ = b'get_%s' % name.encode('utf8') + responder.__name__ = 'get_{0}'.format(name) return responder return make_responder @@ -101,10 +119,13 @@ def resource_query(name): def make_responder(query_func): def responder(queries): return app.response_class( - json_generator(query_func(queries), root='results'), + json_generator( + query_func(queries), + root='results', expand=is_expand() + ), mimetype='application/json' ) - responder.__name__ = b'query_%s' % name.encode('utf8') + responder.__name__ = 'query_{0}'.format(name) return responder return make_responder @@ -116,14 +137,24 @@ def resource_list(name): def make_responder(list_all): def responder(): return app.response_class( - json_generator(list_all(), root=name), + json_generator(list_all(), root=name, expand=is_expand()), mimetype='application/json' ) - responder.__name__ = b'all_%s' % name.encode('utf8') + responder.__name__ = 'all_{0}'.format(name) return responder return make_responder +def _get_unique_table_field_values(model, field, sort_field): + """ retrieve all unique values belonging to a key from a model """ + if field not in model.all_keys() or sort_field not in model.all_keys(): + raise KeyError + with g.lib.transaction() as tx: + rows = tx.query('SELECT DISTINCT "{0}" FROM "{1}" ORDER BY "{2}"' + .format(field, model._table, sort_field)) + return [row[0] for row in rows] + + class IdListConverter(BaseConverter): """Converts comma separated lists of ids in urls to integer lists. """ @@ -152,11 +183,16 @@ class QueryConverter(PathConverter): return ','.join(value) +class EverythingConverter(PathConverter): + regex = '.*?' + + # Flask setup. app = flask.Flask(__name__) app.url_map.converters['idlist'] = IdListConverter app.url_map.converters['query'] = QueryConverter +app.url_map.converters['everything'] = EverythingConverter @app.before_request @@ -182,9 +218,34 @@ def all_items(): @app.route('/item/<int:item_id>/file') def item_file(item_id): item = g.lib.get_item(item_id) - response = flask.send_file(item.path, as_attachment=True, - attachment_filename=os.path.basename(item.path)) - response.headers['Content-Length'] = os.path.getsize(item.path) + + # On Windows under Python 2, Flask wants a Unicode path. On Python 3, it + # *always* wants a Unicode path. + if os.name == 'nt': + item_path = util.syspath(item.path) + else: + item_path = util.py3_path(item.path) + + try: + unicode_item_path = util.text_string(item.path) + except (UnicodeDecodeError, UnicodeEncodeError): + unicode_item_path = util.displayable_path(item.path) + + base_filename = os.path.basename(unicode_item_path) + try: + # Imitate http.server behaviour + base_filename.encode("latin-1", "strict") + except UnicodeEncodeError: + safe_filename = unidecode(base_filename) + else: + safe_filename = base_filename + + response = flask.send_file( + item_path, + as_attachment=True, + attachment_filename=safe_filename + ) + response.headers['Content-Length'] = os.path.getsize(item_path) return response @@ -194,6 +255,27 @@ def item_query(queries): return g.lib.items(queries) +@app.route('/item/path/<everything:path>') +def item_at_path(path): + query = beets.library.PathQuery('path', path.encode('utf-8')) + item = g.lib.items(query).get() + if item: + return flask.jsonify(_rep(item)) + else: + return flask.abort(404) + + +@app.route('/item/values/<string:key>') +def item_unique_field_values(key): + sort_key = flask.request.args.get('sort_key', key) + try: + values = _get_unique_table_field_values(beets.library.Item, key, + sort_key) + except KeyError: + return flask.abort(404) + return flask.jsonify(values=values) + + # Albums. @app.route('/album/<idlist:ids>') @@ -218,7 +300,21 @@ def album_query(queries): @app.route('/album/<int:album_id>/art') def album_art(album_id): album = g.lib.get_album(album_id) - return flask.send_file(album.artpath) + if album and album.artpath: + return flask.send_file(album.artpath.decode()) + else: + return flask.abort(404) + + +@app.route('/album/values/<string:key>') +def album_unique_field_values(key): + sort_key = flask.request.args.get('sort_key', key) + try: + values = _get_unique_table_field_values(beets.library.Album, key, + sort_key) + except KeyError: + return flask.abort(404) + return flask.jsonify(values=values) # Artists. @@ -260,12 +356,15 @@ class WebPlugin(BeetsPlugin): 'host': u'127.0.0.1', 'port': 8337, 'cors': '', + 'cors_supports_credentials': False, + 'reverse_proxy': False, + 'include_paths': False, }) def commands(self): - cmd = ui.Subcommand('web', help='start a Web interface') - cmd.parser.add_option('-d', '--debug', action='store_true', - default=False, help='debug mode') + cmd = ui.Subcommand('web', help=u'start a Web interface') + cmd.parser.add_option(u'-d', u'--debug', action='store_true', + default=False, help=u'debug mode') def func(lib, opts, args): args = ui.decargs(args) @@ -275,19 +374,70 @@ class WebPlugin(BeetsPlugin): self.config['port'] = int(args.pop(0)) app.config['lib'] = lib + # Normalizes json output + app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False + + app.config['INCLUDE_PATHS'] = self.config['include_paths'] + # Enable CORS if required. if self.config['cors']: - self._log.info('Enabling CORS with origin: {0}', + self._log.info(u'Enabling CORS with origin: {0}', self.config['cors']) from flask.ext.cors import CORS app.config['CORS_ALLOW_HEADERS'] = "Content-Type" app.config['CORS_RESOURCES'] = { r"/*": {"origins": self.config['cors'].get(str)} } - CORS(app) + CORS( + app, + supports_credentials=self.config[ + 'cors_supports_credentials' + ].get(bool) + ) + + # Allow serving behind a reverse proxy + if self.config['reverse_proxy']: + app.wsgi_app = ReverseProxied(app.wsgi_app) + # Start the web application. - app.run(host=self.config['host'].get(unicode), + app.run(host=self.config['host'].as_str(), port=self.config['port'].get(int), debug=opts.debug, threaded=True) cmd.func = func return [cmd] + + +class ReverseProxied(object): + '''Wrap the application in this middleware and configure the + front-end server to add these headers, to let you quietly bind + this to a URL other than / and to an HTTP scheme that is + different than what is used locally. + + In nginx: + location /myprefix { + proxy_pass http://192.168.0.1:5001; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Scheme $scheme; + proxy_set_header X-Script-Name /myprefix; + } + + From: http://flask.pocoo.org/snippets/35/ + + :param app: the WSGI application + ''' + def __init__(self, app): + self.app = app + + def __call__(self, environ, start_response): + script_name = environ.get('HTTP_X_SCRIPT_NAME', '') + if script_name: + environ['SCRIPT_NAME'] = script_name + path_info = environ['PATH_INFO'] + if path_info.startswith(script_name): + environ['PATH_INFO'] = path_info[len(script_name):] + + scheme = environ.get('HTTP_X_SCHEME', '') + if scheme: + environ['wsgi.url_scheme'] = scheme + return self.app(environ, start_response) diff --git a/beetsplug/web/static/beets.js b/beetsplug/web/static/beets.js index 757f2cdab..51985c183 100644 --- a/beetsplug/web/static/beets.js +++ b/beetsplug/web/static/beets.js @@ -4,7 +4,7 @@ var timeFormat = function(secs) { return '0:00'; } secs = Math.round(secs); - var mins = '' + Math.round(secs / 60); + var mins = '' + Math.floor(secs / 60); secs = '' + (secs % 60); if (secs.length < 2) { secs = '0' + secs; @@ -147,7 +147,7 @@ var BeetsRouter = Backbone.Router.extend({ }, itemQuery: function(query) { var queryURL = query.split(/\s+/).map(encodeURIComponent).join('/'); - $.getJSON('/item/query/' + queryURL, function(data) { + $.getJSON('item/query/' + queryURL, function(data) { var models = _.map( data['results'], function(d) { return new Item(d); } @@ -161,7 +161,7 @@ var router = new BeetsRouter(); // Model. var Item = Backbone.Model.extend({ - urlRoot: '/item' + urlRoot: 'item' }); var Items = Backbone.Collection.extend({ model: Item @@ -264,7 +264,7 @@ var AppView = Backbone.View.extend({ $('#extra-detail').empty().append(extraDetailView.render().el); }, playItem: function(item) { - var url = '/item/' + item.get('id') + '/file'; + var url = 'item/' + item.get('id') + '/file'; $('#player audio').attr('src', url); $('#player audio').get(0).play(); diff --git a/beetsplug/web/static/jquery.js b/beetsplug/web/static/jquery.js index 5b43a3ece..e14142126 100644 --- a/beetsplug/web/static/jquery.js +++ b/beetsplug/web/static/jquery.js @@ -2,13 +2,13 @@ * jQuery JavaScript Library v1.7.1 * http://jquery.com/ * - * Copyright 2015, John Resig + * Copyright 2016, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ - * Copyright 2015, The Dojo Foundation + * Copyright 2016, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Mon Nov 21 21:11:03 2011 -0500 @@ -3851,7 +3851,7 @@ jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblcl /*! * Sizzle CSS Selector Engine - * Copyright 2015, The Dojo Foundation + * Copyright 2016, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ diff --git a/beetsplug/web/templates/index.html b/beetsplug/web/templates/index.html index 7c37c82d6..0fdd46d15 100644 --- a/beetsplug/web/templates/index.html +++ b/beetsplug/web/templates/index.html @@ -82,7 +82,7 @@ <% } %> <dt>File</dt> <dd> - <a target="_blank" class="download" href="/item/<%= id %>/file">download</a> + <a target="_blank" class="download" href="item/<%= id %>/file">download</a> </dd> <% if (lyrics) { %> <dt>Lyrics</dt> diff --git a/beetsplug/zero.py b/beetsplug/zero.py index abccde36f..022c2c721 100644 --- a/beetsplug/zero.py +++ b/beetsplug/zero.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Blemjhoo Tezoulbr <baobab@heresiarch.info>. +# Copyright 2016, Blemjhoo Tezoulbr <baobab@heresiarch.info>. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,91 +15,149 @@ """ Clears tag fields in media files.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function +import six import re + from beets.plugins import BeetsPlugin from beets.mediafile import MediaFile from beets.importer import action +from beets.ui import Subcommand, decargs, input_yn from beets.util import confit __author__ = 'baobab@heresiarch.info' -__version__ = '0.10' class ZeroPlugin(BeetsPlugin): - - _instance = None - def __init__(self): super(ZeroPlugin, self).__init__() - # Listeners. self.register_listener('write', self.write_event) self.register_listener('import_task_choice', self.import_task_choice_event) self.config.add({ + 'auto': True, 'fields': [], + 'keep_fields': [], 'update_database': False, }) - self.patterns = {} + self.fields_to_progs = {} self.warned = False - for field in self.config['fields'].as_str_seq(): - if field in ('id', 'path', 'album_id'): - self._log.warn(u'field \'{0}\' ignored, zeroing ' - u'it would be dangerous', field) - continue - if field not in MediaFile.fields(): - self._log.error(u'invalid field: {0}', field) - continue + """Read the bulk of the config into `self.fields_to_progs`. + After construction, `fields_to_progs` contains all the fields that + should be zeroed as keys and maps each of those to a list of compiled + regexes (progs) as values. + A field is zeroed if its value matches one of the associated progs. If + progs is empty, then the associated field is always zeroed. + """ + if self.config['fields'] and self.config['keep_fields']: + self._log.warning( + u'cannot blacklist and whitelist at the same time' + ) + # Blacklist mode. + elif self.config['fields']: + for field in self.config['fields'].as_str_seq(): + self._set_pattern(field) + # Whitelist mode. + elif self.config['keep_fields']: + for field in MediaFile.fields(): + if (field not in self.config['keep_fields'].as_str_seq() and + # These fields should always be preserved. + field not in ('id', 'path', 'album_id')): + self._set_pattern(field) + def commands(self): + zero_command = Subcommand('zero', help='set fields to null') + + def zero_fields(lib, opts, args): + if not decargs(args) and not input_yn( + u"Remove fields for all items? (Y/n)", + True): + return + for item in lib.items(decargs(args)): + self.process_item(item) + + zero_command.func = zero_fields + return [zero_command] + + def _set_pattern(self, field): + """Populate `self.fields_to_progs` for a given field. + Do some sanity checks then compile the regexes. + """ + if field not in MediaFile.fields(): + self._log.error(u'invalid field: {0}', field) + elif field in ('id', 'path', 'album_id'): + self._log.warning(u'field \'{0}\' ignored, zeroing ' + u'it would be dangerous', field) + else: try: - self.patterns[field] = self.config[field].as_str_seq() + for pattern in self.config[field].as_str_seq(): + prog = re.compile(pattern, re.IGNORECASE) + self.fields_to_progs.setdefault(field, []).append(prog) except confit.NotFoundError: # Matches everything - self.patterns[field] = True + self.fields_to_progs[field] = [] def import_task_choice_event(self, session, task): - """Listen for import_task_choice event.""" if task.choice_flag == action.ASIS and not self.warned: - self._log.warn(u'cannot zero in \"as-is\" mode') + self._log.warning(u'cannot zero in \"as-is\" mode') self.warned = True # TODO request write in as-is mode - @classmethod - def match_patterns(cls, field, patterns): - """Check if field (as string) is matching any of the patterns in - the list. - """ - if patterns is True: - return True - for p in patterns: - if re.search(p, unicode(field), flags=re.IGNORECASE): - return True - return False - def write_event(self, item, path, tags): - """Set values in tags to `None` if the key and value are matched - by `self.patterns`. - """ - if not self.patterns: - self._log.warn(u'no fields, nothing to do') - return + if self.config['auto']: + self.set_fields(item, tags) - for field, patterns in self.patterns.items(): + def set_fields(self, item, tags): + """Set values in `tags` to `None` if the field is in + `self.fields_to_progs` and any of the corresponding `progs` matches the + field value. + Also update the `item` itself if `update_database` is set in the + config. + """ + fields_set = False + + if not self.fields_to_progs: + self._log.warning(u'no fields, nothing to do') + return False + + for field, progs in self.fields_to_progs.items(): if field in tags: value = tags[field] - match = self.match_patterns(tags[field], patterns) + match = _match_progs(tags[field], progs) else: value = '' - match = patterns is True + match = not progs if match: + fields_set = True self._log.debug(u'{0}: {1} -> None', field, value) tags[field] = None if self.config['update_database']: item[field] = None + + return fields_set + + def process_item(self, item): + tags = dict(item) + + if self.set_fields(item, tags): + item.write(tags=tags) + if self.config['update_database']: + item.store(fields=tags) + + +def _match_progs(value, progs): + """Check if `value` (as string) is matching any of the compiled regexes in + the `progs` list. + """ + if not progs: + return True + for prog in progs: + if prog.search(six.text_type(value)): + return True + return False diff --git a/codecov.yml b/codecov.yml new file mode 100644 index 000000000..cbbe408ba --- /dev/null +++ b/codecov.yml @@ -0,0 +1,9 @@ +# Don't post a comment on pull requests. +comment: off + +# I think this disables commit statuses? +coverage: + status: + project: no + patch: no + changes: no diff --git a/docs/Makefile b/docs/Makefile index fd1707f27..f940dd931 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -38,10 +38,6 @@ help: @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" -# My magical rebuilding, Safari-reloading auto target. -auto: - watchmedo shell-command --patterns='*.rst' --ignore-pattern='_build/*' --recursive --command='if [ "$${watch_event_type}" == "created" -o "$${watch_event_type}" == "modified" ]; then make html ; osascript -l JavaScript refresh_safari.js; fi' --wait - clean: -rm -rf $(BUILDDIR)/* diff --git a/docs/changelog.rst b/docs/changelog.rst index f41243e65..8f45aa69c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,35 +1,973 @@ Changelog ========= -1.3.15 (in development) +1.4.7 (in development) +---------------------- + +New features: + +* :doc:`/plugins/replaygain`: add ``--force``, ``--write`` and ``--nowrite`` + options to ``beet replaygain``. :bug:`2778` +* A new importer configuration ``incremental_skip_later`` allows you to avoid + recording skipped directories to the incremental list, so you can revisit them + later. Thanks to :user:`sekjun9878`. + :bug:`2773` +* :doc:`/plugins/fetchart`: extended syntax for the ``sources`` option to give + fine-grained control over the search order for backends with several matching + strategies. +* :doc:`/plugins/web`: added the boolean ``cors_supports_credentials`` option to + allow in-browser clients to login to the beet web server even when it is + protected by an authorization mechanism. +* A new importer configuration ``artist_credit`` will tell beets to prefer the + artist credit over the artist when autotagging. + :bug:`1249` +* A new interoperability plugin to automatically notify Sonos controllers to + update the music library once the beets library got updated. + Thanks to :user:`cgtobi`. +* :doc:`/plugins/discogs`: The plugin now stores master release ids into + ``mb_releasegroupid`` as well as simulates track ids using release id + and tracklist positions. Track ids are stored in ``mb_trackid``. :bug:`#2336` + Thanks to :user:`dbogdanov`. + + +Fixes: + +* Non-audio media (DVD-Video, etc.) are now skipped by default by the + autotagger. A new option ``ignored_media`` controls which media formats to + ignore. :bug:`2688` +* Non-audio tracks (data tracks, video tracks) are now skipped by the + autotagger. Data tracks will always be ignored, but a new option + ``ignore_video_tracks`` has been added to control if video tracks should be + ignored or not. :bug:`1210` +* :doc:`/plugins/replaygain`: Fix a corner-case with the ``bs1770gain`` backend + where ReplayGain values were assigned to the wrong files. Now ``bs1770gain`` + version 0.4.6 or later is required. :bug:`2777` +* :doc:`/plugins/lyrics`: The plugin no longer crashes in the Genius source + when BeautifulSoup is not found. Instead, it just logs a message and + disables the source. +* :doc:`/plugins/lyrics`: Handle network and API errors when communicating + with Genius. :bug:`2771` +* :doc:`/plugins/lyrics`: The ``lyrics`` command previously write ReST files + by default. This default has been fixed. +* Plugins can now see updated import task state, such as when rejecting the + initial candidates and finding new ones via a manual search. Notably, this + means that the importer prompt options that the :doc:`/plugins/edit` + provides show up more reliably after doing a secondary import search. + :bug:`2441` :bug:`2731` +* :doc:`/plugins/importadded`: Fix a crash on non-autotagged imports. + :bug:`2601` :bug:`1918` + Thanks to :user:`m42i`. +* :doc:`/plugins/plexupdate`: The Plex token is now redacted in configuration + output. + :bug:`2804` + Thanks to :user:`Kovrinic`. +* Avoid a crash when importing a non-ASCII filename when using an ASCII locale + on Unix under Python 3. + :bug:`2793` :bug:`2803` +* Fix a problem caused by time zone misalignment that could make date queries + fail to match certain dates that are near the edges of a range. For example, + querying for dates within a certain month would fail to match dates within + hours of the end of that month. + :bug:`2652` +* :doc:`/plugins/convert`: The plugin now runs before other plugin-provided + import stages, which addresses an issue with generating ReplayGain data + incompatible between the source and target file formats. + :bug:`2814` + Thanks to :user:`autrimpo`. +* :doc:`/plugins/ftintitle`: The ``drop`` config option had no effect; it now + does what it says it should do. + :bug:`2817` +* Importing a release with multiple release events now selects the + event based on the order of your :ref:`preferred` countries rather than + the order of release events in MusicBrainz. :bug:`2816` +* :doc:`/plugins/web`: The time display in the web interface would incorrectly jump + at the 30-second mark of every minute. Now, it correctly changes over at zero + seconds. :bug:`2822` +* :doc:`/plugins/web`: In a python 3 enviroment, the function to fetch the + album art would not work and throw an exception. It now works as expected. + Additionally, the server will now return a 404 response when the album id + is unknown, instead of a 500 response and a thrown exception. :bug:`2823` +* :doc:`/plugins/web`: In a python 3 enviroment, the server would throw an + exception if non latin-1 characters where in the File name. + It now checks if non latin-1 characters are in the filename and changes + them to ascii-characters in that case :bug:`2815` +* Partially fix bash completion for subcommand names that contain hyphens. + :bug:`2836` :bug:`2837` + Thanks to :user:`jhermann`. +* Really fix album replaygain calculation with gstreamer backend. :bug:`2846` +* Avoid an error when doing a "no-op" move on non-existent files (i.e., moving + a file onto itself). :bug:`2863` +* :doc:`/plugins/discogs`: Fix ``medium`` and ``medium_index`` values which + were occasionally incorrect for releases with two-sided mediums. Fix + ``medium_total`` value. It now contains total number of tracks on the medium + to which a track belongs, not the total number of different mediums present + on the release. :bug:`2887` + Thanks to :user:`dbogdanov`. + + +For developers: + +* Plugins can now run their import stages *early*, before other plugins. Use + the ``early_import_stages`` list instead of plain ``import_stages`` to + request this behavior. + :bug:`2814` + + +1.4.6 (December 21, 2017) +------------------------- + +The highlight of this release is "album merging," an oft-requested option in +the importer to add new tracks to an existing album you already have in your +library. This way, you no longer need to resort to removing the partial album +from your library, combining the files manually, and importing again. + +Here are the larger new features in this release: + +* When the importer finds duplicate albums, you can now merge all the + tracks---old and new---together and try importing them as a single, combined + album. + Thanks to :user:`udiboy1209`. + :bug:`112` :bug:`2725` +* :doc:`/plugins/lyrics`: The plugin can now produce reStructuredText files + for beautiful, readable books of lyrics. Thanks to :user:`anarcat`. + :bug:`2628` +* A new :ref:`from_scratch` configuration option makes the importer remove old + metadata before applying new metadata. This new feature complements the + :doc:`zero </plugins/zero>` and :doc:`scrub </plugins/scrub>` plugins but is + slightly different: beets clears out all the old tags it knows about and + only keeps the new data it gets from the remote metadata source. + Thanks to :user:`tummychow`. + :bug:`934` :bug:`2755` + +There are also somewhat littler, but still great, new features: + +* :doc:`/plugins/convert`: A new ``no_convert`` option lets you skip + transcoding items matching a query. Instead, the files are just copied + as-is. Thanks to :user:`Stunner`. + :bug:`2732` :bug:`2751` +* :doc:`/plugins/fetchart`: A new quiet switch that only prints out messages + when album art is missing. + Thanks to :user:`euri10`. + :bug:`2683` +* :doc:`/plugins/mbcollection`: You can configure a custom MusicBrainz + collection via the new ``collection`` configuration option. + :bug:`2685` +* :doc:`/plugins/mbcollection`: The collection update command can now remove + albums from collections that are longer in the beets library. +* :doc:`/plugins/fetchart`: The ``clearart`` command now asks for confirmation + before touching your files. + Thanks to :user:`konman2`. + :bug:`2708` :bug:`2427` +* :doc:`/plugins/mpdstats`: The plugin now correctly updates song statistics + when MPD switches from a song to a stream and when it plays the same song + multiple times consecutively. + :bug:`2707` +* :doc:`/plugins/acousticbrainz`: The plugin can now be configured to write only + a specific list of tags. + Thanks to :user:`woparry`. + +There are lots and lots of bug fixes: + +* :doc:`/plugins/hook`: Fixed a problem where accessing non-string properties + of ``item`` or ``album`` (e.g., ``item.track``) would cause a crash. + Thanks to :user:`broddo`. + :bug:`2740` +* :doc:`/plugins/play`: When ``relative_to`` is set, the plugin correctly + emits relative paths even when querying for albums rather than tracks. + Thanks to :user:`j000`. + :bug:`2702` +* We suppress a spurious Python warning about a ``BrokenPipeError`` being + ignored. This was an issue when using beets in simple shell scripts. + Thanks to :user:`Azphreal`. + :bug:`2622` :bug:`2631` +* :doc:`/plugins/replaygain`: Fix a regression in the previous release related + to the new R128 tags. :bug:`2615` :bug:`2623` +* :doc:`/plugins/lyrics`: The MusixMatch backend now detects and warns + when the server has blocked the client. + Thanks to :user:`anarcat`. :bug:`2634` :bug:`2632` +* :doc:`/plugins/importfeeds`: Fix an error on Python 3 in certain + configurations. Thanks to :user:`djl`. :bug:`2467` :bug:`2658` +* :doc:`/plugins/edit`: Fix a bug when editing items during a re-import with + the ``-L`` flag. Previously, diffs against against unrelated items could be + shown or beets could crash. :bug:`2659` +* :doc:`/plugins/kodiupdate`: Fix the server URL and add better error + reporting. + :bug:`2662` +* Fixed a problem where "no-op" modifications would reset files' mtimes, + resulting in unnecessary writes. This most prominently affected the + :doc:`/plugins/edit` when saving the text file without making changes to some + music. :bug:`2667` +* :doc:`/plugins/chroma`: Fix a crash when running the ``submit`` command on + Python 3 on Windows with non-ASCII filenames. :bug:`2671` +* :doc:`/plugins/absubmit`: Fix an occasional crash on Python 3 when the AB + analysis tool produced non-ASCII metadata. :bug:`2673` +* :doc:`/plugins/duplicates`: Use the default tiebreak for items or albums + when the configuration only specifies a tiebreak for the other kind of + entity. + Thanks to :user:`cgevans`. + :bug:`2758` +* :doc:`/plugins/duplicates`: Fix the ``--key`` command line option, which was + ignored. +* :doc:`/plugins/replaygain`: Fix album ReplayGain calculation with the + GStreamer backend. :bug:`2636` +* :doc:`/plugins/scrub`: Handle errors when manipulating files using newer + versions of Mutagen. :bug:`2716` +* :doc:`/plugins/fetchart`: The plugin no longer gets skipped during import + when the "Edit Candidates" option is used from the :doc:`/plugins/edit`. + :bug:`2734` +* Fix a crash when numeric metadata fields contain just a minus or plus sign + with no following numbers. Thanks to :user:`eigengrau`. :bug:`2741` +* :doc:`/plugins/fromfilename`: Recognize file names that contain *only* a + track number, such as `01.mp3`. Also, the plugin now allows underscores as a + separator between fields. + Thanks to :user:`Vrihub`. + :bug:`2738` :bug:`2759` +* Fixed an issue where images would be resized according to their longest + edge, instead of their width, when using the ``maxwidth`` config option in + the :doc:`/plugins/fetchart` and :doc:`/plugins/embedart`. Thanks to + :user:`sekjun9878`. :bug:`2729` + +There are some changes for developers: + +* "Fixed fields" in Album and Item objects are now more strict about translating + missing values into type-specific null-like values. This should help in + cases where a string field is unexpectedly `None` sometimes instead of just + showing up as an empty string. :bug:`2605` +* Refactored the move functions the `beets.library` module and the + `manipulate_files` function in `beets.importer` to use a single parameter + describing the file operation instead of multiple Boolean flags. + There is a new numerated type describing how to move, copy, or link files. + :bug:`2682` + + +1.4.5 (June 20, 2017) +--------------------- + +Version 1.4.5 adds some oft-requested features. When you're importing files, +you can now manually set fields on the new music. Date queries have gotten +much more powerful: you can write precise queries down to the second, and we +now have *relative* queries like ``-1w``, which means *one week ago*. + +Here are the new features: + +* You can now set fields to certain values during :ref:`import-cmd`, using + either a ``--set field=value`` command-line flag or a new :ref:`set_fields` + configuration option under the `importer` section. + Thanks to :user:`bartkl`. :bug:`1881` :bug:`2581` +* :ref:`Date queries <datequery>` can now include times, so you can filter + your music down to the second. Thanks to :user:`discopatrick`. :bug:`2506` + :bug:`2528` +* :ref:`Date queries <datequery>` can also be *relative*. You can say + ``added:-1w..`` to match music added in the last week, for example. Thanks + to :user:`euri10`. :bug:`2598` +* A new :doc:`/plugins/gmusic` lets you interact with your Google Play Music + library. Thanks to :user:`tigranl`. :bug:`2553` :bug:`2586` +* :doc:`/plugins/replaygain`: We now keep R128 data in separate tags from + classic ReplayGain data for formats that need it (namely, Ogg Opus). A new + `r128` configuration option enables this behavior for specific formats. + Thanks to :user:`autrimpo`. :bug:`2557` :bug:`2560` +* The :ref:`move-cmd` command gained a new ``--export`` flag, which copies + files to an external location without changing their paths in the library + database. Thanks to :user:`SpirosChadoulos`. :bug:`435` :bug:`2510` + +There are also some bug fixes: + +* :doc:`/plugins/lastgenre`: Fix a crash when using the `prefer_specific` and + `canonical` options together. Thanks to :user:`yacoob`. :bug:`2459` + :bug:`2583` +* :doc:`/plugins/web`: Fix a crash on Windows under Python 2 when serving + non-ASCII filenames. Thanks to :user:`robot3498712`. :bug:`2592` :bug:`2593` +* :doc:`/plugins/metasync`: Fix a crash in the Amarok backend when filenames + contain quotes. Thanks to :user:`aranc23`. :bug:`2595` :bug:`2596` +* More informative error messages are displayed when the file format is not + recognized. :bug:`2599` + + +1.4.4 (June 10, 2017) +--------------------- + +This release built up a longer-than-normal list of nifty new features. We now +support DSF audio files and the importer can hard-link your files, for +example. + +Here's a full list of new features: + +* Added support for DSF files, once a future version of Mutagen is released + that supports them. Thanks to :user:`docbobo`. :bug:`459` :bug:`2379` +* A new :ref:`hardlink` config option instructs the importer to create hard + links on filesystems that support them. Thanks to :user:`jacobwgillespie`. + :bug:`2445` +* A new :doc:`/plugins/kodiupdate` lets you keep your Kodi library in sync + with beets. Thanks to :user:`Pauligrinder`. :bug:`2411` +* A new :ref:`bell` configuration option under the ``import`` section enables + a terminal bell when input is required. Thanks to :user:`SpirosChadoulos`. + :bug:`2366` :bug:`2495` +* A new field, ``composer_sort``, is now supported and fetched from + MusicBrainz. + Thanks to :user:`dosoe`. + :bug:`2519` :bug:`2529` +* The MusicBrainz backend and :doc:`/plugins/discogs` now both provide a new + attribute called ``track_alt`` that stores more nuanced, possibly + non-numeric track index data. For example, some vinyl or tape media will + report the side of the record using a letter instead of a number in that + field. :bug:`1831` :bug:`2363` +* :doc:`/plugins/web`: Added a new endpoint, ``/item/path/foo``, which will + return the item info for the file at the given path, or 404. +* :doc:`/plugins/web`: Added a new config option, ``include_paths``, + which will cause paths to be included in item API responses if set to true. +* The ``%aunique`` template function for :ref:`aunique` now takes a third + argument that specifies which brackets to use around the disambiguator + value. The argument can be any two characters that represent the left and + right brackets. It defaults to `[]` and can also be blank to turn off + bracketing. :bug:`2397` :bug:`2399` +* Added a ``--move`` or ``-m`` option to the importer so that the files can be + moved to the library instead of being copied or added "in place." + :bug:`2252` :bug:`2429` +* :doc:`/plugins/badfiles`: Added a ``--verbose`` or ``-v`` option. Results are + now displayed only for corrupted files by default and for all the files when + the verbose option is set. :bug:`1654` :bug:`2434` +* :doc:`/plugins/embedart`: The explicit ``embedart`` command now asks for + confirmation before embedding art into music files. Thanks to + :user:`Stunner`. :bug:`1999` +* You can now run beets by typing `python -m beets`. :bug:`2453` +* :doc:`/plugins/smartplaylist`: Different playlist specifications that + generate identically-named playlist files no longer conflict; instead, the + resulting lists of tracks are concatenated. :bug:`2468` +* :doc:`/plugins/missing`: A new mode lets you see missing albums from artists + you have in your library. Thanks to :user:`qlyoung`. :bug:`2481` +* :doc:`/plugins/web` : Add new `reverse_proxy` config option to allow serving + the web plugins under a reverse proxy. +* Importing a release with multiple release events now selects the + event based on your :ref:`preferred` countries. :bug:`2501` +* :doc:`/plugins/play`: A new ``-y`` or ``--yes`` parameter lets you skip + the warning message if you enqueue more items than the warning threshold + usually allows. +* Fix a bug where commands which forked subprocesses would sometimes prevent + further inputs. This bug mainly affected :doc:`/plugins/convert`. + Thanks to :user:`jansol`. + :bug:`2488` + :bug:`2524` + +There are also quite a few fixes: + +* In the :ref:`replace` configuration option, we now replace a leading hyphen + (-) with an underscore. :bug:`549` :bug:`2509` +* :doc:`/plugins/absubmit`: We no longer filter audio files for specific + formats---we will attempt the submission process for all formats. :bug:`2471` +* :doc:`/plugins/mpdupdate`: Fix Python 3 compatibility. :bug:`2381` +* :doc:`/plugins/replaygain`: Fix Python 3 compatibility in the ``bs1770gain`` + backend. :bug:`2382` +* :doc:`/plugins/bpd`: Report playback times as integers. :bug:`2394` +* :doc:`/plugins/mpdstats`: Fix Python 3 compatibility. The plugin also now + requires version 0.4.2 or later of the ``python-mpd2`` library. :bug:`2405` +* :doc:`/plugins/mpdstats`: Improve handling of MPD status queries. +* :doc:`/plugins/badfiles`: Fix Python 3 compatibility. +* Fix some cases where album-level ReplayGain/SoundCheck metadata would be + written to files incorrectly. :bug:`2426` +* :doc:`/plugins/badfiles`: The command no longer bails out if the validator + command is not found or exits with an error. :bug:`2430` :bug:`2433` +* :doc:`/plugins/lyrics`: The Google search backend no longer crashes when the + server responds with an error. :bug:`2437` +* :doc:`/plugins/discogs`: You can now authenticate with Discogs using a + personal access token. :bug:`2447` +* Fix Python 3 compatibility when extracting rar archives in the importer. + Thanks to :user:`Lompik`. :bug:`2443` :bug:`2448` +* :doc:`/plugins/duplicates`: Fix Python 3 compatibility when using the + ``copy`` and ``move`` options. :bug:`2444` +* :doc:`/plugins/mbsubmit`: The tracks are now sorted properly. Thanks to + :user:`awesomer`. :bug:`2457` +* :doc:`/plugins/thumbnails`: Fix a string-related crash on Python 3. + :bug:`2466` +* :doc:`/plugins/beatport`: More than just 10 songs are now fetched per album. + :bug:`2469` +* On Python 3, the :ref:`terminal_encoding` setting is respected again for + output and printing will no longer crash on systems configured with a + limited encoding. +* :doc:`/plugins/convert`: The default configuration uses FFmpeg's built-in + AAC codec instead of faac. Thanks to :user:`jansol`. :bug:`2484` +* Fix the importer's detection of multi-disc albums when other subdirectories + are present. :bug:`2493` +* Invalid date queries now print an error message instead of being silently + ignored. Thanks to :user:`discopatrick`. :bug:`2513` :bug:`2517` +* When the SQLite database stops being accessible, we now print a friendly + error message. Thanks to :user:`Mary011196`. :bug:`1676` :bug:`2508` +* :doc:`/plugins/web`: Avoid a crash when sending binary data, such as + Chromaprint fingerprints, in music attributes. :bug:`2542` :bug:`2532` +* Fix a hang when parsing templates that end in newlines. :bug:`2562` +* Fix a crash when reading non-ASCII characters in configuration files on + Windows under Python 3. :bug:`2456` :bug:`2565` :bug:`2566` + +We removed backends from two metadata plugins because of bitrot: + +* :doc:`/plugins/lyrics`: The Lyrics.com backend has been removed. (It stopped + working because of changes to the site's URL structure.) + :bug:`2548` :bug:`2549` +* :doc:`/plugins/fetchart`: The documentation no longer recommends iTunes + Store artwork lookup because the unmaintained `python-itunes`_ is broken. + Want to adopt it? :bug:`2371` :bug:`1610` + +.. _python-itunes: https://github.com/ocelma/python-itunes + + +1.4.3 (January 9, 2017) ----------------------- -The new features: +Happy new year! This new version includes a cornucopia of new features from +contributors, including new tags related to classical music and a new +:doc:`/plugins/absubmit` for performing acoustic analysis on your music. The +:doc:`/plugins/random` has a new mode that lets you generate time-limited +music---for example, you might generate a random playlist that lasts the +perfect length for your walk to work. We also access as many Web services as +possible over secure connections now---HTTPS everywhere! + +The most visible new features are: + +* We now support the composer, lyricist, and arranger tags. The MusicBrainz + data source will fetch data for these fields when the next version of + `python-musicbrainzngs`_ is released. Thanks to :user:`ibmibmibm`. + :bug:`506` :bug:`507` :bug:`1547` :bug:`2333` +* A new :doc:`/plugins/absubmit` lets you run acoustic analysis software and + upload the results for others to use. Thanks to :user:`inytar`. :bug:`2253` + :bug:`2342` +* :doc:`/plugins/play`: The plugin now provides an importer prompt choice to + play the music you're about to import. Thanks to :user:`diomekes`. + :bug:`2008` :bug:`2360` +* We now use SSL to access Web services whenever possible. That includes + MusicBrainz itself, several album art sources, some lyrics sources, and + other servers. Thanks to :user:`tigranl`. :bug:`2307` +* :doc:`/plugins/random`: A new ``--time`` option lets you generate a random + playlist that takes a given amount of time. Thanks to :user:`diomekes`. + :bug:`2305` :bug:`2322` + +Some smaller new features: + +* :doc:`/plugins/zero`: A new ``zero`` command manually triggers the zero + plugin. Thanks to :user:`SJoshBrown`. :bug:`2274` :bug:`2329` +* :doc:`/plugins/acousticbrainz`: The plugin will avoid re-downloading data + for files that already have it by default. You can override this behavior + using a new ``force`` option. Thanks to :user:`SusannaMaria`. :bug:`2347` + :bug:`2349` +* :doc:`/plugins/bpm`: The ``import.write`` configuration option now + decides whether or not to write tracks after updating their BPM. :bug:`1992` + +And the fixes: + +* :doc:`/plugins/bpd`: Fix a crash on non-ASCII MPD commands. :bug:`2332` +* :doc:`/plugins/scrub`: Avoid a crash when files cannot be read or written. + :bug:`2351` +* :doc:`/plugins/scrub`: The image type values on scrubbed files are preserved + instead of being reset to "other." :bug:`2339` +* :doc:`/plugins/web`: Fix a crash on Python 3 when serving files from the + filesystem. :bug:`2353` +* :doc:`/plugins/discogs`: Improve the handling of releases that contain + subtracks. :bug:`2318` +* :doc:`/plugins/discogs`: Fix a crash when a release does not contain format + information, and increase robustness when other fields are missing. + :bug:`2302` +* :doc:`/plugins/lyrics`: The plugin now reports a beets-specific User-Agent + header when requesting lyrics. :bug:`2357` +* :doc:`/plugins/embyupdate`: The plugin now checks whether an API key or a + password is provided in the configuration. +* :doc:`/plugins/play`: The misspelled configuration option + ``warning_treshold`` is no longer supported. + +For plugin developers: when providing new importer prompt choices (see +:ref:`append_prompt_choices`), you can now provide new candidates for the user +to consider. For example, you might provide an alternative strategy for +picking between the available alternatives or for looking up a release on +MusicBrainz. + + +1.4.2 (December 16, 2016) +------------------------- + +This is just a little bug fix release. With 1.4.2, we're also confident enough +to recommend that anyone who's interested give Python 3 a try: bugs may still +lurk, but we've deemed things safe enough for broad adoption. If you can, +please install beets with ``pip3`` instead of ``pip2`` this time and let us +know how it goes! + +Here are the fixes: + +* :doc:`/plugins/badfiles`: Fix a crash on non-ASCII filenames. :bug:`2299` +* The ``%asciify{}`` path formatting function and the :ref:`asciify-paths` + setting properly substitute path separators generated by converting some + Unicode characters, such as ½ and ¢, into ASCII. +* :doc:`/plugins/convert`: Fix a logging-related crash when filenames contain + curly braces. Thanks to :user:`kierdavis`. :bug:`2323` +* We've rolled back some changes to the included zsh completion script that + were causing problems for some users. :bug:`2266` + +Also, we've removed some special handling for logging in the +:doc:`/plugins/discogs` that we believe was unnecessary. If spurious log +messages appear in this version, please let us know by filing a bug. + + +1.4.1 (November 25, 2016) +------------------------- + +Version 1.4 has **alpha-level** Python 3 support. Thanks to the heroic efforts +of :user:`jrobeson`, beets should run both under Python 2.7, as before, and +now under Python 3.4 and above. The support is still new: it undoubtedly +contains bugs, so it may replace all your music with Limp Bizkit---but if +you're brave and you have backups, please try installing on Python 3. Let us +know how it goes. + +If you package beets for distribution, here's what you'll want to know: + +* This version of beets now depends on the `six`_ library. +* We also bumped our minimum required version of `Mutagen`_ to 1.33 (from + 1.27). +* Please don't package beets as a Python 3 application *yet*, even though most + things work under Python 3.4 and later. + +This version also makes a few changes to the command-line interface and +configuration that you may need to know about: + +* :doc:`/plugins/duplicates`: The ``duplicates`` command no longer accepts + multiple field arguments in the form ``-k title albumartist album``. Each + argument must be prefixed with ``-k``, as in ``-k title -k albumartist -k + album``. +* The old top-level ``colors`` configuration option has been removed (the + setting is now under ``ui``). +* The deprecated ``list_format_album`` and ``list_format_item`` + configuration options have been removed (see :ref:`format_album` and + :ref:`format_item`). + +The are a few new features: + +* :doc:`/plugins/mpdupdate`, :doc:`/plugins/mpdstats`: When the ``host`` option + is not set, these plugins will now look for the ``$MPD_HOST`` environment + variable before falling back to ``localhost``. Thanks to :user:`tarruda`. + :bug:`2175` +* :doc:`/plugins/web`: Added an ``expand`` option to show the items of an + album. :bug:`2050` +* :doc:`/plugins/embyupdate`: The plugin can now use an API key instead of a + password to authenticate with Emby. :bug:`2045` :bug:`2117` +* :doc:`/plugins/acousticbrainz`: The plugin now adds a ``bpm`` field. +* ``beet --version`` now includes the Python version used to run beets. +* :doc:`/reference/pathformat` can now include unescaped commas (``,``) when + they are not part of a function call. :bug:`2166` :bug:`2213` +* The :ref:`update-cmd` command takes a new ``-F`` flag to specify the fields + to update. Thanks to :user:`dangmai`. :bug:`2229` :bug:`2231` + +And there are a few bug fixes too: + +* :doc:`/plugins/convert`: The plugin no longer asks for confirmation if the + query did not return anything to convert. :bug:`2260` :bug:`2262` +* :doc:`/plugins/embedart`: The plugin now uses ``jpg`` as an extension rather + than ``jpeg``, to ensure consistency with the :doc:`plugins/fetchart`. + Thanks to :user:`tweitzel`. :bug:`2254` :bug:`2255` +* :doc:`/plugins/embedart`: The plugin now works for all jpeg files, including + those that are only recognizable by their magic bytes. + :bug:`1545` :bug:`2255` +* :doc:`/plugins/web`: The JSON output is no longer pretty-printed (for a + space savings). :bug:`2050` +* :doc:`/plugins/permissions`: Fix a regression in the previous release where + the plugin would always fail to set permissions (and log a warning). + :bug:`2089` +* :doc:`/plugins/beatport`: Use track numbers from Beatport (instead of + determining them from the order of tracks) and set the `medium_index` + value. +* With :ref:`per_disc_numbering` enabled, some metadata sources (notably, the + :doc:`/plugins/beatport`) would not set the track number at all. This is + fixed. :bug:`2085` +* :doc:`/plugins/play`: Fix ``$args`` getting passed verbatim to the play + command if it was set in the configuration but ``-A`` or ``--args`` was + omitted. +* With :ref:`ignore_hidden` enabled, non-UTF-8 filenames would cause a crash. + This is fixed. :bug:`2168` +* :doc:`/plugins/embyupdate`: Fixes authentication header problem that caused + a problem that it was not possible to get tokens from the Emby API. +* :doc:`/plugins/lyrics`: Some titles use a colon to separate the main title + from a subtitle. To find more matches, the plugin now also searches for + lyrics using the part part preceding the colon character. :bug:`2206` +* Fix a crash when a query uses a date field and some items are missing that + field. :bug:`1938` +* :doc:`/plugins/discogs`: Subtracks are now detected and combined into a + single track, two-sided mediums are treated as single discs, and tracks + have ``media``, ``medium_total`` and ``medium`` set correctly. :bug:`2222` + :bug:`2228`. +* :doc:`/plugins/missing`: ``missing`` is now treated as an integer, allowing + the use of (for example) ranges in queries. +* :doc:`/plugins/smartplaylist`: Playlist names will be sanitized to + ensure valid filenames. :bug:`2258` +* The ID3 APIC tag now uses the Latin-1 encoding when possible instead of a + Unicode encoding. This should increase compatibility with other software, + especially with iTunes and when using ID3v2.3. Thanks to :user:`lazka`. + :bug:`899` :bug:`2264` :bug:`2270` + +The last release, 1.3.19, also erroneously reported its version as "1.3.18" +when you typed ``beet version``. This has been corrected. + +.. _six: https://pythonhosted.org/six/ + + +1.3.19 (June 25, 2016) +---------------------- + +This is primarily a bug fix release: it cleans up a couple of regressions that +appeared in the last version. But it also features the triumphant return of the +:doc:`/plugins/beatport` and a modernized :doc:`/plugins/bpd`. + +It's also the first version where beets passes all its tests on Windows! May +this herald a new age of cross-platform reliability for beets. + +New features: + +* :doc:`/plugins/beatport`: This metadata source plugin has arisen from the + dead! It now works with Beatport's new OAuth-based API. Thanks to + :user:`jbaiter`. :bug:`1989` :bug:`2067` +* :doc:`/plugins/bpd`: The plugin now uses the modern GStreamer 1.0 instead of + the old 0.10. Thanks to :user:`philippbeckmann`. :bug:`2057` :bug:`2062` +* A new ``--force`` option for the :ref:`remove-cmd` command allows removal of + items without prompting beforehand. :bug:`2042` +* A new :ref:`duplicate_action` importer config option controls how duplicate + albums or tracks treated in import task. :bug:`185` + +Some fixes for Windows: + +* Queries are now detected as paths when they contain backslashes (in + addition to forward slashes). This only applies on Windows. +* :doc:`/plugins/embedart`: Image similarity comparison with ImageMagick + should now work on Windows. +* :doc:`/plugins/fetchart`: The plugin should work more reliably with + non-ASCII paths. + +And other fixes: + +* :doc:`/plugins/replaygain`: The ``bs1770gain`` backend now correctly + calculates sample peak instead of true peak. This comes with a major + speed increase. :bug:`2031` +* :doc:`/plugins/lyrics`: Avoid a crash and a spurious warning introduced in + the last version about a Google API key, which appeared even when you hadn't + enabled the Google lyrics source. +* Fix a hard-coded path to ``bash-completion`` to work better with Homebrew + installations. Thanks to :user:`bismark`. :bug:`2038` +* Fix a crash introduced in the previous version when the standard input was + connected to a Unix pipe. :bug:`2041` +* Fix a crash when specifying non-ASCII format strings on the command line + with the ``-f`` option for many commands. :bug:`2063` +* :doc:`/plugins/fetchart`: Determine the file extension for downloaded images + based on the image's magic bytes. The plugin prints a warning if result is + not consistent with the server-supplied ``Content-Type`` header. In previous + versions, the plugin would use a ``.jpg`` extension for all images. + :bug:`2053` + + +1.3.18 (May 31, 2016) +--------------------- + +This update adds a new :doc:`/plugins/hook` that lets you integrate beets with +command-line tools and an :doc:`/plugins/export` that can dump data from the +beets database as JSON. You can also automatically translate lyrics using a +machine translation service. + +The ``echonest`` plugin has been removed in this version because the API it +used is `shutting down`_. You might want to try the +:doc:`/plugins/acousticbrainz` instead. + +.. _shutting down: https://developer.spotify.com/news-stories/2016/03/29/api-improvements-update/ + +Some of the larger new features: + +* The new :doc:`/plugins/hook` lets you execute commands in response to beets + events. +* The new :doc:`/plugins/export` can export data from beets' database as + JSON. Thanks to :user:`GuilhermeHideki`. +* :doc:`/plugins/lyrics`: The plugin can now translate the fetched lyrics to + your native language using the Bing translation API. Thanks to + :user:`Kraymer`. +* :doc:`/plugins/fetchart`: Album art can now be fetched from `fanart.tv`_. + +Smaller new things: + +* There are two new functions available in templates: ``%first`` and ``%ifdef``. + See :ref:`template-functions`. +* :doc:`/plugins/convert`: A new `album_art_maxwidth` setting lets you resize + album art while copying it. +* :doc:`/plugins/convert`: The `extension` setting is now optional for + conversion formats. By default, the extension is the same as the name of the + configured format. +* :doc:`/plugins/importadded`: A new `preserve_write_mtimes` option + lets you preserve mtime of files even when beets updates their metadata. +* :doc:`/plugins/fetchart`: The `enforce_ratio` option now lets you tolerate + images that are *almost* square but differ slightly from an exact 1:1 + aspect ratio. +* :doc:`/plugins/fetchart`: The plugin can now optionally save the artwork's + source in an attribute in the database. +* The :ref:`terminal_encoding` configuration option can now also override the + *input* encoding. (Previously, it only affected the encoding of the standard + *output* stream.) +* A new :ref:`ignore_hidden` configuration option lets you ignore files that + your OS marks as invisible. +* :doc:`/plugins/web`: A new `values` endpoint lets you get the distinct values + of a field. Thanks to :user:`sumpfralle`. :bug:`2010` + +.. _fanart.tv: https://fanart.tv/ + +Fixes: + +* Fix a problem with the :ref:`stats-cmd` command in exact mode when filenames + on Windows use non-ASCII characters. :bug:`1891` +* Fix a crash when iTunes Sound Check tags contained invalid data. :bug:`1895` +* :doc:`/plugins/mbcollection`: The plugin now redacts your MusicBrainz + password in the ``beet config`` output. :bug:`1907` +* :doc:`/plugins/scrub`: Fix an occasional problem where scrubbing on import + could undo the :ref:`id3v23` setting. :bug:`1903` +* :doc:`/plugins/lyrics`: Add compatibility with some changes to the + LyricsWiki page markup. :bug:`1912` :bug:`1909` +* :doc:`/plugins/lyrics`: Fix retrieval from Musixmatch by improving the way + we guess the URL for lyrics on that service. :bug:`1880` +* :doc:`/plugins/edit`: Fail gracefully when the configured text editor + command can't be invoked. :bug:`1927` +* :doc:`/plugins/fetchart`: Fix a crash in the Wikipedia backend on non-ASCII + artist and album names. :bug:`1960` +* :doc:`/plugins/convert`: Change the default `ogg` encoding quality from 2 to + 3 (to fit the default from the `oggenc(1)` manpage). :bug:`1982` +* :doc:`/plugins/convert`: The `never_convert_lossy_files` option now + considers AIFF a lossless format. :bug:`2005` +* :doc:`/plugins/web`: A proper 404 error, instead of an internal exception, + is returned when missing album art is requested. Thanks to + :user:`sumpfralle`. :bug:`2011` +* Tolerate more malformed floating-point numbers in metadata tags. :bug:`2014` +* The :ref:`ignore` configuration option now includes the ``lost+found`` + directory by default. +* :doc:`/plugins/acousticbrainz`: AcousticBrainz lookups are now done over + HTTPS. Thanks to :user:`Freso`. :bug:`2007` + + +1.3.17 (February 7, 2016) +------------------------- + +This release introduces one new plugin to fetch audio information from the +`AcousticBrainz`_ project and another plugin to make it easier to submit your +handcrafted metadata back to MusicBrainz. +The importer also gained two oft-requested features: a way to skip the initial +search process by specifying an ID ahead of time, and a way to *manually* +provide metadata in the middle of the import process (via the +:doc:`/plugins/edit`). + +Also, as of this release, the beets project has some new Internet homes! Our +new domain name is `beets.io`_, and we have a shiny new GitHub organization: +`beetbox`_. + +Here are the big new features: + +* A new :doc:`/plugins/acousticbrainz` fetches acoustic-analysis information + from the `AcousticBrainz`_ project. Thanks to :user:`opatel99`, and thanks + to `Google Code-In`_! :bug:`1784` +* A new :doc:`/plugins/mbsubmit` lets you print music's current metadata in a + format that the MusicBrainz data parser can understand. You can trigger it + during an interactive import session. :bug:`1779` +* A new ``--search-id`` importer option lets you manually specify + IDs (i.e., MBIDs or Discogs IDs) for imported music. Doing this skips the + initial candidate search, which can be important for huge albums where this + initial lookup is slow. + Also, the ``enter Id`` prompt choice now accepts several IDs, separated by + spaces. :bug:`1808` +* :doc:`/plugins/edit`: You can now edit metadata *on the fly* during the + import process. The plugin provides two new interactive options: one to edit + *your music's* metadata, and one to edit the *matched metadata* retrieved + from MusicBrainz (or another data source). This feature is still in its + early stages, so please send feedback if you find anything missing. + :bug:`1846` :bug:`396` + +There are even more new features: + +* :doc:`/plugins/fetchart`: The Google Images backend has been restored. It + now requires an API key from Google. Thanks to :user:`lcharlick`. + :bug:`1778` +* :doc:`/plugins/info`: A new option will print only fields' names and not + their values. Thanks to :user:`GuilhermeHideki`. :bug:`1812` +* The :ref:`fields-cmd` command now displays flexible attributes. + Thanks to :user:`GuilhermeHideki`. :bug:`1818` +* The :ref:`modify-cmd` command lets you interactively select which albums or + items you want to change. :bug:`1843` +* The :ref:`move-cmd` command gained a new ``--timid`` flag to print and + confirm which files you want to move. :bug:`1843` +* The :ref:`move-cmd` command no longer prints filenames for files that + don't actually need to be moved. :bug:`1583` + +.. _Google Code-In: https://codein.withgoogle.com/ +.. _AcousticBrainz: http://acousticbrainz.org/ + +Fixes: + +* :doc:`/plugins/play`: Fix a regression in the last version where there was + no default command. :bug:`1793` +* :doc:`/plugins/lastimport`: The plugin now works again after being broken by + some unannounced changes to the Last.fm API. :bug:`1574` +* :doc:`/plugins/play`: Fixed a typo in a configuration option. The option is + now ``warning_threshold`` instead of ``warning_treshold``, but we kept the + old name around for compatibility. Thanks to :user:`JesseWeinstein`. + :bug:`1802` :bug:`1803` +* :doc:`/plugins/edit`: Editing metadata now moves files, when appropriate + (like the :ref:`modify-cmd` command). :bug:`1804` +* The :ref:`stats-cmd` command no longer crashes when files are missing or + inaccessible. :bug:`1806` +* :doc:`/plugins/fetchart`: Possibly fix a Unicode-related crash when using + some versions of pyOpenSSL. :bug:`1805` +* :doc:`/plugins/replaygain`: Fix an intermittent crash with the GStreamer + backend. :bug:`1855` +* :doc:`/plugins/lastimport`: The plugin now works with the beets API key by + default. You can still provide a different key the configuration. +* :doc:`/plugins/replaygain`: Fix a crash using the Python Audio Tools + backend. :bug:`1873` + +.. _beets.io: http://beets.io/ +.. _Beetbox: https://github.com/beetbox + + + +1.3.16 (December 28, 2015) +-------------------------- + +The big news in this release is a new :doc:`interactive editor plugin +</plugins/edit>`. It's really nifty: you can now change your music's metadata +by making changes in a visual text editor, which can sometimes be far more +efficient than the built-in :ref:`modify-cmd` command. No more carefully +retyping the same artist name with slight capitalization changes. + +This version also adds an oft-requested "not" operator to beets' queries, so +you can exclude music from any operation. It also brings friendlier formatting +(and querying!) of song durations. + +The big new stuff: + +* A new :doc:`/plugins/edit` lets you manually edit your music's metadata + using your favorite text editor. :bug:`164` :bug:`1706` +* Queries can now use "not" logic. Type a ``^`` before part of a query to + *exclude* matching music from the results. For example, ``beet list -a + beatles ^album:1`` will find all your albums by the Beatles except for their + singles compilation, "1." See :ref:`not_query`. :bug:`819` :bug:`1728` +* A new :doc:`/plugins/embyupdate` can trigger a library refresh on an `Emby`_ + server when your beets database changes. +* Track length is now displayed as "M:SS" rather than a raw number of seconds. + Queries on track length also accept this format: for example, ``beet list + length:5:30..`` will find all your tracks that have a duration over 5 + minutes and 30 seconds. You can turn off this new behavior using the + ``format_raw_length`` configuration option. :bug:`1749` + +Smaller changes: + +* Three commands, ``modify``, ``update``, and ``mbsync``, would previously + move files by default after changing their metadata. Now, these commands + will only move files if you have the :ref:`config-import-copy` or + :ref:`config-import-move` options enabled in your importer configuration. + This way, if you configure the importer not to touch your filenames, other + commands will respect that decision by default too. Each command also + sprouted a ``--move`` command-line option to override this default (in + addition to the ``--nomove`` flag they already had). :bug:`1697` +* A new configuration option, ``va_name``, controls the album artist name for + various-artists albums. The setting defaults to "Various Artists," the + MusicBrainz standard. In order to match MusicBrainz, the + :doc:`/plugins/discogs` also adopts the same setting. +* :doc:`/plugins/info`: The ``info`` command now accepts a ``-f/--format`` + option for customizing how items are displayed, just like the built-in + ``list`` command. :bug:`1737` + +Some changes for developers: + +* Two new :ref:`plugin hooks <plugin_events>`, ``albuminfo_received`` and + ``trackinfo_received``, let plugins intercept metadata as soon as it is + received, before it is applied to music in the database. :bug:`872` +* Plugins can now add options to the interactive importer prompts. See + :ref:`append_prompt_choices`. :bug:`1758` + +Fixes: + +* :doc:`/plugins/plexupdate`: Fix a crash when Plex libraries use non-ASCII + collection names. :bug:`1649` +* :doc:`/plugins/discogs`: Maybe fix a crash when using some versions of the + ``requests`` library. :bug:`1656` +* Fix a race in the importer when importing two albums with the same artist + and name in quick succession. The importer would fail to detect them as + duplicates, claiming that there were "empty albums" in the database even + when there were not. :bug:`1652` +* :doc:`plugins/lastgenre`: Clean up the reggae-related genres somewhat. + Thanks to :user:`Freso`. :bug:`1661` +* The importer now correctly moves album art files when re-importing. + :bug:`314` +* :doc:`/plugins/fetchart`: In auto mode, the plugin now skips albums that + already have art attached to them so as not to interfere with re-imports. + :bug:`314` +* :doc:`plugins/fetchart`: The plugin now only resizes album art if necessary, + rather than always by default. :bug:`1264` +* :doc:`plugins/fetchart`: Fix a bug where a database reference to a + non-existent album art file would prevent the command from fetching new art. + :bug:`1126` +* :doc:`/plugins/thumbnails`: Fix a crash with Unicode paths. :bug:`1686` +* :doc:`/plugins/embedart`: The ``remove_art_file`` option now works on import + (as well as with the explicit command). :bug:`1662` :bug:`1675` +* :doc:`/plugins/metasync`: Fix a crash when syncing with recent versions of + iTunes. :bug:`1700` +* :doc:`/plugins/duplicates`: Fix a crash when merging items. :bug:`1699` +* :doc:`/plugins/smartplaylist`: More gracefully handle malformed queries and + missing configuration. +* Fix a crash with some files with unreadable iTunes SoundCheck metadata. + :bug:`1666` +* :doc:`/plugins/thumbnails`: Fix a nasty segmentation fault crash that arose + with some library versions. :bug:`1433` +* :doc:`/plugins/convert`: Fix a crash with Unicode paths in ``--pretend`` + mode. :bug:`1735` +* Fix a crash when sorting by nonexistent fields on queries. :bug:`1734` +* Probably fix some mysterious errors when dealing with images using + ImageMagick on Windows. :bug:`1721` +* Fix a crash when writing some Unicode comment strings to MP3s that used + older encodings. The encoding is now always updated to UTF-8. :bug:`879` +* :doc:`/plugins/fetchart`: The Google Images backend has been removed. It + used an API that has been shut down. :bug:`1760` +* :doc:`/plugins/lyrics`: Fix a crash in the Google backend when searching for + bands with regular-expression characters in their names, like Sunn O))). + :bug:`1673` +* :doc:`/plugins/scrub`: In ``auto`` mode, the plugin now *actually* only + scrubs files on import, as the documentation always claimed it did---not + every time files were written, as it previously did. :bug:`1657` +* :doc:`/plugins/scrub`: Also in ``auto`` mode, album art is now correctly + restored. :bug:`1657` +* Possibly allow flexible attributes to be used with the ``%aunique`` template + function. :bug:`1775` +* :doc:`/plugins/lyrics`: The Genius backend is now more robust to + communication errors. The backend has also been disabled by default, since + the API it depends on is currently down. :bug:`1770` + +.. _Emby: http://emby.media + + +1.3.15 (October 17, 2015) +------------------------- + +This release adds a new plugin for checking file quality and a new source for +lyrics. The larger features are: + +* A new :doc:`/plugins/badfiles` helps you scan for corruption in your music + collection. Thanks to :user:`fxthomas`. :bug:`1568` +* :doc:`/plugins/lyrics`: You can now fetch lyrics from Genius.com. + Thanks to :user:`sadatay`. :bug:`1626` :bug:`1639` +* :doc:`/plugins/zero`: The plugin can now use a "whitelist" policy as an + alternative to the (default) "blacklist" mode. Thanks to :user:`adkow`. + :bug:`1621` :bug:`1641` + +And there are smaller new features too: * Add new color aliases for standard terminal color names (e.g., cyan and magenta). Thanks to :user:`mathstuf`. :bug:`1548` * :doc:`/plugins/play`: A new ``--args`` option lets you specify options for the player command. :bug:`1532` -* A new :doc:`/plugins/badfiles` helps you scan for corruption in your music - collection. Thanks to :user:`fxthomas`. :bug:`1568` * :doc:`/plugins/play`: A new ``raw`` configuration option lets the command work with players (such as VLC) that expect music filenames as arguments, rather than in a playlist. Thanks to :user:`nathdwek`. :bug:`1578` +* :doc:`/plugins/play`: You can now configure the number of tracks that + trigger a "lots of music" warning. :bug:`1577` * :doc:`/plugins/embedart`: A new ``remove_art_file`` option lets you clean up if you prefer *only* embedded album art. Thanks to :user:`jackwilsdon`. :bug:`1591` :bug:`733` -* :doc:`/plugins/play`: You can now configure the number of tracks that - trigger a "lots of music" warning. :bug:`1577` * :doc:`/plugins/plexupdate`: A new ``library_name`` option allows you to select which Plex library to update. :bug:`1572` :bug:`1595` -* Add new `include` config option to allow including external config files. -* The importer now supports audio files contained in data tracks when they are - listed in MusicBrainz: the corresponding audio tracks are now merged into the - main track list. (This feature depends on a new version of the - ``musicbrainzngs`` library which is not yet released, but will start working - when it is available.) Thanks to :user:`jdetrey`. :bug:`1638` +* A new ``include`` option lets you import external configuration files. -Fixes: +This release has plenty of fixes: * :doc:`/plugins/lastgenre`: Fix a bug that prevented tag popularity from being considered. Thanks to :user:`svoos`. :bug:`1559` @@ -51,11 +989,15 @@ Fixes: written to files. Thanks to :user:`jdetrey`. :bug:`1303` :bug:`1589` * :doc:`/plugins/replaygain`: Avoid a crash when the PyAudioTools backend encounters an error. :bug:`1592` +* The case sensitivity of path queries is more useful now: rather than just + guessing based on the platform, we now check the case sensitivity of your + filesystem. :bug:`1586` * Case-insensitive path queries might have returned nothing because of a wrong SQL query. * Fix a crash when a query contains a "+" or "-" alone in a component. :bug:`1605` -* Fixed unit of file size to MiB, GiB, etc. instead of MB, GB, etc. :bug:`1623` +* Fixed unit of file size to powers of two (MiB, GiB, etc.) instead of powers + of ten (MB, GB, etc.). :bug:`1623` 1.3.14 (August 2, 2015) @@ -80,7 +1022,7 @@ The new features: how the items will be moved without actually changing anything. * The importer now supports matching of "pregap" or HTOA (hidden track-one audio) tracks when they are listed in MusicBrainz. (This feature depends on a - new version of the ``musicbrainzngs`` library that is not yet released, but + new version of the `python-musicbrainzngs`_ library that is not yet released, but will start working when it is available.) Thanks to :user:`ruippeixotog`. :bug:`1104` :bug:`1493` * :doc:`/plugins/plexupdate`: A new ``token`` configuration option lets you @@ -149,6 +1091,8 @@ Fixes: does not exist, beets creates an empty file before editing it. This fixes an error on OS X, where the ``open`` command does not work with non-existent files. :bug:`1480` +* :doc:`/plugins/convert`: Fix a problem with filename encoding on Windows + under Python 3. :bug:`2515` :bug:`2516` .. _Python bug: http://bugs.python.org/issue16512 .. _ipfs: http://ipfs.io @@ -471,10 +1415,10 @@ As usual, there are loads of little fixes and improvements: the field cannot be removed (i.e., when it does not exist, when it is a built-in field, or when it is a computed field). :bug:`1124` * The deprecated ``echonest_tempo`` plugin has been removed. Please use the - :doc:`/plugins/echonest` instead. -* :doc:`/plugins/echonest`: Fingerprint-based lookup has been removed in + ``echonest`` plugin instead. +* ``echonest`` plugin: Fingerprint-based lookup has been removed in accordance with `API changes`_. :bug:`1121` -* :doc:`/plugins/echonest`: Avoid a crash when the song has no duration +* ``echonest`` plugin: Avoid a crash when the song has no duration information. :bug:`896` * :doc:`/plugins/lyrics`: Avoid a crash when retrieving non-ASCII lyrics from the Google backend. :bug:`1135` :bug:`1136` @@ -608,7 +1552,7 @@ And countless little improvements and fixes: * Fix an issue where modifying an album's field without actually changing it would not update the corresponding tracks to bring differing tracks back in line with the album. :bug:`856` -* :doc:`/plugins/echonest`: When communicating with the Echo Nest servers +* ``echonest`` plugin: When communicating with the Echo Nest servers fails repeatedly, log an error instead of exiting. :bug:`1096` * :doc:`/plugins/lyrics`: Avoid an error when the Google source returns a result without a title. Thanks to Alberto Leal. :bug:`1097` @@ -628,7 +1572,7 @@ If you want to see all your songs in reverse chronological order, just type Flexible field types mean that some functionality that has previously only worked for built-in fields, like range queries, can now work with plugin- and -user-defined fields too. For starters, the :doc:`/plugins/echonest/` and +user-defined fields too. For starters, the ``echonest`` plugin and :doc:`/plugins/mpdstats` now mark the types of the fields they provide---so you can now say, for example, ``beet ls liveness:0.5..1.5`` for the Echo Nest "liveness" attribute. The :doc:`/plugins/types` makes it easy to specify field @@ -872,14 +1816,14 @@ new in this release: * A new `initial_key` field is available in the database and files' tags. You can set the field manually using a command like ``beet modify initial_key=Am``. -* The :doc:`/plugins/echonest` sets the `initial_key` field if the data is +* The ``echonest`` plugin sets the `initial_key` field if the data is available. * A new :doc:`/plugins/keyfinder` runs a command-line tool to get the key from audio data and store it in the `initial_key` field. There are also many bug fixes and little enhancements: -* :doc:`/plugins/echonest`: Truncate files larger than 50MB before uploading for +* ``echonest`` plugin: Truncate files larger than 50MB before uploading for analysis. * :doc:`/plugins/fetchart`: Fix a crash when the server does not specify a content type. Thanks to Lee Reinhardt. @@ -936,7 +1880,7 @@ New stuff: queries (combined with "or" logic). Album-level queries are also now possible and automatic playlist regeneration can now be disabled. Thanks to brilnius. -* :doc:`/plugins/echonest`: Echo Nest similarity now weights the tempo in +* ``echonest`` plugin: Echo Nest similarity now weights the tempo in better proportion to other metrics. Also, options were added to specify custom thresholds and output formats. Thanks to Adam M. * Added the :ref:`after_write <plugin_events>` plugin event. @@ -957,7 +1901,7 @@ Fixes: legibility). * Fixed a regression that made it impossible to use the :ref:`modify-cmd` command to add new flexible fields. Thanks to brilnius. -* :doc:`/plugins/echonest`: Avoid crashing when the audio analysis fails. +* ``echonest`` plugin: Avoid crashing when the audio analysis fails. Thanks to Pedro Silva. * :doc:`/plugins/duplicates`: Fix checksumming command execution for files with quotation marks in their names. Thanks again to Pedro Silva. @@ -1033,7 +1977,7 @@ Unrelated new stuff: Other little fixes: -* :doc:`/plugins/echonest`: Tempo (BPM) is now always stored as an integer. +* ``echonest`` plugin: Tempo (BPM) is now always stored as an integer. Thanks to Heinz Wiesinger. * Fix Python 2.6 compatibility in some logging statements in :doc:`/plugins/chroma` and :doc:`/plugins/lastgenre`. @@ -1074,7 +2018,7 @@ Other little fixes: no changes are necessary. Thanks to brilnius. * :doc:`/plugins/fetchart`: When using the ``remote_priority`` config option, local image files are no longer completely ignored. -* :doc:`/plugins/echonest`: Fix an issue causing the plugin to appear twice in +* ``echonest`` plugin: Fix an issue causing the plugin to appear twice in the output of the ``beet version`` command. * :doc:`/plugins/lastgenre`: Fix an occasional crash when no tag weight was returned by Last.fm. @@ -1099,7 +2043,7 @@ into sync with your database. Thanks to Heinz Wiesinger. We added some plugins and overhauled some existing ones: -* The new :doc:`/plugins/echonest` plugin can fetch a wide range of `acoustic +* The new ``echonest`` plugin plugin can fetch a wide range of `acoustic attributes`_ from `The Echo Nest`_, including the "speechiness" and "liveness" of each track. The new plugin supersedes an older version (``echonest_tempo``) that only fetched the BPM field. Thanks to Pedro Silva @@ -1269,7 +2213,7 @@ previous versions would spit out a warning and then list your entire library. There's more detail than you could ever need `on the beets blog`_. -.. _on the beets blog: http://beets.radbox.org/blog/flexattr.html +.. _on the beets blog: http://beets.io/blog/flexattr.html 1.2.2 (August 27, 2013) @@ -1528,7 +2472,7 @@ query syntax. New configuration options: * :ref:`languages` controls the preferred languages when selecting an alias - from MusicBrainz. This feature requires `python-musicbrainz-ngs`_ 0.3 or + from MusicBrainz. This feature requires `python-musicbrainzngs`_ 0.3 or later. Thanks to Sam Doshi. * :ref:`detail` enables a mode where all tracks are listed in the importer UI, as opposed to only changed tracks. @@ -1857,7 +2801,7 @@ begins today on features for version 1.1. unintentionally loading the plugins they contain. .. _The Echo Nest: http://the.echonest.com/ -.. _Tomahawk resolver: http://beets.radbox.org/blog/tomahawk-resolver.html +.. _Tomahawk resolver: http://beets.io/blog/tomahawk-resolver.html .. _mp3gain: http://mp3gain.sourceforge.net/download.php .. _aacgain: http://aacgain.altosdesign.com @@ -2054,7 +2998,7 @@ release. * Significant internal restructuring to avoid SQLite locking errors. As part of these changes, the not-very-useful "save" plugin event has been removed. -.. _pyacoustid: https://github.com/sampsyo/pyacoustid +.. _pyacoustid: https://github.com/beetbox/pyacoustid 1.0b13 (March 16, 2012) @@ -2194,7 +3138,7 @@ tracks from a given release. Two other new plugins are also included with this release: one for assigning genres and another for ReplayGain analysis. * Beets now communicates with MusicBrainz via the new `Next Generation Schema`_ - (NGS) service via `python-musicbrainz-ngs`_. The bindings are included with + (NGS) service via `python-musicbrainzngs`_. The bindings are included with this version of beets, but a future version will make them an external dependency. * The importer now detects **multi-disc albums** and tags them together. Using a @@ -2240,7 +3184,7 @@ release: one for assigning genres and another for ReplayGain analysis. .. _KraYmer: https://github.com/KraYmer .. _Next Generation Schema: http://musicbrainz.org/doc/XML_Web_Service/Version_2 -.. _python-musicbrainz-ngs: https://github.com/alastair/python-musicbrainz-ngs +.. _python-musicbrainzngs: https://github.com/alastair/python-musicbrainzngs .. _acoustid: http://acoustid.org/ .. _Peter Brunner: https://github.com/Lugoues .. _Simon Chopin: https://github.com/laarmen @@ -2609,7 +3553,7 @@ issue involves correct ordering of autotagged albums. * Added `` beet version`` command that just shows the current release version. -.. _upstream bug: http://code.google.com/p/mutagen/issues/detail?id=7 +.. _upstream bug: https://github.com/quodlibet/mutagen/issues/7 .. _Bluelet: https://github.com/sampsyo/bluelet 1.0b5 (September 28, 2010) @@ -2820,16 +3764,16 @@ BPD). To "upgrade" an old database, you can use the included ``albumify`` plugin your library path format strings like ``$artist - $album ($format)`` to get directories with names like ``Paul Simon - Graceland (FLAC)``. -.. _for the future: http://code.google.com/p/beets/issues/detail?id=69 +.. _for the future: https://github.com/google-code-export/beets/issues/69 .. _the beetsplug directory: - http://code.google.com/p/beets/source/browse/#hg/beetsplug + https://github.com/beetbox/beets/tree/master/beetsplug Beets also now has its first third-party plugin: `beetfs`_, by Martin Eve! It exposes your music in a FUSE filesystem using a custom directory structure. Even cooler: it lets you keep your files intact on-disk while correcting their tags when accessed through FUSE. Check it out! -.. _beetfs: http://code.google.com/p/beetfs/ +.. _beetfs: https://github.com/jbaiter/beetfs 1.0b2 (July 7, 2010) -------------------- diff --git a/docs/conf.py b/docs/conf.py index ac5124435..8f8e6f9ab 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,3 +1,7 @@ +# -*- coding: utf-8 -*- + +from __future__ import division, absolute_import, print_function + AUTHOR = u'Adrian Sampson' # General configuration @@ -9,16 +13,16 @@ source_suffix = '.rst' master_doc = 'index' project = u'beets' -copyright = u'2012, Adrian Sampson' +copyright = u'2016, Adrian Sampson' -version = '1.3' -release = '1.3.15' +version = '1.4' +release = '1.4.7' pygments_style = 'sphinx' # External links to the bug tracker. extlinks = { - 'bug': ('https://github.com/sampsyo/beets/issues/%s', '#'), + 'bug': ('https://github.com/beetbox/beets/issues/%s', '#'), 'user': ('https://github.com/%s', ''), } diff --git a/docs/dev/plugins.rst b/docs/dev/plugins.rst index b1cf2deca..bab0e604d 100644 --- a/docs/dev/plugins.rst +++ b/docs/dev/plugins.rst @@ -133,39 +133,43 @@ registration process in this case:: The events currently available are: -* *pluginload*: called after all the plugins have been loaded after the ``beet`` +* `pluginload`: called after all the plugins have been loaded after the ``beet`` command starts -* *import*: called after a ``beet import`` command finishes (the ``lib`` keyword +* `import`: called after a ``beet import`` command finishes (the ``lib`` keyword argument is a Library object; ``paths`` is a list of paths (strings) that were imported) -* *album_imported*: called with an ``Album`` object every time the ``import`` +* `album_imported`: called with an ``Album`` object every time the ``import`` command finishes adding an album to the library. Parameters: ``lib``, ``album`` -* *item_copied*: called with an ``Item`` object whenever its file is copied. +* `item_copied`: called with an ``Item`` object whenever its file is copied. Parameters: ``item``, ``source`` path, ``destination`` path -* *item_imported*: called with an ``Item`` object every time the importer adds a +* `item_imported`: called with an ``Item`` object every time the importer adds a singleton to the library (not called for full-album imports). Parameters: ``lib``, ``item`` -* *before_item_moved*: called with an ``Item`` object immediately before its +* `before_item_moved`: called with an ``Item`` object immediately before its file is moved. Parameters: ``item``, ``source`` path, ``destination`` path -* *item_moved*: called with an ``Item`` object whenever its file is moved. +* `item_moved`: called with an ``Item`` object whenever its file is moved. Parameters: ``item``, ``source`` path, ``destination`` path -* *item_linked*: called with an ``Item`` object whenever a symlink is created +* `item_linked`: called with an ``Item`` object whenever a symlink is created for a file. Parameters: ``item``, ``source`` path, ``destination`` path -* *item_removed*: called with an ``Item`` object every time an item (singleton +* `item_hardlinked`: called with an ``Item`` object whenever a hardlink is + created for a file. + Parameters: ``item``, ``source`` path, ``destination`` path + +* `item_removed`: called with an ``Item`` object every time an item (singleton or album's part) is removed from the library (even when its file is not deleted from disk). -* *write*: called with an ``Item`` object, a ``path``, and a ``tags`` +* `write`: called with an ``Item`` object, a ``path``, and a ``tags`` dictionary just before a file's metadata is written to disk (i.e., just before the file on disk is opened). Event handlers may change the ``tags`` dictionary to customize the tags that are written to the @@ -174,49 +178,70 @@ The events currently available are: operation. Beets will catch that exception, print an error message and continue. -* *after_write*: called with an ``Item`` object after a file's metadata is +* `after_write`: called with an ``Item`` object after a file's metadata is written to disk (i.e., just after the file on disk is closed). -* *import_task_created*: called immediately after an import task is +* `import_task_created`: called immediately after an import task is initialized. Plugins can use this to, for example, change imported files of a task before anything else happens. It's also possible to replace the task with another task by returning a list of tasks. This list can contain zero or more `ImportTask`s. Returning an empty list will stop the task. Parameters: ``task`` (an `ImportTask`) and ``session`` (an `ImportSession`). -* *import_task_start*: called when before an import task begins processing. +* `import_task_start`: called when before an import task begins processing. Parameters: ``task`` and ``session``. -* *import_task_apply*: called after metadata changes have been applied in an - import task. Parameters: ``task`` and ``session``. +* `import_task_apply`: called after metadata changes have been applied in an + import task. This is called on the same thread as the UI, so use this + sparingly and only for tasks that can be done quickly. For most plugins, an + import pipeline stage is a better choice (see :ref:`plugin-stage`). + Parameters: ``task`` and ``session``. -* *import_task_choice*: called after a decision has been made about an import +* `import_task_choice`: called after a decision has been made about an import task. This event can be used to initiate further interaction with the user. Use ``task.choice_flag`` to determine or change the action to be taken. Parameters: ``task`` and ``session``. -* *import_task_files*: called after an import task finishes manipulating the +* `import_task_files`: called after an import task finishes manipulating the filesystem (copying and moving files, writing metadata tags). Parameters: ``task`` and ``session``. -* *library_opened*: called after beets starts up and initializes the main +* `library_opened`: called after beets starts up and initializes the main Library object. Parameter: ``lib``. -* *database_change*: a modification has been made to the library database. The +* `database_change`: a modification has been made to the library database. The change might not be committed yet. Parameters: ``lib`` and ``model``. -* *cli_exit*: called just before the ``beet`` command-line program exits. +* `cli_exit`: called just before the ``beet`` command-line program exits. Parameter: ``lib``. -* *import_begin*: called just before a ``beet import`` session starts up. +* `import_begin`: called just before a ``beet import`` session starts up. Parameter: ``session``. +* `trackinfo_received`: called after metadata for a track item has been + fetched from a data source, such as MusicBrainz. You can modify the tags + that the rest of the pipeline sees on a ``beet import`` operation or during + later adjustments, such as ``mbsync``. Slow handlers of the event can impact + the operation, since the event is fired for any fetched possible match + `before` the user (or the autotagger machinery) gets to see the match. + Parameter: ``info``. + +* `albuminfo_received`: like `trackinfo_received`, the event indicates new + metadata for album items. The parameter is an ``AlbumInfo`` object instead + of a ``TrackInfo``. + Parameter: ``info``. + +* `before_choose_candidate`: called before the user is prompted for a decision + during a ``beet import`` interactive session. Plugins can use this event for + :ref:`appending choices to the prompt <append_prompt_choices>` by returning a + list of ``PromptChoices``. Parameters: ``task`` and ``session``. + The included ``mpdupdate`` plugin provides an example use case for event listeners. Extend the Autotagger ^^^^^^^^^^^^^^^^^^^^^ -Plugins in can also enhance the functionality of the autotagger. For a +Plugins can also enhance the functionality of the autotagger. For a comprehensive example, try looking at the ``chroma`` plugin, which is included with beets. @@ -378,6 +403,8 @@ Here's an example plugin that provides a meaningless new field "foo":: # The "foo" tag of the file is now "ham" +.. _plugin-stage: + Add Import Pipeline Stages ^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -405,6 +432,11 @@ to register it:: def stage(self, session, task): print('Importing something!') +It is also possible to request your function to run early in the pipeline by +adding the function to the plugin's ``early_import_stages`` field instead:: + + self.early_import_stages = [self.stage] + .. _extend-query: Extend the Query Syntax @@ -494,19 +526,81 @@ str.format-style string formatting. So you can write logging calls like this:: When beets is in verbose mode, plugin messages are prefixed with the plugin name to make them easier to see. -What messages will be logged depends on the logging level and the action +Which messages will be logged depends on the logging level and the action performed: -* On import stages and event handlers, the default is ``WARNING`` messages and - above. -* On direct actions, the default is ``INFO`` or above, as with the rest of - beets. +* Inside import stages and event handlers, the default is ``WARNING`` messages + and above. +* Everywhere else, the default is ``INFO`` or above. -The verbosity can be increased with ``--verbose`` flags: each flags lowers the -level by a notch. +The verbosity can be increased with ``--verbose`` (``-v``) flags: each flags +lowers the level by a notch. That means that, with a single ``-v`` flag, event +handlers won't have their ``DEBUG`` messages displayed, but command functions +(for example) will. With ``-vv`` on the command line, ``DEBUG`` messages will +be displayed everywhere. This addresses a common pattern where plugins need to use the same code for a command and an import stage, but the command needs to print more messages than the import stage. (For example, you'll want to log "found lyrics for this song" when you're run explicitly as a command, but you don't want to noisily interrupt the importer interface when running automatically.) + +.. _append_prompt_choices: + +Append Prompt Choices +^^^^^^^^^^^^^^^^^^^^^ + +Plugins can also append choices to the prompt presented to the user during +an import session. + +To do so, add a listener for the ``before_choose_candidate`` event, and return +a list of ``PromptChoices`` that represent the additional choices that your +plugin shall expose to the user:: + + from beets.plugins import BeetsPlugin + from beets.ui.commands import PromptChoice + + class ExamplePlugin(BeetsPlugin): + def __init__(self): + super(ExamplePlugin, self).__init__() + self.register_listener('before_choose_candidate', + self.before_choose_candidate_event) + + def before_choose_candidate_event(self, session, task): + return [PromptChoice('p', 'Print foo', self.foo), + PromptChoice('d', 'Do bar', self.bar)] + + def foo(self, session, task): + print('User has chosen "Print foo"!') + + def bar(self, session, task): + print('User has chosen "Do bar"!') + +The previous example modifies the standard prompt:: + + # selection (default 1), Skip, Use as-is, as Tracks, Group albums, + Enter search, enter Id, aBort? + +by appending two additional options (``Print foo`` and ``Do bar``):: + + # selection (default 1), Skip, Use as-is, as Tracks, Group albums, + Enter search, enter Id, aBort, Print foo, Do bar? + +If the user selects a choice, the ``callback`` attribute of the corresponding +``PromptChoice`` will be called. It is the responsibility of the plugin to +check for the status of the import session and decide the choices to be +appended: for example, if a particular choice should only be presented if the +album has no candidates, the relevant checks against ``task.candidates`` should +be performed inside the plugin's ``before_choose_candidate_event`` accordingly. + +Please make sure that the short letter for each of the choices provided by the +plugin is not already in use: the importer will emit a warning and discard +all but one of the choices using the same letter, giving priority to the +core importer prompt choices. As a reference, the following characters are used +by the choices on the core importer prompt, and hence should not be used: +``a``, ``s``, ``u``, ``t``, ``g``, ``e``, ``i``, ``b``. + +Additionally, the callback function can optionally specify the next action to +be performed by returning a ``importer.action`` value. It may also return a +``autotag.Proposal`` value to update the set of current proposals to be +considered. diff --git a/docs/faq.rst b/docs/faq.rst index 447be45e1..b7ec10df5 100644 --- a/docs/faq.rst +++ b/docs/faq.rst @@ -2,11 +2,12 @@ FAQ ### Here are some answers to frequently-asked questions from IRC and elsewhere. -Got a question that isn't answered here? Try `IRC`_, the `mailing list`_, or +Got a question that isn't answered here? Try `IRC`_, the `discussion board`_, or :ref:`filing an issue <bugs>` in the bug tracker. .. _IRC: irc://irc.freenode.net/beets .. _mailing list: http://groups.google.com/group/beets-users +.. _discussion board: http://discourse.beets.io .. contents:: :local: @@ -138,13 +139,13 @@ it's helpful to run on the "bleeding edge". To run the latest source: 2. Install from source. There are a few easy ways to do this: - Use ``pip`` to install the latest snapshot tarball: just type - ``pip install https://github.com/sampsyo/beets/tarball/master``. + ``pip install https://github.com/beetbox/beets/tarball/master``. - Grab the source using Git: - ``git clone https://github.com/sampsyo/beets.git``. Then + ``git clone https://github.com/beetbox/beets.git``. Then ``cd beets`` and type ``python setup.py install``. - Use ``pip`` to install an "editable" version of beets based on an automatic source checkout. For example, run - ``pip install -e git+https://github.com/sampsyo/beets#egg=beets`` + ``pip install -e git+https://github.com/beetbox/beets#egg=beets`` to clone beets and install it, allowing you to modify the source in-place to try out changes. @@ -157,8 +158,8 @@ pages. …report a bug in beets? ----------------------- -We use the `issue tracker <https://github.com/sampsyo/beets/issues>`__ -on GitHub. `Enter a new issue <https://github.com/sampsyo/beets/issues/new>`__ +We use the `issue tracker <https://github.com/beetbox/beets/issues>`__ +on GitHub. `Enter a new issue <https://github.com/beetbox/beets/issues/new>`__ there to report a bug. Please follow these guidelines when reporting an issue: - Most importantly: if beets is crashing, please `include the @@ -208,6 +209,23 @@ Use the ``%asciify{}`` function in your path formats. See :ref:`template-functions`. +.. _move-dir: + +…point beets at a new music directory? +-------------------------------------- + +If you want to move your music from one directory to another, the best way is +to let beets do it for you. First, edit your configuration and set the +``directory`` setting to the new place. Then, type ``beet move`` to have beets +move all your files. + +If you've already moved your music *outside* of beets, you have a few options: + +- Move the music back (with an ordinary ``mv``) and then use the above steps. +- Delete your database and re-create it from the new paths using ``beet import -AWC``. +- Resort to manually modifying the SQLite database (not recommended). + + Why does beets… =============== @@ -272,7 +290,7 @@ Also note that beets may take some time to quit after ^C is typed; it tries to clean up after itself briefly even when canceled. (For developers: this is because the UI thread is blocking on -``raw_input`` and cannot be interrupted by the main thread, which is +``input`` and cannot be interrupted by the main thread, which is trying to close all pipeline stages in the exception handler by setting a flag. There is no simple way to remedy this.) @@ -308,9 +326,9 @@ integrity---for example, type ``metaflac --list music.flac`` to check FLAC files. If beets still complains about a file that seems to be valid, `file a -bug <https://github.com/sampsyo/beets/issues/new>`__ and we'll look into +bug <https://github.com/beetbox/beets/issues/new>`__ and we'll look into it. There's always a possibility that there's a bug "upstream" in the -`Mutagen <http://code.google.com/p/mutagen/>`__ library used by beets, +`Mutagen <https://github.com/quodlibet/mutagen>`__ library used by beets, in which case we'll forward the bug to that project's tracker. diff --git a/docs/guides/advanced.rst b/docs/guides/advanced.rst index c83c39f27..ba7ca12b6 100644 --- a/docs/guides/advanced.rst +++ b/docs/guides/advanced.rst @@ -72,16 +72,6 @@ typing ``beet web`` and head to http://localhost:8337 in a browser. You can browse your collection with queries and, if your browser supports it, play music using HTML5 audio. -But for a great listening experience, pair beets with the `Tomahawk`_ music -player. Tomahawk lets you listen to music from many different sources, -including a beets server. Just download Tomahawk and open its settings to -connect it to beets. `A post on the beets blog`_ has a more detailed guide. - -.. _A post on the beets blog: - http://beets.radbox.org/blog/tomahawk-resolver.html -.. _Tomahawk: http://www.tomahawk-player.org - - Transcode music files for media players --------------------------------------- @@ -117,7 +107,12 @@ using the :ref:`modify-cmd` command:: beet modify context=party artist:'beastie boys' -And then :doc:`query </reference/query>` your music just as you would with any +By default beets will show you the changes that are about to be applied and ask +if you really want to apply them to all, some or none of the items or albums. +You can type y for "yes", n for "no", or s for "select". If you choose the latter, +the command will prompt you for each individual matching item or album. + +Then :doc:`query </reference/query>` your music just as you would with any other field:: beet ls context:mope @@ -132,7 +127,7 @@ And, unlike :ref:`built-in fields <itemfields>`, such fields can be removed:: Read more than you ever wanted to know about the *flexible attributes* feature `on the beets blog`_. -.. _on the beets blog: http://beets.radbox.org/blog/flexattr.html +.. _on the beets blog: http://beets.io/blog/flexattr.html Choose a path style manually for some music diff --git a/docs/guides/main.rst b/docs/guides/main.rst index 1358e7005..f5f1118e1 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -4,17 +4,19 @@ Getting Started Welcome to `beets`_! This guide will help you begin using it to make your music collection better. -.. _beets: http://beets.radbox.org/ +.. _beets: http://beets.io/ Installing ---------- -You will need Python. (Beets is written for `Python 2.7`_. 2.6 support has been -dropped, and Python 3.x is not yet supported.) +You will need Python. +Beets works on `Python 2.7`_ and Python 3.4 or later. .. _Python 2.7: http://www.python.org/download/ -* **Mac OS X** v10.7 (Lion) and later include Python 2.7 out of the box. +* **macOS** v10.7 (Lion) and later include Python 2.7 out of the box. + You can opt for Python 3 by installing it via `Homebrew`_: + ``brew install python3`` * On **Debian or Ubuntu**, depending on the version, beets is available as an official package (`Debian details`_, `Ubuntu details`_), so try typing: @@ -38,16 +40,16 @@ dropped, and Python 3.x is not yet supported.) * For **Slackware**, there's a `SlackBuild`_ available. -* On **Fedora 21**, you there is a `copr`_ for beets, which you can install - using `DNF`_ like so:: +* On **Fedora** 22 or later, there is a `DNF package`_ (or three):: - $ yum install dnf dnf-plugins-core - $ dnf copr enable afreof/beets - $ yum update - $ yum install beets + $ sudo dnf install beets beets-plugins beets-doc + +* On **Solus**, run ``eopkg install beets``. + +* On **NixOS**, run ``nix-env -i beets``. .. _copr: https://copr.fedoraproject.org/coprs/afreof/beets/ -.. _dnf: http://fedoraproject.org/wiki/Features/DNF +.. _dnf package: https://apps.fedoraproject.org/packages/beets .. _SlackBuild: http://slackbuilds.org/repository/14.1/multimedia/beets/ .. _beets port: http://portsmon.freebsd.org/portoverview.py?category=audio&portname=beets .. _beets from AUR: https://aur.archlinux.org/packages/beets-git/ @@ -57,13 +59,13 @@ dropped, and Python 3.x is not yet supported.) .. _beets is in [community]: https://www.archlinux.org/packages/community/any/beets/ If you have `pip`_, just say ``pip install beets`` (you might need ``sudo`` in -front of that). On Arch, you'll need to use ``pip2`` instead of ``pip``. +front of that). To install without pip, download beets from `its PyPI page`_ and run ``python setup.py install`` in the directory therein. .. _its PyPI page: http://pypi.python.org/pypi/beets#downloads -.. _pip: http://pip.openplans.org/ +.. _pip: http://www.pip-installer.org/ The best way to upgrade beets to a new version is by running ``pip install -U beets``. You may want to follow `@b33ts`_ on Twitter to hear about progress on @@ -71,41 +73,57 @@ new versions. .. _@b33ts: http://twitter.com/b33ts +Installing on macOS 10.11 and Higher +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Starting with version 10.11 (El Capitan), macOS has a new security feature +called `System Integrity Protection`_ (SIP) that prevents you from modifying +some parts of the system. This means that some ``pip`` commands may fail with +a permissions error, even when you use ``sudo``. (You probably *won't* run +into this if you've installed Python yourself with `Homebrew`_ or otherwise.) + +If this happens, you can install beets for the current user only (sans +``sudo``) by typing ``pip install --user beets``. If you do that, you might want +to add ``~/Library/Python/3.6/bin`` to your ``$PATH``. + +.. _System Integrity Protection: https://support.apple.com/en-us/HT204899 +.. _Homebrew: http://brew.sh + Installing on Windows ^^^^^^^^^^^^^^^^^^^^^ Installing beets on Windows can be tricky. Following these steps might help you get it right: -1. If you don't have it, `install Python`_ (you want Python 2.7). +1. If you don't have it, `install Python`_ (you want Python 3.6). The + installer should give you the option to "add Python to PATH." Check this + box. If you do that, you can skip the next step. 2. If you haven't done so already, set your ``PATH`` environment variable to include Python and its scripts. To do so, you have to get the "Properties" window for "My Computer", then choose the "Advanced" tab, then hit the "Environment Variables" button, and then look for the ``PATH`` variable in the table. Add the following to the end of the variable's value: - ``;C:\Python27;C:\Python27\Scripts``. + ``;C:\Python36;C:\Python36\Scripts``. You may need to adjust these paths to + point to your Python installation. -3. Next, `install pip`_ (if you don't have it already) by downloading and - running the `get-pip.py`_ script. +3. Now install beets by running: ``pip install beets`` -4. Now install beets by running: ``pip install beets`` - -5. You're all set! Type ``beet`` at the command prompt to make sure everything's +4. You're all set! Type ``beet`` at the command prompt to make sure everything's in order. Windows users may also want to install a context menu item for importing files -into beets. Just download and open `beets.reg`_ to add the necessary keys to the -registry. You can then right-click a directory and choose "Import with beets". -If Python is in a nonstandard location on your system, you may have to edit the -command path manually. +into beets. Download the `beets.reg`_ file and open it in a text file to make +sure the paths to Python match your system. Then double-click the file add the +necessary keys to your registry. You can then right-click a directory and +choose "Import with beets". Because I don't use Windows myself, I may have missed something. If you have trouble or you have more detail to contribute here, please direct it to `the mailing list`_. .. _install Python: http://python.org/download/ -.. _beets.reg: https://github.com/sampsyo/beets/blob/master/extra/beets.reg +.. _beets.reg: https://github.com/beetbox/beets/blob/master/extra/beets.reg .. _install pip: http://www.pip-installer.org/en/latest/installing.html#install-pip .. _get-pip.py: https://raw.github.com/pypa/pip/master/contrib/get-pip.py @@ -121,13 +139,13 @@ favorite text editor. The file will start out empty, but here's good place to start:: directory: ~/music - library: ~/data/musiclibrary.blb + library: ~/data/musiclibrary.db Change that first path to a directory where you'd like to keep your music. Then, for ``library``, choose a good place to keep a database file that keeps an index of your music. (The config's format is `YAML`_. You'll want to configure your -text editor to use spaces, not real tabs, for indentation.) - +text editor to use spaces, not real tabs, for indentation. Also, ``~`` means +your home directory in these paths, even on Windows.) The default configuration assumes you want to start a new organized music folder (that ``directory`` above) and that you'll *copy* cleaned-up music into that @@ -166,6 +184,11 @@ here, including the directory and file naming scheme. See Importing Your Library ---------------------- +The next step is to import your music files into the beets library database. +Because this can involve modifying files and moving them around, data loss is +always a possibility, so now would be a good time to make sure you have a +recent backup of all your music. We'll wait. + There are two good ways to bring your existing library into beets. You can either: (a) quickly bring all your files with all their current metadata into beets' database, or (b) use beets' highly-refined autotagger to find canonical @@ -222,21 +245,30 @@ songs. Thus:: $ beet ls album:bird The Mae Shi - Terrorbird - Revelation Six -As you can see, search terms by default search all attributes of songs. (They're +By default, a search term will match any of a handful of :ref:`common +attributes <keywordquery>` of songs. +(They're also implicitly joined by ANDs: a track must match *all* criteria in order to match the query.) To narrow a search term to a particular metadata field, just put the field before the term, separated by a : character. So ``album:bird`` only looks for ``bird`` in the "album" field of your songs. (Need to know more? :doc:`/reference/query/` will answer all your questions.) -The ``beet list`` command has another useful option worth mentioning, ``-a``, -which searches for albums instead of songs:: +The ``beet list`` command also has an ``-a`` option, which searches for albums instead of songs:: $ beet ls -a forever Bon Iver - For Emma, Forever Ago Freezepop - Freezepop Forever -So handy! +There's also an ``-f`` option (for *format*) that lets you specify what gets displayed in the results of a search:: + + $ beet ls -a forever -f "[$format] $album ($year) - $artist - $title" + [MP3] For Emma, Forever Ago (2009) - Bon Iver - Flume + [AAC] Freezepop Forever (2011) - Freezepop - Harebrained Scheme + +In the format option, field references like `$format` and `$year` are filled +in with data from each result. You can see a full list of available fields by +running ``beet fields``. Beets also has a ``stats`` command, just in case you want to see how much music you have:: @@ -265,8 +297,9 @@ You can always get help using the ``beet help`` command. The plain ``beet help`` command lists all the available commands; then, for example, ``beet help import`` gives more specific help about the ``import`` command. -Please let me know what you think of beets via `the mailing list`_ or +Please let me know what you think of beets via `the discussion board`_ or `Twitter`_. .. _the mailing list: http://groups.google.com/group/beets-users +.. _the discussion board: http://discourse.beets.io .. _twitter: http://twitter.com/b33ts diff --git a/docs/guides/tagger.rst b/docs/guides/tagger.rst index c557bbcaf..b70857ca5 100644 --- a/docs/guides/tagger.rst +++ b/docs/guides/tagger.rst @@ -60,8 +60,8 @@ all of these limitations. because beets by default infers tags based on existing metadata. But this is not a hard and fast rule---there are a few ways to tag metadata-poor music: - * You can use the *E* option described below to search in MusicBrainz for - a specific album or song. + * You can use the *E* or *I* options described below to search in + MusicBrainz for a specific album or song. * The :doc:`Acoustid plugin </plugins/chroma>` extends the autotagger to use acoustic fingerprinting to find information for arbitrary audio. Install that plugin if you're willing to spend a little more CPU power @@ -76,7 +76,7 @@ all of these limitations. Musepack, Windows Media, Opus, and AIFF files are supported. (Do you use some other format? Please `file a feature request`_!) -.. _file a feature request: https://github.com/sampsyo/beets/issues/new +.. _file a feature request: https://github.com/beetbox/beets/issues/new Now that that's out of the way, let's tag some music. @@ -95,6 +95,9 @@ command-line options you should know: * ``beet import -C``: don't copy imported files to your music directory; leave them where they are +* ``beet import -m``: move imported files to your music directory (overrides + the ``-c`` option) + * ``beet import -l LOGFILE``: write a message to ``LOGFILE`` every time you skip an album or choose to take its tags "as-is" (see below) or the album is skipped as a duplicate; this lets you come back later and reexamine albums @@ -160,10 +163,10 @@ When beets needs your input about a match, it says something like this:: Beirut - Lon Gisland (Similarity: 94.4%) * Scenic World (Second Version) -> Scenic World - [A]pply, More candidates, Skip, Use as-is, as Tracks, Enter search, or aBort? + [A]pply, More candidates, Skip, Use as-is, as Tracks, Enter search, enter Id, or aBort? When beets asks you this question, it wants you to enter one of the capital -letters: A, M, S, U, T, G, E, or B. That is, you can choose one of the +letters: A, M, S, U, T, G, E, I or B. That is, you can choose one of the following: * *A*: Apply the suggested changes shown and move on. @@ -190,6 +193,11 @@ following: option if beets hasn't found any good options because the album is mistagged or untagged. +* *I*: Enter a metadata backend ID to use as search in the database. Use this + option to specify a backend entity (for example, a MusicBrainz release or + recording) directly, by pasting its ID or the full URL. You can also specify + several IDs by separating them by a space. + * *B*: Cancel this import task altogether. No further albums will be tagged; beets shuts down immediately. The next time you attempt to import the same directory, though, beets will ask you if you want to resume tagging where you @@ -226,17 +234,25 @@ If beets finds an album or item in your library that seems to be the same as the one you're importing, you may see a prompt like this:: This album is already in the library! - [S]kip new, Keep both, Remove old? + [S]kip new, Keep both, Remove old, Merge all? Beets wants to keep you safe from duplicates, which can be a real pain, so you -have three choices in this situation. You can skip importing the new music, +have four choices in this situation. You can skip importing the new music, choosing to keep the stuff you already have in your library; you can keep both -the old and the new music; or you can remove the existing music and choose the -new stuff. If you choose that last "trump" option, any duplicates will be +the old and the new music; you can remove the existing music and choose the +new stuff; or you can merge all the new and old tracks into a single album. +If you choose that "remove" option, any duplicates will be removed from your library database---and, if the corresponding files are located inside of your beets library directory, the files themselves will be deleted as well. +If you choose "merge", beets will try re-importing the existing and new tracks +as one bundle together. +This is particularly helpful when you have an album that's missing some tracks +and then want to import the remaining songs. +The importer will ask you the same questions as it would if you were importing +all tracks at once. + If you choose to keep two identically-named albums, beets can avoid storing both in the same directory. See :ref:`aunique` for details. @@ -281,12 +297,13 @@ MusicBrainz---so consider adding the data yourself. If you think beets is ignoring an album that's listed in MusicBrainz, please `file a bug report`_. -.. _file a bug report: https://github.com/sampsyo/beets/issues +.. _file a bug report: https://github.com/beetbox/beets/issues I Hope That Makes Sense ----------------------- -If I haven't made the process clear, please send an email to `the mailing -list`_ and I'll try to improve this guide. +If we haven't made the process clear, please post on `the discussion +board`_ and we'll try to improve this guide. .. _the mailing list: http://groups.google.com/group/beets-users +.. _the discussion board: http://discourse.beets.io diff --git a/docs/index.rst b/docs/index.rst index 57a736a48..43ba0526a 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -13,13 +13,14 @@ Then you can get a more detailed look at beets' features in the be interested in exploring the :doc:`plugins </plugins/index>`. If you still need help, your can drop by the ``#beets`` IRC channel on -Freenode, send email to `the mailing list`_, or `file a bug`_ in the issue -tracker. Please let us know where you think this documentation can be -improved. +Freenode, drop by `the discussion board`_, send email to `the mailing list`_, +or `file a bug`_ in the issue tracker. Please let us know where you think this +documentation can be improved. -.. _beets: http://beets.radbox.org/ +.. _beets: http://beets.io/ .. _the mailing list: http://groups.google.com/group/beets-users -.. _file a bug: https://github.com/sampsyo/beets/issues +.. _file a bug: https://github.com/beetbox/beets/issues +.. _the discussion board: http://discourse.beets.io Contents -------- diff --git a/docs/modd.conf b/docs/modd.conf new file mode 100644 index 000000000..9067700d3 --- /dev/null +++ b/docs/modd.conf @@ -0,0 +1,7 @@ +**/*.rst { + prep: make html +} + +_build/html/** { + daemon: devd -m _build/html +} diff --git a/docs/plugins/absubmit.rst b/docs/plugins/absubmit.rst new file mode 100644 index 000000000..feebc1642 --- /dev/null +++ b/docs/plugins/absubmit.rst @@ -0,0 +1,49 @@ +AcousticBrainz Submit Plugin +============================ + +The `absubmit` plugin lets you submit acoustic analysis results to the +`AcousticBrainz`_ server. + +Installation +------------ + +The `absubmit` plugin requires the `streaming_extractor_music`_ program to run. Its source can be found on `GitHub`_, and while it is possible to compile the extractor from source, AcousticBrainz would prefer if you used their binary (see the AcousticBrainz `FAQ`_). + +The `absubmit` also plugin requires `requests`_, which you can install using `pip`_ by typing:: + + pip install requests + +After installing both the extractor binary and requests you can enable the plugin ``absubmit`` in your configuration (see :ref:`using-plugins`). + +Submitting Data +--------------- + +Type:: + + beet absubmit [QUERY] + +to run the analysis program and upload its results. + +The plugin works on music with a MusicBrainz track ID attached. The plugin +will also skip music that the analysis tool doesn't support. +`streaming_extractor_music`_ currently supports files with the extensions +``mp3``, ``ogg``, ``oga``, ``flac``, ``mp4``, ``m4a``, ``m4r``, ``m4b``, +``m4p``, ``aac``, ``wma``, ``asf``, ``mpc``, ``wv``, ``spx``, ``tta``, +``3g2``, ``aif``, ``aiff`` and ``ape``. + +Configuration +------------- + +To configure the plugin, make a ``absubmit:`` section in your configuration file. The available options are: + +- **auto**: Analyze every file on import. Otherwise, you need to use the ``beet absubmit`` command explicitly. + Default: ``no`` +- **extractor**: The absolute path to the `streaming_extractor_music`_ binary. + Default: search for the program in your ``$PATH`` + +.. _streaming_extractor_music: http://acousticbrainz.org/download +.. _FAQ: http://acousticbrainz.org/faq +.. _pip: http://www.pip-installer.org/ +.. _requests: http://docs.python-requests.org/en/master/ +.. _github: https://github.com/MTG/essentia +.. _AcousticBrainz: https://acousticbrainz.org diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst new file mode 100644 index 000000000..5bd514c64 --- /dev/null +++ b/docs/plugins/acousticbrainz.rst @@ -0,0 +1,65 @@ +AcousticBrainz Plugin +===================== + +The ``acousticbrainz`` plugin gets acoustic-analysis information from the +`AcousticBrainz`_ project. + +.. _AcousticBrainz: http://acousticbrainz.org/ + +Enable the ``acousticbrainz`` plugin in your configuration (see :ref:`using-plugins`) and run it by typing:: + + $ beet acousticbrainz [-f] [QUERY] + +By default, the command will only look for AcousticBrainz data when the tracks +doesn't already have it; the ``-f`` or ``--force`` switch makes it re-download +data even when it already exists. If you specify a query, only matching tracks +will be processed; otherwise, the command processes every track in your +library. + +For all tracks with a MusicBrainz recording ID, the plugin currently sets +these fields: + +* ``average_loudness`` +* ``bpm`` +* ``chords_changes_rate`` +* ``chords_key`` +* ``chords_number_rate`` +* ``chords_scale`` +* ``danceable`` +* ``gender`` +* ``genre_rosamerica`` +* ``initial_key`` (This is a built-in beets field, which can also be provided + by :doc:`/plugins/keyfinder`.) +* ``key_strength`` +* ``mood_acoustic`` +* ``mood_aggressive`` +* ``mood_electronic`` +* ``mood_happy`` +* ``mood_party`` +* ``mood_relaxed`` +* ``mood_sad`` +* ``rhythm`` +* ``tonal`` +* ``voice_instrumental`` + +Automatic Tagging +----------------- + +To automatically tag files using AcousticBrainz data during import, just +enable the ``acousticbrainz`` plugin (see :ref:`using-plugins`). When importing +new files, beets will query the AcousticBrainz API using MBID and +set the appropriate metadata. + +Configuration +------------- + +To configure the plugin, make a ``acousticbrainz:`` section in your +configuration file. There are three options: + +- **auto**: Enable AcousticBrainz during ``beet import``. + Default: ``yes``. +- **force**: Download AcousticBrainz data even for tracks that already have + it. + Default: ``no``. +- **tags**: Which tags from the list above to set on your files. + Default: [] (all) diff --git a/docs/plugins/badfiles.rst b/docs/plugins/badfiles.rst index 80f543c54..0a32f1a36 100644 --- a/docs/plugins/badfiles.rst +++ b/docs/plugins/badfiles.rst @@ -52,3 +52,7 @@ Note that the default `mp3val` checker is a bit verbose and can output a lot of "stream error" messages, even for files that play perfectly well. Generally, if more than one stream error happens, or if a stream error happens in the middle of a file, this is a bad sign. + +By default, only errors for the bad files will be shown. In order for the +results for all of the checked files to be seen, including the uncorrupted +ones, use the ``-v`` or ``--verbose`` option. diff --git a/docs/plugins/beatport.rst b/docs/plugins/beatport.rst new file mode 100644 index 000000000..da77cd4cd --- /dev/null +++ b/docs/plugins/beatport.rst @@ -0,0 +1,36 @@ +Beatport Plugin +=============== + +The ``beatport`` plugin adds support for querying the `Beatport`_ catalogue +during the autotagging process. This can potentially be helpful for users +whose collection includes a lot of diverse electronic music releases, for which +both MusicBrainz and (to a lesser degree) Discogs show no matches. + +Installation +------------ + +To use the ``beatport`` plugin, first enable it in your configuration (see +:ref:`using-plugins`). Then, install the `requests`_ and `requests_oauthlib`_ +libraries (which we need for querying and authorizing with the Beatport API) +by typing:: + + pip install requests requests_oauthlib + +You will also need to register for a `Beatport`_ account. The first time you +run the :ref:`import-cmd` command after enabling the plugin, it will ask you +to authorize with Beatport by visiting the site in a browser. On the site +you will be asked to enter your username and password to authorize beets +to query the Beatport API. You will then be displayed with a single line of +text that you should paste into your terminal. This will store the +authentication data for subsequent runs and you will not be required to +repeat the above steps. + +Matches from Beatport should now show up alongside matches +from MusicBrainz and other sources. + +If you have a Beatport ID or a URL for a release or track you want to tag, you +can just enter one of the two at the "enter Id" prompt in the importer. + +.. _requests: http://docs.python-requests.org/en/latest/ +.. _requests_oauthlib: https://github.com/requests/requests-oauthlib +.. _Beatport: http://beatport.com diff --git a/docs/plugins/beetsweb.png b/docs/plugins/beetsweb.png index c335104eb..dcb5aae17 100644 Binary files a/docs/plugins/beetsweb.png and b/docs/plugins/beetsweb.png differ diff --git a/docs/plugins/bpd.rst b/docs/plugins/bpd.rst index eed0f2833..fc22846de 100644 --- a/docs/plugins/bpd.rst +++ b/docs/plugins/bpd.rst @@ -16,25 +16,19 @@ Dependencies Before you can use BPD, you'll need the media library called GStreamer (along with its Python bindings) on your system. -* On Mac OS X, you can use `MacPorts`_ or `Homebrew`_. For MacPorts, just run - ``port install py27-gst-python``. For Homebrew, the appropriate formulae are - in `homebrew-versions`_, so run ``brew tap homebrew/versions`` and then - ``brew install gst-python010``. (Note that you'll need the Mac OS X - Developer Tools in either case.) +* On Mac OS X, you can use `Homebrew`_. Run ``brew install gstreamer + gst-plugins-base pygobject3``. -.. _homebrew-versions: https://github.com/Homebrew/homebrew-versions +* On Linux, you need to install GStreamer 1.0 and the GObject bindings for + python. Under Ubuntu, they are called `python-gi` and `gstreamer1.0`. -* On Linux, it's likely that you already have gst-python. (If not, your - distribution almost certainly has a package for it.) - -* On Windows, you may want to try `GStreamer WinBuilds`_ (cavet emptor: I +* On Windows, you may want to try `GStreamer WinBuilds`_ (caveat emptor: I haven't tried this). You will also need the various GStreamer plugin packages to make everything work. See the :doc:`/plugins/chroma` documentation for more information on installing GStreamer plugins. -.. _MacPorts: http://www.macports.org/ .. _GStreamer WinBuilds: http://www.gstreamer-winbuild.ylatuya.es/ .. _Homebrew: http://mxcl.github.com/homebrew/ diff --git a/docs/plugins/bpm.rst b/docs/plugins/bpm.rst index ce1f62298..012c3903c 100644 --- a/docs/plugins/bpm.rst +++ b/docs/plugins/bpm.rst @@ -22,6 +22,21 @@ for instance, with ``mpc`` you can do something like:: beet bpm $(mpc |head -1|tr -d "-") +If :ref:`import.write <config-import-write>` is ``yes``, the song's tags are +written to disk. + +Configuration +------------- + +To configure the plugin, make a ``bpm:`` section in your configuration file. +The available options are: + +- **max_strokes**: The maximum number of strokes to accept when tapping out the + BPM. + Default: 3. +- **overwrite**: Overwrite the track's existing BPM. + Default: ``yes``. + Credit ------ diff --git a/docs/plugins/chroma.rst b/docs/plugins/chroma.rst index 2f52aa858..617d8cf69 100644 --- a/docs/plugins/chroma.rst +++ b/docs/plugins/chroma.rst @@ -31,7 +31,7 @@ First, install pyacoustid itself. You can do this using `pip`_, like so:: $ pip install pyacoustid -.. _pip: http://pip.openplans.org/ +.. _pip: http://www.pip-installer.org/ Then, you will need to install `Chromaprint`_, either as a dynamic library or in the form of a command-line tool (``fpcalc``). @@ -75,22 +75,21 @@ You will also need a mechanism for decoding audio files supported by the Note that if you install beets in a virtualenv, you'll need it to have ``--system-site-packages`` enabled for Python to see the GStreamer bindings. -* On Windows, try the Gstreamer "WinBuilds" from the `OSSBuild`_ project. +* On Windows, builds are provided by `GStreamer`_ -.. _audioread: https://github.com/sampsyo/audioread -.. _pyacoustid: http://github.com/sampsyo/pyacoustid +.. _audioread: https://github.com/beetbox/audioread +.. _pyacoustid: http://github.com/beetbox/pyacoustid .. _FFmpeg: http://ffmpeg.org/ .. _MAD: http://spacepants.org/src/pymad/ .. _pymad: http://www.underbit.com/products/mad/ .. _Core Audio: http://developer.apple.com/technologies/mac/audio-and-video.html -.. _OSSBuild: http://code.google.com/p/ossbuild/ .. _Gstreamer: http://gstreamer.freedesktop.org/ .. _PyGObject: https://wiki.gnome.org/Projects/PyGObject To decode audio formats (MP3, FLAC, etc.) with GStreamer, you'll need the standard set of Gstreamer plugins. For example, on Ubuntu, install the packages -``gstreamer0.10-plugins-good``, ``gstreamer0.10-plugins-bad``, and -``gstreamer0.10-plugins-ugly``. +``gstreamer1.0-plugins-good``, ``gstreamer1.0-plugins-bad``, and +``gstreamer1.0-plugins-ugly``. Usage ----- diff --git a/docs/plugins/convert.rst b/docs/plugins/convert.rst index 7480bacbb..a631f7891 100644 --- a/docs/plugins/convert.rst +++ b/docs/plugins/convert.rst @@ -62,6 +62,9 @@ file. The available options are: Default: none (system default), - **copy_album_art**: Copy album art when copying or transcoding albums matched using the ``-a`` option. Default: ``no``. +- **album_art_maxwidth**: Downscale album art if it's too big. The resize + operation reduces image width to at most ``maxwidth`` pixels while + preserving the aspect ratio. - **dest**: The directory where the files will be converted (or copied) to. Default: none. - **embed**: Embed album art in converted items. Default: ``yes``. @@ -70,6 +73,9 @@ file. The available options are: this does not guarantee that all converted files will have a lower bitrate---that depends on the encoder and its configuration. Default: none. +- **no_convert**: Does not transcode items matching provided query string + (see :doc:`/reference/query`). (i.e. ``format:AAC, format:WMA`` or + ``path::\.(m4a|wma)$``) - **never_convert_lossy_files**: Cross-conversions between lossy codecs---such as mp3, ogg vorbis, etc.---makes little sense as they will decrease quality even further. If set to ``yes``, lossy files are always copied. @@ -84,7 +90,14 @@ file. The available options are: By default, the plugin will detect the number of processors available and use them all. -You can also configure the format to use for transcoding. +You can also configure the format to use for transcoding (see the next +section): + +- **format**: The name of the format to transcode to when none is specified on + the command line. + Default: ``mp3``. +- **formats**: A set of formats and associated command lines for transcoding + each. .. _convert-format-config: @@ -110,12 +123,12 @@ default. To convert the audio to `wav`, run ``beet convert -f wav``. This will also use the format key (`wav`) as the file extension. Each entry in the ``formats`` map consists of a key (the name of the -format) as well as the command and the possibly the file extension. +format) as well as the command and optionally the file extension. ``extension`` is the filename extension to be used for newly transcoded -files. If only the command is given as a string, the file extension -defaults to the format's name. ``command`` is the command-line to use -to transcode audio. The tokens ``$source`` and ``$dest`` in the command -are replaced with the paths to the existing and new file. +files. If only the command is given as a string or the extension is not +provided, the file extension defaults to the format's name. ``command`` is the +command to use to transcode audio. The tokens ``$source`` and ``$dest`` in the +command are replaced with the paths to the existing and new file. The plugin in comes with default commands for the most common audio formats: `mp3`, `alac`, `flac`, `aac`, `opus`, `ogg`, `wmv`. For @@ -130,3 +143,31 @@ and the given command is used for all conversions. convert: command: ffmpeg -i $source -y -vn -aq 2 $dest extension: mp3 + + +Gapless MP3 encoding +```````````````````` + +While FFmpeg cannot produce "`gapless`_" MP3s by itself, you can create them +by using `LAME`_ directly. Use a shell script like this to pipe the output of +FFmpeg into the LAME tool:: + + #!/bin/sh + ffmpeg -i "$1" -f wav - | lame -V 2 --noreplaygain - "$2" + +Then configure the ``convert`` plugin to use the script:: + + convert: + command: /path/to/script.sh $source $dest + extension: mp3 + +This strategy configures FFmpeg to produce a WAV file with an accurate length +header for LAME to use. Using ``--noreplaygain`` disables gain analysis; you +can use the :doc:`/plugins/replaygain` to do this analysis. See the LAME +`documentation`_ and the `HydrogenAudio wiki`_ for other LAME configuration +options and a thorough discussion of MP3 encoding. + +.. _documentation: http://lame.sourceforge.net/using.php +.. _HydrogenAudio wiki: http://wiki.hydrogenaud.io/index.php?title=LAME +.. _gapless: http://wiki.hydrogenaud.io/index.php?title=Gapless_playback +.. _LAME: http://lame.sourceforge.net/ diff --git a/docs/plugins/discogs.rst b/docs/plugins/discogs.rst index 038718f9b..a02b34590 100644 --- a/docs/plugins/discogs.rst +++ b/docs/plugins/discogs.rst @@ -14,10 +14,9 @@ To use the ``discogs`` plugin, first enable it in your configuration (see pip install discogs-client -You will also need to register for a `Discogs`_ account. The first time you -run the :ref:`import-cmd` command after enabling the plugin, it will ask you -to authorize with Discogs by visiting the site in a browser. Subsequent runs -will not require re-authorization. +You will also need to register for a `Discogs`_ account, and provide +authentication credentials via a personal access token or an OAuth2 +authorization. Matches from Discogs will now show up during import alongside matches from MusicBrainz. @@ -25,12 +24,31 @@ MusicBrainz. If you have a Discogs ID for an album you want to tag, you can also enter it at the "enter Id" prompt in the importer. +OAuth Authorization +``````````````````` + +The first time you run the :ref:`import-cmd` command after enabling the plugin, +it will ask you to authorize with Discogs by visiting the site in a browser. +Subsequent runs will not require re-authorization. + +Authentication via Personal Access Token +```````````````````````````````````````` + +As an alternative to OAuth, you can get a token from Discogs and add it to +your configuration. +To get a personal access token (called a "user token" in the `discogs-client`_ +documentation), login to `Discogs`_, and visit the +`Developer settings page +<https://www.discogs.com/settings/developers>`_. Press the ``Generate new +token`` button, and place the generated token in your configuration, as the +``user_token`` config option in the ``discogs`` section. + Troubleshooting --------------- Several issues have been encountered with the Discogs API. If you have one, please start by searching for `a similar issue on the repo -<https://github.com/sampsyo/beets/issues?utf8=%E2%9C%93&q=is%3Aissue+discogs>`_. +<https://github.com/beetbox/beets/issues?utf8=%E2%9C%93&q=is%3Aissue+discogs>`_. Here are two things you can try: diff --git a/docs/plugins/duplicates.rst b/docs/plugins/duplicates.rst index a0369a95e..8b11b6661 100644 --- a/docs/plugins/duplicates.rst +++ b/docs/plugins/duplicates.rst @@ -28,7 +28,7 @@ duplicates themselves via command-line switches :: -d, --delete delete items from library and disk -F, --full show all versions of duplicate tracks or albums -s, --strict report duplicates only if all attributes are set - -k, --keys report duplicates based on keys + -k, --key report duplicates based on keys (can be used multiple times) -M, --merge merge duplicate items -m DEST, --move=DEST move items to dest -o DEST, --copy=DEST copy items to dest @@ -46,9 +46,9 @@ file. The available options mirror the command-line options: - **checksum**: Use an arbitrary command to compute a checksum of items. This overrides the ``keys`` option the first time it is run; however, because it caches the resulting checksum as ``flexattrs`` in the - database, you can use ``--keys=name_of_the_checksumming_program - any_other_keys`` (or set configuration ``keys`` option) the second time - around. + database, you can use ``--key=name_of_the_checksumming_program + --key=any_other_keys`` (or set the ``keys`` configuration option) the second + time around. Default: ``ffmpeg -i {file} -f crc -``. - **copy**: A destination base directory into which to copy matched items. @@ -67,9 +67,6 @@ file. The available options mirror the command-line options: - **full**: List every track or album that has duplicates, not just the duplicates themselves. Default: ``no`` -- **strict**: Do not report duplicate matches if some of the - attributes are not defined (ie. null or empty). - Default: ``no`` - **keys**: Define in which track or album fields duplicates are to be searched. By default, the plugin uses the musicbrainz track and album IDs for this purpose. Using the ``keys`` option (as a YAML list in the configuration @@ -83,6 +80,9 @@ file. The available options mirror the command-line options: Default: none (disabled). - **path**: Output the path instead of metadata when listing duplicates. Default: ``no``. +- **strict**: Do not report duplicate matches if some of the + attributes are not defined (ie. null or empty). + Default: ``no`` - **tag**: A ``key=value`` pair. The plugin will add a new ``key`` attribute with ``value`` value as a flexattr to the database for duplicate items. Default: ``no``. @@ -120,7 +120,7 @@ The same as the above but include the original album, and show the path:: Get tracks with the same title, artist, and album:: - beet duplicates -k title albumartist album + beet duplicates -k title -k albumartist -k album Compute Adler CRC32 or MD5 checksums, storing them as flexattrs, and report back duplicates based on those values:: @@ -138,7 +138,7 @@ Move likely duplicates to ``trash`` directory:: Delete items (careful!), if they're Nickelback:: - beet duplicates --delete --keys albumartist albumartist:nickelback + beet duplicates --delete -k albumartist -k albumartist:nickelback Tag duplicate items with some flag:: diff --git a/docs/plugins/echonest.rst b/docs/plugins/echonest.rst deleted file mode 100644 index 8ae7a11e6..000000000 --- a/docs/plugins/echonest.rst +++ /dev/null @@ -1,75 +0,0 @@ -Echo Nest Plugin -================ - -The ``echonest`` plugin fetches `acoustic attributes`_ from `the Echo Nest`_. -It automatically fills in the following attributes: - -- danceability -- energy -- liveness -- loudness -- speechiness -- bpm - -All attributes except ``bpm`` are stored in flexible attributes (i.e., not -in files' metadata). -See the Echo Nest's page on `acoustic attributes`_ for a detailed description. -(Their name for ``bpm`` is ``tempo``.) - -.. _the Echo Nest: http://the.echonest.com/ -.. _acoustic attributes: http://developer.echonest.com/acoustic-attributes.html - - -Installing Dependencies ------------------------ - -This plugin requires the pyechonest library in order to talk to the Echo Nest -API. At least version 8.0.1 is required. - -There are packages for most major linux distributions, you can download the -library from the Echo Nest, or you can install the library from `pip`_, -like so:: - - $ pip install pyechonest - -To transcode music for server-side analysis (optional, of course), install -the `ffmpeg`_ command-line tool. - -Finally, enable the ``echonest`` plugin in your configuration (see -:ref:`using-plugins`). - -.. _pip: http://pip.openplans.org/ -.. _FFmpeg: http://ffmpeg.org - - -Configuration -------------- - -To configure the plugin, make an ``echonest:`` section in your configuration -file. The available options are: - -- **apikey**: A custom EchoNest API key. You can `apply for your own`_ for - free from the EchoNest. - Default: beets' own Echo Nest API key. -- **auto**: Enable automatic metadata fetching during import. - Default: ``yes``. -- **upload**: Send files to the Echo Nest server if they can not be identified - by other means. - Default: ``yes``. -- **convert**: Because the Echo Nest server only supports a limited range of - file formats, the plugin automatically converts unsupported files to ``ogg``. - Default: ``yes``. -- **truncate**: Automatically truncate large files to their first 5 minutes - before uploading them to The Echo Nest server (as files with sizes greater - than 50MB are rejected). - Default: ``yes``. - -.. _apply for your own: http://developer.echonest.com/account/register - - -Running Manually ----------------- - -In addition to running automatically on import, the plugin can also be run -manually from the command line. Use the command ``beet echonest [QUERY]`` to -fetch acoustic attributes for albums matching a certain query. diff --git a/docs/plugins/edit.rst b/docs/plugins/edit.rst new file mode 100644 index 000000000..44286f79c --- /dev/null +++ b/docs/plugins/edit.rst @@ -0,0 +1,60 @@ +Edit Plugin +=========== + +The ``edit`` plugin lets you modify music metadata using your favorite text +editor. + +Enable the ``edit`` plugin in your configuration (see :ref:`using-plugins`) and +then type:: + + beet edit QUERY + +Your text editor (i.e., the command in your ``$EDITOR`` environment variable) +will open with a list of tracks to edit. Make your changes and exit your text +editor to apply them to your music. + +Command-Line Options +-------------------- + +The ``edit`` command has these command-line options: + +- ``-a`` or ``--album``: Edit albums instead of individual items. +- ``-f FIELD`` or ``--field FIELD``: Specify an additional field to edit + (in addition to the defaults set in the configuration). +- ``--all``: Edit *all* available fields. + +Interactive Usage +----------------- + +The ``edit`` plugin can also be invoked during an import session. If enabled, it +adds two new options to the user prompt:: + + [A]pply, More candidates, Skip, Use as-is, as Tracks, Group albums, Enter search, enter Id, aBort, eDit, edit Candidates? + +- ``eDit``: use this option for using the original items' metadata as the + starting point for your edits. +- ``edit Candidates``: use this option for using a candidate's metadata as the + starting point for your edits. + +Please note that currently the interactive usage of the plugin will only allow +you to change the item-level fields. In case you need to edit the album-level +fields, the recommended approach is to invoke the plugin via the command line +in album mode (``beet edit -a QUERY``) after the import. + +Also, please be aware that the ``edit Candidates`` choice can only be used with +the matches found during the initial search (and currently not supporting the +candidates found via the ``Enter search`` or ``enter Id`` choices). You might +find the ``--search-id SEARCH_ID`` :ref:`import-cmd` option useful for those +cases where you already have a specific candidate ID that you want to edit. + +Configuration +------------- + +To configure the plugin, make an ``edit:`` section in your configuration +file. The available options are: + +- **itemfields**: A space-separated list of item fields to include in the + editor by default. + Default: ``track title artist album`` +- **albumfields**: The same when editing albums (with the ``-a`` option). + Default: ``album albumartist`` diff --git a/docs/plugins/embedart.rst b/docs/plugins/embedart.rst index 41cfaa87c..2a34a59e8 100644 --- a/docs/plugins/embedart.rst +++ b/docs/plugins/embedart.rst @@ -66,9 +66,9 @@ file. The available options are: Default: ``no``. Note: ``compare_threshold`` option requires `ImageMagick`_, and ``maxwidth`` -requires either `ImageMagick`_ or `PIL`_. +requires either `ImageMagick`_ or `Pillow`_. -.. _PIL: http://www.pythonware.com/products/pil/ +.. _Pillow: https://github.com/python-pillow/Pillow .. _ImageMagick: http://www.imagemagick.org/ .. _PHASH: http://www.fmwconcepts.com/misc_tests/perceptual_hash_test_results_510/ @@ -81,7 +81,8 @@ embedded album art: * ``beet embedart [-f IMAGE] QUERY``: embed images into the every track on the albums matching the query. If the ``-f`` (``--file``) option is given, then use a specific image file from the filesystem; otherwise, each album embeds - its own currently associated album art. + its own currently associated album art. The command prompts for confirmation + before making the change unless you specify the ``-y`` (``--yes``) option. * ``beet extractart [-a] [-n FILE] QUERY``: extracts the images for all albums matching the query. The images are placed inside the album folder. You can @@ -98,4 +99,5 @@ embedded album art: automatically. * ``beet clearart QUERY``: removes all embedded images from all items matching - the query. (Use with caution!) + the query. The command prompts for confirmation before making the change + unless you specify the ``-y`` (``--yes``) option. diff --git a/docs/plugins/embyupdate.rst b/docs/plugins/embyupdate.rst new file mode 100644 index 000000000..00373b98c --- /dev/null +++ b/docs/plugins/embyupdate.rst @@ -0,0 +1,38 @@ +EmbyUpdate Plugin +================= + +``embyupdate`` is a plugin that lets you automatically update `Emby`_'s library whenever you change your beets library. + +To use ``embyupdate`` plugin, enable it in your configuration (see :ref:`using-plugins`). Then, you'll want to configure the specifics of your Emby server. You can do that using an ``emby:`` section in your ``config.yaml``, which looks like this:: + + emby: + host: localhost + port: 8096 + username: user + apikey: apikey + +To use the ``embyupdate`` plugin you need to install the `requests`_ library with:: + + pip install requests + +With that all in place, you'll see beets send the "update" command to your Emby server every time you change your beets library. + +.. _Emby: http://emby.media/ +.. _requests: http://docs.python-requests.org/en/latest/ + +Configuration +------------- + +The available options under the ``emby:`` section are: + +- **host**: The Emby server host. You also can include ``http://`` or ``https://``. + Default: ``localhost`` +- **port**: The Emby server port. + Default: 8096 +- **username**: A username of a Emby user that is allowed to refresh the library. +- **apikey**: An Emby API key for the user. +- **password**: The password for the user. (This is only necessary if no API + key is provided.) + +You can choose to authenticate either with `apikey` or `password`, but only +one of those two is required. diff --git a/docs/plugins/export.rst b/docs/plugins/export.rst new file mode 100644 index 000000000..4192f00c5 --- /dev/null +++ b/docs/plugins/export.rst @@ -0,0 +1,65 @@ +Export Plugin +============= + +The ``export`` plugin lets you get data from the items and export the content +as `JSON`_. + +.. _JSON: http://www.json.org + +Enable the ``export`` plugin (see :ref:`using-plugins` for help). Then, type ``beet export`` followed by a :doc:`query </reference/query>` to get the data from +your library. For example, run this:: + + $ beet export beatles + +to print a JSON file containing information about your Beatles tracks. + +Command-Line Options +-------------------- + +The ``export`` command has these command-line options: + +* ``--include-keys`` or ``-i``: Choose the properties to include in the output + data. The argument is a comma-separated list of simple glob patterns where + ``*`` matches any string. For example:: + + $ beet export -i 'title,mb*' beatles + + will include the ``title`` property and all properties starting with + ``mb``. You can add the ``-i`` option multiple times to the command + line. + +* ``--library`` or ``-l``: Show data from the library database instead of the + files' tags. + +* ``--output`` or ``-o``: Path for an output file. If not informed, will print + the data in the console. + +* ``--append``: Appends the data to the file instead of writing. + +Configuration +------------- + +To configure the plugin, make a ``export:`` section in your configuration +file. Under the ``json`` key, these options are available: + +- **ensure_ascii**: Escape non-ASCII characters with `\uXXXX` entities. + +- **indent**: The number of spaces for indentation. + +- **separators**: A ``[item_separator, dict_separator]`` tuple. + +- **sort_keys**: Sorts the keys in JSON dictionaries. + +These options match the options from the `Python json module`_. + +.. _Python json module: https://docs.python.org/2/library/json.html#basic-usage + +The default options look like this:: + + export: + json: + formatting: + ensure_ascii: False + indent: 4 + separators: [',' , ': '] + sort_keys: true diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 21d58fed4..d6d9adeff 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -42,31 +42,54 @@ file. The available options are: too big. The resize operation reduces image width to at most ``maxwidth`` pixels. The height is recomputed so that the aspect ratio is preserved. - **enforce_ratio**: Only images with a width:height ratio of 1:1 are - considered as valid album art candidates. Default: ``no``. -- **remote_priority**: Query remote sources every time and use local image only - as fallback. - Default: ``no``; remote (Web) art sources are only queried if no local art is - found in the filesystem. + considered as valid album art candidates if set to ``yes``. + It is also possible to specify a certain deviation to the exact ratio to + still be considered valid. This can be done either in pixels + (``enforce_ratio: 10px``) or as a percentage of the longer edge + (``enforce_ratio: 0.5%``). Default: ``no``. - **sources**: List of sources to search for images. An asterisk `*` expands to all available sources. - Default: ``coverart itunes amazon albumart``, i.e., everything but - ``wikipedia`` and ``google``. Enable those two sources for more matches at - the cost of some speed. + Default: ``filesystem coverart amazon albumart``, i.e., everything but + ``wikipedia``, ``google`` and ``fanarttv``. Enable those sources for more + matches at the cost of some speed. They are searched in the given order, + thus in the default config, no remote (Web) art source are queried if + local art is found in the filesystem. To use a local image as fallback, + move it to the end of the list. For even more fine-grained control over + the search order, see the section on :ref:`album-art-sources` below. +- **google_key**: Your Google API key (to enable the Google Custom Search + backend). + Default: None. +- **google_engine**: The custom search engine to use. + Default: The `beets custom search engine`_, which searches the entire web. +- **fanarttv_key**: The personal API key for requesting art from + fanart.tv. See below. +- **store_source**: If enabled, fetchart stores the artwork's source in a + flexible tag named ``art_source``. See below for the rationale behind this. + Default: ``no``. -Note: ``minwidth`` and ``enforce_ratio`` options require either `ImageMagick`_ -or `PIL`_. +Note: ``maxwidth`` and ``enforce_ratio`` options require either `ImageMagick`_ +or `Pillow`_. -.. _PIL: http://www.pythonware.com/products/pil/ +.. note:: + + Previously, there was a `remote_priority` option to specify when to + look for art on the filesystem. This is + still respected, but a deprecation message will be shown until you + replace this configuration with the new `filesystem` value in the + `sources` array. + +.. _beets custom search engine: https://cse.google.com.au:443/cse/publicurl?cx=001442825323518660753:hrh5ch1gjzm +.. _Pillow: https://github.com/python-pillow/Pillow .. _ImageMagick: http://www.imagemagick.org/ Here's an example that makes plugin select only images that contain *front* or -*back* keywords in their filenames and prioritizes the iTunes source over +*back* keywords in their filenames and prioritizes the Amazon source over others:: fetchart: cautious: true cover_names: front back - sources: itunes * + sources: amazon * Manually Fetching Album Art @@ -82,32 +105,46 @@ already have it; the ``-f`` or ``--force`` switch makes it search for art in Web databases regardless. If you specify a query, only matching albums will be processed; otherwise, the command processes every album in your library. +Display Only Missing Album Art +------------------------------ + +Use the ``fetchart`` command with the ``-q`` switch in order to display only missing +art:: + + $ beet fetchart [-q] [query] + +By default the command will display all results, the ``-q`` or ``--quiet`` +switch will only display results for album arts that are still missing. + .. _image-resizing: Image Resizing -------------- -Beets can resize images using `PIL`_, `ImageMagick`_, or a server-side resizing -proxy. If either PIL or ImageMagick is installed, beets will use those; +Beets can resize images using `Pillow`_, `ImageMagick`_, or a server-side resizing +proxy. If either Pillow or ImageMagick is installed, beets will use those; otherwise, it falls back to the resizing proxy. If the resizing proxy is used, no resizing is performed for album art found on the filesystem---only downloaded art is resized. Server-side resizing can also be slower than local resizing, so consider installing one of the two backends for better performance. -When using ImageMagic, beets looks for the ``convert`` executable in your path. +When using ImageMagick, beets looks for the ``convert`` executable in your path. On some versions of Windows, the program can be shadowed by a system-provided ``convert.exe``. On these systems, you may need to modify your ``%PATH%`` -environment variable so that ImageMagick comes first or use PIL instead. +environment variable so that ImageMagick comes first or use Pillow instead. -.. _PIL: http://www.pythonware.com/products/pil/ +.. _Pillow: https://github.com/python-pillow/Pillow .. _ImageMagick: http://www.imagemagick.org/ +.. _album-art-sources: + Album Art Sources ----------------- By default, this plugin searches for art in the local filesystem as well as on -the Cover Art Archive, the iTunes Store, Amazon, AlbumArt.org, -and Google Image Search, and Wikipedia, in that order. You can reorder the sources or remove +the Cover Art Archive, Amazon, and AlbumArt.org, in that +order. +You can reorder the sources or remove some to speed up the process using the ``sources`` configuration option. When looking for local album art, beets checks for image files located in the @@ -116,33 +153,75 @@ file whose name contains "cover", "front", "art", "album" or "folder", but in the absence of well-known names, it will use any image file in the same folder as your music files. +For some of the art sources, the backend service can match artwork by various +criteria. If you want finer control over the search order in such cases, you +can use this alternative syntax for the ``sources`` option:: + + fetchart: + sources: + - filesystem + - coverart: release + - itunes + - coverart: releasegroup + - '*' + +where listing a source without matching criteria will default to trying all +available strategies. Entries of the forms ``coverart: release releasegroup`` +and ``coverart: *`` are also valid. +Currently, only the ``coverart`` source supports multiple criteria: +namely, ``release`` and ``releasegroup``, which refer to the +respective MusicBrainz IDs. + When you choose to apply changes during an import, beets will search for art as described above. For "as-is" imports (and non-autotagged imports using the ``-A`` flag), beets only looks for art on the local filesystem. -iTunes Store -'''''''''''' +Google custom search +'''''''''''''''''''' -To use the iTunes Store as an art source, install the `python-itunes`_ -library. You can do this using `pip`_, like so:: +To use the google image search backend you need to +`register for a Google API key`_. Set the ``google_key`` configuration +option to your key, then add ``google`` to the list of sources in your +configuration. - $ pip install python-itunes +.. _register for a Google API key: https://console.developers.google.com. -Once the library is installed, the plugin will use it to search automatically. +Optionally, you can `define a custom search engine`_. Get your search engine's +token and use it for your ``google_engine`` configuration option. The +default engine searches the entire web for cover art. -.. _python-itunes: https://github.com/ocelma/python-itunes -.. _pip: http://pip.openplans.org/ +.. _define a custom search engine: http://www.google.com/cse/all -Google Image Search -''''''''''''''''''' +Note that the Google custom search API is limited to 100 queries per day. +After that, the fetchart plugin will fall back on other declared data sources. -You can optionally search for cover art on `Google Images`_. This option uses -the first hit for a search query consisting of the artist and album name. It -is therefore approximate: "incorrect" image matches are possible (although -unlikely). +Fanart.tv +''''''''' -.. _Google Images: http://images.google.com/ +Although not strictly necessary right now, you might think about +`registering a personal fanart.tv API key`_. Set the ``fanarttv_key`` +configuration option to your key, then add ``fanarttv`` to the list of sources +in your configuration. +.. _registering a personal fanart.tv API key: https://fanart.tv/get-an-api-key/ + +More detailed information can be found `on their blog`_. Specifically, the +personal key will give you earlier access to new art. + +.. _on their blog: https://fanart.tv/2015/01/personal-api-keys/ + +Storing the Artwork's Source +---------------------------- + +Storing the current artwork's source might be used to narrow down +``fetchart`` commands. For example, if some albums have artwork placed +manually in their directories that should not be replaced by a forced +album art fetch, you could do + +``beet fetchart -f ^art_source:filesystem`` + +The values written to ``art_source`` are the same names used in the ``sources`` +configuration value. Embedding Album Art ------------------- diff --git a/docs/plugins/gmusic.rst b/docs/plugins/gmusic.rst new file mode 100644 index 000000000..d0ba96671 --- /dev/null +++ b/docs/plugins/gmusic.rst @@ -0,0 +1,53 @@ +Gmusic Plugin +============= + +The ``gmusic`` plugin lets you upload songs to Google Play Music and query +songs in your library. + + +Installation +------------ + +The plugin requires `gmusicapi`_. You can install it using `pip`:: + + pip install gmusicapi + +.. _gmusicapi: https://github.com/simon-weber/gmusicapi/ + +Then, you can enable the ``gmusic`` plugin in your configuration (see +:ref:`using-plugins`). + + +Usage +----- + +To upload tracks to Google Play Music, use the ``gmusic-upload`` command:: + + beet gmusic-upload [QUERY] + +If you don't include a query, the plugin will upload your entire collection. + +To query the songs in your collection, you will need to add your Google +credentials to your beets configuration file. Put your Google username and +password under a section called ``gmusic``, like so:: + + gmusic: + email: user@example.com + password: seekrit + +If you have enabled two-factor authentication in your Google account, you will +need to set up and use an *application-specific password*. You can obtain one +from your Google security settings page. + +Then, use the ``gmusic-songs`` command to list music:: + + beet gmusic-songs [-at] [ARGS] + +Use the ``-a`` option to search by artist and ``-t`` to search by track. For +example:: + + beet gmusic-songs -a John Frusciante + beet gmusic-songs -t Black Hole Sun + +For a list of all songs in your library, run ``beet gmusic-songs`` without any +arguments. diff --git a/docs/plugins/hook.rst b/docs/plugins/hook.rst new file mode 100644 index 000000000..2c1dfec25 --- /dev/null +++ b/docs/plugins/hook.rst @@ -0,0 +1,72 @@ +Hook Plugin +=========== + +Internally, beets uses *events* to tell plugins when something happens. For +example, one event fires when the importer finishes processes a song, and +another triggers just before the ``beet`` command exits. +The ``hook`` plugin lets you run commands in response to these events. + +.. _hook-configuration: + +Configuration +------------- + +To configure the plugin, make a ``hook`` section in your configuration +file. The available options are: + +- **hooks**: A list of events and the commands to run + (see :ref:`individual-hook-configuration`). Default: Empty. + +.. _individual-hook-configuration: + +Configuring Each Hook +''''''''''''''''''''' + +Each element under ``hooks`` should have these keys: + +- **event**: The name of the event that will trigger this hook. + See the :ref:`plugin events <plugin_events>` documentation for a list + of possible values. +- **command**: The command to run when this hook executes. + +.. _command-substitution: + +Command Substitution +'''''''''''''''''''' + +Commands can access the parameters of events using `Python string +formatting`_. Use ``{name}`` in your command and the plugin will substitute it +with the named value. The name can also refer to a field, as in +``{album.path}``. + +.. _Python string formatting: https://www.python.org/dev/peps/pep-3101/ + +You can find a list of all available events and their arguments in the +:ref:`plugin events <plugin_events>` documentation. + +Example Configuration +--------------------- + +.. code-block:: yaml + + hook: + hooks: + # Output on exit: + # beets just exited! + # have a nice day! + - event: cli_exit + command: echo "beets just exited!" + - event: cli_exit + command: echo "have a nice day!" + + # Output on item import: + # importing "<file_name_here>" + # Where <file_name_here> is the item being imported + - event: item_imported + command: echo "importing \"{item.path}\"" + + # Output on write: + # writing to "<file_name_here>" + # Where <file_name_here> is the file being written to + - event: write + command: echo "writing to {path}" diff --git a/docs/plugins/ihate.rst b/docs/plugins/ihate.rst index f2224bf5a..f9cde39eb 100644 --- a/docs/plugins/ihate.rst +++ b/docs/plugins/ihate.rst @@ -25,7 +25,7 @@ Here's an example:: ihate: warn: - artist:rnb - - genre: soul + - genre:soul # Only warn about tribute albums in rock genre. - genre:rock album:tribute skip: diff --git a/docs/plugins/importadded.rst b/docs/plugins/importadded.rst index 677879da8..2a2e8ea29 100644 --- a/docs/plugins/importadded.rst +++ b/docs/plugins/importadded.rst @@ -22,8 +22,11 @@ The ``item.added`` field is populated as follows: set to the oldest mtime of the files in the album before they were imported. The mtime of album directories is ignored. -This plugin can optionally be configured to also preserve mtimes using the -``preserve_mtimes`` option. +This plugin can optionally be configured to also preserve mtimes at +import using the ``preserve_mtimes`` option. + +When ``preserve_write_mtimes`` option is set, this plugin preserves +mtimes after each write to files using the ``item.added`` attribute. File modification times are preserved as follows: @@ -40,9 +43,13 @@ Configuration ------------- To configure the plugin, make an ``importadded:`` section in your -configuration file. There is one option available: +configuration file. There are two options available: -- **preserve_mtimes**: After writing files, re-set their mtimes to their +- **preserve_mtimes**: After importing files, re-set their mtimes to their + original value. + Default: ``no``. + +- **preserve_write_mtimes**: After writing files, re-set their mtimes to their original value. Default: ``no``. diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index 0c95f366f..edd82a255 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -13,7 +13,7 @@ Using Plugins ------------- To use one of the plugins included with beets (see the rest of this page for a -list), just use the `plugins` option in your :doc:`config.yaml </reference/config>`: file, like so:: +list), just use the `plugins` option in your :doc:`config.yaml </reference/config>` file, like so:: plugins: inline convert web @@ -28,10 +28,20 @@ Each plugin has its own set of options that can be defined in a section bearing convert: auto: true +Some plugins have special dependencies that you'll need to install. The +documentation page for each plugin will list them in the setup instructions. +For some, you can use `pip`'s "extras" feature to install the dependencies, +like this:: + + pip install beets[fetchart,lyrics,lastgenre] + .. toctree:: :hidden: + absubmit + acousticbrainz badfiles + beatport bpd bpm bucket @@ -39,13 +49,18 @@ Each plugin has its own set of options that can be defined in a section bearing convert discogs duplicates - echonest + edit embedart + embyupdate + export fetchart + filefilter + freedesktop fromfilename ftintitle fuzzy - freedesktop + gmusic + hook ihate importadded importfeeds @@ -53,10 +68,12 @@ Each plugin has its own set of options that can be defined in a section bearing inline ipfs keyfinder + kodiupdate lastgenre lastimport lyrics mbcollection + mbsubmit mbsync metasync missing @@ -66,11 +83,11 @@ Each plugin has its own set of options that can be defined in a section bearing play plexupdate random - filefilter replaygain rewrite scrub smartplaylist + sonosupdate spotify the thumbnails @@ -92,9 +109,10 @@ Autotagger Extensions Metadata -------- +* :doc:`absubmit`: Analyse audio with the `streaming_extractor_music`_ program and submit the metadata to the AcousticBrainz server +* :doc:`acousticbrainz`: Fetch various AcousticBrainz metadata * :doc:`bpm`: Measure tempo using keystrokes. -* :doc:`echonest`: Automatically fetch `acoustic attributes`_ from - `the Echo Nest`_ (tempo, energy, danceability, ...). +* :doc:`edit`: Edit metadata from a text editor. * :doc:`embedart`: Embed album art images into files' metadata. * :doc:`fetchart`: Fetch album cover art from various sources. * :doc:`ftintitle`: Move "featured" artists from the artist field to the title @@ -114,9 +132,8 @@ Metadata * :doc:`scrub`: Clean extraneous metadata from music files. * :doc:`zero`: Nullify fields by pattern or unconditionally. -.. _Acoustic Attributes: http://developer.echonest.com/acoustic-attributes.html -.. _the Echo Nest: http://www.echonest.com .. _KeyFinder: http://www.ibrahimshaath.co.uk/keyfinder/ +.. _streaming_extractor_music: http://acousticbrainz.org/download Path Formats ------------ @@ -131,19 +148,27 @@ Path Formats Interoperability ---------------- +* :doc:`badfiles`: Check audio file integrity. +* :doc:`embyupdate`: Automatically notifies `Emby`_ whenever the beets library changes. * :doc:`importfeeds`: Keep track of imported files via ``.m3u`` playlist file(s) or symlinks. * :doc:`ipfs`: Import libraries from friends and get albums from them via ipfs. +* :doc:`kodiupdate`: Automatically notifies `Kodi`_ whenever the beets library + changes. * :doc:`mpdupdate`: Automatically notifies `MPD`_ whenever the beets library changes. * :doc:`play`: Play beets queries in your music player. * :doc:`plexupdate`: Automatically notifies `Plex`_ whenever the beets library changes. * :doc:`smartplaylist`: Generate smart playlists based on beets queries. +* :doc:`sonosupdate`: Automatically notifies `Sonos`_ whenever the beets library + changes. * :doc:`thumbnails`: Get thumbnails with the cover art on your album folders. -* :doc:`badfiles`: Check audio file integrity. +.. _Emby: http://emby.media .. _Plex: http://plex.tv +.. _Kodi: http://kodi.tv +.. _Sonos: http://sonos.com Miscellaneous ------------- @@ -153,14 +178,18 @@ Miscellaneous * :doc:`convert`: Transcode music and embed album art while exporting to a different directory. * :doc:`duplicates`: List duplicate tracks or albums. +* :doc:`export`: Export data from queries to a format. +* :doc:`filefilter`: Automatically skip files during the import process based + on regular expressions. * :doc:`fuzzy`: Search albums and tracks with fuzzy string matching. +* :doc:`gmusic`: Search and upload files to Google Play Music. +* :doc:`hook`: Run a command when an event is emitted by beets. * :doc:`ihate`: Automatically skip albums and tracks during the import process. * :doc:`info`: Print music files' tags to the console. * :doc:`mbcollection`: Maintain your MusicBrainz collection list. +* :doc:`mbsubmit`: Print an album's tracks in a MusicBrainz-friendly format. * :doc:`missing`: List missing tracks. * :doc:`random`: Randomly choose albums and tracks from your library. -* :doc:`filefilter`: Automatically skip files during the import process based - on regular expressions. * :doc:`spotify`: Create Spotify playlists from the Beets library. * :doc:`types`: Declare types for flexible attributes. * :doc:`web`: An experimental Web-based GUI for beets. @@ -215,11 +244,15 @@ Here are a few of the plugins written by the beets community: * `whatlastgenre`_ fetches genres from various music sites. +* `beets-usertag`_ lets you use keywords to tag and organize your music. + +* `beets-popularity`_ fetches popularity values from Spotify. + .. _beets-check: https://github.com/geigerzaehler/beets-check .. _copyartifacts: https://github.com/sbarakat/beets-copyartifacts .. _dsedivec: https://github.com/dsedivec/beets-plugins .. _beets-artistcountry: https://github.com/agrausem/beets-artistcountry -.. _beetFs: https://code.google.com/p/beetfs/ +.. _beetFs: https://github.com/jbaiter/beetfs .. _Beet-MusicBrainz-Collection: https://github.com/jeffayle/Beet-MusicBrainz-Collection/ .. _A cmus plugin: @@ -229,5 +262,7 @@ Here are a few of the plugins written by the beets community: .. _beets-alternatives: https://github.com/geigerzaehler/beets-alternatives .. _beets-follow: https://github.com/nolsto/beets-follow .. _beets-setlister: https://github.com/tomjaspers/beets-setlister -.. _beets-noimport: https://github.com/ttsda/beets-noimport +.. _beets-noimport: https://gitlab.com/tiago.dias/beets-noimport .. _whatlastgenre: https://github.com/YetAnotherNerd/whatlastgenre/tree/master/plugin/beets +.. _beets-usertag: https://github.com/igordertigor/beets-usertag +.. _beets-popularity: https://github.com/abba23/beets-popularity diff --git a/docs/plugins/info.rst b/docs/plugins/info.rst index 5bfde0b41..238a957ff 100644 --- a/docs/plugins/info.rst +++ b/docs/plugins/info.rst @@ -36,6 +36,10 @@ Additional command-line options include: * ``--summarize`` or ``-s``: Merge all the information from multiple files into a single list of values. If the tags differ across the files, print ``[various]``. +* ``--format`` or ``-f``: Specify a specific format with which to print every + item. This uses the same template syntax as beets’ :doc:`path formats + </reference/pathformat>`. +* ``--keys-only`` or ``-k``: Show the name of the tags without the values. .. _id3v2: http://id3v2.sourceforge.net .. _mp3info: http://www.ibiblio.org/mp3info/ diff --git a/docs/plugins/inline.rst b/docs/plugins/inline.rst index ebe298ae7..4dfca261d 100644 --- a/docs/plugins/inline.rst +++ b/docs/plugins/inline.rst @@ -6,9 +6,9 @@ it, you can define template fields in your beets configuration file and refer to them from your template strings in the ``paths:`` section (see :doc:`/reference/config/`). -To use the `ìnline`` plugin, enable it in your configuration +To use the ``inline`` plugin, enable it in your configuration (see :ref:`using-plugins`). -Then, make a `item_fields:`` block in your config file. Under this key, every line defines a +Then, make a ``item_fields:`` block in your config file. Under this key, every line defines a new template field; the key is the name of the field (you'll use the name to refer to the field in your templates) and the value is a Python expression or function body. The Python code has all of a track's fields in scope, so you can diff --git a/docs/plugins/kodiupdate.rst b/docs/plugins/kodiupdate.rst new file mode 100644 index 000000000..a1ec04775 --- /dev/null +++ b/docs/plugins/kodiupdate.rst @@ -0,0 +1,44 @@ +KodiUpdate Plugin +================= + +The ``kodiupdate`` plugin lets you automatically update `Kodi`_'s music +library whenever you change your beets library. + +To use ``kodiupdate`` plugin, enable it in your configuration +(see :ref:`using-plugins`). +Then, you'll want to configure the specifics of your Kodi host. +You can do that using a ``kodi:`` section in your ``config.yaml``, +which looks like this:: + + kodi: + host: localhost + port: 8080 + user: kodi + pwd: kodi + +To use the ``kodiupdate`` plugin you need to install the `requests`_ library with:: + + pip install requests + +You'll also need to enable JSON-RPC in Kodi in order the use the plugin. +In Kodi's interface, navigate to System/Settings/Network/Services and choose "Allow control of Kodi via HTTP." + +With that all in place, you'll see beets send the "update" command to your Kodi +host every time you change your beets library. + +.. _Kodi: http://kodi.tv/ +.. _requests: http://docs.python-requests.org/en/latest/ + +Configuration +------------- + +The available options under the ``kodi:`` section are: + +- **host**: The Kodi host name. + Default: ``localhost`` +- **port**: The Kodi host port. + Default: 8080 +- **user**: The Kodi host user. + Default: ``kodi`` +- **pwd**: The Kodi host password. + Default: ``kodi`` diff --git a/docs/plugins/lastgenre.rst b/docs/plugins/lastgenre.rst index 9d3242467..5e3235bd7 100644 --- a/docs/plugins/lastgenre.rst +++ b/docs/plugins/lastgenre.rst @@ -35,19 +35,45 @@ For the curious, the default genre list is generated by a `script that scrapes Wikipedia`_. .. _pip: http://www.pip-installer.org/ -.. _pylast: http://code.google.com/p/pylast/ +.. _pylast: https://github.com/pylast/pylast .. _script that scrapes Wikipedia: https://gist.github.com/1241307 -.. _internal whitelist: https://raw.githubusercontent.com/sampsyo/beets/master/beetsplug/lastgenre/genres.txt +.. _internal whitelist: https://raw.githubusercontent.com/beetbox/beets/master/beetsplug/lastgenre/genres.txt Canonicalization ^^^^^^^^^^^^^^^^ The plugin can also *canonicalize* genres, meaning that more obscure genres can be turned into coarser-grained ones that are present in the whitelist. This -works using a tree of nested genre names, represented using `YAML`_, where the +works using a `tree of nested genre names`_, represented using `YAML`_, where the leaves of the tree represent the most specific genres. +The most common way to use this would be with a custom whitelist containing only +a desired subset of genres. Consider for a example this minimal whitelist:: + + rock + heavy metal + pop + +together with the default genre tree. Then an item that has its genre specified +as *viking metal* would actually be tagged as *heavy metal* because neither +*viking metal* nor its parent *black metal* are in the whitelist. It always +tries to use the most specific genre that's available in the whitelist. + +The relevant subtree path in the default tree looks like this:: + + - rock: + - heavy metal: + - black metal: + - viking metal + +Considering that, it's not very useful to use the default whitelist (which +contains about any genre contained in the tree) with canonicalization because +nothing would ever be matched to a more generic node since all the specific +subgenres are in the whitelist to begin with. + + .. _YAML: http://www.yaml.org/ +.. _tree of nested genre names: https://raw.githubusercontent.com/beetbox/beets/master/beetsplug/lastgenre/genres-tree.yaml Genre Source @@ -77,6 +103,19 @@ The plugin uses this weight to discard unpopular tags. The default is to ignore tags with a weight less then 10. You can change this by setting the ``min_weight`` config option. +Specific vs. Popular Genres +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +By default, the plugin sorts genres by popularity. However, you can use the +``prefer_specific`` option to override this behavior and instead sort genres +by specificity, as determined by your whitelist and canonicalization tree. + +For instance, say you have both ``folk`` and ``americana`` in your whitelist +and canonicalization tree and ``americana`` is a leaf within ``folk``. If +Last.fm returns both of those tags, lastgenre is going to use the most +popular, which is often the most generic (in this case ``folk``). By setting +``prefer_specific`` to true, lastgenre would use ``americana`` instead. + Configuration ------------- @@ -100,6 +139,8 @@ configuration file. The available options are: Default: ``yes``. - **min_weight**: Minimum popularity factor below which genres are discarded. Default: 10. +- **prefer_specific**: Sort genres by the most to least specific, rather than + most to least popular. Default: ``no``. - **source**: Which entity to look up in Last.fm. Can be either ``artist``, ``album`` or ``track``. Default: ``album``. diff --git a/docs/plugins/lastimport.rst b/docs/plugins/lastimport.rst index 7d8ede891..8006d6bbb 100644 --- a/docs/plugins/lastimport.rst +++ b/docs/plugins/lastimport.rst @@ -6,21 +6,25 @@ library into beets' database. You can later create :doc:`smart playlists </plugins/smartplaylist>` by querying ``play_count`` and do other fun stuff with this field. +.. _Last.fm: http://last.fm + Installation ------------ -To use the ``lastimport`` plugin, first enable it in your configuration (see -:ref:`using-plugins`). Then install the `requests`_ library by typing:: +The plugin requires `pylast`_, which you can install using `pip`_ by typing:: - pip install requests + pip install pylast + +After you have pylast installed, enable the ``lastimport`` plugin in your +configuration (see :ref:`using-plugins`). Next, add your Last.fm username to your beets configuration file:: lastfm: user: beetsfanatic -.. _requests: http://docs.python-requests.org/en/latest/ -.. _Last.fm: http://last.fm +.. _pip: http://www.pip-installer.org/ +.. _pylast: https://github.com/pylast/pylast Importing Play Counts --------------------- @@ -49,3 +53,9 @@ options under the ``lastimport:`` section: * **retry_limit**: How many times should we re-send requests to Last.fm on failure? Default: 3. + +By default, the plugin will use beets's own Last.fm API key. You can also +override it with your own API key:: + + lastfm: + api_key: your_api_key diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index 1d91a00eb..4131c85d9 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -2,12 +2,12 @@ Lyrics Plugin ============= The ``lyrics`` plugin fetches and stores song lyrics from databases on the Web. -Namely, the current version of the plugin uses `Lyric Wiki`_, `Lyrics.com`_, -`Musixmatch`_, and, optionally, the Google custom search API. +Namely, the current version of the plugin uses `Lyric Wiki`_, +`Musixmatch`_, `Genius.com`_, and, optionally, the Google custom search API. .. _Lyric Wiki: http://lyrics.wikia.com/ -.. _Lyrics.com: http://www.lyrics.com/ .. _Musixmatch: https://www.musixmatch.com/ +.. _Genius.com: http://genius.com/ Fetch Lyrics During Import @@ -37,6 +37,14 @@ configuration file. The available options are: - **auto**: Fetch lyrics automatically during import. Default: ``yes``. +- **bing_client_secret**: Your Bing Translation application password + (to :ref:`lyrics-translation`) +- **bing_lang_from**: By default all lyrics with a language other than + ``bing_lang_to`` are translated. Use a list of lang codes to restrict the set + of source languages to translate. + Default: ``[]`` +- **bing_lang_to**: Language to translate lyrics into. + Default: None. - **fallback**: By default, the file will be left unchanged when no lyrics are found. Use the empty string ``''`` to reset the lyrics in such a case. Default: None. @@ -51,9 +59,11 @@ configuration file. The available options are: sources known to be scrapeable. - **sources**: List of sources to search for lyrics. An asterisk ``*`` expands to all available sources. - Default: ``google lyricwiki lyrics.com musixmatch``, i.e., all sources. - *google* source will be automatically deactivated if no ``google_API_key`` is - setup. + Default: ``google lyricwiki musixmatch genius``, i.e., all the + available sources. The `google` source will be automatically + deactivated if no ``google_API_key`` is setup. + Both it and the `genius` source will only be enabled if BeautifulSoup is + installed. Here's an example of ``config.yaml``:: @@ -79,11 +89,44 @@ The ``-p`` option to the ``lyrics`` command makes it print lyrics out to the console so you can view the fetched (or previously-stored) lyrics. The ``-f`` option forces the command to fetch lyrics, even for tracks that -already have lyrics. +already have lyrics. Inversely, the ``-l`` option restricts operations +to lyrics that are locally available, which show lyrics faster without using +the network at all. + +Rendering Lyrics into Other Formats +----------------------------------- + +The ``-r directory`` option renders all lyrics as `reStructuredText`_ (ReST) +documents in ``directory`` (by default, the current directory). That +directory, in turn, can be parsed by tools like `Sphinx`_ to generate HTML, +ePUB, or PDF documents. + +A minimal ``conf.py`` and ``index.rst`` files are created the first time the +command is run. They are not overwritten on subsequent runs, so you can safely +modify these files to customize the output. + +.. _Sphinx: http://www.sphinx-doc.org/ +.. _reStructuredText: http://docutils.sourceforge.net/rst.html + +Sphinx supports various `builders +<http://www.sphinx-doc.org/en/stable/builders.html>`_, but here are a +few suggestions. + + * Build an HTML version:: + + sphinx-build -b html . _build/html + + * Build an ePUB3 formatted file, usable on ebook readers:: + + sphinx-build -b epub3 . _build/epub + + * Build a PDF file, which incidentally also builds a LaTeX file:: + + sphinx-build -b latex %s _build/latex && make -C _build/latex all-pdf .. _activate-google-custom-search: -Activate Google custom search +Activate Google Custom Search ------------------------------ Using the Google backend requires `BeautifulSoup`_, which you can install @@ -99,7 +142,7 @@ If you use default ``google_engine_ID``, we recommend limiting the sources to ``musixmatch google`` as the other sources are already included in the Google results. -.. _register for a Google API key: https://code.google.com/apis/console. +.. _register for a Google API key: https://console.developers.google.com/ Optionally, you can `define a custom search engine`_. Get your search engine's token and use it for your ``google_engine_ID`` configuration option. By @@ -112,3 +155,33 @@ After that, the lyrics plugin will fall back on other declared data sources. .. _pip: http://www.pip-installer.org/ .. _BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/bs4/doc/ + +Activate Genius Lyrics +---------------------- + +Like the Google backend, the Genius backend requires the `BeautifulSoup`_ +library. Install it by typing:: + + pip install beautifulsoup4 + +The backend is enabled by default. + +.. _lyrics-translation: + +Activate On-the-Fly Translation +------------------------------- + +Using the Bing Translation API requires `langdetect`_, which you can install +using `pip`_ by typing:: + + pip install langdetect + +You also need to register for a Microsoft Azure Marketplace free account and +to the `Microsoft Translator API`_. Follow the four steps process, specifically +at step 3 enter ``beets`` as *Client ID* and copy/paste the generated +*Client secret* into your ``bing_client_secret`` configuration, alongside +``bing_lang_to`` target `language code`_. + +.. _langdetect: https://pypi.python.org/pypi/langdetect +.. _Microsoft Translator API: https://www.microsoft.com/en-us/translator/getstarted.aspx +.. _language code: https://msdn.microsoft.com/en-us/library/hh456380.aspx diff --git a/docs/plugins/mbcollection.rst b/docs/plugins/mbcollection.rst index df9a5ddc8..803d34904 100644 --- a/docs/plugins/mbcollection.rst +++ b/docs/plugins/mbcollection.rst @@ -20,6 +20,12 @@ command automatically adds all of your albums to the first collection it finds. If you don't have a MusicBrainz collection yet, you may need to add one to your profile first. +The command has one command-line option: + +* To remove albums from the collection which are no longer present in + the beets database, use the ``-r`` (``--remove``) flag. + + Configuration ------------- @@ -29,3 +35,8 @@ configuration file. There is one option available: - **auto**: Automatically amend your MusicBrainz collection whenever you import a new album. Default: ``no``. +- **collection**: Which MusicBrainz collection to update. + Default: ``None``. +- **remove**: Remove albums from collections which are no longer + present in the beets database. + Default: ``None``. diff --git a/docs/plugins/mbsubmit.rst b/docs/plugins/mbsubmit.rst new file mode 100644 index 000000000..5c13375ba --- /dev/null +++ b/docs/plugins/mbsubmit.rst @@ -0,0 +1,54 @@ +MusicBrainz Submit Plugin +========================= + +The ``mbsubmit`` plugin provides an extra prompt choice during an import +session that prints the tracks of the current album in a format that is +parseable by MusicBrainz's `track parser`_. + +.. _track parser: http://wiki.musicbrainz.org/History:How_To_Parse_Track_Listings + +Usage +----- + +Enable the ``mbsubmit`` plugin in your configuration (see :ref:`using-plugins`) +and select the ``Print tracks`` choice which is by default displayed when no +strong recommendations are found for the album:: + + No matching release found for 3 tracks. + For help, see: http://beets.readthedocs.org/en/latest/faq.html#nomatch + [U]se as-is, as Tracks, Group albums, Skip, Enter search, enter Id, aBort, + Print tracks? p + 01. An Obscure Track - An Obscure Artist (3:37) + 02. Another Obscure Track - An Obscure Artist (2:05) + 03. The Third Track - Another Obscure Artist (3:02) + + No matching release found for 3 tracks. + For help, see: http://beets.readthedocs.org/en/latest/faq.html#nomatch + [U]se as-is, as Tracks, Group albums, Skip, Enter search, enter Id, aBort, + Print tracks? + +As MusicBrainz currently does not support submitting albums programmatically, +the recommended workflow is to copy the output of the ``Print tracks`` choice +and paste it into the parser that can be found by clicking on the +"Track Parser" button on MusicBrainz "Tracklist" tab. + +Configuration +------------- + +To configure the plugin, make a ``mbsubmit:`` section in your configuration +file. The following options are available: + +- **format**: The format used for printing the tracks, defined using the + same template syntax as beets’ :doc:`path formats </reference/pathformat>`. + Default: ``$track. $title - $artist ($length)``. +- **threshold**: The minimum strength of the autotagger recommendation that + will cause the ``Print tracks`` choice to be displayed on the prompt. + Default: ``medium`` (causing the choice to be displayed for all albums that + have a recommendation of medium strength or lower). Valid values: ``none``, + ``low``, ``medium``, ``strong``. + +Please note that some values of the ``threshold`` configuration option might +require other ``beets`` command line switches to be enabled in order to work as +intended. In particular, setting a threshold of ``strong`` will only display +the prompt if ``timid`` mode is enabled. You can find more information about +how the recommendation system works at :ref:`match-config`. diff --git a/docs/plugins/missing.rst b/docs/plugins/missing.rst index aab04e71b..38a0d5a08 100644 --- a/docs/plugins/missing.rst +++ b/docs/plugins/missing.rst @@ -11,7 +11,8 @@ Usage Add the ``missing`` plugin to your configuration (see :ref:`using-plugins`). By default, the ``beet missing`` command lists the names of tracks that your -library is missing from each album. +library is missing from each album. It can also list the names of albums that +your library is missing from each artist. You can customize the output format, count the number of missing tracks per album, or total up the number of missing tracks over your whole library, using command-line switches:: @@ -19,10 +20,13 @@ tracks over your whole library, using command-line switches:: -f FORMAT, --format=FORMAT print with custom FORMAT -c, --count count missing tracks per album - -t, --total count total of missing tracks + -t, --total count total of missing tracks or albums + -a, --album show missing albums for artist instead of tracks …or by editing corresponding options. +Note that ``-c`` is ignored when used with ``-a``. + Configuration ------------- @@ -60,6 +64,10 @@ List all missing tracks in your collection:: beet missing +List all missing albums in your collection:: + + beet missing -a + List all missing tracks from 2008:: beet missing year:2008 diff --git a/docs/plugins/mpdstats.rst b/docs/plugins/mpdstats.rst index 1f74a0976..5472e7294 100644 --- a/docs/plugins/mpdstats.rst +++ b/docs/plugins/mpdstats.rst @@ -39,7 +39,8 @@ To configure the plugin, make an ``mpd:`` section in your configuration file. The available options are: - **host**: The MPD server hostname. - Default: ``localhost``. + Default: The ``$MPD_HOST`` environment variable if set, + falling back to ``localhost`` otherwise. - **port**: The MPD server port. Default: 6600. - **password**: The MPD server password. @@ -95,4 +96,4 @@ Warning This has only been tested with MPD versions >= 0.16. It may not work on older versions. If that is the case, please report an `issue`_. -.. _issue: https://github.com/sampsyo/beets/issues +.. _issue: https://github.com/beetbox/beets/issues diff --git a/docs/plugins/mpdupdate.rst b/docs/plugins/mpdupdate.rst index 954a87b33..c846b917f 100644 --- a/docs/plugins/mpdupdate.rst +++ b/docs/plugins/mpdupdate.rst @@ -31,7 +31,7 @@ Configuration The available options under the ``mpd:`` section are: - **host**: The MPD server name. - Default: ``localhost``. + Default: The ``$MPD_HOST`` environment variable if set, falling back to ``localhost`` otherwise. - **port**: The MPD server port. Default: 6600. - **password**: The MPD server password. diff --git a/docs/plugins/play.rst b/docs/plugins/play.rst index 9a7210b4e..3a08a4239 100644 --- a/docs/plugins/play.rst +++ b/docs/plugins/play.rst @@ -2,10 +2,10 @@ Play Plugin =========== The ``play`` plugin allows you to pass the results of a query to a music -player in the form of an m3u playlist. +player in the form of an m3u playlist or paths on the command line. -Usage ------ +Command Line Usage +------------------ To use the ``play`` plugin, enable it in your configuration (see :ref:`using-plugins`). Then use it by invoking the ``beet play`` command with @@ -29,6 +29,18 @@ would on the command-line):: While playing you'll be able to interact with the player if it is a command-line oriented, and you'll get its output in real time. +Interactive Usage +----------------- + +The `play` plugin can also be invoked during an import. If enabled, the plugin +adds a `plaY` option to the prompt, so pressing `y` will execute the configured +command and play the items currently being imported. + +Once the configured command exits, you will be returned to the import +decision prompt. If your player is configured to run in the background (in a +client/server setup), the music will play until you choose to stop it, and the +import operation continues immediately. + Configuration ------------- @@ -37,7 +49,7 @@ configuration file. The available options are: - **command**: The command used to open the playlist. Default: ``open`` on OS X, ``xdg-open`` on other Unixes and ``start`` on - Windows. Insert ``{}`` to make use of the ``--args``-feature. + Windows. Insert ``$args`` to use the ``--args`` feature. - **relative_to**: If set, emit paths relative to this directory. Default: None. - **use_folders**: When using the ``-a`` option, the m3u will contain the @@ -47,7 +59,7 @@ configuration file. The available options are: - **raw**: Instead of creating a temporary m3u playlist and then opening it, simply call the command with the paths returned by the query as arguments. Default: ``no``. -- **warning_treshold**: Set the minimum number of files to play which will +- **warning_threshold**: Set the minimum number of files to play which will trigger a warning to be emitted. If set to ``no``, warning are never issued. Default: 100. @@ -82,3 +94,21 @@ example:: indicates that you need to insert extra arguments before specifying the playlist. + +The ``--yes`` (or ``-y``) flag to the ``play`` command will skip the warning +message if you choose to play more items than the **warning_threshold** +value usually allows. + +Note on the Leakage of the Generated Playlists +---------------------------------------------- + +Because the command that will open the generated ``.m3u`` files can be +arbitrarily configured by the user, beets won't try to delete those files. For +this reason, using this plugin will leave one or several playlist(s) in the +directory selected to create temporary files (Most likely ``/tmp/`` on Unix-like +systems. See `tempfile.tempdir`_ in the Python docs.). Leaking those playlists until +they are externally wiped could be an issue for privacy or storage reasons. If +this is the case for you, you might want to use the ``raw`` config option +described above. + +.. _tempfile.tempdir: https://docs.python.org/2/library/tempfile.html#tempfile.tempdir diff --git a/docs/plugins/random.rst b/docs/plugins/random.rst index 5b04d5ab7..b0c437819 100644 --- a/docs/plugins/random.rst +++ b/docs/plugins/random.rst @@ -23,3 +23,7 @@ of Bob Dylan won't make you listen to Bob Dylan 50% of the time. The ``-n NUMBER`` option controls the number of objects that are selected and printed (default 1). To select 5 tracks from your library, type ``beet random -n5``. + +As an alternative, you can use ``-t MINUTES`` to choose a set of music with a +given play time. To select tracks that total one hour, for example, type +``beet random -t60``. diff --git a/docs/plugins/replaygain.rst b/docs/plugins/replaygain.rst index 968e996e6..7f520c334 100644 --- a/docs/plugins/replaygain.rst +++ b/docs/plugins/replaygain.rst @@ -67,7 +67,7 @@ Python Audio Tools This backend uses the `Python Audio Tools`_ package to compute ReplayGain for a range of different file formats. The package is not available via PyPI; it -must be installed manually. +must be installed manually (only versions preceding 3.x are compatible). On OS X, most of the dependencies can be installed with `Homebrew`_:: @@ -79,8 +79,8 @@ bs1770gain `````````` To use this backend, you will need to install the `bs1770gain`_ command-line -tool. Follow the instructions at the `bs1770gain`_ Web site and ensure that -the tool is on your ``$PATH``. +tool, version 0.4.6 or greater. Follow the instructions at the `bs1770gain`_ +Web site and ensure that the tool is on your ``$PATH``. .. _bs1770gain: http://bs1770gain.sourceforge.net/ @@ -108,6 +108,10 @@ configuration file. The available options are: Default: ``no``. - **targetlevel**: A number of decibels for the target loudness level. Default: 89. +- **r128**: A space separated list of formats that will use ``R128_`` tags with + integer values instead of the common ``REPLAYGAIN_`` tags with floating point + values. Requires the "bs1770gain" backend. + Default: ``Opus``. These options only work with the "command" backend: @@ -136,11 +140,15 @@ By default, the plugin will analyze all items an albums as they are implemented. However, you can also manually analyze files that are already in your library. Use the ``beet replaygain`` command:: - $ beet replaygain [-a] [QUERY] + $ beet replaygain [-Waf] [QUERY] The ``-a`` flag analyzes whole albums instead of individual tracks. Provide a query (see :doc:`/reference/query`) to indicate which items or albums to -analyze. +analyze. Files that already have ReplayGain values are skipped unless ``-f`` is +supplied. Use ``-w`` (write tags) or ``-W`` (don't write tags) to control +whether ReplayGain tags are written into the music files, or stored in the +beets database only (the default is to use :ref:`the importer's configuration +<config-import-write>`). ReplayGain analysis is not fast, so you may want to disable it during import. Use the ``auto`` config option to control this:: diff --git a/docs/plugins/sonosupdate.rst b/docs/plugins/sonosupdate.rst new file mode 100644 index 000000000..97a13bd07 --- /dev/null +++ b/docs/plugins/sonosupdate.rst @@ -0,0 +1,18 @@ +SonosUpdate Plugin +================== + +The ``sonosupdate`` plugin lets you automatically update `Sonos`_'s music +library whenever you change your beets library. + +To use ``sonosupdate`` plugin, enable it in your configuration +(see :ref:`using-plugins`). + +To use the ``sonosupdate`` plugin you need to install the `soco`_ library with:: + + pip install soco + +With that all in place, you'll see beets send the "update" command to your Sonos +controller every time you change your beets library. + +.. _Sonos: http://sonos.com/ +.. _soco: http://python-soco.com diff --git a/docs/plugins/spotify.rst b/docs/plugins/spotify.rst index 2295c70b4..b993a66d2 100644 --- a/docs/plugins/spotify.rst +++ b/docs/plugins/spotify.rst @@ -73,7 +73,7 @@ Here's an example:: spotify: mode: open region_filter: US - show_faiulres: on + show_failures: on tiebreak: first regex: [ diff --git a/docs/plugins/thumbnails.rst b/docs/plugins/thumbnails.rst index 267c149cf..5753a9f7e 100644 --- a/docs/plugins/thumbnails.rst +++ b/docs/plugins/thumbnails.rst @@ -1,7 +1,7 @@ Thumbnails Plugin ================== -The ``thumbnails`` plugin creates thumbnails your for album folders with the +The ``thumbnails`` plugin creates thumbnails for your album folders with the album cover. This works on freedesktop.org-compliant file managers such as Nautilus or Thunar, and is therefore POSIX-only. @@ -10,9 +10,9 @@ as the :doc:`/plugins/fetchart`. You'll need 2 additional python packages: `pyxdg` and `pathlib`. ``thumbnails`` needs to resize the covers, and therefore requires either -`ImageMagick`_ or `PIL`_. +`ImageMagick`_ or `Pillow`_. -.. _PIL: http://www.pythonware.com/products/pil/ +.. _Pillow: https://github.com/python-pillow/Pillow .. _ImageMagick: http://www.imagemagick.org/ Configuration diff --git a/docs/plugins/types.rst b/docs/plugins/types.rst index 67742ee0f..9847fec44 100644 --- a/docs/plugins/types.rst +++ b/docs/plugins/types.rst @@ -23,4 +23,4 @@ queries <numericquery>` to filter them.:: beet ls rating:4..5 beet modify --album "My favorite album" rating=5 - beet modify --album rating:4..5 + beet ls --album rating:4..5 diff --git a/docs/plugins/web.rst b/docs/plugins/web.rst index 7b2bfedef..35287acc8 100644 --- a/docs/plugins/web.rst +++ b/docs/plugins/web.rst @@ -63,6 +63,13 @@ configuration file. The available options are: Default: 8337. - **cors**: The CORS allowed origin (see :ref:`web-cors`, below). Default: CORS is disabled. +- **cors_supports_credentials**: Support credentials when using CORS (see :ref:`web-cors`, below). + Default: CORS_SUPPORTS_CREDENTIALS is disabled. +- **reverse_proxy**: If true, enable reverse proxy support (see + :ref:`reverse-proxy`, below). + Default: false. +- **include_paths**: If true, includes paths in item objects. + Default: false. Implementation -------------- @@ -72,7 +79,7 @@ The Web backend is built using a simple REST+JSON API with the excellent `Backbone.js`_. This allows future non-Web clients to use the same backend API. .. _Flask: http://flask.pocoo.org/ -.. _Backbone.js: http://documentcloud.github.com/backbone/ +.. _Backbone.js: http://backbonejs.org Eventually, to make the Web player really viable, we should use a Flash fallback for unsupported formats/browsers. There are a number of options for this: @@ -95,13 +102,17 @@ default, browsers will only allow access from clients running on the same server as the API. (You will get an arcane error about ``XMLHttpRequest`` otherwise.) A technology called `CORS`_ lets you relax this restriction. -If you want to use an in-browser client hosted elsewhere (or running from -a different server on your machine), first install the `flask-cors`_ plugin by -typing ``pip install flask-cors``. Then set the ``cors`` configuration option -to the "origin" (protocol, host, and optional port number) where the client is -served. Or set it to ``'*'`` to enable access from all origins. Note that -there are security implications if you set the origin to ``'*'``, so please -research this before using it. +If you want to use an in-browser client hosted elsewhere (or running from a +different server on your machine), first install the `flask-cors`_ plugin by +typing ``pip install flask-cors``. Then set the ``cors`` configuration option to +the "origin" (protocol, host, and optional port number) where the client is +served. Or set it to ``'*'`` to enable access from all origins. Note that there +are security implications if you set the origin to ``'*'``, so please research +this before using it. + +If the ``web`` server is behind a proxy that uses credentials, you might want +to set the ``cors_supports_credentials`` configuration option to true to let +in-browser clients log in. For example:: @@ -109,11 +120,37 @@ For example:: host: 0.0.0.0 cors: 'http://example.com' +.. _reverse-proxy: + +Reverse Proxy Support +--------------------- + +When the server is running behind a reverse proxy, you can tell the plugin to +respect forwarded headers. Specifically, this can help when you host the +plugin at a base URL other than the root ``/`` or when you use the proxy to +handle secure connections. Enable the ``reverse_proxy`` configuration option +if you do this. + +Technically, this option lets the proxy provide ``X-Script-Name`` and +``X-Scheme`` HTTP headers to control the plugin's the ``SCRIPT_NAME`` and its +``wsgi.url_scheme`` parameter. + +Here's a sample `Nginx`_ configuration that serves the web plugin under the +/beets directory:: + + location /beets { + proxy_pass http://127.0.0.1:8080; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Scheme $scheme; + proxy_set_header X-Script-Name /beets; + } + +.. _Nginx: https://www.nginx.com JSON API -------- - ``GET /item/`` ++++++++++++++ @@ -160,6 +197,16 @@ response includes all the items requested. If a track is not found it is silentl dropped from the response. +``GET /item/path/...`` +++++++++++++++++++++++ + +Look for an item at the given absolute path on the server. If it corresponds to +a track, return the track in the same format as ``/item/*``. + +If the server runs UNIX, you'll need to include an extra leading slash: +``http://localhost:8337/item/path//Users/beets/Music/Foo/Bar/Baz.mp3`` + + ``GET /item/query/querystring`` +++++++++++++++++++++++++++++++ @@ -197,6 +244,7 @@ The interface and response format is similar to the item API, except replacing the encapsulation key ``"items"`` with ``"albums"`` when requesting ``/album/`` or ``/album/5,7``. In addition we can request the cover art of an album with ``GET /album/5/art``. +You can also add the '?expand' flag to get the individual items of an album. ``GET /stats`` diff --git a/docs/plugins/zero.rst b/docs/plugins/zero.rst index 2682ee6ca..3ef241c87 100644 --- a/docs/plugins/zero.rst +++ b/docs/plugins/zero.rst @@ -5,6 +5,10 @@ The ``zero`` plugin allows you to null fields in files' metadata tags. Fields can be nulled unconditionally or conditioned on a pattern match. For example, the plugin can strip useless comments like "ripped by MyGreatRipper." +The plugin can work in one of two modes. The first mode, the default, is a +blacklist, where you choose the tags you want to remove. The second mode is a +whitelist, where you instead specify the tags you want to keep. + To use the ``zero`` plugin, enable the plugin in your configuration (see :ref:`using-plugins`). @@ -14,10 +18,15 @@ Configuration Make a ``zero:`` section in your configuration file. You can specify the fields to nullify and the conditions for nullifying them: +* Set ``auto`` to ``yes`` to null fields automatically on import. + Default: ``yes``. * Set ``fields`` to a whitespace-separated list of fields to change. You can get the list of all available fields by running ``beet fields``. In addition, the ``images`` field allows you to remove any images embedded in the media file. +* Set ``keep_fields`` to *invert* the logic of the plugin. Only these fields + will be kept; other fields will be removed. Remember to set only + ``fields`` or ``keep_fields``---not both! * To conditionally filter a field, use ``field: [regexp, regexp]`` to specify regular expressions. * By default this plugin only affects files' tags ; the beets database is left @@ -35,3 +44,19 @@ If a custom pattern is not defined for a given field, the field will be nulled unconditionally. Note that the plugin currently does not zero fields when importing "as-is". + +Manually Triggering Zero +------------------------ + +You can also type ``beet zero [QUERY]`` to manually invoke the plugin on music +in your library. + +Preserving Album Art +-------------------- + +If you use the ``keep_fields`` option, the plugin will remove embedded album +art from files' tags unless you tell it not to. To keep the album art, include +the special field ``images`` in the list. For example:: + + zero: + keep_fields: title artist album year track genre images diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index f39dad393..39a4b3f10 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -72,7 +72,8 @@ box. To extract `rar` files, install the `rarfile`_ package and the Optional command flags: * By default, the command copies files your the library directory and - updates the ID3 tags on your music. If you'd like to leave your music + updates the ID3 tags on your music. In order to move the files, instead of + copying, use the ``-m`` (move) option. If you'd like to leave your music files untouched, try the ``-C`` (don't copy) and ``-W`` (don't write tags) options. You can also disable this behavior by default in the configuration file (below). @@ -110,6 +111,12 @@ Optional command flags: time, when no subdirectories will be skipped. So consider enabling the ``incremental`` configuration option. +* When beets applies metadata to your music, it will retain the value of any + existing tags that weren't overwritten, and import them into the database. You + may prefer to only use existing metadata for finding matches, and to erase it + completely when new metadata is applied. You can enforce this behavior with + the ``--from-scratch`` option, or the ``from_scratch`` configuration option. + * By default, beets will proceed without asking if it finds a very close metadata match. To disable this and have the importer ask you every time, use the ``-t`` (for *timid*) option. @@ -132,6 +139,18 @@ Optional command flags: option. If set, beets will just print a list of files that it would otherwise import. +* If you already have a metadata backend ID that matches the items to be + imported, you can instruct beets to restrict the search to that ID instead of + searching for other candidates by using the ``--search-id SEARCH_ID`` option. + Multiple IDs can be specified by simply repeating the option several times. + +* You can supply ``--set field=value`` to assign `field` to `value` on import. + These assignments will merge with (and possibly override) the + :ref:`set_fields` configuration dictionary. You can use the option multiple + times on the command line, like so:: + + beet import --set genre="Alternative Rock" --set mood="emotional" + .. _rarfile: https://pypi.python.org/pypi/rarfile/2.2 .. only:: html @@ -206,7 +225,7 @@ remove `````` :: - beet remove [-ad] QUERY + beet remove [-adf] QUERY Remove music from your library. @@ -214,6 +233,7 @@ This command uses the same :doc:`query <query>` syntax as the ``list`` command. You'll be shown a list of the files that will be removed and asked to confirm. By default, this just removes entries from the library database; it doesn't touch the files on disk. To actually delete the files, use ``beet remove -d``. +If you do not want to be prompted to remove the files, use ``beet remove -f``. .. _modify-cmd: @@ -221,7 +241,7 @@ modify `````` :: - beet modify [-MWay] QUERY [FIELD=VALUE...] [FIELD!...] + beet modify [-MWay] [-f FORMAT] QUERY [FIELD=VALUE...] [FIELD!...] Change the metadata for items or albums in the database. @@ -231,13 +251,27 @@ artist="Tom Tom Club"`` will change the artist for the track "Genius of Love." To remove fields (which is only possible for flexible attributes), follow a field name with an exclamation point: ``field!``. -The ``-a`` switch operates on albums instead of -individual tracks. Items will automatically be moved around when necessary if -they're in your library directory, but you can disable that with ``-M``. Tags -will be written to the files according to the settings you have for imports, -but these can be overridden with ``-w`` (write tags, the default) and ``-W`` -(don't write tags). Finally, this command politely asks for your permission -before making any changes, but you can skip that prompt with the ``-y`` switch. +The ``-a`` switch operates on albums instead of individual tracks. Without +this flag, the command will only change *track-level* data, even if all the +tracks belong to the same album. If you want to change an *album-level* field, +such as ``year`` or ``albumartist``, you'll want to use the ``-a`` flag to +avoid a confusing situation where the data for individual tracks conflicts +with the data for the whole album. + +Items will automatically be moved around when necessary if they're in your +library directory, but you can disable that with ``-M``. Tags will be written +to the files according to the settings you have for imports, but these can be +overridden with ``-w`` (write tags, the default) and ``-W`` (don't write +tags). + +When you run the ``modify`` command, it prints a list of all +affected items in the library and asks for your permission before making any +changes. You can then choose to abort the change (type `n`), confirm +(`y`), or interactively choose some of the items (`s`). In the latter case, +the command will prompt you for every matching item or album and invite you to +type `y` or `n`. This option lets you choose precisely which data to change +without spending too much time to carefully craft a query. To skip the prompts +entirely, use the ``-y`` option. .. _move-cmd: @@ -245,7 +279,7 @@ move ```` :: - beet move [-cap] [-d DIR] QUERY + beet move [-capt] [-d DIR] QUERY Move or copy items in your library. @@ -254,10 +288,12 @@ query are renamed into your library directory structure. By specifying a destination directory with ``-d`` manually, you can move items matching a query anywhere in your filesystem. The ``-c`` option copies files instead of moving them. As with other commands, the ``-a`` option matches albums instead of items. +The ``-e`` flag (for "export") copies files without changing the database. To perform a "dry run", just use the ``-p`` (for "pretend") flag. This will -show you all how the files would be moved but won't actually change anything -on disk. +show you a list of files that would be moved but won't actually change anything +on disk. The ``-t`` option sets the timid mode which will ask again +before really moving or copying the files. .. _update-cmd: @@ -265,7 +301,7 @@ update `````` :: - beet update [-aM] QUERY + beet update [-F] FIELD [-aM] QUERY Update the library (and, optionally, move files) to reflect out-of-band metadata changes and file deletions. @@ -281,6 +317,11 @@ To perform a "dry run" of an update, just use the ``-p`` (for "pretend") flag. This will show you all the proposed changes but won't actually change anything on disk. +By default, all the changed metadata will be populated back to the database. +If you only want certain fields to be written, specify them with the ```-F``` +flags (which can be used multiple times). For the list of supported fields, +please see ```beet fields```. + When an updated track is part of an album, the album-level fields of *all* tracks from the album are also updated. (Specifically, the command copies album-level data from the first track on the album and applies it to the @@ -311,7 +352,7 @@ You can think of this command as the opposite of :ref:`update-cmd`. The ``-p`` option previews metadata changes without actually applying them. -The ``-f`` option forces a write to the file, even if the file tags match the database. This is useful for making sure that enabled plugins that run on write (e.g., the Scrub and Zero plugins) are run on the file. +The ``-f`` option forces a write to the file, even if the file tags match the database. This is useful for making sure that enabled plugins that run on write (e.g., the Scrub and Zero plugins) are run on the file. @@ -339,7 +380,9 @@ fields beet fields Show the item and album metadata fields available for use in :doc:`query` and -:doc:`pathformat`. Includes any template fields provided by plugins. +:doc:`pathformat`. The listing includes any template fields provided by +plugins and any flexible attributes you've manually assigned to your items and +albums. .. _config-cmd: @@ -380,7 +423,11 @@ import ...``. * ``-v``: verbose mode; prints out a deluge of debugging information. Please use this flag when reporting bugs. You can use it twice, as in ``-vv``, to make beets even more verbose. -* ``-c FILE``: read a specified YAML :doc:`configuration file <config>`. +* ``-c FILE``: read a specified YAML :doc:`configuration file <config>`. This + configuration works as an overlay: rather than replacing your normal + configuration options entirely, the two are merged. Any individual options set + in this config file will override the corresponding settings in your base + configuration. Beets also uses the ``BEETSDIR`` environment variable to look for configuration and data. @@ -427,7 +474,10 @@ later on you will want to re-generate the script. zsh ``` -If you use zsh, take a look at the included `completion script`_. +If you use zsh, take a look at the included `completion script`_. The script +should be placed in a directory that is part of your ``fpath``, and `not` +sourced in your ``.zshrc``. Running ``echo $fpath`` will give you a list of +valid directories. Another approach is to use zsh's bash completion compatibility. This snippet defines some bash-specific functions to make this work without errors:: @@ -439,7 +489,7 @@ defines some bash-specific functions to make this work without errors:: _filedir() { :; } eval "$(beet completion)" -.. _completion script: https://github.com/sampsyo/beets/blob/master/extra/_beet +.. _completion script: https://github.com/beetbox/beets/blob/master/extra/_beet .. only:: man diff --git a/docs/reference/config.rst b/docs/reference/config.rst index e01711111..94dab4345 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -83,13 +83,27 @@ have multiple paths, format them as a YAML list like so:: - /path/one - /path/two +.. _ignore: + ignore ~~~~~~ A list of glob patterns specifying file and directory names to be ignored when -importing. By default, this consists of ``.*``, ``*~``, and ``System Volume -Information`` (i.e., beets ignores Unix-style hidden files, backup files, and -a directory that appears at the root of some Windows filesystems). +importing. By default, this consists of ``.*``, ``*~``, ``System Volume +Information``, ``lost+found`` (i.e., beets ignores Unix-style hidden files, +backup files, and directories that appears at the root of some Linux and Windows +filesystems). + +.. _ignore_hidden: + +ignore_hidden +~~~~~~~~~~~~~ + +Either ``yes`` or ``no``; whether to ignore hidden files when importing. On +Windows, the "Hidden" property of files is used to detect whether or not a file +is hidden. On OS X, the file's "IsHidden" flag is used to detect whether or not +a file is hidden. On both OS X and other platforms (excluding Windows), files +(and directories) starting with a dot are detected as hidden files. .. _replace: @@ -117,6 +131,7 @@ unexpected behavior on all popular platforms:: '\.$': _ '\s+$': '' '^\s+': '' + '^-': _ These substitutions remove forward and back slashes, leading dots, and control characters—all of which is a good idea on any OS. The fourth line @@ -215,7 +230,7 @@ Default sort order to use when fetching items from the database. Defaults to sort_album ~~~~~~~~~~ -Default sort order to use when fetching items from the database. Defaults to +Default sort order to use when fetching albums from the database. Defaults to ``albumartist+ album+``. Explicit sort orders override this default. .. _sort_case_insensitive: @@ -238,6 +253,15 @@ Either ``yes`` or ``no``, indicating whether matched albums should have their That is, if this option is turned on, then ``year`` will always equal ``original_year`` and so on. Default: ``no``. +.. _artist_credit: + +artist_credit +~~~~~~~~~~~~~ + +Either ``yes`` or ``no``, indicating whether matched tracks and albums should +use the artist credit, rather than the artist. That is, if this option is turned +on, then ``artist`` will contain the artist as credited on the release. + .. _per_disc_numbering: per_disc_numbering @@ -268,7 +292,8 @@ terminal_encoding ~~~~~~~~~~~~~~~~~ The text encoding, as `known to Python`_, to use for messages printed to the -standard output. By default, this is determined automatically from the locale +standard output. It's also used to read messages from the standard input. +By default, this is determined automatically from the locale environment variables. .. _known to python: http://docs.python.org/2/library/codecs.html#standard-encodings @@ -304,6 +329,15 @@ By default, beets writes MP3 tags using the ID3v2.4 standard, the latest version of ID3. Enable this option to instead use the older ID3v2.3 standard, which is preferred by certain older software such as Windows Media Player. +.. _va_name: + +va_name +~~~~~~~ + +Sets the albumartist for various-artist compilations. Defaults to ``'Various +Artists'`` (the MusicBrainz standard). Affects other sources, such as +:doc:`/plugins/discogs`, too. + UI Options ---------- @@ -363,6 +397,8 @@ file that looks like this:: These options are available in this section: +.. _config-import-write: + write ~~~~~ @@ -370,6 +406,8 @@ Either ``yes`` or ``no``, controlling whether metadata (e.g., ID3) tags are written to files when using ``beet import``. Defaults to ``yes``. The ``-w`` and ``-W`` command-line options override this setting. +.. _config-import-copy: + copy ~~~~ @@ -380,6 +418,8 @@ overridden with the ``-c`` and ``-C`` command-line options. The option is ignored if ``move`` is enabled (i.e., beets can move or copy files but it doesn't make sense to do both). +.. _config-import-move: + move ~~~~ @@ -403,8 +443,8 @@ link ~~~~ Either ``yes`` or ``no``, indicating whether to use symbolic links instead of -moving or copying files. (It conflicts with the ``move`` and ``copy`` -options.) Defaults to ``no``. +moving or copying files. (It conflicts with the ``move``, ``copy`` and +``hardlink`` options.) Defaults to ``no``. This option only works on platforms that support symbolic links: i.e., Unixes. It will fail on Windows. @@ -412,6 +452,19 @@ It will fail on Windows. It's likely that you'll also want to set ``write`` to ``no`` if you use this option to preserve the metadata on the linked files. +.. _hardlink: + +hardlink +~~~~~~~~ + +Either ``yes`` or ``no``, indicating whether to use hard links instead of +moving or copying or symlinking files. (It conflicts with the ``move``, +``copy``, and ``link`` options.) Defaults to ``no``. + +As with symbolic links (see :ref:`link`, above), this will not work on Windows +and you will want to set ``write`` to ``no``. Otherwise, metadata on the +original file will be modified. + resume ~~~~~~ @@ -431,6 +484,25 @@ Either ``yes`` or ``no``, controlling whether imported directories are recorded and whether these recorded directories are skipped. This corresponds to the ``-i`` flag to ``beet import``. +.. _incremental_skip_later: + +incremental_skip_later +~~~~~~~~~~~~~~~~~~~~~~ + +Either ``yes`` or ``no``, controlling whether skipped directories are +recorded in the incremental list. Set this option to ``yes`` if you would +like to revisit skipped directories later whilst using incremental +mode. Defaults to ``no``. + +.. _from_scratch: + +from_scratch +~~~~~~~~~~~~ + +Either ``yes`` or ``no`` (default), controlling whether existing metadata is +discarded when a match is applied. This corresponds to the ``--from_scratch`` +flag to ``beet import``. + quiet_fallback ~~~~~~~~~~~~~~ @@ -522,6 +594,43 @@ with the ``-a`` flag to the :ref:`import-cmd` command.) Default: ``yes``. +.. _duplicate_action: + +duplicate_action +~~~~~~~~~~~~~~~~ + +Either ``skip``, ``keep``, ``remove``, ``merge`` or ``ask``. +Controls how duplicates are treated in import task. +"skip" means that new item(album or track) will be skipped; +"keep" means keep both old and new items; "remove" means remove old +item; "merge" means merge into one album; "ask" means the user +should be prompted for the action each time. The default is ``ask``. + +.. _bell: + +bell +~~~~ + +Ring the terminal bell to get your attention when the importer needs your input. + +Default: ``no``. + +.. _set_fields: + +set_fields +~~~~~~~~~~ + +A dictionary indicating fields to set to values for newly imported music. +Here's an example:: + + set_fields: + genre: 'To Listen' + collection: 'Unordered' + +Other field/value pairs supplied via the ``--set`` option on the command-line +override any settings here for fields with the same name. + +Default: ``{}`` (empty). .. _musicbrainz-config: @@ -579,7 +688,7 @@ automatically accept any matches above 90% similarity, use:: The default strong recommendation threshold is 0.04. The ``medium_rec_thresh`` and ``rec_gap_thresh`` options work similarly. When a -match is above the *medium* recommendation threshold or the distance between it +match is below the *medium* recommendation threshold or the distance between it and the next-best match is above the *gap* threshold, the importer will suggest that match but not automatically confirm it. Otherwise, you'll see a list of options to choose from. @@ -684,6 +793,33 @@ want to enforce to the ``required`` setting:: No tags are required by default. +.. _ignored_media: + +ignored_media +~~~~~~~~~~~~~ + +A list of media (i.e., formats) in metadata databases to ignore when matching +music. You can use this to ignore all media that usually contain video instead +of audio, for example:: + + match: + ignored_media: ['Data CD', 'DVD', 'DVD-Video', 'Blu-ray', 'HD-DVD', + 'VCD', 'SVCD', 'UMD', 'VHS'] + +No formats are ignored by default. + + +.. _ignore_video_tracks: + +ignore_video_tracks +~~~~~~~~~~~~~~~~~~~ + +By default, video tracks within a release will be ignored. If you want them to +be included (for example if you would like to track the audio-only versions of +the video tracks), set it to ``no``. + +Default: ``yes``. + .. _path-format-config: Path Format Configuration @@ -702,7 +838,7 @@ defaults look like this:: singleton: Non-Album/$artist/$title comp: Compilations/$album%aunique{}/$track $title -Note the use of ``$albumartist`` instead of ``$artist``; this ensure that albums +Note the use of ``$albumartist`` instead of ``$artist``; this ensures that albums will be well-organized. For more about these format strings, see :doc:`pathformat`. The ``aunique{}`` function ensures that identically-named albums are placed in different directories; see :ref:`aunique` for details. @@ -775,21 +911,16 @@ Example Here's an example file:: - library: /var/music.blb directory: /var/mp3 import: copy: yes write: yes - resume: ask - quiet_fallback: skip - timid: no log: beetslog.txt - ignore: .AppleDouble ._* *~ .DS_Store art_filename: albumart plugins: bpd pluginpath: ~/beets/myplugins - threaded: yes - color: yes + ui: + color: yes paths: default: $genre/$albumartist/$album/$track $title diff --git a/docs/reference/pathformat.rst b/docs/reference/pathformat.rst index 8efe54cd2..667be3150 100644 --- a/docs/reference/pathformat.rst +++ b/docs/reference/pathformat.rst @@ -71,11 +71,21 @@ These functions are built in to beets: For example, "café" becomes "cafe". Uses the mapping provided by the `unidecode module`_. See the :ref:`asciify-paths` configuration option. -* ``%aunique{identifiers,disambiguators}``: Provides a unique string to - disambiguate similar albums in the database. See :ref:`aunique`, below. +* ``%aunique{identifiers,disambiguators,brackets}``: Provides a unique string + to disambiguate similar albums in the database. See :ref:`aunique`, below. * ``%time{date_time,format}``: Return the date and time in any format accepted by `strftime`_. For example, to get the year some music was added to your library, use ``%time{$added,%Y}``. +* ``%first{text}``: Returns the first item, separated by ``;`` (a semicolon + followed by a space). + You can use ``%first{text,count,skip}``, where ``count`` is the number of + items (default 1) and ``skip`` is number to skip (default 0). You can also use + ``%first{text,count,skip,sep,join}`` where ``sep`` is the separator, like + ``;`` or ``/`` and join is the text to concatenate the items. +* ``%ifdef{field}``, ``%ifdef{field,truetext}`` or + ``%ifdef{field,truetext,falsetext}``: If ``field`` exists, then return + ``truetext`` or ``field`` (default). Otherwise, returns ``falsetext``. + The ``field`` should be entered without ``$``. .. _unidecode module: http://pypi.python.org/pypi/Unidecode .. _strftime: http://docs.python.org/2/library/time.html#time.strftime @@ -102,14 +112,16 @@ will expand to "[2008]" for one album and "[2010]" for the other. The function detects that you have two albums with the same artist and title but that they have different release years. -For full flexibility, the ``%aunique`` function takes two arguments, each of -which are whitespace-separated lists of album field names: a set of -*identifiers* and a set of *disambiguators*. Any group of albums with identical -values for all the identifiers will be considered "duplicates". Then, the -function tries each disambiguator field, looking for one that distinguishes each -of the duplicate albums from each other. The first such field is used as the -result for ``%aunique``. If no field suffices, an arbitrary number is used to -distinguish the two albums. +For full flexibility, the ``%aunique`` function takes three arguments. The +first two are whitespace-separated lists of album field names: a set of +*identifiers* and a set of *disambiguators*. The third argument is a pair of +characters used to surround the disambiguator. + +Any group of albums with identical values for all the identifiers will be +considered "duplicates". Then, the function tries each disambiguator field, +looking for one that distinguishes each of the duplicate albums from each +other. The first such field is used as the result for ``%aunique``. If no field +suffices, an arbitrary number is used to distinguish the two albums. The default identifiers are ``albumartist album`` and the default disambiguators are ``albumtype year label catalognum albumdisambig``. So you can get reasonable @@ -117,6 +129,10 @@ disambiguation behavior if you just use ``%aunique{}`` with no parameters in your path forms (as in the default path formats), but you can customize the disambiguation if, for example, you include the year by default in path formats. +The default characters used as brackets are ``[]``. To change this, provide a +third argument to the ``%aunique`` function consisting of two characters: the left +and right brackets. Or, to turn off bracketing entirely, leave argument blank. + One caveat: When you import an album that is named identically to one already in your library, the *first* album—the one already in your library— will not consider itself a duplicate at import time. This means that ``%aunique{}`` will @@ -132,11 +148,17 @@ Syntax Details The characters ``$``, ``%``, ``{``, ``}``, and ``,`` are "special" in the path template syntax. This means that, for example, if you want a ``%`` character to appear in your paths, you'll need to be careful that you don't accidentally -write a function call. To escape any of these characters (except ``{``), prefix -it with a ``$``. For example, ``$$`` becomes ``$``; ``$%`` becomes ``%``, etc. -The only exception is ``${``, which is ambiguous with the variable reference -syntax (like ``${title}``). To insert a ``{`` alone, it's always sufficient to -just type ``{``. +write a function call. To escape any of these characters (except ``{``, and +``,`` outside a function argument), prefix it with a ``$``. For example, +``$$`` becomes ``$``; ``$%`` becomes ``%``, etc. The only exceptions are: + +* ``${``, which is ambiguous with the variable reference syntax (like + ``${title}``). To insert a ``{`` alone, it's always sufficient to just type + ``{``. +* commas are used as argument separators in function calls. Inside of a + function's argument, use ``$,`` to get a literal ``,`` character. Outside of + any function argument, escaping is not necessary: ``,`` by itself will + produce ``,`` in the output. If a value or function is undefined, the syntax is simply left unreplaced. For example, if you write ``$foo`` in a path template, this will yield ``$foo`` in diff --git a/docs/reference/query.rst b/docs/reference/query.rst index e2091bb14..d103d9aec 100644 --- a/docs/reference/query.rst +++ b/docs/reference/query.rst @@ -6,6 +6,8 @@ searches that select tracks and albums from your library. This page explains the query string syntax, which is meant to vaguely resemble the syntax used by Web search engines. +.. _keywordquery: + Keyword ------- @@ -13,7 +15,7 @@ This command:: $ beet list love -will show all tracks matching the query string ``love``. Any unadorned word like this matches *anywhere* in a track's metadata, so you'll see all the tracks with "love" in their title, in their album name, in the artist, and so on. +will show all tracks matching the query string ``love``. By default any unadorned word like this matches in a track's title, artist, album name, album artist, genre and comments. See below on how to search other fields. For example, this is what I might see when I run the command above:: @@ -144,6 +146,11 @@ and this command finds MP3 files with bitrates of 128k or lower:: $ beet list format:MP3 bitrate:..128000 +The ``length`` field also lets you use a "M:SS" format. For example, this +query finds tracks that are less than four and a half minutes in length:: + + $ beet list length:..4:30 + .. _datequery: @@ -181,6 +188,81 @@ Find all items with a file modification time between 2008-12-01 and $ beet ls 'mtime:2008-12-01..2008-12-02' +You can also add an optional time value to date queries, specifying hours, +minutes, and seconds. + +Times are separated from dates by a space, an uppercase 'T' or a lowercase +'t', for example: ``2008-12-01T23:59:59``. If you specify a time, then the +date must contain a year, month, and day. The minutes and seconds are +optional. + +Here is an example that finds all items added on 2008-12-01 at or after 22:00 +but before 23:00:: + + $ beet ls 'added:2008-12-01T22' + +To find all items added on or after 2008-12-01 at 22:45:: + + $ beet ls 'added:2008-12-01T22:45..' + +To find all items added on 2008-12-01, at or after 22:45:20 but before +22:45:41:: + + $ beet ls 'added:2008-12-01T22:45:20..2008-12-01T22:45:40' + +Here are example of the three ways to separate dates from times. All of these +queries do the same thing:: + + $ beet ls 'added:2008-12-01T22:45:20' + $ beet ls 'added:2008-12-01t22:45:20' + $ beet ls 'added:2008-12-01 22:45:20' + +You can also use *relative* dates. For example, ``-3w`` means three weeks ago, +and ``+4d`` means four days in the future. A relative date has three parts: + +- Either ``+`` or ``-``, to indicate the past or the future. The sign is + optional; if you leave this off, it defaults to the future. +- A number. +- A letter indicating the unit: ``d``, ``w``, ``m`` or ``y``, meaning days, + weeks, months or years. (A "month" is always 30 days and a "year" is always + 365 days.) + +Here's an example that finds all the albums added since last week:: + + $ beet ls -a 'added:-1w..' + +And here's an example that lists items added in a two-week period starting +four weeks ago:: + + $ beet ls 'added:-6w..-4w' + +.. _not_query: + +Query Term Negation +------------------- + +Query terms can also be negated, acting like a Boolean "not," by prefixing +them with ``-`` or ``^``. This has the effect of returning all the items that +do **not** match the query term. For example, this command:: + + $ beet list ^love + +matches all the songs in the library that do not have "love" in any of their +fields. + +Negation can be combined with the rest of the query mechanisms, so you can +negate specific fields, regular expressions, etc. For example, this command:: + + $ beet list -a artist:dylan ^year:1980..1989 "^album::the(y)?" + +matches all the albums with an artist containing "dylan", but excluding those +released in the eighties and those that have "the" or "they" on the title. + +The syntax supports both ``^`` and ``-`` as synonyms because the latter +indicates flags on the command line. To use a minus sign in a command-line +query, use a double dash ``--`` to separate the options from the query:: + + $ beet list -a -- artist:dylan -year:1980..1990 "-album::the(y)?" .. _pathquery: @@ -202,8 +284,8 @@ Note that this only matches items that are *already in your library*, so a path query won't necessarily find *all* the audio files in a directory---just the ones you've already added to your beets library. -Path queries are case-sensitive on most platforms but case-insensitive on -Windows. +Path queries are case sensitive if the queried path is on a case-sensitive +filesystem. .. _query-sort: @@ -234,5 +316,9 @@ sort order: ``Bar foo Qux``. This behavior can be changed with the result in lower-case values being placed after upper-case values, e.g., ``Bar Qux foo``. +Note that when sorting by fields that are not present on all items (such as +flexible fields, or those defined by plugins) in *ascending* order, the items +that lack that particular field will be listed at the *beginning* of the list. + You can set the default sorting behavior with the :ref:`sort_item` and :ref:`sort_album` configuration options. diff --git a/docs/refresh_safari.js b/docs/refresh_safari.js deleted file mode 100644 index 7f5cc0ccc..000000000 --- a/docs/refresh_safari.js +++ /dev/null @@ -1,19 +0,0 @@ -var safari = Application('com.apple.Safari'); - -for (var i = 0; i < safari.windows.length; ++i) { - var win = safari.windows[i]; - var tabs = win.tabs; - if (Object.keys(tabs).length) { - for (var j = 0; j < win.tabs.length; ++j) { - var tab = win.tabs[j]; - var url = tab.url(); - if (url.indexOf("file:") == 0) { - // A local file URL. - safari.doJavaScript("location.reload();", { in: tab }); - console.log(url); - } - } - } -} - -'done'; diff --git a/extra/_beet b/extra/_beet index 055072943..23155b8e5 100644 --- a/extra/_beet +++ b/extra/_beet @@ -1,6 +1,20 @@ #compdef beet -# Completion for beets music library manager and MusicBrainz tagger: http://beets.radbox.org/ +# zsh completion for beets music library manager and MusicBrainz tagger: http://beets.radbox.org/ + +# NOTE: it will be very slow the first time you try to complete in a zsh shell (especially if you've enable many plugins) +# You can make it faster in future by creating a cached version: +# 1) perform a query completion with this file (_beet), e.g. do: beet list artist:"<TAB> +# to create the completion function (takes a few seconds) +# 2) save a copy of the completion function: which _beet > _beet_cached +# 3) save a copy of the query completion function: which _beet_query > _beet_query_cached +# 4) copy the contents of _beet_query_cached to the top of _beet_cached +# 5) copy and paste the _beet_field_values function from _beet to the top of _beet_cached +# 6) add the following line to the top of _beet_cached: #compdef beet +# 7) add the following line to the bottom of _beet_cached: _beet "$@" +# 8) save _beet_cached to your completions directory (e.g. /usr/share/zsh/functions/Completion) +# 9) add the following line to your .zshrc file: compdef _beet_cached beet +# You will need to repeat this proceedure each time you enable new plugins if you want them to complete properly. # useful: argument to _regex_arguments for matching any word local matchany=/$'[^\0]##\0'/ @@ -13,15 +27,23 @@ fields=(`beet fields | grep -G '^ ' | sort -u | colrm 1 2`) # regexps for matching query and modify terms on the command line matchquery=/"(${(j/|/)fields[@]})"$':[^\0]##\0'/ matchmodify=/"(${(j/|/)fields[@]})"$'(=[^\0]##|!)\0'/ + +# Function for joining grouped lines of output into single lines (taken from _completion_helpers) +function _join_lines() { + awk -v SEP="$1" -v ARG2="$2" -v START="$3" -v END2="$4" 'BEGIN {if(START==""){f=1}{f=0}; + if(ARG2 ~ "^[0-9]+"){LINE1 = "^[[:space:]]{,"ARG2"}[^[:space:]]"}else{LINE1 = ARG2}} + ($0 ~ END2 && f>0 && END2!="") {exit} + ($0 ~ START && f<1) {f=1; if(length(START)!=0){next}} + ($0 ~ LINE1 && f>0) {if(f<2){f=2; printf("%s",$0)}else{printf("\n%s",$0)}; next} + (f>1) {gsub(/^[[:space:]]+|[[:space:]]+$/,"",$0); printf("%s%s",SEP, $0); next} + END {print ""}' +} + # Function for getting unique values for field from database (you may need to change the path to the database). function _beet_field_values() { local -a output fieldvals local library="$(beet config|grep library|cut -f 2 -d ' ')" - if [ -z "$library" ]; then - # Use default library location if there is no user defined one - library="~/.config/beets/library.db" - fi output=$(sqlite3 ${~library} "select distinct $1 from items;") case $1 in @@ -54,7 +76,7 @@ query=( \( "$matchquery" ":query:query string:{_beet_query}" \) \( "$matchquery" modify=( \( "$matchmodify" ":modify:modify string:$modifyelem" \) \( "$matchmodify" ":modify:modify string:$modifyelem" \) \# ) # arguments to _regex_arguments for completing files and directories -local -a files dirs +local -a files dirs files=("$matchany" ':file:file:_files') dirs=("$matchany" ':dir:directory:_dirs') @@ -86,7 +108,7 @@ retagopt='-L:retag items matching a query:${query[@]}' skipopt='-i:skip already-imported directories' noskipopt='-I:do not skip already-imported directories' flatopt='--flat:import an entire tree as a single album' -groupopt='-g:group tracks in a folder into seperate albums' +groupopt='-g:group tracks in a folder into separate albums' editopt='-e:edit user configuration with $EDITOR' defaultopt='-d:include the default configuration' copynomoveopt='-c:copy instead of moving' @@ -106,45 +128,45 @@ function _beet_subcmd_options() regex_words=() for i in ${${(f)"$(beet help $1 | awk '/^ +-/{if(x)print x;x=$0;next}/^ *$/{if(x) exit}{if(x) x=x$0}END{print x}')"}[@]} do - shortopt="${i[(w)1]/,/}" - optarg="${$(echo ${i[(w)2]}|grep -o '[A-Z]\+')[(w)1]}" - optdesc="${${${${${i[(w)2,-1]/[A-Z, ]#--[a-z]##[=A-Z]# #/}//:/-}//\[/(}//\]/)}//\'/}" + opt="${i[(w)1]/,/}" + optarg="${${${i## #[-a-zA-Z]# }##[- ]##*}%%[, ]*}" + optdesc="${${${${${i[(w)2,-1]/[A-Z, ]#--[-a-z]##[=A-Z]# #/}//:/-}//\[/(}//\]/)}//\'/}" case $optarg in ("") - if [[ "$1" == "import" && "$shortopt" == "-L" ]]; then - regex_words+=("$shortopt:$optdesc:\${query[@]}") + if [[ "$1" == "import" && "$opt" == "-L" ]]; then + regex_words+=("$opt:$optdesc:\${query[@]}") else - regex_words+=("$shortopt:$optdesc") + regex_words+=("$opt:$optdesc") fi ;; (LOG) - regex_words+=("$shortopt:$optdesc:\$files") + regex_words+=("$opt:$optdesc:\$files") ;; (CONFIG) local -a configfile configfile=("$matchany" ':file:config file:{_files -g *.yaml}') - regex_words+=("$shortopt:$optdesc:\$configfile") + regex_words+=("$opt:$optdesc:\$configfile") ;; (LIB|LIBRARY) local -a libfile libfile=("$matchany" ':file:database file:{_files -g *.db}') - regex_words+=("$shortopt:$optdesc:\$libfile") + regex_words+=("$opt:$optdesc:\$libfile") ;; (DIR|DIRECTORY) - regex_words+=("$shortopt:$optdesc:\$dirs") + regex_words+=("$opt:$optdesc:\$dirs") ;; (SOURCE) if [[ $1 -eq lastgenre ]]; then local -a lastgenresource lastgenresource=(/$'(artist|album|track)\0'/ ':source:genre source:(artist album track)') - regex_words+=("$shortopt:$optdesc:\$lastgenresource") + regex_words+=("$opt:$optdesc:\$lastgenresource") else - regex_words+=("$shortopt:$optdesc:\$matchany") + regex_words+=("$opt:$optdesc:\$matchany") fi ;; (*) - regex_words+=("$shortopt:$optdesc:\$matchany") + regex_words+=("$opt:$optdesc:\$matchany") ;; esac done @@ -154,20 +176,21 @@ function _beet_subcmd_options() # Now build the arguments to _regex_arguments for each subcommand. local -a options regex_words_subcmds regex_words_help local subcmd cmddesc -for i in ${${(f)"$(beet help | awk 'f;/Commands:/{f=1}' | grep '^ \w.*')"[@]}[@]} +for i in ${${(f)"$(beet help | _join_lines ' ' 3 'Commands:')"[@]}[@]} do subcmd="${i[(w)1]}" + # remove first word and parenthesised alias, replace : with -, [ with (, ] with ), and remove single quotes cmddesc="${${${${${i[(w)2,-1]##\(*\) #}//:/-}//\[/(}//\]/)}//\'/}" case $subcmd in (config) - _regex_words options "config options" "$helpopt" "$pathopt" "$editopt" "$defaultopt" + _regex_words options "config options" "$helpopt" "$pathopt" "$editopt" "$defaultopt" options=("${reply[@]}") ;; (import) - _regex_words options "import options" "$helpopt" "$writeopt" "$nowriteopt" "$copyopt" "$nocopyopt" "$inferopt" \ - "$noinferopt" "$resumeopt" "$noresumeopt" "$nopromptopt" "$logopt" "$individualopt" "$confirmopt" "$retagopt" \ - "$skipopt" "$noskipopt" "$flatopt" "$groupopt" + _regex_words options "import options" "$helpopt" "$writeopt" "$nowriteopt" "$copyopt" "$nocopyopt"\ + "$inferopt" "$noinferopt" "$resumeopt" "$noresumeopt" "$nopromptopt" "$logopt" "$individualopt" "$confirmopt"\ + "$retagopt" "$skipopt" "$noskipopt" "$flatopt" "$groupopt" options=( "${reply[@]}" \# "${files[@]}" \# ) ;; (list) @@ -188,7 +211,7 @@ do options=( "${reply[@]}" \# "${query[@]}" ) ;; (stats) - _regex_words options "stats options" "$helpopt" "$exactopt" + _regex_words options "stats options" "$helpopt" "$exactopt" options=( "${reply[@]}" \# "${query[@]}" ) ;; (update) @@ -204,9 +227,9 @@ do ;; (help) # The help subcommand is treated separately - continue + continue ;; - (*) # completions for plugin commands are generated using _beet_subcmd_options + (*) # completions for plugin commands are generated using _beet_subcmd_options _beet_subcmd_options "$subcmd" options=( \( "${reply[@]}" \# "${query[@]}" \) ) ;; @@ -241,6 +264,6 @@ zstyle ":completion:${curcontext}:" tag-order '! options' # Execute the completion function _beet "$@" -# Local Variables: +# Local Variables: # mode:shell-script # End: diff --git a/extra/beets.reg b/extra/beets.reg index 30fb6e0e4..c02303d3d 100644 Binary files a/extra/beets.reg and b/extra/beets.reg differ diff --git a/extra/release.py b/extra/release.py index de4d55029..b0b7a96e0 100755 --- a/extra/release.py +++ b/extra/release.py @@ -1,4 +1,6 @@ #!/usr/bin/env python3 +# -*- coding: utf-8 -*- + """A utility script for automating the beets release process. """ import click @@ -33,8 +35,8 @@ VERSION_LOCS = [ os.path.join(BASE, 'beets', '__init__.py'), [ ( - r'__version__\s*=\s*[\'"]([0-9\.]+)[\'"]', - "__version__ = '{version}'", + r'__version__\s*=\s*u[\'"]([0-9\.]+)[\'"]', + "__version__ = u'{version}'", ) ] ), @@ -62,6 +64,9 @@ VERSION_LOCS = [ ), ] +GITHUB_USER = 'beetbox' +GITHUB_REPO = 'beets' + def bump_version(version): """Update the version number in setup.py, docs config, changelog, @@ -161,11 +166,11 @@ def rst2md(text): """Use Pandoc to convert text from ReST to Markdown. """ pandoc = subprocess.Popen( - ['pandoc', '--from=rst', '--to=markdown', '--no-wrap'], + ['pandoc', '--from=rst', '--to=markdown', '--wrap=none'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) - stdout, _ = pandoc.communicate(text.encode('utf8')) - md = stdout.decode('utf8').strip() + stdout, _ = pandoc.communicate(text.encode('utf-8')) + md = stdout.decode('utf-8').strip() # Fix up odd spacing in lists. return re.sub(r'^- ', '- ', md, flags=re.M) @@ -310,5 +315,40 @@ def publish(): subprocess.check_call(['twine', 'upload', path]) +@release.command() +def ghrelease(): + """Create a GitHub release using the `github-release` command-line + tool. + + Reads the changelog to upload from `changelog.md`. Uploads the + tarball from the `dist` directory. + """ + version = get_version(1) + tag = 'v' + version + + # Load the changelog. + with open(os.path.join(BASE, 'changelog.md')) as f: + cl_md = f.read() + + # Create the release. + subprocess.check_call([ + 'github-release', 'release', + '-u', GITHUB_USER, '-r', GITHUB_REPO, + '--tag', tag, + '--name', '{} {}'.format(GITHUB_REPO, version), + '--description', cl_md, + ]) + + # Attach the release tarball. + tarball = os.path.join(BASE, 'dist', 'beets-{}.tar.gz'.format(version)) + subprocess.check_call([ + 'github-release', 'upload', + '-u', GITHUB_USER, '-r', GITHUB_REPO, + '--tag', tag, + '--name', os.path.basename(tarball), + '--file', tarball, + ]) + + if __name__ == '__main__': release() diff --git a/setup.cfg b/setup.cfg index 40eda74ec..be2dbe543 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,10 +1,23 @@ [nosetests] verbosity=1 logging-clear-handlers=1 -eval-attr="!=slow" [flake8] -# E241 missing whitespace after ',' (used to align visually) -# E221 multiple spaces before operator (used to align visually) -# E731 do not assign a lambda expression, use a def -ignore=E241,E221,E731 +min-version=2.7 +accept-encodings=utf-8 +# Errors we ignore: +# - E121,E123,E126,E226,E24,E704,W503,W504 flake8 default ignores (have to be listed here to not be overridden) +# - E221: multiple spaces before operator (used to align visually) +# - E731: do not assign a lambda expression, use a def +# - F405 object may be undefined, or defined from star imports +# - C901: function/method complexity +# - E305: spacing after a declaration (might be nice to change eventually) +# `flake8-future-import` errors we ignore: +# - FI50: `__future__` import "division" present +# - FI51: `__future__` import "absolute_import" present +# - FI12: `__future__` import "with_statement" missing +# - FI53: `__future__` import "print_function" present +# - FI14: `__future__` import "unicode_literals" missing +# - FI15: `__future__` import "generator_stop" missing +# - E741: ambiguous variable name +ignore=E121,E123,E126,E226,E24,E704,W503,W504,E305,C901,E221,E731,F405,FI50,FI51,FI12,FI53,FI14,FI15,E741 diff --git a/setup.py b/setup.py index f5e2cbbcf..903f9d17f 100755 --- a/setup.py +++ b/setup.py @@ -1,7 +1,8 @@ #!/usr/bin/env python +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -55,11 +56,11 @@ if 'sdist' in sys.argv: setup( name='beets', - version='1.3.15', + version='1.4.7', description='music tagger and library organizer', author='Adrian Sampson', author_email='adrian@radbox.org', - url='http://beets.radbox.org/', + url='http://beets.io/', license='MIT', platforms='ALL', long_description=_read('README.rst'), @@ -85,45 +86,48 @@ setup( }, install_requires=[ - 'enum34>=1.0.4', - 'mutagen>=1.27', + 'six>=1.9', + 'mutagen>=1.33', 'munkres', 'unidecode', 'musicbrainzngs>=0.4', 'pyyaml', 'jellyfish', ] + (['colorama'] if (sys.platform == 'win32') else []) + - (['ordereddict'] if sys.version_info < (2, 7, 0) else []), + (['enum34>=1.0.4'] if sys.version_info < (3, 4, 0) else []), tests_require=[ 'beautifulsoup4', 'flask', 'mock', - 'pyechonest', 'pylast', 'rarfile', 'responses', 'pyxdg', 'pathlib', 'python-mpd2', + 'discogs-client' ], # Plugin (optional) dependencies: extras_require={ + 'absubmit': ['requests'], 'fetchart': ['requests'], 'chroma': ['pyacoustid'], - 'discogs': ['discogs-client>=2.1.0'], - 'echonest': ['pyechonest'], + 'discogs': ['discogs-client>=2.2.1'], + 'beatport': ['requests-oauthlib>=0.6.1'], 'lastgenre': ['pylast'], - 'mpdstats': ['python-mpd2'], + 'mpdstats': ['python-mpd2>=0.4.2'], 'web': ['flask', 'flask-cors'], 'import': ['rarfile'], - 'thumbnails': ['pathlib', 'pyxdg'], + 'thumbnails': ['pyxdg'] + + (['pathlib'] if (sys.version_info < (3, 4, 0)) else []), 'metasync': ['dbus-python'], }, # Non-Python/non-PyPI plugin dependencies: # convert: ffmpeg - # bpd: pygst + # bpd: python-gi and GStreamer + # absubmit: extractor binary from http://acousticbrainz.org/download classifiers=[ 'Topic :: Multimedia :: Sound/Audio', @@ -131,7 +135,13 @@ setup( 'License :: OSI Approved :: MIT License', 'Environment :: Console', 'Environment :: Web Environment', + 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: Implementation :: CPython', ], ) diff --git a/test/__init__.py b/test/__init__.py index 52514cb73..8214c3b8e 100644 --- a/test/__init__.py +++ b/test/__init__.py @@ -1 +1,5 @@ +# -*- coding: utf-8 -*- + # Make python -m testall.py work. + +from __future__ import division, absolute_import, print_function diff --git a/test/_common.py b/test/_common.py index 4588dbb41..fc7b650b3 100644 --- a/test/_common.py +++ b/test/_common.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -13,39 +14,37 @@ # included in all copies or substantial portions of the Software. """Some common functionality for beets' test cases.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import time import sys import os import tempfile import shutil +import six +import unittest from contextlib import contextmanager -# Use unittest2 on Python < 2.7. -try: - import unittest2 as unittest -except ImportError: - import unittest # Mangle the search path to include the beets sources. -sys.path.insert(0, '..') # noqa -import beets.library -from beets import importer, logging -from beets.ui import commands -import beets +sys.path.insert(0, '..') +import beets.library # noqa: E402 +from beets import importer, logging # noqa: E402 +from beets.ui import commands # noqa: E402 +from beets import util # noqa: E402 +import beets # noqa: E402 # Make sure the development versions of the plugins are used -import beetsplug +import beetsplug # noqa: E402 beetsplug.__path__ = [os.path.abspath( os.path.join(__file__, '..', '..', 'beetsplug') )] # Test resources path. -RSRC = os.path.join(os.path.dirname(__file__), b'rsrc') +RSRC = util.bytestring_path(os.path.join(os.path.dirname(__file__), 'rsrc')) +PLUGINPATH = os.path.join(os.path.dirname(__file__), 'rsrc', 'beetsplug') -# Propagate to root loger so nosetest can capture it +# Propagate to root logger so nosetest can capture it log = logging.getLogger('beets') log.propagate = True log.setLevel(logging.DEBUG) @@ -54,7 +53,8 @@ log.setLevel(logging.DEBUG) _item_ident = 0 # OS feature test. -HAVE_SYMLINK = hasattr(os, 'symlink') +HAVE_SYMLINK = sys.platform != 'win32' +HAVE_HARDLINK = sys.platform != 'win32' def item(lib=None): @@ -66,7 +66,9 @@ def item(lib=None): albumartist=u'the album artist', album=u'the album', genre=u'the genre', + lyricist=u'the lyricist', composer=u'the composer', + arranger=u'the arranger', grouping=u'the grouping', year=1, month=2, @@ -88,6 +90,7 @@ def item(lib=None): mb_artistid='someID-3', mb_albumartistid='someID-4', album_id=None, + mtime=12345, ) if lib: lib.add(i) @@ -101,11 +104,11 @@ def album(lib=None): _item_ident += 1 i = beets.library.Album( artpath=None, - albumartist='some album artist', - albumartist_sort='some sort album artist', - albumartist_credit='some album artist credit', - album='the album', - genre='the genre', + albumartist=u'some album artist', + albumartist_sort=u'some sort album artist', + albumartist_credit=u'some album artist credit', + album=u'the album', + genre=u'the genre', year=2014, month=2, day=5, @@ -126,9 +129,26 @@ def import_session(lib=None, loghandler=None, paths=[], query=[], cli=False): return cls(lib, loghandler, paths, query) +class Assertions(object): + """A mixin with additional unit test assertions.""" + + def assertExists(self, path): # noqa + self.assertTrue(os.path.exists(util.syspath(path)), + u'file does not exist: {!r}'.format(path)) + + def assertNotExists(self, path): # noqa + self.assertFalse(os.path.exists(util.syspath(path)), + u'file exists: {!r}'.format((path))) + + def assert_equal_path(self, a, b): + """Check that two paths are equal.""" + self.assertEqual(util.normpath(a), util.normpath(b), + u'paths are not equal: {!r} and {!r}'.format(a, b)) + + # A test harness for all beets tests. # Provides temporary, isolated configuration. -class TestCase(unittest.TestCase): +class TestCase(unittest.TestCase, Assertions): """A unittest.TestCase subclass that saves and restores beets' global configuration. This allows tests to make temporary modifications that will then be automatically removed when the test @@ -142,15 +162,19 @@ class TestCase(unittest.TestCase): # Direct paths to a temporary directory. Tests can also use this # temporary directory. - self.temp_dir = tempfile.mkdtemp() - beets.config['statefile'] = os.path.join(self.temp_dir, 'state.pickle') - beets.config['library'] = os.path.join(self.temp_dir, 'library.db') - beets.config['directory'] = os.path.join(self.temp_dir, 'libdir') + self.temp_dir = util.bytestring_path(tempfile.mkdtemp()) + + beets.config['statefile'] = \ + util.py3_path(os.path.join(self.temp_dir, b'state.pickle')) + beets.config['library'] = \ + util.py3_path(os.path.join(self.temp_dir, b'library.db')) + beets.config['directory'] = \ + util.py3_path(os.path.join(self.temp_dir, b'libdir')) # Set $HOME, which is used by confit's `config_dir()` to create # directories. self._old_home = os.environ.get('HOME') - os.environ['HOME'] = self.temp_dir + os.environ['HOME'] = util.py3_path(self.temp_dir) # Initialize, but don't install, a DummyIO. self.io = DummyIO() @@ -167,14 +191,6 @@ class TestCase(unittest.TestCase): beets.config.clear() beets.config._materialized = False - def assertExists(self, path): - self.assertTrue(os.path.exists(path), - 'file does not exist: {!r}'.format(path)) - - def assertNotExists(self, path): - self.assertFalse(os.path.exists(path), - 'file exists: {!r}'.format((path))) - class LibTestCase(TestCase): """A test case that includes an in-memory library object (`lib`) and @@ -227,12 +243,12 @@ class InputException(Exception): def __str__(self): msg = "Attempt to read with no input provided." if self.output is not None: - msg += " Output: %s" % self.output + msg += " Output: {!r}".format(self.output) return msg class DummyOut(object): - encoding = 'utf8' + encoding = 'utf-8' def __init__(self): self.buf = [] @@ -241,14 +257,20 @@ class DummyOut(object): self.buf.append(s) def get(self): - return b''.join(self.buf) + if six.PY2: + return b''.join(self.buf) + else: + return ''.join(self.buf) + + def flush(self): + self.clear() def clear(self): self.buf = [] class DummyIn(object): - encoding = 'utf8' + encoding = 'utf-8' def __init__(self, out=None): self.buf = [] @@ -256,7 +278,10 @@ class DummyIn(object): self.out = out def add(self, s): - self.buf.append(s + b'\n') + if six.PY2: + self.buf.append(s + b'\n') + else: + self.buf.append(s + '\n') def readline(self): if not self.buf: @@ -312,6 +337,29 @@ class Bag(object): return self.fields.get(key) +# Convenience methods for setting up a temporary sandbox directory for tests +# that need to interact with the filesystem. + +class TempDirMixin(object): + """Text mixin for creating and deleting a temporary directory. + """ + + def create_temp_dir(self): + """Create a temporary directory and assign it into `self.temp_dir`. + Call `remove_temp_dir` later to delete it. + """ + path = tempfile.mkdtemp() + if not isinstance(path, bytes): + path = path.encode('utf8') + self.temp_dir = path + + def remove_temp_dir(self): + """Delete the temporary directory created by `create_temp_dir`. + """ + if os.path.isdir(self.temp_dir): + shutil.rmtree(self.temp_dir) + + # Platform mocking. @contextmanager @@ -345,3 +393,11 @@ def system_mock(name): yield finally: platform.system = old_system + + +def slow_test(unused=None): + def _id(obj): + return obj + if 'SKIP_SLOW_TESTS' in os.environ: + return unittest.skip(u'test is slow') + return _id diff --git a/test/helper.py b/test/helper.py index c23e036e4..5b3bec8b5 100644 --- a/test/helper.py +++ b/test/helper.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -30,8 +31,7 @@ information or mock the environment. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import sys import os @@ -40,7 +40,7 @@ import shutil import subprocess from tempfile import mkdtemp, mkstemp from contextlib import contextmanager -from StringIO import StringIO +from six import StringIO from enum import Enum import beets @@ -51,10 +51,12 @@ from beets.library import Library, Item, Album from beets import importer from beets.autotag.hooks import AlbumInfo, TrackInfo from beets.mediafile import MediaFile, Image -from beets.ui import _arg_encoding +from beets import util +from beets.util import MoveOperation # TODO Move AutotagMock here from test import _common +import six class LogCapture(logging.Handler): @@ -64,7 +66,7 @@ class LogCapture(logging.Handler): self.messages = [] def emit(self, record): - self.messages.append(unicode(record.msg)) + self.messages.append(six.text_type(record.msg)) @contextmanager @@ -88,7 +90,8 @@ def control_stdin(input=None): """ org = sys.stdin sys.stdin = StringIO(input) - sys.stdin.encoding = 'utf8' + if six.PY2: # StringIO encoding attr isn't writable in python >= 3 + sys.stdin.encoding = 'utf-8' try: yield sys.stdin finally: @@ -107,7 +110,8 @@ def capture_stdout(): """ org = sys.stdout sys.stdout = capture = StringIO() - sys.stdout.encoding = 'utf8' + if six.PY2: # StringIO encoding attr isn't writable in python >= 3 + sys.stdout.encoding = 'utf-8' try: yield sys.stdout finally: @@ -115,13 +119,25 @@ def capture_stdout(): print(capture.getvalue()) +def _convert_args(args): + """Convert args to bytestrings for Python 2 and convert them to strings + on Python 3. + """ + for i, elem in enumerate(args): + if six.PY2: + if isinstance(elem, six.text_type): + args[i] = elem.encode(util.arg_encoding()) + else: + if isinstance(elem, bytes): + args[i] = elem.decode(util.arg_encoding()) + + return args + + def has_program(cmd, args=['--version']): """Returns `True` if `cmd` can be executed. """ - full_cmd = [cmd] + args - for i, elem in enumerate(full_cmd): - if isinstance(elem, unicode): - full_cmd[i] = elem.encode(_arg_encoding()) + full_cmd = _convert_args([cmd] + args) try: with open(os.devnull, 'wb') as devnull: subprocess.check_call(full_cmd, stderr=devnull, @@ -165,7 +181,7 @@ class TestHelper(object): Make sure you call ``teardown_beets()`` afterwards. """ self.create_temp_dir() - os.environ['BEETSDIR'] = self.temp_dir + os.environ['BEETSDIR'] = util.py3_path(self.temp_dir) self.config = beets.config self.config.clear() @@ -176,18 +192,20 @@ class TestHelper(object): self.config['ui']['color'] = False self.config['threaded'] = False - self.libdir = os.path.join(self.temp_dir, 'libdir') + self.libdir = os.path.join(self.temp_dir, b'libdir') os.mkdir(self.libdir) - self.config['directory'] = self.libdir + self.config['directory'] = util.py3_path(self.libdir) if disk: - dbpath = self.config['library'].as_filename() + dbpath = util.bytestring_path( + self.config['library'].as_filename() + ) else: dbpath = ':memory:' self.lib = Library(dbpath, self.libdir) def teardown_beets(self): - del self.lib._connections + self.lib._close() if 'BEETSDIR' in os.environ: del os.environ['BEETSDIR'] self.remove_temp_dir() @@ -226,13 +244,13 @@ class TestHelper(object): Copies the specified number of files to a subdirectory of `self.temp_dir` and creates a `TestImportSession` for this path. """ - import_dir = os.path.join(self.temp_dir, 'import') + import_dir = os.path.join(self.temp_dir, b'import') if not os.path.isdir(import_dir): os.mkdir(import_dir) album_no = 0 while album_count: - album = u'album {0}'.format(album_no) + album = util.bytestring_path(u'album {0}'.format(album_no)) album_dir = os.path.join(import_dir, album) if os.path.exists(album_dir): album_no += 1 @@ -243,9 +261,10 @@ class TestHelper(object): track_no = 0 album_item_count = item_count while album_item_count: - title = 'track {0}'.format(track_no) - src = os.path.join(_common.RSRC, 'full.mp3') - dest = os.path.join(album_dir, '{0}.mp3'.format(title)) + title = u'track {0}'.format(track_no) + src = os.path.join(_common.RSRC, b'full.mp3') + title_file = util.bytestring_path('{0}.mp3'.format(title)) + dest = os.path.join(album_dir, title_file) if os.path.exists(dest): track_no += 1 continue @@ -297,6 +316,8 @@ class TestHelper(object): item = Item(**values_) if 'path' not in values: item['path'] = 'audio.' + item['format'].lower() + # mtime needs to be set last since other assignments reset it. + item.mtime = 12345 return item def add_item(self, **values): @@ -306,11 +327,19 @@ class TestHelper(object): If `path` is not set in `values` it is set to `item.destination()`. """ + # When specifying a path, store it normalized (as beets does + # ordinarily). + if 'path' in values: + values['path'] = util.normpath(values['path']) + item = self.create_item(**values) item.add(self.lib) + + # Ensure every item has a path. if 'path' not in values: item['path'] = item.destination() item.store() + return item def add_item_fixture(self, **values): @@ -318,9 +347,10 @@ class TestHelper(object): """ item = self.create_item(**values) extension = item['format'].lower() - item['path'] = os.path.join(_common.RSRC, 'min.' + extension) + item['path'] = os.path.join(_common.RSRC, + util.bytestring_path('min.' + extension)) item.add(self.lib) - item.move(copy=True) + item.move(operation=MoveOperation.COPY) item.store() return item @@ -333,13 +363,15 @@ class TestHelper(object): """ # TODO base this on `add_item()` items = [] - path = os.path.join(_common.RSRC, 'full.' + ext) + path = os.path.join(_common.RSRC, util.bytestring_path('full.' + ext)) for i in range(count): - item = Item.from_path(bytes(path)) + item = Item.from_path(path) item.album = u'\u00e4lbum {0}'.format(i) # Check unicode paths item.title = u't\u00eftle {0}'.format(i) + # mtime needs to be set last since other assignments reset it. + item.mtime = 12345 item.add(self.lib) - item.move(copy=True) + item.move(operation=MoveOperation.COPY) item.store() items.append(item) return items @@ -348,13 +380,15 @@ class TestHelper(object): """Add an album with files to the database. """ items = [] - path = os.path.join(_common.RSRC, 'full.' + ext) + path = os.path.join(_common.RSRC, util.bytestring_path('full.' + ext)) for i in range(track_count): - item = Item.from_path(bytes(path)) + item = Item.from_path(path) item.album = u'\u00e4lbum' # Check unicode paths item.title = u't\u00eftle {0}'.format(i) + # mtime needs to be set last since other assignments reset it. + item.mtime = 12345 item.add(self.lib) - item.move(copy=True) + item.move(operation=MoveOperation.COPY) item.store() items.append(item) return self.lib.add_album(items) @@ -370,7 +404,7 @@ class TestHelper(object): specified extension a cover art image is added to the media file. """ - src = os.path.join(_common.RSRC, 'full.' + ext) + src = os.path.join(_common.RSRC, util.bytestring_path('full.' + ext)) handle, path = mkstemp() os.close(handle) shutil.copyfile(src, path) @@ -379,8 +413,8 @@ class TestHelper(object): mediafile = MediaFile(path) imgs = [] for img_ext in images: - img_path = os.path.join(_common.RSRC, - 'image-2x3.{0}'.format(img_ext)) + file = util.bytestring_path('image-2x3.{0}'.format(img_ext)) + img_path = os.path.join(_common.RSRC, file) with open(img_path, 'rb') as f: imgs.append(Image(f.read())) mediafile.images = imgs @@ -405,17 +439,22 @@ class TestHelper(object): # Running beets commands - def run_command(self, *args): + def run_command(self, *args, **kwargs): + """Run a beets command with an arbitrary amount of arguments. The + Library` defaults to `self.lib`, but can be overridden with + the keyword argument `lib`. + """ + sys.argv = ['beet'] # avoid leakage from test suite args + lib = None if hasattr(self, 'lib'): lib = self.lib - else: - lib = Library(':memory:') - beets.ui._raw_main(list(args), lib) + lib = kwargs.get('lib', lib) + beets.ui._raw_main(_convert_args(list(args)), lib) def run_with_output(self, *args): with capture_stdout() as out: self.run_command(*args) - return out.getvalue().decode('utf-8') + return util.text_string(out.getvalue()) # Safe file operations @@ -423,7 +462,8 @@ class TestHelper(object): """Create a temporary directory and assign it into `self.temp_dir`. Call `remove_temp_dir` later to delete it. """ - self.temp_dir = mkdtemp() + temp_dir = mkdtemp() + self.temp_dir = util.bytestring_path(temp_dir) def remove_temp_dir(self): """Delete the temporary directory created by `create_temp_dir`. @@ -445,9 +485,9 @@ class TestHelper(object): parent = os.path.dirname(path) if not os.path.isdir(parent): - os.makedirs(parent) + os.makedirs(util.syspath(parent)) - with open(path, 'a+') as f: + with open(util.syspath(path), 'a+') as f: f.write(content) return path @@ -495,7 +535,7 @@ class TestImportSession(importer.ImportSession): choose_item = choose_match - Resolution = Enum('Resolution', 'REMOVE SKIP KEEPBOTH') + Resolution = Enum('Resolution', 'REMOVE SKIP KEEPBOTH MERGE') default_resolution = 'REMOVE' @@ -513,6 +553,8 @@ class TestImportSession(importer.ImportSession): task.set_choice(importer.action.SKIP) elif res == self.Resolution.REMOVE: task.should_remove_duplicates = True + elif res == self.Resolution.MERGE: + task.should_merge_duplicates = True def generate_album_info(album_id, track_ids): @@ -526,14 +568,14 @@ def generate_album_info(album_id, track_ids): """ tracks = [generate_track_info(id) for id in track_ids] album = AlbumInfo( - album_id='album info', - album='album info', - artist='album info', - artist_id='album info', + album_id=u'album info', + album=u'album info', + artist=u'album info', + artist_id=u'album info', tracks=tracks, ) for field in ALBUM_INFO_FIELDS: - setattr(album, field, 'album info') + setattr(album, field, u'album info') return album @@ -552,11 +594,11 @@ def generate_track_info(track_id='track info', values={}): string fields are set to "track info". """ track = TrackInfo( - title='track info', + title=u'track info', track_id=track_id, ) for field in TRACK_INFO_FIELDS: - setattr(track, field, 'track info') + setattr(track, field, u'track info') for field, value in values.items(): setattr(track, field, value) return track diff --git a/test/lyrics_download_samples.py b/test/lyrics_download_samples.py index f144263fa..9e7b69731 100644 --- a/test/lyrics_download_samples.py +++ b/test/lyrics_download_samples.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Fabrice Laporte +# Copyright 2016, Fabrice Laporte # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import os import sys @@ -44,7 +44,7 @@ def main(argv=None): """ if argv is None: argv = sys.argv - print('Fetching samples from:') + print(u'Fetching samples from:') for s in test_lyrics.GOOGLE_SOURCES + test_lyrics.DEFAULT_SOURCES: print(s['url']) url = s['url'] + s['path'] @@ -52,7 +52,7 @@ def main(argv=None): if not os.path.isfile(fn): html = requests.get(url, verify=False).text with safe_open_w(fn) as f: - f.write(html.encode('utf8')) + f.write(html.encode('utf-8')) -if __name__ == b'__main__': +if __name__ == "__main__": sys.exit(main()) diff --git a/test/rsrc/acousticbrainz/data.json b/test/rsrc/acousticbrainz/data.json new file mode 100644 index 000000000..1a89c9a99 --- /dev/null +++ b/test/rsrc/acousticbrainz/data.json @@ -0,0 +1,4115 @@ +{ + "tonal":{ + "thpcp":[ + 1, + 0.638657510281, + 0.293813556433, + 0.259863913059, + 0.21968896687, + 0.218203336, + 0.252398610115, + 0.22969686985, + 0.447383195162, + 0.749422073364, + 0.580664932728, + 0.310822367668, + 0.238883554935, + 0.178785249591, + 0.194924846292, + 0.299323320389, + 0.282649427652, + 0.18946044147, + 0.181915551424, + 0.231100782752, + 0.554247200489, + 0.831909179688, + 0.589426040649, + 0.387799620628, + 0.422363936901, + 0.429372549057, + 0.408978521824, + 0.326897829771, + 0.266663640738, + 0.429461866617, + 0.633336126804, + 0.477401226759, + 0.261826515198, + 0.238164439797, + 0.287726253271, + 0.690547764301 + ], + "chords_number_rate":0.00194468453992, + "chords_scale":"minor", + "chords_changes_rate":0.0445116683841, + "key_strength":0.636936545372, + "tuning_diatonic_strength":0.495492935181, + "hpcp_entropy":{ + "min":0, + "max":4.48086500168, + "dvar2":0.867867648602, + "median":2.02990412712, + "dmean2":1.14721953869, + "dmean":0.68769723177, + "var":0.635742008686, + "dvar":0.33780092001, + "mean":2.00384068489 + }, + "key_scale":"minor", + "chords_strength":{ + "min":0.24240244925, + "max":0.793840110302, + "dvar2":9.58399032243e-05, + "median":0.586153388023, + "dmean2":0.0106231365353, + "dmean":0.00929547380656, + "var":0.00910324696451, + "dvar":6.61800950184e-05, + "mean":0.576524615288 + }, + "key_key":"A", + "tuning_nontempered_energy_ratio":0.721719145775, + "tuning_equal_tempered_deviation":0.0515233427286, + "chords_histogram":[ + 56.2445983887, + 8.10285186768, + 1.79343128204, + 0.0864304229617, + 0, + 0.605012953281, + 2.20397591591, + 12.1650819778, + 0.0216076057404, + 0.0216076057404, + 0, + 0, + 0, + 0, + 0, + 0, + 2.67934322357, + 0.21607606113, + 10.8686256409, + 0, + 2.07433009148, + 0.0864304229617, + 0.648228168488, + 2.1823682785 + ], + "chords_key":"A", + "tuning_frequency":441.272583008, + "hpcp":{ + "min":[ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "max":[ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1 + ], + "dvar2":[ + 0.159377709031, + 0.118723139167, + 0.0969077348709, + 0.0841393470764, + 0.0857475027442, + 0.0681946650147, + 0.0922033339739, + 0.0763805955648, + 0.08953332901, + 0.134413808584, + 0.117157392204, + 0.0784328207374, + 0.0576078519225, + 0.0540019907057, + 0.0537950210273, + 0.0788798704743, + 0.0758254900575, + 0.0659088715911, + 0.0595937520266, + 0.0897909551859, + 0.117696471512, + 0.141075149179, + 0.116812512279, + 0.143778041005, + 0.157332316041, + 0.206293225288, + 0.187901929021, + 0.16186593473, + 0.119209326804, + 0.107413217425, + 0.119033068419, + 0.101279519498, + 0.102868333459, + 0.108767814934, + 0.105039291084, + 0.133028581738 + ], + "median":[ + 0.200053632259, + 0.138681918383, + 0.0352100357413, + 0.0198299698532, + 0.0150980614126, + 0.0205171480775, + 0.026256872341, + 0.0286095552146, + 0.0424337461591, + 0.0602139532566, + 0.0744276791811, + 0.0494470596313, + 0.0350396670401, + 0.0212194472551, + 0.0196186862886, + 0.0201223343611, + 0.0170610919595, + 0.0120322443545, + 0.0105668697506, + 0.0191436801106, + 0.0846247002482, + 0.135070502758, + 0.113241240382, + 0.0424886606634, + 0.0378469713032, + 0.02946896106, + 0.0286043733358, + 0.0198593121022, + 0.0253958441317, + 0.0672319456935, + 0.0957452505827, + 0.0639808028936, + 0.026175301522, + 0.0180807597935, + 0.0324410535395, + 0.125212281942 + ], + "dmean2":[ + 0.353859990835, + 0.294070899487, + 0.217189013958, + 0.180236533284, + 0.162956178188, + 0.144071772695, + 0.172789543867, + 0.171253859997, + 0.22391949594, + 0.284728109837, + 0.274570196867, + 0.198656648397, + 0.154297873378, + 0.124744221568, + 0.124510832131, + 0.157537952065, + 0.158150732517, + 0.135058999062, + 0.123808719218, + 0.177607372403, + 0.277576059103, + 0.324962347746, + 0.298212528229, + 0.308668285608, + 0.311420857906, + 0.344731658697, + 0.335885316133, + 0.283822774887, + 0.227637752891, + 0.252195805311, + 0.288448363543, + 0.249307155609, + 0.212308287621, + 0.205825775862, + 0.223324626684, + 0.315198987722 + ], + "dmean":[ + 0.206140458584, + 0.16949801147, + 0.121237404644, + 0.101308584213, + 0.0920756608248, + 0.0820758640766, + 0.0983714461327, + 0.0957674309611, + 0.130757495761, + 0.167563140392, + 0.159212738276, + 0.113431841135, + 0.0875298455358, + 0.0698468312621, + 0.0709747001529, + 0.092557400465, + 0.0927894487977, + 0.0761438235641, + 0.0697580873966, + 0.0992580577731, + 0.162719354033, + 0.194310605526, + 0.174188151956, + 0.171439617872, + 0.174783751369, + 0.191449582577, + 0.185274213552, + 0.155063658953, + 0.124152831733, + 0.143824338913, + 0.167870178819, + 0.144021183252, + 0.116702638566, + 0.112653404474, + 0.125104308128, + 0.184472203255 + ], + "var":[ + 0.143021538854, + 0.0637424811721, + 0.0320195667446, + 0.037381041795, + 0.0286979582161, + 0.0301742851734, + 0.0303927082568, + 0.0223984327167, + 0.052778493613, + 0.13409627974, + 0.0731517747045, + 0.0302681028843, + 0.0220995694399, + 0.0194978509098, + 0.0208596177399, + 0.0510722063482, + 0.0462048053741, + 0.0236530210823, + 0.0288583170623, + 0.0295663233846, + 0.0644663274288, + 0.119045428932, + 0.0609758161008, + 0.0493184439838, + 0.0607626289129, + 0.070556551218, + 0.0664848089218, + 0.0493576526642, + 0.0335861295462, + 0.0447917319834, + 0.0859667509794, + 0.0526875928044, + 0.0304508917034, + 0.0315008088946, + 0.0328483134508, + 0.0794815197587 + ], + "dvar":[ + 0.0686646401882, + 0.0436623394489, + 0.0358338914812, + 0.0332863405347, + 0.0316647030413, + 0.027725789696, + 0.0338032282889, + 0.0273791830987, + 0.0345646068454, + 0.0615020208061, + 0.0457257218659, + 0.0297911148518, + 0.0221415478736, + 0.0201385207474, + 0.0201426595449, + 0.033235758543, + 0.0318886972964, + 0.0243560094386, + 0.0229729004204, + 0.0327679589391, + 0.0460740588605, + 0.0626438856125, + 0.0435314439237, + 0.0521778166294, + 0.0578555390239, + 0.0772548541427, + 0.0728902295232, + 0.05926451087, + 0.0424739196897, + 0.0389089211822, + 0.0483759790659, + 0.0381603203714, + 0.036982499063, + 0.0398408733308, + 0.0387278683484, + 0.0517609193921 + ], + "mean":[ + 0.366864055395, + 0.234300479293, + 0.107789635658, + 0.0953347310424, + 0.080595985055, + 0.0800509601831, + 0.0925959795713, + 0.084267526865, + 0.164128810167, + 0.274936020374, + 0.213025093079, + 0.114029549062, + 0.0876377895474, + 0.0655898824334, + 0.0715109184384, + 0.109810970724, + 0.103693917394, + 0.0695062279701, + 0.0667382776737, + 0.0847825706005, + 0.203333377838, + 0.305197566748, + 0.216239228845, + 0.142269745469, + 0.154950141907, + 0.157521352172, + 0.15003952384, + 0.119927063584, + 0.0978293046355, + 0.157554119825, + 0.232348263264, + 0.175141349435, + 0.0960547402501, + 0.0873739719391, + 0.105556420982, + 0.253337144852 + ] + } + }, + "rhythm":{ + "bpm_histogram_second_peak_bpm":{ + "min":167, + "max":167, + "dvar2":0, + "median":167, + "dmean2":0, + "dmean":0, + "var":0, + "dvar":0, + "mean":167 + }, + "bpm_histogram_second_peak_spread":{ + "min":0, + "max":0, + "dvar2":0, + "median":0, + "dmean2":0, + "dmean":0, + "var":0, + "dvar":0, + "mean":0 + }, + "beats_count":577, + "beats_loudness":{ + "min":4.48232695405e-09, + "max":0.181520029902, + "dvar2":0.00434844521806, + "median":0.0302296206355, + "dmean2":0.0709233134985, + "dmean":0.0362482257187, + "var":0.0014705004869, + "dvar":0.00124853104353, + "mean":0.0407853461802 + }, + "bpm":162.532119751, + "bpm_histogram_first_peak_spread":{ + "min":0.164835140109, + "max":0.164835140109, + "dvar2":0, + "median":0.164835140109, + "dmean2":0, + "dmean":0, + "var":0, + "dvar":0, + "mean":0.164835140109 + }, + "danceability":1.14192211628, + "bpm_histogram_first_peak_bpm":{ + "min":161, + "max":161, + "dvar2":0, + "median":161, + "dmean2":0, + "dmean":0, + "var":0, + "dvar":0, + "mean":161 + }, + "beats_loudness_band_ratio":{ + "min":[ + 0.00683269277215, + 0.00988945644349, + 0.00177479430567, + 0.000523661612533, + 0.000248342636041, + 0.00070228939876 + ], + "max":[ + 0.970164954662, + 0.725397408009, + 0.739950060844, + 0.658194899559, + 0.676319360733, + 0.622089266777 + ], + "dvar2":[ + 0.0699004009366, + 0.0290632098913, + 0.035205449909, + 0.0226975940168, + 0.0168868545443, + 0.0086750369519 + ], + "median":[ + 0.619332075119, + 0.176913484931, + 0.0926762372255, + 0.0303400773555, + 0.0398489944637, + 0.0262520890683 + ], + "dmean2":[ + 0.369491040707, + 0.230186283588, + 0.192849993706, + 0.106605380774, + 0.107576675713, + 0.0616580061615 + ], + "dmean":[ + 0.207789510489, + 0.129003107548, + 0.110624760389, + 0.0578341074288, + 0.0602345280349, + 0.035002540797 + ], + "var":[ + 0.0565228238702, + 0.0165011454374, + 0.0193302389234, + 0.0086074648425, + 0.00634109321982, + 0.00296737346798 + ], + "dvar":[ + 0.0250691790134, + 0.00962078291923, + 0.0126609709114, + 0.00782771967351, + 0.00567667419091, + 0.00305109703913 + ], + "mean":[ + 0.577607989311, + 0.195795580745, + 0.138790622354, + 0.0610357522964, + 0.065284781158, + 0.04240244627 + ] + }, + "onset_rate":5.17941665649, + "beats_position":[ + 0.383129239082, + 0.789478421211, + 1.16099774837, + 1.53251695633, + 1.90403628349, + 2.27555561066, + 2.6470746994, + 3.01859402657, + 3.39011335373, + 3.76163268089, + 4.13315200806, + 4.5046710968, + 4.87619018555, + 5.24770975113, + 5.60761880875, + 5.9675283432, + 6.33904743195, + 6.71056699753, + 7.08208608627, + 7.45360517502, + 7.81351470947, + 8.17342376709, + 8.54494285583, + 8.91646194458, + 9.287981987, + 9.64789104462, + 10.0194101334, + 10.379319191, + 10.7508392334, + 11.110748291, + 11.4822673798, + 11.8421764374, + 12.2136955261, + 12.5852155685, + 12.9567346573, + 13.3166437149, + 13.6765527725, + 14.0364627838, + 14.3963718414, + 14.7678909302, + 15.1394100189, + 15.5109291077, + 15.870839119, + 16.2307472229, + 16.602268219, + 16.9621772766, + 17.3220863342, + 17.693605423, + 18.0535144806, + 18.4134235382, + 18.7733325958, + 19.1332416534, + 19.4931507111, + 19.853061676, + 20.2245807648, + 20.5844898224, + 20.9560089111, + 21.3159179688, + 21.6874370575, + 22.0473461151, + 22.4072551727, + 22.7787742615, + 23.1386852264, + 23.4985942841, + 23.8701133728, + 24.2416324615, + 24.6131515503, + 24.984670639, + 25.3561897278, + 25.7277088165, + 26.0992279053, + 26.4591369629, + 26.830657959, + 27.2021770477, + 27.5736961365, + 27.9452152252, + 28.316734314, + 28.6766433716, + 29.0481624603, + 29.4196815491, + 29.7912006378, + 30.1627197266, + 30.5342407227, + 30.9057598114, + 31.265668869, + 31.6255779266, + 31.9854869843, + 32.3453979492, + 32.6704750061, + 33.0071640015, + 33.3554649353, + 33.7153739929, + 34.0868911743, + 34.4351921082, + 34.8067131042, + 35.1898422241, + 35.5961914062, + 35.9793205261, + 36.362449646, + 36.7339668274, + 37.1054878235, + 37.4886169434, + 37.8601341248, + 38.2316551208, + 38.6147842407, + 38.9863014221, + 39.3578224182, + 39.7293434143, + 40.1124725342, + 40.4723815918, + 40.8438987732, + 41.2154197693, + 41.5869369507, + 41.9584579468, + 42.3299751282, + 42.7014961243, + 43.0730133057, + 43.4445343018, + 43.8160552979, + 44.1875724792, + 44.5590934753, + 44.9306106567, + 45.3021316528, + 45.6736488342, + 46.0335578918, + 46.3934669495, + 46.7533760071, + 47.1132888794, + 47.4848060608, + 47.8563270569, + 48.2394561768, + 48.6225852966, + 48.994102478, + 49.3656234741, + 49.748752594, + 50.1318817139, + 50.5033988953, + 50.8749198914, + 51.2580490112, + 51.6411781311, + 52.0126991272, + 52.3842163086, + 52.7557373047, + 53.1272544861, + 53.4987754822, + 53.8702926636, + 54.2534217834, + 54.6365509033, + 55.0080718994, + 55.3795890808, + 55.7511100769, + 56.122631073, + 56.4941482544, + 56.8656692505, + 57.2487983704, + 57.6203155518, + 58.0034446716, + 58.3749656677, + 58.7464828491, + 59.1180038452, + 59.4895210266, + 59.8610420227, + 60.2325630188, + 60.6040802002, + 60.9756011963, + 61.3471183777, + 61.7186393738, + 62.0901565552, + 62.4616775513, + 62.8331947327, + 63.2163238525, + 63.5994529724, + 63.9709739685, + 64.3424911499, + 64.714012146, + 65.0855331421, + 65.4570541382, + 65.8285675049, + 66.200088501, + 66.5716094971, + 66.9431304932, + 67.3146438599, + 67.686164856, + 68.0344696045, + 68.4175949097, + 68.8007278442, + 69.1722412109, + 69.5321502686, + 69.8920593262, + 70.2635803223, + 70.6351013184, + 70.995010376, + 71.3549194336, + 71.7264404297, + 72.1095657349, + 72.481086731, + 72.8642196655, + 73.2357330322, + 73.6072540283, + 73.9787750244, + 74.3502960205, + 74.7218093872, + 75.1049423218, + 75.488067627, + 75.859588623, + 76.2311096191, + 76.6026306152, + 76.9741516113, + 77.345664978, + 77.7171859741, + 78.1003189087, + 78.4834442139, + 78.85496521, + 79.2264862061, + 79.5979995728, + 79.9695205688, + 80.3410415649, + 80.712562561, + 81.0840835571, + 81.4555969238, + 81.8271179199, + 82.198638916, + 82.5701599121, + 82.9416732788, + 83.3131942749, + 83.684715271, + 84.0678405762, + 84.4509735107, + 84.8224945068, + 85.1824035645, + 85.5423126221, + 85.9138336182, + 86.2853469849, + 86.656867981, + 87.0283889771, + 87.3999099731, + 87.7714233398, + 88.1429443359, + 88.514465332, + 88.8859863281, + 89.2575073242, + 89.6290206909, + 89.9889297485, + 90.3488388062, + 90.7203598022, + 91.0918807983, + 91.451789856, + 91.8116989136, + 92.1832199097, + 92.5547409058, + 92.9262542725, + 93.2861633301, + 93.6460723877, + 94.0175933838, + 94.3891143799, + 94.760635376, + 95.1205444336, + 95.4804534912, + 95.8403625488, + 96.2002716064, + 96.5717926025, + 96.9433059692, + 97.3148269653, + 97.6863479614, + 98.0578689575, + 98.4293823242, + 98.8009033203, + 99.1724243164, + 99.532333374, + 99.9038543701, + 100.263763428, + 100.635284424, + 101.006797791, + 101.378318787, + 101.738227844, + 102.098136902, + 102.469657898, + 102.841178894, + 103.21269989, + 103.584213257, + 103.944122314, + 104.304031372, + 104.675552368, + 105.047073364, + 105.406982422, + 105.766891479, + 106.138412476, + 106.509933472, + 106.881446838, + 107.252967834, + 107.624488831, + 107.984397888, + 108.355918884, + 108.715827942, + 109.087341309, + 109.458862305, + 109.818771362, + 110.17868042, + 110.538589478, + 110.898498535, + 111.270019531, + 111.641540527, + 112.001449585, + 112.361358643, + 112.732879639, + 113.104400635, + 113.464309692, + 113.82421875, + 114.184127808, + 114.544036865, + 114.915550232, + 115.287071228, + 115.658592224, + 116.006889343, + 116.366798401, + 116.726707458, + 117.086616516, + 117.446525574, + 117.794830322, + 118.15473938, + 118.514648438, + 118.886169434, + 119.269294739, + 119.652427673, + 120.035552979, + 120.418685913, + 120.813423157, + 121.2081604, + 121.602897644, + 121.997642517, + 122.380767822, + 122.763900757, + 123.147026062, + 123.530158997, + 123.92489624, + 124.319633484, + 124.69115448, + 125.085891724, + 125.480628967, + 125.863761902, + 126.246894836, + 126.630020142, + 127.013153076, + 127.396278381, + 127.779411316, + 128.17414856, + 128.568893433, + 128.963623047, + 129.346755981, + 129.729888916, + 130.113006592, + 130.496139526, + 130.867660522, + 131.239181519, + 131.610702515, + 131.982223511, + 132.353744507, + 132.725265503, + 133.09677124, + 133.456680298, + 133.816589355, + 134.188110352, + 134.559631348, + 134.931152344, + 135.30267334, + 135.674194336, + 136.045715332, + 136.417236328, + 136.788757324, + 137.160263062, + 137.520172119, + 137.880081177, + 138.251602173, + 138.623123169, + 138.994644165, + 139.366165161, + 139.737686157, + 140.109207153, + 140.480728149, + 140.852249146, + 141.223754883, + 141.595275879, + 141.943572998, + 142.315093994, + 142.675003052, + 143.034912109, + 143.406433105, + 143.777954102, + 144.149475098, + 144.520996094, + 144.89251709, + 145.264038086, + 145.635559082, + 146.007064819, + 146.378585815, + 146.750106812, + 147.121627808, + 147.493148804, + 147.8646698, + 148.236190796, + 148.607711792, + 148.979232788, + 149.362350464, + 149.745483398, + 150.117004395, + 150.488525391, + 150.860046387, + 151.231567383, + 151.603088379, + 151.974594116, + 152.346115112, + 152.717636108, + 153.089157104, + 153.460678101, + 153.832199097, + 154.203720093, + 154.575241089, + 154.946762085, + 155.318267822, + 155.689788818, + 156.061309814, + 156.432830811, + 156.804351807, + 157.175872803, + 157.547393799, + 157.918914795, + 158.290420532, + 158.661941528, + 159.033462524, + 159.404983521, + 159.776504517, + 160.148025513, + 160.519546509, + 160.891067505, + 161.262588501, + 161.634094238, + 162.005615234, + 162.37713623, + 162.737045288, + 163.096954346, + 163.468475342, + 163.839996338, + 164.211517334, + 164.58303833, + 164.954559326, + 165.326080322, + 165.674377441, + 166.045898438, + 166.417419434, + 166.788925171, + 167.160446167, + 167.531967163, + 167.903488159, + 168.275009155, + 168.646530151, + 169.018051147, + 169.389572144, + 169.772689819, + 170.155822754, + 170.52734375, + 170.898864746, + 171.270385742, + 171.641906738, + 172.025024414, + 172.408157349, + 172.779678345, + 173.151199341, + 173.522720337, + 173.894241333, + 174.265762329, + 174.637283325, + 175.032012939, + 175.415145874, + 175.798278809, + 176.169799805, + 176.541305542, + 176.9012146, + 177.272735596, + 177.632644653, + 178.004165649, + 178.375686646, + 178.747207642, + 179.130340576, + 179.513473511, + 179.884979248, + 180.256500244, + 180.62802124, + 180.999542236, + 181.382675171, + 181.754196167, + 182.137313843, + 182.508834839, + 182.880355835, + 183.251876831, + 183.623397827, + 183.994918823, + 184.378051758, + 184.761169434, + 185.13269043, + 185.504211426, + 185.875732422, + 186.247253418, + 186.618774414, + 186.99029541, + 187.361816406, + 187.733337402, + 188.10484314, + 188.476364136, + 188.847885132, + 189.219406128, + 189.590927124, + 189.96244812, + 190.345581055, + 190.72869873, + 191.100219727, + 191.471740723, + 191.843261719, + 192.214782715, + 192.597915649, + 192.981033325, + 193.352554321, + 193.724075317, + 194.095596313, + 194.478729248, + 194.861862183, + 195.23336792, + 195.604888916, + 195.976409912, + 196.347930908, + 196.719451904, + 197.0909729, + 197.474105835, + 197.857223511, + 198.228744507, + 198.600265503, + 198.971786499, + 199.343307495, + 199.714828491, + 200.086349487, + 200.457870483, + 200.829391479, + 201.200897217, + 201.572418213, + 201.943939209, + 202.303848267, + 202.663757324, + 203.03527832, + 203.406799316, + 203.778320312, + 204.149841309, + 204.521362305, + 204.892883301, + 205.264389038, + 205.647521973, + 206.030654907, + 206.402175903, + 206.773696899, + 207.145217896, + 207.516723633, + 207.888244629, + 208.259765625, + 208.631286621, + 209.002807617, + 209.385940552, + 209.757461548, + 210.128982544, + 210.500488281, + 210.883621216, + 211.255142212, + 211.626663208, + 212.009796143, + 212.392913818, + 212.776046753, + 213.170791626, + 213.565536499, + 213.971878052, + 214.378234863 + ], + "bpm_histogram_second_peak_weight":{ + "min":0.163194447756, + "max":0.163194447756, + "dvar2":0, + "median":0.163194447756, + "dmean2":0, + "dmean":0, + "var":0, + "dvar":0, + "mean":0.163194447756 + }, + "bpm_histogram_first_peak_weight":{ + "min":0.659722208977, + "max":0.659722208977, + "dvar2":0, + "median":0.659722208977, + "dmean2":0, + "dmean":0, + "var":0, + "dvar":0, + "mean":0.659722208977 + } + }, + "lowlevel":{ + "spectral_complexity":{ + "min":0, + "max":51, + "dvar2":34.109500885, + "median":15, + "dmean2":5.03252983093, + "dmean":3.31208133698, + "var":108.135475159, + "dvar":16.1623840332, + "mean":15.1260938644 + }, + "silence_rate_20dB":{ + "min":1, + "max":1, + "dvar2":0, + "median":1, + "dmean2":0, + "dmean":0, + "var":0, + "dvar":0, + "mean":1 + }, + "average_loudness":0.815025985241, + "erbbands_spread":{ + "min":0.907018482685, + "max":163.113571167, + "dvar2":511.106719971, + "median":34.9861183167, + "dmean2":17.4016342163, + "dmean":11.4227361679, + "var":572.351501465, + "dvar":220.769592285, + "mean":39.7502365112 + }, + "spectral_kurtosis":{ + "min":-1.22816824913, + "max":77.2247085571, + "dvar2":28.6044521332, + "median":4.62249898911, + "dmean2":4.51546525955, + "dmean":2.82785224915, + "var":33.1767959595, + "dvar":13.1654214859, + "mean":6.00768327713 + }, + "barkbands_kurtosis":{ + "min":-1.96124887466, + "max":732.31427002, + "dvar2":588.577392578, + "median":2.02856016159, + "dmean2":8.05669307709, + "dmean":5.11299228668, + "var":374.321380615, + "dvar":247.842544556, + "mean":7.06718301773 + }, + "spectral_strongpeak":{ + "min":1.71490974199e-10, + "max":16.1200447083, + "dvar2":3.3518705368, + "median":0.39955753088, + "dmean2":0.941311240196, + "dmean":0.545010268688, + "var":2.96148967743, + "dvar":1.33243703842, + "mean":0.93408870697 + }, + "spectral_spread":{ + "min":1388334.875, + "max":41575076, + "dvar2":1619247235070.0, + "median":3420763.25, + "dmean2":983456.875, + "dmean":732694.4375, + "var":4945877663740.0, + "dvar":854983901184, + "mean":4104934.25 + }, + "spectral_rms":{ + "min":3.15950651059e-12, + "max":0.0132316453382, + "dvar2":3.71212809114e-06, + "median":0.00425734650344, + "dmean2":0.0013317943085, + "dmean":0.000880118692294, + "var":5.96411746301e-06, + "dvar":1.66359927789e-06, + "mean":0.0039903158322 + }, + "erbbands":{ + "min":[ + 1.77816177391e-22, + 1.16505097519e-21, + 1.25622764484e-20, + 2.42817334007e-20, + 1.54258117469e-20, + 1.0398112018e-19, + 1.45132858053e-19, + 2.45289269564e-19, + 4.01068342766e-19, + 8.21050273636e-19, + 3.81530310848e-19, + 8.81511903137e-19, + 1.07499647945e-18, + 8.4783438187e-19, + 1.00474413342e-18, + 2.63416224414e-18, + 2.7020495774e-18, + 3.62243276547e-18, + 3.19863277569e-18, + 3.43176763428e-18, + 6.46998299903e-18, + 5.15079866686e-18, + 8.52004633608e-18, + 1.02257547977e-17, + 1.00997123247e-17, + 1.05472856921e-17, + 1.00685656659e-17, + 1.10003920706e-17, + 1.51110777052e-17, + 1.5046216819e-17, + 1.31580720189e-17, + 1.30844504628e-17, + 1.13508668418e-17, + 1.02681982621e-17, + 8.04728449187e-18, + 4.73097927698e-18, + 2.75997186582e-18, + 1.08864568334e-18, + 2.8601904839e-19, + 3.5584382605e-20 + ], + "max":[ + 2.05614852905, + 10.580906868, + 60.5060195923, + 152.843505859, + 450.042755127, + 175.338409424, + 237.807418823, + 238.884460449, + 443.897521973, + 525.930541992, + 518.611022949, + 1031.67468262, + 954.232910156, + 1123.45935059, + 556.857299805, + 356.125640869, + 342.635467529, + 1293.60327148, + 1103.80981445, + 1287.36242676, + 2169.76928711, + 1266.18579102, + 601.754516602, + 1258.96850586, + 444.097320557, + 240.62600708, + 303.504180908, + 56.5521354675, + 72.2374343872, + 85.4121780396, + 25.407957077, + 19.8146400452, + 46.2547264099, + 16.3226490021, + 16.8903636932, + 5.15064907074, + 0.893250703812, + 0.284754753113, + 0.106889992952, + 0.00452945847064 + ], + "dvar2":[ + 0.0137821119279, + 4.26913785934, + 97.7259292603, + 622.611999512, + 3656.42504883, + 376.053527832, + 307.56942749, + 320.293243408, + 2445.90405273, + 1300.15063477, + 729.621582031, + 2693.6159668, + 2013.25512695, + 3353.13598633, + 573.952941895, + 269.22253418, + 457.528259277, + 1406.78710938, + 1557.82128906, + 793.165527344, + 5019.24316406, + 4039.60839844, + 970.312316895, + 1538.21313477, + 721.875244141, + 195.41003418, + 88.4793777466, + 31.4306335449, + 42.7237434387, + 32.8801956177, + 6.04226541519, + 1.52690029144, + 1.47338938713, + 0.542356073856, + 0.211627364159, + 0.0269440039992, + 0.00465576630086, + 0.000269315525657, + 1.98406451091e-05, + 4.38383267465e-08 + ], + "median":[ + 0.00466703856364, + 0.101253904402, + 1.64267027378, + 5.13034963608, + 6.49109458923, + 4.258228302, + 3.18711066246, + 4.03815889359, + 7.81102657318, + 7.54452610016, + 5.75877952576, + 8.21393203735, + 11.6316785812, + 9.69087696075, + 4.23464298248, + 1.69191777706, + 2.67072510719, + 4.43968248367, + 4.24516201019, + 7.75287914276, + 16.0199928284, + 12.5332527161, + 9.28721427917, + 9.18504428864, + 6.87661838531, + 4.15781497955, + 3.11850094795, + 0.707400023937, + 0.422007799149, + 0.326348185539, + 0.171605303884, + 0.0764799118042, + 0.0530340671539, + 0.0369812250137, + 0.0170799326152, + 0.00388540537097, + 0.000607917027082, + 0.000106923354906, + 2.54503829638e-05, + 2.41674279096e-05 + ], + "dmean2":[ + 0.0468679144979, + 1.00080478191, + 4.60071754456, + 11.530172348, + 27.0302009583, + 10.1726131439, + 8.18716049194, + 9.02602672577, + 21.6493034363, + 17.5054721832, + 11.9851293564, + 23.2072429657, + 23.1678962708, + 24.8249855042, + 9.62737751007, + 5.9968290329, + 8.08820819855, + 12.5483970642, + 11.0777654648, + 12.6770420074, + 31.1724281311, + 22.2209968567, + 15.6441850662, + 17.6994724274, + 11.4936075211, + 6.59135293961, + 5.08022689819, + 2.30506944656, + 2.95904040337, + 2.46585559845, + 1.15297198296, + 0.531184136868, + 0.382049500942, + 0.275081396103, + 0.141834661365, + 0.0498343594372, + 0.0225136969239, + 0.00503297196701, + 0.000977287418209, + 5.82068387303e-05 + ], + "dmean":[ + 0.0350424982607, + 0.580041825771, + 2.61035442352, + 6.80757236481, + 16.318693161, + 6.28967905045, + 5.23286628723, + 5.70099258423, + 13.4230766296, + 10.8768568039, + 7.74926900864, + 15.0034389496, + 15.0271100998, + 16.6018199921, + 6.02632713318, + 3.79855132103, + 5.38237333298, + 8.43670463562, + 7.43314123154, + 8.2191324234, + 20.6921386719, + 13.7538080215, + 9.77100944519, + 11.3139772415, + 7.25735664368, + 4.1218457222, + 3.17433810234, + 1.45581579208, + 1.87883663177, + 1.61556243896, + 0.779599308968, + 0.371349811554, + 0.264476120472, + 0.193502560258, + 0.100708886981, + 0.0353026203811, + 0.0144239943475, + 0.00325388251804, + 0.000670222449116, + 3.95594870497e-05 + ], + "var":[ + 0.0116662262008, + 1.27503490448, + 25.6204109192, + 206.069885254, + 1430.30371094, + 234.442382812, + 206.473526001, + 288.805267334, + 1444.05480957, + 817.272949219, + 625.690795898, + 2697.92749023, + 2397.11669922, + 7130.13330078, + 515.86315918, + 346.633789062, + 809.448486328, + 2584.76660156, + 2616.26757812, + 3138.03320312, + 20583.1132812, + 3381.78515625, + 1288.27880859, + 2477.11401367, + 682.099060059, + 216.604751587, + 97.8326339722, + 13.7823019028, + 19.9818115234, + 16.6690158844, + 4.43811273575, + 1.2346996069, + 1.27807950974, + 0.517578363419, + 0.177246898413, + 0.0190207827836, + 0.00211605615914, + 0.000168058744748, + 1.65621640917e-05, + 3.32350325039e-08 + ], + "dvar":[ + 0.00734147289768, + 1.59334981441, + 34.9658050537, + 236.386993408, + 1519.1640625, + 157.498901367, + 126.366111755, + 127.708183289, + 921.020629883, + 497.140319824, + 303.813903809, + 1122.60107422, + 868.916992188, + 1545.74194336, + 241.721923828, + 118.562904358, + 218.458129883, + 734.227844238, + 762.639587402, + 405.900024414, + 2714.4777832, + 1520.69287109, + 428.032836914, + 696.146972656, + 272.255096436, + 80.3479690552, + 38.2512245178, + 12.4188299179, + 17.8483753204, + 13.7868928909, + 2.77658462524, + 0.731714189053, + 0.67433899641, + 0.263227701187, + 0.108624838293, + 0.0132785160094, + 0.00197272375226, + 0.000125091624795, + 1.03948887045e-05, + 2.18264126772e-08 + ], + "mean":[ + 0.0470404699445, + 0.51214581728, + 2.94917726517, + 8.56711673737, + 16.8939933777, + 9.74743175507, + 8.58794498444, + 10.7102499008, + 23.4056625366, + 18.6381034851, + 13.9866991043, + 27.1086997986, + 28.1797733307, + 34.376159668, + 10.7114057541, + 6.6013917923, + 10.7804918289, + 16.5257949829, + 15.1251926422, + 19.3569641113, + 49.2880210876, + 27.8654499054, + 20.180316925, + 22.9017887115, + 15.1088733673, + 8.45034122467, + 5.79618597031, + 1.91187810898, + 2.04077577591, + 1.82269322872, + 0.964613378048, + 0.475511223078, + 0.359998822212, + 0.270887732506, + 0.138232842088, + 0.0431671403348, + 0.0138024548069, + 0.00314460648224, + 0.000714557303581, + 5.64505244256e-05 + ] + }, + "zerocrossingrate":{ + "min":0.00244140625, + "max":0.525390625, + "dvar2":0.000216632659431, + "median":0.04736328125, + "dmean2":0.0121012274176, + "dmean":0.0100563038141, + "var":0.00131242838688, + "dvar":0.000186675912119, + "mean":0.0536084286869 + }, + "spectral_contrast_coeffs":{ + "min":[ + -0.981265366077, + -0.957678437233, + -0.97364538908, + -0.967074155807, + -0.96257597208, + -0.963937044144 + ], + "max":[ + -0.232828617096, + -0.450794398785, + -0.464783608913, + -0.367899239063, + -0.556100070477, + -0.624147236347 + ], + "dvar2":[ + 0.0063711241819, + 0.00358002260327, + 0.00270585925318, + 0.0017158848932, + 0.00113679806236, + 0.00189194327686 + ], + "median":[ + -0.592801511288, + -0.736532092094, + -0.745844006538, + -0.781389117241, + -0.797656714916, + -0.772757589817 + ], + "dmean2":[ + 0.0916584655643, + 0.074229337275, + 0.0648957416415, + 0.0500396862626, + 0.0380141288042, + 0.0374387130141 + ], + "dmean":[ + 0.0592447705567, + 0.0465519614518, + 0.0414465926588, + 0.0322540737689, + 0.024834824726, + 0.0243127625436 + ], + "var":[ + 0.00911337323487, + 0.00655136583373, + 0.00618056347594, + 0.00577284349129, + 0.00380114861764, + 0.00231571029872 + ], + "dvar":[ + 0.00270068016835, + 0.00148758781143, + 0.00118501938414, + 0.000784370582551, + 0.000524090020917, + 0.000761664705351 + ], + "mean":[ + -0.594863533974, + -0.735448241234, + -0.745020091534, + -0.775078713894, + -0.790849328041, + -0.779701292515 + ] + }, + "dissonance":{ + "min":0.155567497015, + "max":0.500000119209, + "dvar2":0.0011708199745, + "median":0.469446510077, + "dmean2":0.0329371914268, + "dmean":0.0200165640563, + "var":0.00120261416305, + "dvar":0.000480501999846, + "mean":0.460001558065 + }, + "spectral_energyband_high":{ + "min":7.11060368084e-21, + "max":0.00607443926856, + "dvar2":2.99654345781e-07, + "median":0.000152749445988, + "dmean2":0.000292699754937, + "dmean":0.000196773456992, + "var":2.3810963512e-07, + "dvar":1.35860290129e-07, + "mean":0.000318794423947 + }, + "gfcc":{ + "mean":[ + -75.1009368896, + 108.134063721, + -114.922393799, + 35.9068107605, + -53.9456176758, + -7.74362421036, + -37.9716300964, + 9.9239988327, + -24.244802475, + -10.4905223846, + -23.3989257812, + -9.61326217651, + -9.66184806824 + ], + "icov":[ + [ + 8.00217167125e-05, + -0.00014524954895, + 0.000159682429512, + -0.000167002261151, + 9.01917956071e-05, + -0.000181695446372, + 0.000171542298631, + -0.000129780688439, + 0.000197500339709, + -0.000278050283669, + 0.000315256824251, + -0.000206819575396, + 0.000114160277008 + ], + [ + -0.00014524954895, + 0.00178359099664, + -0.000247094896622, + 0.00111800106242, + -0.000636783661321, + 0.000774645654019, + -0.000396145915147, + 0.000103466474684, + -0.00112135277595, + 0.00229536322877, + -0.00234188255854, + 0.00232740258798, + -0.00131408020388 + ], + [ + 0.000159682429512, + -0.000247094896622, + 0.00116660131607, + -0.000234406528762, + 0.000154832057888, + -0.00112980930135, + 0.000650760543067, + -5.60496459912e-07, + 0.000167754784343, + -0.000856044876855, + 0.0014209097717, + -0.00128671491984, + 0.00078388658585 + ], + [ + -0.000167002261151, + 0.00111800106242, + -0.000234406528762, + 0.00312983314507, + -0.000794405816123, + -0.00058439996792, + 2.24104460358e-05, + 0.000424961413955, + -0.00152624503244, + 0.00239069177769, + -0.00202889670618, + 0.00110484787729, + -0.00148455286399 + ], + [ + 9.01917956071e-05, + -0.000636783661321, + 0.000154832057888, + -0.000794405816123, + 0.00397709663957, + -0.000828172138426, + -0.000291677570203, + -0.000975954462774, + 0.00101370830089, + -0.00107421039138, + -0.000894718454219, + 0.00066822959343, + -0.000943991879467 + ], + [ + -0.000181695446372, + 0.000774645654019, + -0.00112980930135, + -0.00058439996792, + -0.000828172138426, + 0.00597975216806, + -0.00177403702401, + -0.000384801533073, + 0.00153620564379, + -0.00195281521883, + 0.00158954621293, + 0.000321330269799, + 0.000257747073192 + ], + [ + 0.000171542298631, + -0.000396145915147, + 0.000650760543067, + 2.24104460358e-05, + -0.000291677570203, + -0.00177403702401, + 0.0080866701901, + -0.00180288043339, + 7.330061635e-05, + 0.00111615261994, + -0.0011511715129, + -0.000984402606264, + 0.000181279159733 + ], + [ + -0.000129780688439, + 0.000103466474684, + -5.60496459912e-07, + 0.000424961413955, + -0.000975954462774, + -0.000384801533073, + -0.00180288043339, + 0.00851836241782, + -0.00320849893615, + 0.00141180318315, + -0.00124999764375, + 0.000833041733131, + -0.00159861764405 + ], + [ + 0.000197500339709, + -0.00112135277595, + 0.000167754784343, + -0.00152624503244, + 0.00101370830089, + 0.00153620564379, + 7.330061635e-05, + -0.00320849893615, + 0.0134673845023, + -0.00816399604082, + 0.00590222747996, + -0.00234723254107, + -0.000930359237827 + ], + [ + -0.000278050283669, + 0.00229536322877, + -0.000856044876855, + 0.00239069177769, + -0.00107421039138, + -0.00195281521883, + 0.00111615261994, + 0.00141180318315, + -0.00816399604082, + 0.0195522867143, + -0.0122134555131, + 0.00327054248191, + 0.000577625120059 + ], + [ + 0.000315256824251, + -0.00234188255854, + 0.0014209097717, + -0.00202889670618, + -0.000894718454219, + 0.00158954621293, + -0.0011511715129, + -0.00124999764375, + 0.00590222747996, + -0.0122134555131, + 0.021111080423, + -0.00721056666225, + 0.00365835893899 + ], + [ + -0.000206819575396, + 0.00232740258798, + -0.00128671491984, + 0.00110484787729, + 0.00066822959343, + 0.000321330269799, + -0.000984402606264, + 0.000833041733131, + -0.00234723254107, + 0.00327054248191, + -0.00721056666225, + 0.015932681039, + -0.00565396249294 + ], + [ + 0.000114160277008, + -0.00131408020388, + 0.00078388658585, + -0.00148455286399, + -0.000943991879467, + 0.000257747073192, + 0.000181279159733, + -0.00159861764405, + -0.000930359237827, + 0.000577625120059, + 0.00365835893899, + -0.00565396249294, + 0.0153731228784 + ] + ], + "cov":[ + [ + 21821.4921875, + 1302.12060547, + -2790.62133789, + 583.293151855, + 63.9840736389, + 26.9333572388, + -119.419998169, + 277.984161377, + -110.454193115, + -76.0569458008, + -16.7917041779, + -162.89515686, + 121.933448792 + ], + [ + 1302.12060547, + 1445.02355957, + -661.351135254, + -311.094665527, + 156.139587402, + -306.730987549, + 60.9609375, + 92.3673324585, + 3.47471880913, + -108.692207336, + 66.6088409424, + -147.776809692, + 75.2410125732 + ], + [ + -2790.62133789, + -661.351135254, + 1889.47399902, + 92.8338088989, + -92.8102874756, + 368.803192139, + -78.5678482056, + -95.1785125732, + 24.1375102997, + 86.254699707, + -94.2749252319, + 117.902046204, + -80.0259933472 + ], + [ + 583.293151855, + -311.094665527, + 92.8338088989, + 515.187255859, + 60.5850448608, + 128.642654419, + -2.62003684044, + 6.46807575226, + 13.7108755112, + -3.07335114479, + -7.74705600739, + 28.8581352234, + 29.7626171112 + ], + [ + 63.9840736389, + 156.139587402, + -92.8102874756, + 60.5850448608, + 339.564758301, + 28.9691524506, + 45.5025405884, + 54.3213920593, + -9.63641166687, + 12.0036411285, + 43.2324829102, + -22.4280166626, + 29.361246109 + ], + [ + 26.9333572388, + -306.730987549, + 368.803192139, + 128.642654419, + 28.9691524506, + 324.149993896, + 20.1203899384, + -3.79410982132, + -15.0688257217, + 43.0340042114, + -26.3511829376, + 28.6324996948, + -22.8170604706 + ], + [ + -119.419998169, + 60.9609375, + -78.5678482056, + -2.62003684044, + 45.5025405884, + 20.1203899384, + 155.001724243, + 42.1054992676, + -1.47882866859, + -8.76181983948, + 19.2513332367, + 2.83816099167, + 11.5606393814 + ], + [ + 277.984161377, + 92.3673324585, + -95.1785125732, + 6.46807575226, + 54.3213920593, + -3.79410982132, + 42.1054992676, + 155.586120605, + 33.8702697754, + -2.8296790123, + 9.17068958282, + -6.04741716385, + 28.1404056549 + ], + [ + -110.454193115, + 3.47471880913, + 24.1375102997, + 13.7108755112, + -9.63641166687, + -15.0688257217, + -1.47882866859, + 33.8702697754, + 114.661575317, + 34.3392486572, + -7.06085252762, + 10.0253458023, + 15.4272651672 + ], + [ + -76.0569458008, + -108.692207336, + 86.254699707, + -3.07335114479, + 12.0036411285, + 43.0340042114, + -8.76181983948, + -2.8296790123, + 34.3392486572, + 112.38079071, + 43.6220817566, + 14.6831378937, + -20.7214431763 + ], + [ + -16.7917041779, + 66.6088409424, + -94.2749252319, + -7.74705600739, + 43.2324829102, + -26.3511829376, + 19.2513332367, + 9.17068958282, + -7.06085252762, + 43.6220817566, + 99.527053833, + 15.1529960632, + -6.4773888588 + ], + [ + -162.89515686, + -147.776809692, + 117.902046204, + 28.8581352234, + -22.4280166626, + 28.6324996948, + 2.83816099167, + -6.04741716385, + 10.0253458023, + 14.6831378937, + 15.1529960632, + 101.876480103, + 16.7505264282 + ], + [ + 121.933448792, + 75.2410125732, + -80.0259933472, + 29.7626171112, + 29.361246109, + -22.8170604706, + 11.5606393814, + 28.1404056549, + 15.4272651672, + -20.7214431763, + -6.4773888588, + 16.7505264282, + 91.9189758301 + ] + ] + }, + "spectral_flux":{ + "min":6.40516528705e-11, + "max":0.355690479279, + "dvar2":0.00278266565874, + "median":0.0625253766775, + "dmean2":0.0423415489495, + "dmean":0.0282820314169, + "var":0.00376007612795, + "dvar":0.00135926820803, + "mean":0.0749769806862 + }, + "silence_rate_30dB":{ + "min":0, + "max":1, + "dvar2":0.0354892387986, + "median":1, + "dmean2":0.0246406570077, + "dmean":0.0123189976439, + "var":0.00654759025201, + "dvar":0.0121672395617, + "mean":0.993408977985 + }, + "spectral_energyband_middle_high":{ + "min":1.27805372214e-21, + "max":0.0389622859657, + "dvar2":9.42645056057e-06, + "median":0.00293085677549, + "dmean2":0.00200005969964, + "dmean":0.00133119279053, + "var":2.5883437047e-05, + "dvar":4.14980877395e-06, + "mean":0.00445337453857 + }, + "barkbands_spread":{ + "min":0.167884364724, + "max":139.821090698, + "dvar2":253.175750732, + "median":18.0125980377, + "dmean2":10.9470348358, + "dmean":6.75650119781, + "var":180.234161377, + "dvar":101.147232056, + "mean":20.320306778 + }, + "spectral_centroid":{ + "min":111.030769348, + "max":11065.2148438, + "dvar2":701335.5625, + "median":1143.22497559, + "dmean2":567.022827148, + "dmean":354.07824707, + "var":626410.0625, + "dvar":292997.4375, + "mean":1266.39624023 + }, + "pitch_salience":{ + "min":0.103756688535, + "max":0.928133249283, + "dvar2":0.013650230132, + "median":0.569122076035, + "dmean2":0.124187774956, + "dmean":0.0767409279943, + "var":0.0128469280899, + "dvar":0.00529233785346, + "mean":0.566493272781 + }, + "erbbands_skewness":{ + "min":-8.09688186646, + "max":6.17588758469, + "dvar2":1.00871086121, + "median":0.283587485552, + "dmean2":0.786845207214, + "dmean":0.512230575085, + "var":1.42545306683, + "dvar":0.427418738604, + "mean":0.235957682133 + }, + "erbbands_crest":{ + "min":2.31988024712, + "max":34.2482185364, + "dvar2":16.2832355499, + "median":8.70411396027, + "dmean2":4.28936433792, + "dmean":2.70263242722, + "var":24.3617858887, + "dvar":6.85065603256, + "mean":9.92293930054 + }, + "melbands":{ + "min":[ + 1.7312522864e-24, + 4.69779527492e-24, + 4.46513652814e-24, + 3.32025441336e-24, + 6.6967940523e-24, + 5.54350662457e-24, + 5.62380004294e-24, + 7.24197266845e-24, + 4.37425935743e-24, + 6.31036856572e-24, + 4.53679113075e-24, + 3.08454218323e-24, + 4.01757944901e-24, + 5.05271286808e-24, + 5.25895581858e-24, + 3.18568913964e-24, + 7.13208118891e-24, + 4.5636159514e-24, + 5.04583400098e-24, + 6.17228950832e-24, + 6.96855978959e-24, + 4.44096109684e-24, + 6.9472211021e-24, + 7.30462636813e-24, + 7.82425851273e-24, + 7.32260214157e-24, + 5.87433201125e-24, + 6.79884662102e-24, + 6.23345462746e-24, + 6.36714722381e-24, + 5.56132344254e-24, + 7.90887173342e-24, + 7.08392990812e-24, + 8.85545433259e-24, + 6.01856418372e-24, + 6.31963413149e-24, + 6.85279050744e-24, + 7.75657976909e-24, + 8.50479856047e-24, + 7.94873918585e-24 + ], + "max":[ + 0.0150078302249, + 0.0248268786818, + 0.0372853949666, + 0.0202775932848, + 0.00924268271774, + 0.00459495186806, + 0.00642714649439, + 0.00673051225021, + 0.00483322422951, + 0.0058145863004, + 0.00487699825317, + 0.00474451202899, + 0.00216139364056, + 0.00089383253362, + 0.000890302297194, + 0.00114067236427, + 0.00265396363102, + 0.00179244857281, + 0.00171541213058, + 0.00327429641038, + 0.00261263479479, + 0.00140622933395, + 0.000604341796134, + 0.000546872266568, + 0.00119282689411, + 0.000385722087231, + 0.000307112553855, + 0.000185638607945, + 0.000196822540602, + 7.07383733243e-05, + 3.59257646778e-05, + 4.41324045823e-05, + 5.90648887737e-05, + 5.03649462189e-05, + 1.98958878173e-05, + 1.04367582026e-05, + 1.49458364831e-05, + 3.54613039235e-05, + 2.11343995034e-05, + 1.33671064759e-05 + ], + "dvar2":[ + 1.97027497961e-06, + 1.79839098564e-05, + 3.41721388395e-05, + 6.39068775854e-06, + 4.12703258235e-07, + 1.60991760367e-07, + 5.84672534387e-07, + 1.35801229817e-07, + 5.67447884237e-08, + 9.04100758703e-08, + 5.12682660769e-08, + 6.00754361813e-08, + 8.33282598478e-09, + 2.19900075926e-09, + 2.22529794591e-09, + 2.68628164157e-09, + 6.38194253e-09, + 4.48827552901e-09, + 1.61791646747e-09, + 5.6524527281e-09, + 7.00124225261e-09, + 5.1307971205e-09, + 1.8114484357e-09, + 6.22804863237e-10, + 1.41800715614e-09, + 5.03870334345e-10, + 3.42071621029e-10, + 8.80266623482e-11, + 5.10801435871e-11, + 1.6358601973e-11, + 1.09966497713e-11, + 1.34551406475e-11, + 2.12651927317e-11, + 8.70376774126e-12, + 2.70498077062e-12, + 8.23377390574e-13, + 6.18267915163e-13, + 8.94622212682e-13, + 5.74140724113e-13, + 4.04918747187e-13 + ], + "median":[ + 6.78846045048e-05, + 0.000686653598677, + 0.00100371893495, + 0.000425793463364, + 0.000121567500173, + 8.67325506988e-05, + 0.000119830452604, + 7.64572032494e-05, + 4.73126528959e-05, + 4.95156273246e-05, + 5.10508471052e-05, + 3.72932154278e-05, + 1.39631702041e-05, + 4.18296076532e-06, + 3.36458288075e-06, + 5.95153596805e-06, + 7.06666241967e-06, + 5.36886500413e-06, + 6.55584017295e-06, + 1.27752928165e-05, + 1.80421066034e-05, + 1.10708388092e-05, + 9.13756139198e-06, + 6.40786538497e-06, + 6.87108331476e-06, + 5.39385519005e-06, + 3.31015212396e-06, + 2.2452804842e-06, + 2.11795463656e-06, + 8.45357135404e-07, + 1.55302529947e-07, + 2.16630468231e-07, + 2.0936421663e-07, + 1.59076819273e-07, + 1.03014848207e-07, + 5.60769883862e-08, + 4.16746956944e-08, + 3.91173387015e-08, + 3.08294119122e-08, + 2.99958919925e-08 + ], + "dmean2":[ + 0.000655197829474, + 0.00202016695403, + 0.00265697692521, + 0.00127012608573, + 0.000302697066218, + 0.000204388590646, + 0.000336306344252, + 0.000177521447768, + 0.000107648374978, + 0.000137986353366, + 0.000116639275802, + 0.000105825478386, + 3.63973231288e-05, + 1.78256286745e-05, + 1.63039130712e-05, + 1.98472516786e-05, + 2.55192408076e-05, + 1.86820070667e-05, + 1.45677859109e-05, + 2.93159864668e-05, + 3.81224999728e-05, + 2.55198028754e-05, + 1.86311717698e-05, + 1.29478112285e-05, + 1.63034928846e-05, + 1.03988468254e-05, + 6.90801107339e-06, + 4.38494134869e-06, + 3.91557023249e-06, + 1.95062216335e-06, + 1.26417035062e-06, + 1.61554555689e-06, + 1.957419272e-06, + 1.21927041619e-06, + 7.50478704958e-07, + 4.08925643569e-07, + 3.15493565495e-07, + 2.87596407134e-07, + 2.50877462804e-07, + 2.38469112901e-07 + ], + "dmean":[ + 0.000433199049439, + 0.00115317711607, + 0.00158822687808, + 0.000778516754508, + 0.000194163410924, + 0.000129944470245, + 0.00020776965539, + 0.000110655011667, + 7.02645556885e-05, + 8.88201902853e-05, + 7.56665394874e-05, + 7.11579850758e-05, + 2.26343472605e-05, + 1.1214566257e-05, + 1.06519555629e-05, + 1.3082231817e-05, + 1.72533091245e-05, + 1.2507844076e-05, + 9.44854855334e-06, + 1.93181331269e-05, + 2.54146216321e-05, + 1.58707625815e-05, + 1.14972417578e-05, + 8.10282745078e-06, + 1.0418824786e-05, + 6.57239706925e-06, + 4.29072770203e-06, + 2.71895851256e-06, + 2.42956934926e-06, + 1.20713775686e-06, + 7.98163171112e-07, + 1.02098283605e-06, + 1.22477297282e-06, + 8.0222929455e-07, + 4.99395412135e-07, + 2.76074587191e-07, + 2.18049038381e-07, + 1.94722304059e-07, + 1.73989079144e-07, + 1.64999249819e-07 + ], + "var":[ + 1.04273829038e-06, + 4.88182786285e-06, + 1.22067667689e-05, + 3.09852111968e-06, + 2.95254579896e-07, + 1.60118688086e-07, + 3.36397903311e-07, + 9.02441499306e-08, + 5.12204714198e-08, + 8.87765096991e-08, + 6.13447141973e-08, + 1.30928043518e-07, + 7.16093628839e-09, + 2.90166846106e-09, + 3.30743610277e-09, + 3.75769282357e-09, + 1.11862910046e-08, + 7.38158290048e-09, + 3.41670158832e-09, + 2.24571348184e-08, + 3.01072198283e-08, + 4.89972462603e-09, + 1.57648072374e-09, + 7.79673825502e-10, + 2.14637396745e-09, + 5.14293607701e-10, + 2.73522648975e-10, + 8.45902653479e-11, + 5.53298171169e-11, + 1.09233455614e-11, + 4.45680905375e-12, + 6.09628753728e-12, + 8.53084356628e-12, + 4.52617804347e-12, + 1.82034248786e-12, + 6.15677430912e-13, + 4.4449592119e-13, + 6.71954570979e-13, + 5.48820374997e-13, + 3.48484424911e-13 + ], + "dvar":[ + 8.33708043046e-07, + 6.49838420941e-06, + 1.36113221743e-05, + 2.76258151644e-06, + 1.75387782519e-07, + 6.53309797372e-08, + 2.18858644985e-07, + 5.17116269805e-08, + 2.40723956324e-08, + 3.69722101823e-08, + 2.22425278196e-08, + 2.84932291095e-08, + 3.64641872252e-09, + 9.5759922214e-10, + 9.86244308443e-10, + 1.3016818734e-09, + 3.31316440949e-09, + 2.19745110996e-09, + 7.73902275597e-10, + 3.32642535739e-09, + 3.88597554135e-09, + 1.99106442444e-09, + 7.00074609394e-10, + 2.79730322239e-10, + 6.32938867984e-10, + 2.10190226335e-10, + 1.22236526456e-10, + 3.66416376407e-11, + 2.22450686344e-11, + 6.52528248449e-12, + 4.34595848892e-12, + 5.58480735616e-12, + 8.46765019213e-12, + 3.64534357561e-12, + 1.20417478072e-12, + 3.81005014864e-13, + 2.8428255301e-13, + 3.87186458025e-13, + 2.78560404994e-13, + 1.87431545436e-13 + ], + "mean":[ + 0.00047609579633, + 0.00126094208099, + 0.00185862951912, + 0.000971358967945, + 0.000324478023686, + 0.000246531388257, + 0.000361267186236, + 0.000190427192138, + 0.000126440427266, + 0.000159403600264, + 0.000136641858262, + 0.000143978060805, + 3.71072310372e-05, + 1.87067053048e-05, + 1.93349878828e-05, + 2.34964645642e-05, + 3.1896517612e-05, + 2.36660616793e-05, + 1.83704396477e-05, + 4.34660541941e-05, + 5.81043132115e-05, + 2.89009076369e-05, + 2.15983145608e-05, + 1.50616651808e-05, + 1.95628890651e-05, + 1.24749267343e-05, + 8.04845058155e-06, + 4.90500542583e-06, + 4.20188916905e-06, + 1.82525320724e-06, + 8.70177814249e-07, + 1.09259167402e-06, + 1.25471365209e-06, + 9.23780646644e-07, + 6.02008753958e-07, + 3.45971272964e-07, + 2.69976595746e-07, + 2.55056221476e-07, + 2.36791535713e-07, + 2.26877631349e-07 + ] + }, + "spectral_entropy":{ + "min":4.61501169205, + "max":9.81467628479, + "dvar2":0.184129029512, + "median":7.38190746307, + "dmean2":0.352754920721, + "dmean":0.243219792843, + "var":0.300432950258, + "dvar":0.0902535244823, + "mean":7.3010840416 + }, + "spectral_rolloff":{ + "min":64.599609375, + "max":21037.9394531, + "dvar2":3396222, + "median":861.328125, + "dmean2":1057.10974121, + "dmean":604.693481445, + "var":2179523.25, + "dvar":1425528, + "mean":1383.6763916 + }, + "barkbands":{ + "min":[ + 6.93473619499e-25, + 5.19568601854e-24, + 1.02416202049e-23, + 4.28463410897e-24, + 3.04471689542e-23, + 2.72335547301e-23, + 3.08580014027e-23, + 1.15517745957e-23, + 5.01556722243e-23, + 3.01743335215e-23, + 3.20834273992e-23, + 6.39242832255e-23, + 4.96037188707e-23, + 6.11980114915e-23, + 7.73605723709e-23, + 1.27850093686e-22, + 8.33913319498e-23, + 1.55698133196e-22, + 1.80609161514e-22, + 2.27535985033e-22, + 3.03975723224e-22, + 3.99622470031e-22, + 4.5185483121e-22, + 7.15649816942e-22, + 1.01532623561e-21, + 1.53862207745e-21, + 2.31706194078e-21 + ], + "max":[ + 0.00229191919789, + 0.047907166183, + 0.0691591277719, + 0.0995827168226, + 0.0820566862822, + 0.0232072826475, + 0.0308443717659, + 0.0302771702409, + 0.0344947054982, + 0.0269099473953, + 0.0134304724634, + 0.00715320091695, + 0.00838674418628, + 0.0218261200935, + 0.019664183259, + 0.0362881943583, + 0.0182446800172, + 0.0173479039222, + 0.0146563379094, + 0.00540218688548, + 0.00442544184625, + 0.00217473763041, + 0.0013186649885, + 0.00208773952909, + 0.00195873784833, + 0.000584891589824, + 0.00050722778542 + ], + "dvar2":[ + 2.09710808718e-08, + 5.00840687891e-05, + 9.50076937443e-05, + 0.000209878431633, + 8.73877215781e-05, + 3.97830672227e-06, + 1.24859725474e-05, + 1.86764350474e-06, + 3.62891637451e-06, + 3.01378167933e-06, + 5.96735674208e-07, + 1.57074438789e-07, + 2.46402947823e-07, + 4.87388831516e-07, + 4.96838595154e-07, + 1.52867119141e-06, + 1.2727361991e-06, + 3.34951494096e-07, + 4.58745859078e-07, + 1.02385989464e-07, + 2.90899002664e-08, + 3.47254207611e-08, + 1.03255741735e-08, + 3.98843491567e-09, + 4.08773503935e-09, + 1.11437570283e-09, + 4.70612881998e-10 + ], + "median":[ + 1.01329169411e-06, + 0.000326245411998, + 0.00187892094254, + 0.00155476410873, + 0.0016892075073, + 0.000451811589301, + 0.000548189680558, + 0.000192572828382, + 0.000307663634885, + 0.000414336362155, + 9.44759449339e-05, + 2.73611021839e-05, + 5.38471249456e-05, + 6.47374472464e-05, + 8.72917589732e-05, + 0.000232024758589, + 0.000200124268304, + 0.000144036966958, + 0.000164192693774, + 8.08068361948e-05, + 4.40170915681e-05, + 1.11471890705e-05, + 6.5616086431e-06, + 3.2568784718e-06, + 2.92447043648e-06, + 4.78593108255e-07, + 7.76246977807e-08 + ], + "dmean2":[ + 5.63530775253e-05, + 0.00340586039238, + 0.00441808719188, + 0.00632638018578, + 0.0048057041131, + 0.00103038607631, + 0.00156902591698, + 0.000596007099375, + 0.000905426510144, + 0.000906587869395, + 0.000307931040879, + 0.000146102538565, + 0.000193360538105, + 0.000240257213591, + 0.000224526840611, + 0.00052686111303, + 0.000436997273937, + 0.000281702930806, + 0.000314143690048, + 0.000150212654262, + 8.88355425559e-05, + 8.39097774588e-05, + 4.62743046228e-05, + 2.28419812629e-05, + 2.21090576815e-05, + 1.11555727926e-05, + 5.03497130921e-06 + ], + "dmean":[ + 4.36054288002e-05, + 0.00207182555459, + 0.00250360206701, + 0.00372918182984, + 0.0029777479358, + 0.00065627245931, + 0.000966914638411, + 0.000378262484446, + 0.000581912638154, + 0.000613346113823, + 0.000192098785192, + 9.08574875211e-05, + 0.000126861719764, + 0.000160341092851, + 0.000145415237057, + 0.00034682394471, + 0.000273586803814, + 0.000176411645953, + 0.000198787456611, + 9.40177123994e-05, + 5.56063205295e-05, + 5.36341467523e-05, + 3.11664407491e-05, + 1.60014496942e-05, + 1.57560625667e-05, + 7.42050679037e-06, + 3.44123100149e-06 + ], + "var":[ + 1.73105885182e-08, + 1.84976615856e-05, + 2.50716802839e-05, + 7.04820486135e-05, + 4.76136665384e-05, + 3.67056259165e-06, + 6.74153125146e-06, + 1.57238355314e-06, + 3.58573174708e-06, + 5.54312009626e-06, + 5.51931407244e-07, + 1.78970466891e-07, + 4.17550438669e-07, + 9.57703605309e-07, + 8.59389047037e-07, + 6.6176985456e-06, + 1.22271069358e-06, + 4.2584204607e-07, + 5.58315321086e-07, + 9.85875061588e-08, + 2.47446703128e-08, + 1.64356386279e-08, + 7.04793423623e-09, + 3.46884565516e-09, + 3.82823417411e-09, + 6.34027108593e-10, + 3.8906944333e-10 + ], + "dvar":[ + 1.15370024645e-08, + 1.92330826394e-05, + 3.36813718604e-05, + 8.24065355118e-05, + 3.870560613e-05, + 1.55360748977e-06, + 4.66681467515e-06, + 7.47769490772e-07, + 1.50442451741e-06, + 1.46062268414e-06, + 2.81505151634e-07, + 6.65834889446e-08, + 1.17960382795e-07, + 2.50351632758e-07, + 2.41593681949e-07, + 8.20324487449e-07, + 5.11046778229e-07, + 1.56924727435e-07, + 1.97066171381e-07, + 4.1844121057e-08, + 1.20861924913e-08, + 1.45208129965e-08, + 4.66174743252e-09, + 1.88047488692e-09, + 2.07477035552e-09, + 5.05100294923e-10, + 2.44846420916e-10 + ], + "mean":[ + 5.19759996678e-05, + 0.00199001817964, + 0.00309076649137, + 0.00392009504139, + 0.0039071268402, + 0.00123883492779, + 0.00161516538355, + 0.000634168100078, + 0.00102682900615, + 0.00122780457605, + 0.000289549614536, + 0.000142228382174, + 0.000236654945184, + 0.000305703491904, + 0.000276061356999, + 0.000822361966129, + 0.000508801313117, + 0.000334064679919, + 0.000397378782509, + 0.00017829038552, + 8.88610738912e-05, + 5.81649801461e-05, + 3.79984667234e-05, + 2.1309551812e-05, + 2.22307517106e-05, + 7.82890947448e-06, + 3.57463068212e-06 + ] + }, + "melbands_flatness_db":{ + "min":0.00437760027125, + "max":0.607957184315, + "dvar2":0.00331180845387, + "median":0.219427987933, + "dmean2":0.0528259426355, + "dmean":0.034728333354, + "var":0.00492821913213, + "dvar":0.00150177872274, + "mean":0.230123117566 + }, + "melbands_skewness":{ + "min":-2.44428515434, + "max":15.3962888718, + "dvar2":2.92571592331, + "median":2.28337860107, + "dmean2":1.4999755621, + "dmean":0.987386882305, + "var":4.25560426712, + "dvar":1.34734094143, + "mean":2.84234952927 + }, + "barkbands_skewness":{ + "min":-6.20005989075, + "max":18.9707603455, + "dvar2":2.02687716484, + "median":1.45346200466, + "dmean2":1.15091514587, + "dmean":0.750691831112, + "var":2.42782378197, + "dvar":0.866045475006, + "mean":1.71697402 + }, + "silence_rate_60dB":{ + "min":0, + "max":1, + "dvar2":0.0371209047735, + "median":0, + "dmean2":0.0337187945843, + "dmean":0.0168575756252, + "var":0.179377868772, + "dvar":0.0165733974427, + "mean":0.234251752496 + }, + "spectral_energyband_low":{ + "min":4.89638611687e-23, + "max":0.116083092988, + "dvar2":0.000277574028587, + "median":0.00443472480401, + "dmean2":0.00833203457296, + "dmean":0.00496239587665, + "var":9.57977899816e-05, + "dvar":0.000101656405604, + "mean":0.00667642848566 + }, + "spectral_energyband_middle_low":{ + "min":2.98093395713e-22, + "max":0.171243280172, + "dvar2":0.000569899275433, + "median":0.0082081919536, + "dmean2":0.0117948763072, + "dmean":0.00737277884036, + "var":0.000299356790492, + "dvar":0.000242799738771, + "mean":0.0127554573119 + }, + "melbands_kurtosis":{ + "min":-1.94107413292, + "max":380.680023193, + "dvar2":1038.95019531, + "median":7.13754844666, + "dmean2":17.6919975281, + "dmean":11.5336751938, + "var":1275.55053711, + "dvar":493.653686523, + "mean":19.2873706818 + }, + "spectral_decrease":{ + "min":-4.64023344193e-08, + "max":6.78438804261e-19, + "dvar2":6.20802821665e-17, + "median":-4.53350113006e-09, + "dmean2":4.26796598063e-09, + "dmean":2.69736544212e-09, + "var":3.69683427013e-17, + "dvar":2.61311086979e-17, + "mean":-5.59147705914e-09 + }, + "erbbands_kurtosis":{ + "min":-1.86338639259, + "max":171.201263428, + "dvar2":23.2438850403, + "median":-0.320037484169, + "dmean2":2.39585089684, + "dmean":1.52739417553, + "var":35.0008544922, + "dvar":11.0155954361, + "mean":1.24987971783 + }, + "melbands_crest":{ + "min":1.85922825336, + "max":32.9627304077, + "dvar2":27.1548709869, + "median":12.5910797119, + "dmean2":5.60343551636, + "dmean":3.39730739594, + "var":20.3299713135, + "dvar":10.5175638199, + "mean":13.3324451447 + }, + "melbands_spread":{ + "min":0.26147004962, + "max":299.135498047, + "dvar2":1027.73010254, + "median":17.4329528809, + "dmean2":16.3484096527, + "dmean":10.0459423065, + "var":529.263366699, + "dvar":403.605499268, + "mean":23.2355747223 + }, + "spectral_energy":{ + "min":1.02320440393e-20, + "max":0.179453358054, + "dvar2":0.000923860818148, + "median":0.0185781233013, + "dmean2":0.0165870357305, + "dmean":0.0105188144371, + "var":0.000572183460463, + "dvar":0.00039060486597, + "mean":0.0224339049309 + }, + "mfcc":{ + "mean":[ + -715.191650391, + 133.878646851, + -2.74888682365, + 38.7127075195, + 3.85699295998, + -10.4443674088, + -5.89105558395, + 4.36424779892, + 2.37372231483, + 1.66640949249, + -7.12301874161, + -9.74494552612, + -3.86338329315 + ], + "icov":[ + [ + 7.98077235231e-05, + -5.86888636462e-05, + 0.000145378129673, + -9.86643281067e-05, + 3.03972447e-05, + -0.000187377940165, + 0.000134168396471, + -0.000129314183141, + 1.27186794998e-05, + -7.31398395146e-05, + 1.38320649512e-06, + 0.000111114335596, + -8.96842757356e-05 + ], + [ + -5.86888636462e-05, + 0.000914695789106, + -1.55892048497e-05, + 0.000330161477905, + -0.000239893066464, + 0.00115360564087, + -0.000499361369293, + 0.000324924068991, + -1.15215043479e-05, + -0.000243278453127, + 0.000191972227185, + -9.64893956734e-07, + 0.000270225456916 + ], + [ + 0.000145378129673, + -1.55892048497e-05, + 0.0013757571578, + 7.94086445239e-05, + -0.000468786456622, + -0.00135524733923, + 0.00098228675779, + -0.000316469959216, + -0.000591932330281, + 0.000769039965235, + -0.000745072495192, + 0.000638137804344, + 0.000274067162536 + ], + [ + -9.86643281067e-05, + 0.000330161477905, + 7.94086445239e-05, + 0.00385635741986, + -0.00140862353146, + 0.000500513473526, + 0.000532710750122, + -0.00153480307199, + 0.000852926750667, + -0.000837227795273, + 0.00151946756523, + -0.00070260866778, + 0.000143392870086 + ], + [ + 3.03972447e-05, + -0.000239893066464, + -0.000468786456622, + -0.00140862353146, + 0.0056857005693, + -0.00172490451951, + -0.00111165409908, + 0.000201825780096, + 0.000247466086876, + -0.00217686733231, + 0.00112909392919, + -0.000958321907092, + -0.000166401950992 + ], + [ + -0.000187377940165, + 0.00115360564087, + -0.00135524733923, + 0.000500513473526, + -0.00172490451951, + 0.00837340857834, + -0.00406587868929, + 0.00216831197031, + -0.0023798532784, + 0.00346444058232, + -0.00286303297617, + 0.00123248388991, + -0.000868651026394 + ], + [ + 0.000134168396471, + -0.000499361369293, + 0.00098228675779, + 0.000532710750122, + -0.00111165409908, + -0.00406587868929, + 0.00986782740802, + -0.00542975915596, + 0.00409825751558, + -0.0044681020081, + 0.00282385596074, + -0.00354772782885, + 0.00168551225215 + ], + [ + -0.000129314183141, + 0.000324924068991, + -0.000316469959216, + -0.00153480307199, + 0.000201825780096, + 0.00216831197031, + -0.00542975915596, + 0.0144132943824, + -0.00864001736045, + 0.00550767453387, + -0.00397388311103, + 0.00314126117155, + -0.00206855195574 + ], + [ + 1.27186794998e-05, + -1.15215043479e-05, + -0.000591932330281, + 0.000852926750667, + 0.000247466086876, + -0.0023798532784, + 0.00409825751558, + -0.00864001736045, + 0.0176015142351, + -0.0112102692947, + 0.0083336783573, + -0.00373222492635, + 0.00208288733847 + ], + [ + -7.31398395146e-05, + -0.000243278453127, + 0.000769039965235, + -0.000837227795273, + -0.00217686733231, + 0.00346444058232, + -0.0044681020081, + 0.00550767453387, + -0.0112102692947, + 0.0205363947898, + -0.0105180032551, + 0.00535045098513, + -0.00213157944381 + ], + [ + 1.38320649512e-06, + 0.000191972227185, + -0.000745072495192, + 0.00151946756523, + 0.00112909392919, + -0.00286303297617, + 0.00282385596074, + -0.00397388311103, + 0.0083336783573, + -0.0105180032551, + 0.0160211343318, + -0.00672314595431, + 0.00358490552753 + ], + [ + 0.000111114335596, + -9.64893956734e-07, + 0.000638137804344, + -0.00070260866778, + -0.000958321907092, + 0.00123248388991, + -0.00354772782885, + 0.00314126117155, + -0.00373222492635, + 0.00535045098513, + -0.00672314595431, + 0.0181408431381, + -0.00800348073244 + ], + [ + -8.96842757356e-05, + 0.000270225456916, + 0.000274067162536, + 0.000143392870086, + -0.000166401950992, + -0.000868651026394, + 0.00168551225215, + -0.00206855195574, + 0.00208288733847, + -0.00213157944381, + 0.00358490552753, + -0.00800348073244, + 0.0156487096101 + ] + ], + "cov":[ + [ + 18717.6230469, + 1395.88500977, + -2566.72802734, + 557.851989746, + -126.109024048, + -374.194091797, + 26.1053237915, + 164.080841064, + 80.1878204346, + 192.214401245, + -182.145751953, + -47.5592041016, + 152.686767578 + ], + [ + 1395.88500977, + 1649.59350586, + -550.320007324, + -49.1516876221, + -56.1948204041, + -331.535217285, + 9.86240959167, + -34.6940498352, + -6.41311454773, + 74.1020736694, + -56.9916381836, + -16.3797187805, + -19.4202880859 + ], + [ + -2566.72802734, + -550.320007324, + 1546.81799316, + -94.7429580688, + 133.984313965, + 339.89239502, + -54.6255912781, + 10.0923881531, + 34.4428405762, + -69.080619812, + 85.0990753174, + -36.5973091125, + -56.1265907288 + ], + [ + 557.851989746, + -49.1516876221, + -94.7429580688, + 342.6902771, + 83.1379013062, + -15.0537748337, + 17.4024486542, + 46.2917900085, + 21.9955101013, + 12.8328580856, + -40.3507461548, + 8.21014022827, + 19.1214065552 + ], + [ + -126.109024048, + -56.1948204041, + 133.984313965, + 83.1379013062, + 261.195220947, + 98.0570144653, + 69.749458313, + 21.4776115417, + 23.9828796387, + 28.7067451477, + 2.99768400192, + 18.3751049042, + 10.1154251099 + ], + [ + -374.194091797, + -331.535217285, + 339.89239502, + -15.0537748337, + 98.0570144653, + 288.139526367, + 71.6913833618, + 15.3370637894, + 9.08637428284, + -21.2720279694, + 42.7490844727, + 11.0748538971, + 0.872315227985 + ], + [ + 26.1053237915, + 9.86240959167, + -54.6255912781, + 17.4024486542, + 69.749458313, + 71.6913833618, + 187.006271362, + 49.2006340027, + 4.36477804184, + 25.2697525024, + 7.5669798851, + 29.0018577576, + 7.81967544556 + ], + [ + 164.080841064, + -34.6940498352, + 10.0923881531, + 46.2917900085, + 21.4776115417, + 15.3370637894, + 49.2006340027, + 122.378990173, + 54.7077331543, + 6.68141078949, + -6.7650809288, + -0.911539852619, + 7.60771179199 + ], + [ + 80.1878204346, + -6.41311454773, + 34.4428405762, + 21.9955101013, + 23.9828796387, + 9.08637428284, + 4.36477804184, + 54.7077331543, + 120.954666138, + 41.4050827026, + -25.8017272949, + -5.81494665146, + -0.236202299595 + ], + [ + 192.214401245, + 74.1020736694, + -69.080619812, + 12.8328580856, + 28.7067451477, + -21.2720279694, + 25.2697525024, + 6.68141078949, + 41.4050827026, + 102.835891724, + 31.3814048767, + -2.45175004005, + -1.74627566338 + ], + [ + -182.145751953, + -56.9916381836, + 85.0990753174, + -40.3507461548, + 2.99768400192, + 42.7490844727, + 7.5669798851, + -6.7650809288, + -25.8017272949, + 31.3814048767, + 120.884010315, + 22.8159122467, + -8.79971408844 + ], + [ + -47.5592041016, + -16.3797187805, + -36.5973091125, + 8.21014022827, + 18.3751049042, + 11.0748538971, + 29.0018577576, + -0.911539852619, + -5.81494665146, + -2.45175004005, + 22.8159122467, + 87.9682235718, + 38.346157074 + ], + [ + 152.686767578, + -19.4202880859, + -56.1265907288, + 19.1214065552, + 10.1154251099, + 0.872315227985, + 7.81967544556, + 7.60771179199, + -0.236202299595, + -1.74627566338, + -8.79971408844, + 38.346157074, + 87.662071228 + ] + ] + }, + "spectral_contrast_valleys":{ + "min":[ + -27.644701004, + -27.7437572479, + -27.5804691315, + -27.6421985626, + -27.3466243744, + -27.4174346924 + ], + "max":[ + -5.21189641953, + -4.43200492859, + -5.37789392471, + -5.91939544678, + -5.84870004654, + -8.253657341 + ], + "dvar2":[ + 0.418128162622, + 0.42821636796, + 0.406443417072, + 0.387645244598, + 0.499291837215, + 0.697984993458 + ], + "median":[ + -7.62850189209, + -6.92876195908, + -7.67359733582, + -8.07751655579, + -7.46400737762, + -11.0671672821 + ], + "dmean2":[ + 0.747626721859, + 0.710296332836, + 0.67908090353, + 0.625626146793, + 0.595694363117, + 0.680769026279 + ], + "dmean":[ + 0.493877381086, + 0.47190451622, + 0.458809673786, + 0.433981686831, + 0.418061226606, + 0.529967188835 + ], + "var":[ + 2.56318879128, + 2.56686043739, + 2.68657803535, + 2.71048474312, + 2.86386156082, + 2.03321886063 + ], + "dvar":[ + 0.185303419828, + 0.210249379277, + 0.205063581467, + 0.197276696563, + 0.240655809641, + 0.327577888966 + ], + "mean":[ + -7.9825963974, + -7.30778980255, + -8.13263988495, + -8.62220096588, + -8.10116863251, + -11.1167650223 + ] + }, + "barkbands_flatness_db":{ + "min":0.00845116842538, + "max":0.463767468929, + "dvar2":0.00153901893646, + "median":0.152025014162, + "dmean2":0.0385256558657, + "dmean":0.0259312130511, + "var":0.00293617043644, + "dvar":0.000700293399859, + "mean":0.161552548409 + }, + "dynamic_complexity":5.97568511963, + "spectral_skewness":{ + "min":-0.258594423532, + "max":7.78090715408, + "dvar2":0.501113593578, + "median":1.41668355465, + "dmean2":0.598508477211, + "dmean":0.382409095764, + "var":0.599681735039, + "dvar":0.224964693189, + "mean":1.57063114643 + }, + "erbbands_flatness_db":{ + "min":0.0321905463934, + "max":0.434577912092, + "dvar2":0.00118384102825, + "median":0.181439816952, + "dmean2":0.0333808884025, + "dmean":0.024810899049, + "var":0.00294912024401, + "dvar":0.000594827288296, + "mean":0.178649738431 + }, + "hfc":{ + "min":1.12110872149e-16, + "max":96.712890625, + "dvar2":109.576454163, + "median":11.9836702347, + "dmean2":6.97959280014, + "dmean":4.67007303238, + "var":197.084396362, + "dvar":50.9854736328, + "mean":14.6673564911 + }, + "barkbands_crest":{ + "min":2.1863629818, + "max":25.4534358978, + "dvar2":11.5983400345, + "median":8.56367301941, + "dmean2":3.74820661545, + "dmean":2.30216050148, + "var":11.5966396332, + "dvar":4.54739236832, + "mean":9.14883136749 + } + }, + "highlevel":{ + "timbre":{ + "all":{ + "dark":0.0808309540153, + "bright":0.919169068336 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"bright", + "probability":0.919169068336 + }, + "ismir04_rhythm":{ + "all":{ + "Rumba-American":0.0406456775963, + "VienneseWaltz":0.338310062885, + "Samba":0.0297329928726, + "Rumba-Misc":0.0135653112084, + "Rumba-International":0.0278510767967, + "Tango":0.330144882202, + "Waltz":0.00898563489318, + "ChaChaCha":0.0889096781611, + "Jive":0.11033257097, + "Quickstep":0.0115221142769 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"VienneseWaltz", + "probability":0.338310062885 + }, + "voice_instrumental":{ + "all":{ + "instrumental":0.999981045723, + "voice":1.89501206478e-05 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"instrumental", + "probability":0.999981045723 + }, + "gender":{ + "all":{ + "male":0.108683988452, + "female":0.891315996647 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"female", + "probability":0.891315996647 + }, + "genre_rosamerica":{ + "all":{ + "hip":0.070330247283, + "rhy":0.225707545877, + "jaz":0.0771619826555, + "dan":0.0574826933444, + "roc":0.270465612411, + "cla":0.0938607081771, + "pop":0.175827592611, + "spe":0.0291636306792 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"roc", + "probability":0.270465612411 + }, + "mood_electronic":{ + "all":{ + "electronic":0.339881360531, + "not_electronic":0.660118639469 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"not_electronic", + "probability":0.660118639469 + }, + "genre_electronic":{ + "all":{ + "house":0.187250360847, + "trance":0.185409858823, + "dnb":0.00702595943585, + "techno":0.0184047427028, + "ambient":0.601909101009 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"ambient", + "probability":0.601909101009 + }, + "mood_sad":{ + "all":{ + "not_sad":0.700305402279, + "sad":0.299694597721 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"not_sad", + "probability":0.700305402279 + }, + "tonal_atonal":{ + "all":{ + "atonal":0.125749841332, + "tonal":0.874250173569 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"tonal", + "probability":0.874250173569 + }, + "mood_party":{ + "all":{ + "party":0.234383180737, + "not_party":0.765616834164 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"not_party", + "probability":0.765616834164 + }, + "moods_mirex":{ + "all":{ + "Cluster2":0.0673071071506, + "Cluster3":0.397048592567, + "Cluster1":0.061667304486, + "Cluster4":0.190215244889, + "Cluster5":0.283761769533 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"Cluster3", + "probability":0.397048592567 + }, + "danceability":{ + "all":{ + "danceable":0.143928021193, + "not_danceable":0.85607200861 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"not_danceable", + "probability":0.85607200861 + }, + "genre_dortmund":{ + "all":{ + "raphiphop":4.74844455312e-05, + "electronic":0.984485208988, + "jazz":0.000787914788816, + "pop":0.000125292601297, + "folkcountry":0.00235203420743, + "rock":0.0010081063956, + "alternative":0.00961782038212, + "funksoulrnb":6.0458383814e-05, + "blues":0.00151570443995 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"electronic", + "probability":0.984485208988 + }, + "mood_acoustic":{ + "all":{ + "acoustic":0.415711194277, + "not_acoustic":0.584288835526 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"not_acoustic", + "probability":0.584288835526 + }, + "mood_happy":{ + "all":{ + "not_happy":0.910523295403, + "happy":0.0894767045975 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"not_happy", + "probability":0.910523295403 + }, + "mood_aggressive":{ + "all":{ + "not_aggressive":0.922077834606, + "aggressive":0.0779221653938 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"not_aggressive", + "probability":0.922077834606 + }, + "genre_tzanetakis":{ + "all":{ + "hip":0.154464527965, + "jaz":0.308918893337, + "bl":0.0514711923897, + "roc":0.0772226303816, + "cla":0.0343172624707, + "pop":0.0617748275399, + "met":0.0441242903471, + "co":0.102957598865, + "reg":0.0617764480412, + "dis":0.102972343564 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"jaz", + "probability":0.308918893337 + }, + "mood_relaxed":{ + "all":{ + "not_relaxed":0.87636756897, + "relaxed":0.123632438481 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"not_relaxed", + "probability":0.87636756897 + } + }, + "metadata":{ + "audio_properties":{ + "analysis_sample_rate":44100, + "length":214.866668701, + "downmix":"mix", + "bit_rate":0, + "codec":"flac", + "md5_encoded":"2b46dab358c1b79a3decd5bd93d7221f", + "equal_loudness":0, + "replay_gain":-14.4778690338, + "lossless":1 + }, + "version":{ + "lowlevel":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "essentia_build_sha":"50a0fbec89d6a9cedea3d45b6611406f7e8c7b1a", + "essentia_git_sha":"v2.1_beta1-7-ge0e83e8-dirty" + }, + "highlevel":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + } + }, + "tags":{ + "albumartistsort":[ + "Various Artists" + ], + "disctotal":[ + "1" + ], + "file_name":"04 La Grange.flac", + "artists":[ + "ZZ Top" + ], + "musicbrainz_workid":[ + "42722fe8-9de7-3729-a506-3c7f41c617a9" + ], + "releasecountry":[ + "DE" + ], + "totaldiscs":[ + "1" + ], + "albumartist":[ + "Various Artists" + ], + "musicbrainz_albumartistid":[ + "89ad4ac3-39f7-470e-963a-56509c546377" + ], + "composer":[ + "Dusty Hill", + "Frank Beard", + "Billy Gibbons" + ], + "catalognumber":[ + "491384 2" + ], + "tracknumber":[ + "4" + ], + "replaygain_track_peak":[ + "0.999969" + ], + "engineer":[ + "Terry Manning", + "Robin Hood Brians" + ], + "album":[ + "Armageddon:The Album" + ], + "asin":[ + "B000024C3A" + ], + "replaygain_album_gain":[ + "-9.32 dB" + ], + "musicbrainz_artistid":[ + "a81259a0-a2f5-464b-866e-71220f2739f1" + ], + "producer":[ + "Bill Ham" + ], + "script":[ + "Latn" + ], + "media":[ + "CD" + ], + "label":[ + "Columbia" + ], + "artistsort":[ + "ZZ Top" + ], + "acoustid_id":[ + "3ed3441e-facc-4fcd-9ef7-9fbc68c206a2" + ], + "replaygain_album_peak":[ + "0.999969" + ], + "lyricist":[ + "Dusty Hill", + "Frank Beard", + "Billy Gibbons" + ], + "musicbrainz_releasegroupid":[ + "f51d56e4-0211-3533-a9a5-08c02d8bb04a" + ], + "compilation":[ + "1" + ], + "barcode":[ + "5099749138421" + ], + "releasestatus":[ + "official" + ], + "composersort":[ + "Hill, Dusty", + "Beard, Frank", + "Gibbons, Billy" + ], + "date":[ + "1998" + ], + "isrc":[ + "USWB10505222" + ], + "discnumber":[ + "1" + ], + "musicbrainz_recordingid":[ + "cd3f5efa-bc5e-4064-a765-960494ad4bb4" + ], + "tracktotal":[ + "14" + ], + "originaldate":[ + "1998-06-23" + ], + "language":[ + "eng" + ], + "artist":[ + "ZZ Top" + ], + "title":[ + "La Grange" + ], + "releasetype":[ + "album", + "soundtrack" + ], + "musicbrainz_albumid":[ + "cfc31187-aebd-309f-a92f-7138c17df7c2" + ], + "work":[ + "La Grange" + ], + "totaltracks":[ + "14" + ], + "replaygain_track_gain":[ + "-9.38 dB" + ], + "musicbrainz_releasetrackid":[ + "befe2741-462b-3568-ba06-c8cc8e4f6eaf" + ] + } + } +} diff --git a/test/rsrc/beetsplug/test.py b/test/rsrc/beetsplug/test.py index 79f787ae0..6dedd0e33 100644 --- a/test/rsrc/beetsplug/test.py +++ b/test/rsrc/beetsplug/test.py @@ -1,5 +1,6 @@ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +# -*- coding: utf-8 -*- + +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets import ui @@ -15,7 +16,7 @@ class TestPlugin(BeetsPlugin): test.func = lambda *args: None # Used in CompletionTest - test.parser.add_option('-o', '--option', dest='my_opt') + test.parser.add_option(u'-o', u'--option', dest='my_opt') plugin = ui.Subcommand('plugin') plugin.func = lambda *args: None diff --git a/test/rsrc/convert_stub.py b/test/rsrc/convert_stub.py new file mode 100755 index 000000000..cb42692d7 --- /dev/null +++ b/test/rsrc/convert_stub.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +"""A tiny tool used to test the `convert` plugin. It copies a file and appends +a specified text tag. +""" + +from __future__ import division, absolute_import, print_function +import sys +import platform +import locale + +PY2 = sys.version_info[0] == 2 + + +# From `beets.util`. +def arg_encoding(): + try: + return locale.getdefaultlocale()[1] or 'utf-8' + except ValueError: + return 'utf-8' + + +def convert(in_file, out_file, tag): + """Copy `in_file` to `out_file` and append the string `tag`. + """ + # On Python 3, encode the tag argument as bytes. + if not isinstance(tag, bytes): + tag = tag.encode('utf-8') + + # On Windows, use Unicode paths. On Python 3, we get the actual, + # Unicode filenames. On Python 2, we get them as UTF-8 byes. + if platform.system() == 'Windows' and PY2: + in_file = in_file.decode('utf-8') + out_file = out_file.decode('utf-8') + + with open(out_file, 'wb') as out_f: + with open(in_file, 'rb') as in_f: + out_f.write(in_f.read()) + out_f.write(tag) + + +if __name__ == '__main__': + convert(sys.argv[1], sys.argv[2], sys.argv[3]) diff --git a/test/rsrc/empty.dsf b/test/rsrc/empty.dsf new file mode 100644 index 000000000..4cbceb3c9 Binary files /dev/null and b/test/rsrc/empty.dsf differ diff --git a/test/rsrc/full.dsf b/test/rsrc/full.dsf new file mode 100644 index 000000000..a90e6946f Binary files /dev/null and b/test/rsrc/full.dsf differ diff --git a/test/rsrc/image-jpeg.mp3 b/test/rsrc/image-jpeg.mp3 new file mode 100644 index 000000000..3f2d22ffb Binary files /dev/null and b/test/rsrc/image-jpeg.mp3 differ diff --git a/test/rsrc/image_unknown_type.mp3 b/test/rsrc/image_unknown_type.mp3 old mode 100755 new mode 100644 diff --git a/test/rsrc/lyricstext.yaml b/test/rsrc/lyricstext.yaml index 814c207df..7ae1a70e7 100644 --- a/test/rsrc/lyricstext.yaml +++ b/test/rsrc/lyricstext.yaml @@ -1,45 +1,56 @@ -Beets_song: - - geeks - - bouquet - - panacea +# Song used by LyricsGooglePluginMachineryTest -Amsterdam: - - oriflammes - - fortune - - batave - - pissent - -Lady_Madonna: - - heaven - - tuesday - - thursday - -Jazz_n_blues: - - parkway - - balance - - impatient - - shoes - -Hey_it_s_ok: - - swear - - forgive - - drink - - found - -City_of_dreams: - - groves - - landmarks - - twilight - - freeways - -Black_magic_woman: - - devil - - magic - - spell - - heart +Beets_song: | + beets is the media library management system for obsessive-compulsive music geeks the purpose of + beets is to get your music collection right once and for all it catalogs your collection + automatically improving its metadata as it goes it then provides a bouquet of tools for + manipulating and accessing your music here's an example of beets' brainy tag corrector doing its + because beets is designed as a library it can do almost anything you can imagine for your + music collection via plugins beets becomes a panacea missing_texts: | Lyricsmania staff is working hard for you to add $TITLE lyrics as soon as they'll be released by $ARTIST, check back soon! In case you have the lyrics to $TITLE and want to send them to us, fill out the following form. + +# Songs lyrics used to test the different sources present in the google custom search engine. +# Text is randomized for copyright infringement reason. + +Amsterdam: | + coup corps coeur invitent mains comme trop morue le hantent mais la dames joli revenir aux + mangent croquer pleine plantent rire de sortent pleins fortune d'amsterdam bruit ruisselants + large poissons braguette leur putains blanches jusque pissent dans soleils dansent et port + bien vertu nez sur chaleur femmes rotant dorment marins boivent bu les que d'un qui je + une cou hambourg plus ils dents ou tournent or berges d'ailleurs tout ciel haubans ce son lueurs + en lune ont mouchent leurs long frottant jusqu'en vous regard montrent langueurs chantent + tordent pleure donnent drames mornes des panse pour un sent encore referment nappes au meurent + geste quand puis alors frites grosses batave expire naissent reboivent oriflammes grave riant a + enfin rance fier y bouffer s'entendre se mieux + +Lady_Madonna: | + feed his money tuesday manage didn't head feet see arrives at in madonna rest morning children + wonder how make thursday your to sunday music papers come tie you has was is listen suitcase + ends friday run that needed breast they child baby mending on lady learned a nun like did wednesday + bed think without afternoon night meet the playing lying + +Jazz_n_blues: | + all shoes money through follow blow til father to his hit jazz kiss now cool bar cause 50 night + heading i'll says yeah cash forgot blues out what for ways away fingers waiting got ever bold + screen sixty throw wait on about last compton days o pick love wall had within jeans jd next + miss standing from it's two long fight extravagant tell today more buy shopping that didn't + what's but russian up can parkway balance my and gone am it as at in check if bags when cross + machine take you drinks coke june wrong coming fancy's i n' impatient so the main's spend + that's + +Hey_it_s_ok: | + and forget be when please it against fighting mama cause ! again what said + things papa hey to much lovers way wet was too do drink and i who forgive + hey fourteen please know not wanted had myself ok friends bed times looked + swear act found the my mean + +Black_magic_woman: | + blind heart sticks just don't into back alone see need yes your out devil make that to black got + you might me woman turning spell stop baby with 'round a on stone messin' magic i of + tricks up leave turn bad so pick she's my can't + diff --git a/test/rsrc/soundcheck-nonascii.m4a b/test/rsrc/soundcheck-nonascii.m4a new file mode 100644 index 000000000..29f5de531 Binary files /dev/null and b/test/rsrc/soundcheck-nonascii.m4a differ diff --git a/test/rsrc/spotify/missing_request.json b/test/rsrc/spotify/missing_request.json new file mode 100644 index 000000000..b18ceb859 --- /dev/null +++ b/test/rsrc/spotify/missing_request.json @@ -0,0 +1,11 @@ +{ + "tracks" : { + "href" : "https://api.spotify.com/v1/search?query=duifhjslkef+album%3Alkajsdflakjsd+artist%3A&offset=0&limit=20&type=track", + "items" : [ ], + "limit" : 20, + "next" : null, + "offset" : 0, + "previous" : null, + "total" : 0 + } +} \ No newline at end of file diff --git a/test/rsrc/spotify/track_request.json b/test/rsrc/spotify/track_request.json new file mode 100644 index 000000000..5d6fb252e --- /dev/null +++ b/test/rsrc/spotify/track_request.json @@ -0,0 +1,89 @@ +{ + "tracks":{ + "href":"https://api.spotify.com/v1/search?query=Happy+album%3ADespicable+Me+2+artist%3APharrell+Williams&offset=0&limit=20&type=track", + "items":[ + { + "album":{ + "album_type":"compilation", + "available_markets":[ + "AD", "AR", "AT", "AU", "BE", "BG", "BO", "BR", "CA", + "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", + "EC", "EE", "ES", "FI", "FR", "GB", "GR", "GT", "HK", + "HN", "HU", "IE", "IS", "IT", "LI", "LT", "LU", "LV", + "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "PA", + "PE", "PH", "PL", "PT", "PY", "RO", "SE", "SG", "SI", + "SK", "SV", "TR", "TW", "US", "UY" + ], + "external_urls":{ + "spotify":"https://open.spotify.com/album/5l3zEmMrOhOzG8d8s83GOL" + }, + "href":"https://api.spotify.com/v1/albums/5l3zEmMrOhOzG8d8s83GOL", + "id":"5l3zEmMrOhOzG8d8s83GOL", + "images":[ + { + "height":640, + "width":640, + "url":"https://i.scdn.co/image/cb7905340c132365bbaee3f17498f062858382e8" + }, + { + "height":300, + "width":300, + "url":"https://i.scdn.co/image/af369120f0b20099d6784ab31c88256113f10ffb" + }, + { + "height":64, + "width":64, + "url":"https://i.scdn.co/image/9dad385ddf2e7db0bef20cec1fcbdb08689d9ae8" + } + ], + "name":"Despicable Me 2 (Original Motion Picture Soundtrack)", + "type":"album", + "uri":"spotify:album:5l3zEmMrOhOzG8d8s83GOL" + }, + "artists":[ + { + "external_urls":{ + "spotify":"https://open.spotify.com/artist/2RdwBSPQiwcmiDo9kixcl8" + }, + "href":"https://api.spotify.com/v1/artists/2RdwBSPQiwcmiDo9kixcl8", + "id":"2RdwBSPQiwcmiDo9kixcl8", + "name":"Pharrell Williams", + "type":"artist", + "uri":"spotify:artist:2RdwBSPQiwcmiDo9kixcl8" + } + ], + "available_markets":[ + "AD", "AR", "AT", "AU", "BE", "BG", "BO", "BR", "CA", + "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", + "EC", "EE", "ES", "FI", "FR", "GB", "GR", "GT", "HK", + "HN", "HU", "IE", "IS", "IT", "LI", "LT", "LU", "LV", + "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "PA", + "PE", "PH", "PL", "PT", "PY", "RO", "SE", "SG", "SI", + "SK", "SV", "TR", "TW", "US", "UY" + ], + "disc_number":1, + "duration_ms":233305, + "explicit":false, + "external_ids":{ + "isrc":"USQ4E1300686" + }, + "external_urls":{ + "spotify":"https://open.spotify.com/track/6NPVjNh8Jhru9xOmyQigds" + }, + "href":"https://api.spotify.com/v1/tracks/6NPVjNh8Jhru9xOmyQigds", + "id":"6NPVjNh8Jhru9xOmyQigds", + "name":"Happy", + "popularity":89, + "preview_url":"https://p.scdn.co/mp3-preview/6b00000be293e6b25f61c33e206a0c522b5cbc87", + "track_number":4, + "type":"track", + "uri":"spotify:track:6NPVjNh8Jhru9xOmyQigds" + } + ], + "limit":20, + "next":null, + "offset":0, + "previous":null, + "total":1 + } +} diff --git a/test/test_completion.sh b/test/rsrc/test_completion.sh similarity index 100% rename from test/test_completion.sh rename to test/rsrc/test_completion.sh diff --git a/test/rsrc/unicode’d.mp3 b/test/rsrc/unicode’d.mp3 index ef732eba6..ebc75ce31 100644 Binary files a/test/rsrc/unicode’d.mp3 and b/test/rsrc/unicode’d.mp3 differ diff --git a/test/rsrc/unparseable.dsf b/test/rsrc/unparseable.dsf new file mode 100644 index 000000000..3b6292e32 Binary files /dev/null and b/test/rsrc/unparseable.dsf differ diff --git a/test/test_acousticbrainz.py b/test/test_acousticbrainz.py new file mode 100644 index 000000000..0b1407581 --- /dev/null +++ b/test/test_acousticbrainz.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Nathan Dwek. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Tests for the 'acousticbrainz' plugin. +""" + +from __future__ import division, absolute_import, print_function + +import json +import os.path +import unittest + +from test._common import RSRC + +from beetsplug.acousticbrainz import AcousticPlugin, ABSCHEME + + +class MapDataToSchemeTest(unittest.TestCase): + def test_basic(self): + ab = AcousticPlugin() + data = {'key 1': 'value 1', 'key 2': 'value 2'} + scheme = {'key 1': 'attribute 1', 'key 2': 'attribute 2'} + mapping = set(ab._map_data_to_scheme(data, scheme)) + self.assertEqual(mapping, {('attribute 1', 'value 1'), + ('attribute 2', 'value 2')}) + + def test_recurse(self): + ab = AcousticPlugin() + data = { + 'key': 'value', + 'group': { + 'subkey': 'subvalue', + 'subgroup': { + 'subsubkey': 'subsubvalue' + } + } + } + scheme = { + 'key': 'attribute 1', + 'group': { + 'subkey': 'attribute 2', + 'subgroup': { + 'subsubkey': 'attribute 3' + } + } + } + mapping = set(ab._map_data_to_scheme(data, scheme)) + self.assertEqual(mapping, {('attribute 1', 'value'), + ('attribute 2', 'subvalue'), + ('attribute 3', 'subsubvalue')}) + + def test_composite(self): + ab = AcousticPlugin() + data = {'key 1': 'part 1', 'key 2': 'part 2'} + scheme = {'key 1': ('attribute', 0), 'key 2': ('attribute', 1)} + mapping = set(ab._map_data_to_scheme(data, scheme)) + self.assertEqual(mapping, {('attribute', 'part 1 part 2')}) + + def test_realistic(self): + ab = AcousticPlugin() + data_path = os.path.join(RSRC, b'acousticbrainz/data.json') + with open(data_path) as res: + data = json.load(res) + mapping = set(ab._map_data_to_scheme(data, ABSCHEME)) + expected = { + ('chords_key', 'A'), + ('average_loudness', 0.815025985241), + ('mood_acoustic', 0.415711194277), + ('chords_changes_rate', 0.0445116683841), + ('tonal', 0.874250173569), + ('mood_sad', 0.299694597721), + ('bpm', 162.532119751), + ('gender', 'female'), + ('initial_key', 'A minor'), + ('chords_number_rate', 0.00194468453992), + ('mood_relaxed', 0.123632438481), + ('chords_scale', 'minor'), + ('voice_instrumental', 'instrumental'), + ('key_strength', 0.636936545372), + ('genre_rosamerica', 'roc'), + ('mood_party', 0.234383180737), + ('mood_aggressive', 0.0779221653938), + ('danceable', 0.143928021193), + ('rhythm', 'VienneseWaltz'), + ('mood_electronic', 0.339881360531), + ('mood_happy', 0.0894767045975) + } + self.assertEqual(mapping, expected) + + +def suite(): + return unittest.TestLoader().loadTestsFromName(__name__) + +if __name__ == '__main__': + unittest.main(defaultTest='suite') diff --git a/test/test_art.py b/test/test_art.py index 3cc24a7a4..a95cd4c95 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,141 +15,186 @@ """Tests for the album art fetchers.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import os import shutil +import unittest import responses +from mock import patch from test import _common -from test._common import unittest from beetsplug import fetchart from beets.autotag import AlbumInfo, AlbumMatch +from beets import config from beets import library from beets import importer -from beets import config from beets import logging +from beets import util from beets.util.artresizer import ArtResizer, WEBPROXY +from beets.util import confit logger = logging.getLogger('beets.test_art') +class Settings(): + """Used to pass settings to the ArtSources when the plugin isn't fully + instantiated. + """ + def __init__(self, **kwargs): + for k, v in kwargs.items(): + setattr(self, k, v) + + class UseThePlugin(_common.TestCase): def setUp(self): super(UseThePlugin, self).setUp() self.plugin = fetchart.FetchArtPlugin() -class FetchImageTest(UseThePlugin): +class FetchImageHelper(_common.TestCase): + """Helper mixin for mocking requests when fetching images + with remote art sources. + """ @responses.activate def run(self, *args, **kwargs): - super(FetchImageTest, self).run(*args, **kwargs) + super(FetchImageHelper, self).run(*args, **kwargs) - def mock_response(self, content_type): - responses.add(responses.GET, 'http://example.com', - content_type=content_type) + IMAGEHEADER = {'image/jpeg': b'\x00' * 6 + b'JFIF', + 'image/png': b'\211PNG\r\n\032\n', } + + def mock_response(self, url, content_type='image/jpeg', file_type=None): + if file_type is None: + file_type = content_type + responses.add(responses.GET, url, + content_type=content_type, + # imghdr reads 32 bytes + body=self.IMAGEHEADER.get( + file_type, b'').ljust(32, b'\x00')) + + +class FetchImageTest(FetchImageHelper, UseThePlugin): + URL = 'http://example.com/test.jpg' + + def setUp(self): + super(FetchImageTest, self).setUp() + self.dpath = os.path.join(self.temp_dir, b'arttest') + self.source = fetchart.RemoteArtSource(logger, self.plugin.config) + self.settings = Settings(maxwidth=0) + self.candidate = fetchart.Candidate(logger, url=self.URL) def test_invalid_type_returns_none(self): - self.mock_response('image/watercolour') - artpath = self.plugin._fetch_image('http://example.com') - self.assertEqual(artpath, None) + self.mock_response(self.URL, 'image/watercolour') + self.source.fetch_image(self.candidate, self.settings) + self.assertEqual(self.candidate.path, None) def test_jpeg_type_returns_path(self): - self.mock_response('image/jpeg') - artpath = self.plugin._fetch_image('http://example.com') - self.assertNotEqual(artpath, None) + self.mock_response(self.URL, 'image/jpeg') + self.source.fetch_image(self.candidate, self.settings) + self.assertNotEqual(self.candidate.path, None) + + def test_extension_set_by_content_type(self): + self.mock_response(self.URL, 'image/png') + self.source.fetch_image(self.candidate, self.settings) + self.assertEqual(os.path.splitext(self.candidate.path)[1], b'.png') + self.assertExists(self.candidate.path) + + def test_does_not_rely_on_server_content_type(self): + self.mock_response(self.URL, 'image/jpeg', 'image/png') + self.source.fetch_image(self.candidate, self.settings) + self.assertEqual(os.path.splitext(self.candidate.path)[1], b'.png') + self.assertExists(self.candidate.path) -class FSArtTest(_common.TestCase): +class FSArtTest(UseThePlugin): def setUp(self): super(FSArtTest, self).setUp() - self.dpath = os.path.join(self.temp_dir, 'arttest') + self.dpath = os.path.join(self.temp_dir, b'arttest') os.mkdir(self.dpath) - self.source = fetchart.FileSystem(logger) + self.source = fetchart.FileSystem(logger, self.plugin.config) + self.settings = Settings(cautious=False, + cover_names=('art',)) def test_finds_jpg_in_directory(self): - _common.touch(os.path.join(self.dpath, 'a.jpg')) - fn = self.source.get(self.dpath, ('art',), False) - self.assertEqual(fn, os.path.join(self.dpath, 'a.jpg')) + _common.touch(os.path.join(self.dpath, b'a.jpg')) + candidate = next(self.source.get(None, self.settings, [self.dpath])) + self.assertEqual(candidate.path, os.path.join(self.dpath, b'a.jpg')) def test_appropriately_named_file_takes_precedence(self): - _common.touch(os.path.join(self.dpath, 'a.jpg')) - _common.touch(os.path.join(self.dpath, 'art.jpg')) - fn = self.source.get(self.dpath, ('art',), False) - self.assertEqual(fn, os.path.join(self.dpath, 'art.jpg')) + _common.touch(os.path.join(self.dpath, b'a.jpg')) + _common.touch(os.path.join(self.dpath, b'art.jpg')) + candidate = next(self.source.get(None, self.settings, [self.dpath])) + self.assertEqual(candidate.path, os.path.join(self.dpath, b'art.jpg')) def test_non_image_file_not_identified(self): - _common.touch(os.path.join(self.dpath, 'a.txt')) - fn = self.source.get(self.dpath, ('art',), False) - self.assertEqual(fn, None) + _common.touch(os.path.join(self.dpath, b'a.txt')) + with self.assertRaises(StopIteration): + next(self.source.get(None, self.settings, [self.dpath])) def test_cautious_skips_fallback(self): - _common.touch(os.path.join(self.dpath, 'a.jpg')) - fn = self.source.get(self.dpath, ('art',), True) - self.assertEqual(fn, None) + _common.touch(os.path.join(self.dpath, b'a.jpg')) + self.settings.cautious = True + with self.assertRaises(StopIteration): + next(self.source.get(None, self.settings, [self.dpath])) def test_empty_dir(self): - fn = self.source.get(self.dpath, ('art',), True) - self.assertEqual(fn, None) + with self.assertRaises(StopIteration): + next(self.source.get(None, self.settings, [self.dpath])) def test_precedence_amongst_correct_files(self): - _common.touch(os.path.join(self.dpath, 'back.jpg')) - _common.touch(os.path.join(self.dpath, 'front.jpg')) - _common.touch(os.path.join(self.dpath, 'front-cover.jpg')) - fn = self.source.get(self.dpath, ('cover', 'front', 'back'), False) - self.assertEqual(fn, os.path.join(self.dpath, 'front-cover.jpg')) + images = [b'front-cover.jpg', b'front.jpg', b'back.jpg'] + paths = [os.path.join(self.dpath, i) for i in images] + for p in paths: + _common.touch(p) + self.settings.cover_names = ['cover', 'front', 'back'] + candidates = [candidate.path for candidate in + self.source.get(None, self.settings, [self.dpath])] + self.assertEqual(candidates, paths) -class CombinedTest(UseThePlugin): +class CombinedTest(FetchImageHelper, UseThePlugin): ASIN = 'xxxx' MBID = 'releaseid' AMAZON_URL = 'http://images.amazon.com/images/P/{0}.01.LZZZZZZZ.jpg' \ .format(ASIN) AAO_URL = 'http://www.albumart.org/index_detail.php?asin={0}' \ .format(ASIN) - CAA_URL = 'http://coverartarchive.org/release/{0}/front' \ + CAA_URL = 'coverartarchive.org/release/{0}/front' \ .format(MBID) def setUp(self): super(CombinedTest, self).setUp() - self.dpath = os.path.join(self.temp_dir, 'arttest') + self.dpath = os.path.join(self.temp_dir, b'arttest') os.mkdir(self.dpath) - @responses.activate - def run(self, *args, **kwargs): - super(CombinedTest, self).run(*args, **kwargs) - - def mock_response(self, url, content_type='image/jpeg'): - responses.add(responses.GET, url, content_type=content_type) - def test_main_interface_returns_amazon_art(self): self.mock_response(self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) - artpath = self.plugin.art_for_album(album, None) - self.assertNotEqual(artpath, None) + candidate = self.plugin.art_for_album(album, None) + self.assertIsNotNone(candidate) def test_main_interface_returns_none_for_missing_asin_and_path(self): album = _common.Bag() - artpath = self.plugin.art_for_album(album, None) - self.assertEqual(artpath, None) + candidate = self.plugin.art_for_album(album, None) + self.assertIsNone(candidate) def test_main_interface_gives_precedence_to_fs_art(self): - _common.touch(os.path.join(self.dpath, 'art.jpg')) + _common.touch(os.path.join(self.dpath, b'art.jpg')) self.mock_response(self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) - artpath = self.plugin.art_for_album(album, [self.dpath]) - self.assertEqual(artpath, os.path.join(self.dpath, 'art.jpg')) + candidate = self.plugin.art_for_album(album, [self.dpath]) + self.assertIsNotNone(candidate) + self.assertEqual(candidate.path, os.path.join(self.dpath, b'art.jpg')) def test_main_interface_falls_back_to_amazon(self): self.mock_response(self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) - artpath = self.plugin.art_for_album(album, [self.dpath]) - self.assertNotEqual(artpath, None) - self.assertFalse(artpath.startswith(self.dpath)) + candidate = self.plugin.art_for_album(album, [self.dpath]) + self.assertIsNotNone(candidate) + self.assertFalse(candidate.path.startswith(self.dpath)) def test_main_interface_tries_amazon_before_aao(self): self.mock_response(self.AMAZON_URL) @@ -164,36 +210,41 @@ class CombinedTest(UseThePlugin): self.assertEqual(responses.calls[-1].request.url, self.AAO_URL) def test_main_interface_uses_caa_when_mbid_available(self): - self.mock_response(self.CAA_URL) + self.mock_response("http://" + self.CAA_URL) + self.mock_response("https://" + self.CAA_URL) album = _common.Bag(mb_albumid=self.MBID, asin=self.ASIN) - artpath = self.plugin.art_for_album(album, None) - self.assertNotEqual(artpath, None) + candidate = self.plugin.art_for_album(album, None) + self.assertIsNotNone(candidate) self.assertEqual(len(responses.calls), 1) - self.assertEqual(responses.calls[0].request.url, self.CAA_URL) + if util.SNI_SUPPORTED: + url = "https://" + self.CAA_URL + else: + url = "http://" + self.CAA_URL + self.assertEqual(responses.calls[0].request.url, url) def test_local_only_does_not_access_network(self): album = _common.Bag(mb_albumid=self.MBID, asin=self.ASIN) - artpath = self.plugin.art_for_album(album, [self.dpath], - local_only=True) - self.assertEqual(artpath, None) + self.plugin.art_for_album(album, None, local_only=True) self.assertEqual(len(responses.calls), 0) def test_local_only_gets_fs_image(self): - _common.touch(os.path.join(self.dpath, 'art.jpg')) + _common.touch(os.path.join(self.dpath, b'art.jpg')) album = _common.Bag(mb_albumid=self.MBID, asin=self.ASIN) - artpath = self.plugin.art_for_album(album, [self.dpath], - local_only=True) - self.assertEqual(artpath, os.path.join(self.dpath, 'art.jpg')) + candidate = self.plugin.art_for_album(album, [self.dpath], + local_only=True) + self.assertIsNotNone(candidate) + self.assertEqual(candidate.path, os.path.join(self.dpath, b'art.jpg')) self.assertEqual(len(responses.calls), 0) -class AAOTest(_common.TestCase): +class AAOTest(UseThePlugin): ASIN = 'xxxx' AAO_URL = 'http://www.albumart.org/index_detail.php?asin={0}'.format(ASIN) def setUp(self): super(AAOTest, self).setUp() - self.source = fetchart.AlbumArtOrg(logger) + self.source = fetchart.AlbumArtOrg(logger, self.plugin.config) + self.settings = Settings() @responses.activate def run(self, *args, **kwargs): @@ -204,32 +255,30 @@ class AAOTest(_common.TestCase): match_querystring=True) def test_aao_scraper_finds_image(self): - body = b""" + body = """ <br /> - <a href="TARGET_URL" title="View larger image" - class="thickbox" style="color: #7E9DA2; text-decoration:none;"> - <img src="http://www.albumart.org/images/zoom-icon.jpg" - alt="View larger image" width="17" height="15" border="0"/></a> + <a href=\"TARGET_URL\" title=\"View larger image\" + class=\"thickbox\" style=\"color: #7E9DA2; text-decoration:none;\"> + <img src=\"http://www.albumart.org/images/zoom-icon.jpg\" + alt=\"View larger image\" width=\"17\" height=\"15\" border=\"0\"/></a> """ self.mock_response(self.AAO_URL, body) album = _common.Bag(asin=self.ASIN) - res = self.source.get(album) - self.assertEqual(list(res)[0], 'TARGET_URL') + candidate = next(self.source.get(album, self.settings, [])) + self.assertEqual(candidate.url, 'TARGET_URL') def test_aao_scraper_returns_no_result_when_no_image_present(self): - self.mock_response(self.AAO_URL, b'blah blah') + self.mock_response(self.AAO_URL, 'blah blah') album = _common.Bag(asin=self.ASIN) - res = self.source.get(album) - self.assertEqual(list(res), []) + with self.assertRaises(StopIteration): + next(self.source.get(album, self.settings, [])) -class GoogleImageTest(_common.TestCase): - - _google_url = 'https://ajax.googleapis.com/ajax/services/search/images' - +class GoogleImageTest(UseThePlugin): def setUp(self): super(GoogleImageTest, self).setUp() - self.source = fetchart.GoogleImages(logger) + self.source = fetchart.GoogleImages(logger, self.plugin.config) + self.settings = Settings() @responses.activate def run(self, *args, **kwargs): @@ -241,29 +290,137 @@ class GoogleImageTest(_common.TestCase): def test_google_art_finds_image(self): album = _common.Bag(albumartist="some artist", album="some album") - json = b"""{"responseData": {"results": - [{"unescapedUrl": "url_to_the_image"}]}}""" - self.mock_response(self._google_url, json) - result_url = self.source.get(album) - self.assertEqual(list(result_url)[0], 'url_to_the_image') + json = '{"items": [{"link": "url_to_the_image"}]}' + self.mock_response(fetchart.GoogleImages.URL, json) + candidate = next(self.source.get(album, self.settings, [])) + self.assertEqual(candidate.url, 'url_to_the_image') - def test_google_art_dont_finds_image(self): + def test_google_art_returns_no_result_when_error_received(self): album = _common.Bag(albumartist="some artist", album="some album") - json = b"""bla blup""" - self.mock_response(self._google_url, json) - result_url = self.source.get(album) - self.assertEqual(list(result_url), []) + json = '{"error": {"errors": [{"reason": "some reason"}]}}' + self.mock_response(fetchart.GoogleImages.URL, json) + with self.assertRaises(StopIteration): + next(self.source.get(album, self.settings, [])) + + def test_google_art_returns_no_result_with_malformed_response(self): + album = _common.Bag(albumartist="some artist", album="some album") + json = """bla blup""" + self.mock_response(fetchart.GoogleImages.URL, json) + with self.assertRaises(StopIteration): + next(self.source.get(album, self.settings, [])) +class FanartTVTest(UseThePlugin): + RESPONSE_MULTIPLE = u"""{ + "name": "artistname", + "mbid_id": "artistid", + "albums": { + "thereleasegroupid": { + "albumcover": [ + { + "id": "24", + "url": "http://example.com/1.jpg", + "likes": "0" + }, + { + "id": "42", + "url": "http://example.com/2.jpg", + "likes": "0" + }, + { + "id": "23", + "url": "http://example.com/3.jpg", + "likes": "0" + } + ], + "cdart": [ + { + "id": "123", + "url": "http://example.com/4.jpg", + "likes": "0", + "disc": "1", + "size": "1000" + } + ] + } + } + }""" + RESPONSE_NO_ART = u"""{ + "name": "artistname", + "mbid_id": "artistid", + "albums": { + "thereleasegroupid": { + "cdart": [ + { + "id": "123", + "url": "http://example.com/4.jpg", + "likes": "0", + "disc": "1", + "size": "1000" + } + ] + } + } + }""" + RESPONSE_ERROR = u"""{ + "status": "error", + "error message": "the error message" + }""" + RESPONSE_MALFORMED = u"bla blup" + + def setUp(self): + super(FanartTVTest, self).setUp() + self.source = fetchart.FanartTV(logger, self.plugin.config) + self.settings = Settings() + + @responses.activate + def run(self, *args, **kwargs): + super(FanartTVTest, self).run(*args, **kwargs) + + def mock_response(self, url, json): + responses.add(responses.GET, url, body=json, + content_type='application/json') + + def test_fanarttv_finds_image(self): + album = _common.Bag(mb_releasegroupid=u'thereleasegroupid') + self.mock_response(fetchart.FanartTV.API_ALBUMS + u'thereleasegroupid', + self.RESPONSE_MULTIPLE) + candidate = next(self.source.get(album, self.settings, [])) + self.assertEqual(candidate.url, 'http://example.com/1.jpg') + + def test_fanarttv_returns_no_result_when_error_received(self): + album = _common.Bag(mb_releasegroupid=u'thereleasegroupid') + self.mock_response(fetchart.FanartTV.API_ALBUMS + u'thereleasegroupid', + self.RESPONSE_ERROR) + with self.assertRaises(StopIteration): + next(self.source.get(album, self.settings, [])) + + def test_fanarttv_returns_no_result_with_malformed_response(self): + album = _common.Bag(mb_releasegroupid=u'thereleasegroupid') + self.mock_response(fetchart.FanartTV.API_ALBUMS + u'thereleasegroupid', + self.RESPONSE_MALFORMED) + with self.assertRaises(StopIteration): + next(self.source.get(album, self.settings, [])) + + def test_fanarttv_only_other_images(self): + # The source used to fail when there were images present, but no cover + album = _common.Bag(mb_releasegroupid=u'thereleasegroupid') + self.mock_response(fetchart.FanartTV.API_ALBUMS + u'thereleasegroupid', + self.RESPONSE_NO_ART) + with self.assertRaises(StopIteration): + next(self.source.get(album, self.settings, [])) + + +@_common.slow_test() class ArtImporterTest(UseThePlugin): def setUp(self): super(ArtImporterTest, self).setUp() # Mock the album art fetcher to always return our test file. - self.art_file = os.path.join(self.temp_dir, 'tmpcover.jpg') + self.art_file = os.path.join(self.temp_dir, b'tmpcover.jpg') _common.touch(self.art_file) self.old_afa = self.plugin.art_for_album - self.afa_response = self.art_file + self.afa_response = fetchart.Candidate(logger, path=self.art_file) def art_for_album(i, p, local_only=False): return self.afa_response @@ -271,12 +428,12 @@ class ArtImporterTest(UseThePlugin): self.plugin.art_for_album = art_for_album # Test library. - self.libpath = os.path.join(self.temp_dir, 'tmplib.blb') - self.libdir = os.path.join(self.temp_dir, 'tmplib') + self.libpath = os.path.join(self.temp_dir, b'tmplib.blb') + self.libdir = os.path.join(self.temp_dir, b'tmplib') os.mkdir(self.libdir) - os.mkdir(os.path.join(self.libdir, 'album')) - itempath = os.path.join(self.libdir, 'album', 'test.mp3') - shutil.copyfile(os.path.join(_common.RSRC, 'full.mp3'), itempath) + os.mkdir(os.path.join(self.libdir, b'album')) + itempath = os.path.join(self.libdir, b'album', b'test.mp3') + shutil.copyfile(os.path.join(_common.RSRC, b'full.mp3'), itempath) self.lib = library.Library(self.libpath) self.i = _common.item() self.i.path = itempath @@ -291,10 +448,10 @@ class ArtImporterTest(UseThePlugin): self.task.is_album = True self.task.album = self.album info = AlbumInfo( - album='some album', - album_id='albumid', - artist='some artist', - artist_id='artistid', + album=u'some album', + album_id=u'albumid', + artist=u'some artist', + artist_id=u'artistid', tracks=[], ) self.task.set_choice(AlbumMatch(0, info, {}, set(), set())) @@ -318,7 +475,7 @@ class ArtImporterTest(UseThePlugin): if should_exist: self.assertEqual( artpath, - os.path.join(os.path.dirname(self.i.path), 'cover.jpg') + os.path.join(os.path.dirname(self.i.path), b'cover.jpg') ) self.assertExists(artpath) else: @@ -342,79 +499,81 @@ class ArtImporterTest(UseThePlugin): self.assertExists(self.art_file) def test_delete_original_file(self): - config['import']['delete'] = True - self._fetch_art(True) - self.assertNotExists(self.art_file) - - def test_move_original_file(self): - config['import']['move'] = True + self.plugin.src_removed = True self._fetch_art(True) self.assertNotExists(self.art_file) def test_do_not_delete_original_if_already_in_place(self): - artdest = os.path.join(os.path.dirname(self.i.path), 'cover.jpg') + artdest = os.path.join(os.path.dirname(self.i.path), b'cover.jpg') shutil.copyfile(self.art_file, artdest) - self.afa_response = artdest + self.afa_response = fetchart.Candidate(logger, path=artdest) self._fetch_art(True) + def test_fetch_art_if_imported_file_deleted(self): + # See #1126. Test the following scenario: + # - Album art imported, `album.artpath` set. + # - Imported album art file subsequently deleted (by user or other + # program). + # `fetchart` should import album art again instead of printing the + # message "<album> has album art". + self._fetch_art(True) + util.remove(self.album.artpath) + self.plugin.batch_fetch_art(self.lib, self.lib.albums(), force=False, + quiet=False) + self.assertExists(self.album.artpath) + class ArtForAlbumTest(UseThePlugin): """ Tests that fetchart.art_for_album respects the size configuration (e.g., minwidth, enforce_ratio) """ - IMG_225x225 = os.path.join(_common.RSRC, 'abbey.jpg') - IMG_348x348 = os.path.join(_common.RSRC, 'abbey-different.jpg') - IMG_500x490 = os.path.join(_common.RSRC, 'abbey-similar.jpg') + IMG_225x225 = os.path.join(_common.RSRC, b'abbey.jpg') + IMG_348x348 = os.path.join(_common.RSRC, b'abbey-different.jpg') + IMG_500x490 = os.path.join(_common.RSRC, b'abbey-similar.jpg') def setUp(self): super(ArtForAlbumTest, self).setUp() - self.old_fs_source_get = self.plugin.fs_source.get - self.old_fetch_img = self.plugin._fetch_image - self.old_source_urls = self.plugin._source_urls + self.old_fs_source_get = fetchart.FileSystem.get - def fs_source_get(*_): - return self.image_file + def fs_source_get(_self, album, settings, paths): + if paths: + yield fetchart.Candidate(logger, path=self.image_file) - def source_urls(_): - return [''] + fetchart.FileSystem.get = fs_source_get - def fetch_img(_): - return self.image_file - - self.plugin.fs_source.get = fs_source_get - self.plugin._source_urls = source_urls - self.plugin._fetch_image = fetch_img + self.album = _common.Bag() def tearDown(self): - self.plugin.fs_source.get = self.old_fs_source_get - self.plugin._source_urls = self.old_source_urls - self.plugin._fetch_image = self.old_fetch_img + fetchart.FileSystem.get = self.old_fs_source_get super(ArtForAlbumTest, self).tearDown() - def _assertImageIsValidArt(self, image_file, should_exist): + def _assertImageIsValidArt(self, image_file, should_exist): # noqa self.assertExists(image_file) self.image_file = image_file - local_artpath = self.plugin.art_for_album(None, [''], True) - remote_artpath = self.plugin.art_for_album(None, [], False) - - self.assertEqual(local_artpath, remote_artpath) + candidate = self.plugin.art_for_album(self.album, [''], True) if should_exist: - self.assertEqual(local_artpath, self.image_file) - self.assertExists(local_artpath) - return local_artpath + self.assertNotEqual(candidate, None) + self.assertEqual(candidate.path, self.image_file) + self.assertExists(candidate.path) else: - self.assertIsNone(local_artpath) + self.assertIsNone(candidate) + + def _assertImageResized(self, image_file, should_resize): # noqa + self.image_file = image_file + with patch.object(ArtResizer.shared, 'resize') as mock_resize: + self.plugin.art_for_album(self.album, [''], True) + self.assertEqual(mock_resize.called, should_resize) def _require_backend(self): """Skip the test if the art resizer doesn't have ImageMagick or PIL (so comparisons and measurements are unavailable). """ if ArtResizer.shared.method[0] == WEBPROXY: - self.skipTest("ArtResizer has no local imaging backend available") + self.skipTest(u"ArtResizer has no local imaging backend available") def test_respect_minwidth(self): self._require_backend() @@ -432,9 +591,81 @@ class ArtForAlbumTest(UseThePlugin): self.plugin.enforce_ratio = False self._assertImageIsValidArt(self.IMG_500x490, True) + def test_respect_enforce_ratio_px_above(self): + self._require_backend() + self.plugin.enforce_ratio = True + self.plugin.margin_px = 5 + self._assertImageIsValidArt(self.IMG_500x490, False) + + def test_respect_enforce_ratio_px_below(self): + self._require_backend() + self.plugin.enforce_ratio = True + self.plugin.margin_px = 15 + self._assertImageIsValidArt(self.IMG_500x490, True) + + def test_respect_enforce_ratio_percent_above(self): + self._require_backend() + self.plugin.enforce_ratio = True + self.plugin.margin_percent = (500 - 490) / 500 * 0.5 + self._assertImageIsValidArt(self.IMG_500x490, False) + + def test_respect_enforce_ratio_percent_below(self): + self._require_backend() + self.plugin.enforce_ratio = True + self.plugin.margin_percent = (500 - 490) / 500 * 1.5 + self._assertImageIsValidArt(self.IMG_500x490, True) + + def test_resize_if_necessary(self): + self._require_backend() + self.plugin.maxwidth = 300 + self._assertImageResized(self.IMG_225x225, False) + self._assertImageResized(self.IMG_348x348, True) + + +class DeprecatedConfigTest(_common.TestCase): + """While refactoring the plugin, the remote_priority option was deprecated, + and a new codepath should translate its effect. Check that it actually does + so. + """ + + # If we subclassed UseThePlugin, the configuration change would either be + # overwritten by _common.TestCase or be set after constructing the + # plugin object + def setUp(self): + super(DeprecatedConfigTest, self).setUp() + config['fetchart']['remote_priority'] = True + self.plugin = fetchart.FetchArtPlugin() + + def test_moves_filesystem_to_end(self): + self.assertEqual(type(self.plugin.sources[-1]), fetchart.FileSystem) + + +class EnforceRatioConfigTest(_common.TestCase): + """Throw some data at the regexes.""" + + def _load_with_config(self, values, should_raise): + if should_raise: + for v in values: + config['fetchart']['enforce_ratio'] = v + with self.assertRaises(confit.ConfigValueError): + fetchart.FetchArtPlugin() + else: + for v in values: + config['fetchart']['enforce_ratio'] = v + fetchart.FetchArtPlugin() + + def test_px(self): + self._load_with_config(u'0px 4px 12px 123px'.split(), False) + self._load_with_config(u'00px stuff5px'.split(), True) + + def test_percent(self): + self._load_with_config(u'0% 0.00% 5.1% 5% 100%'.split(), False) + self._load_with_config(u'00% 1.234% foo5% 100.1%'.split(), True) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': + +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_autotag.py b/test/test_autotag.py index 59c564066..932616be1 100644 --- a/test/test_autotag.py +++ b/test/test_autotag.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,14 +15,13 @@ """Tests for autotagging functionality. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import re import copy +import unittest from test import _common -from test._common import unittest from beets import autotag from beets.autotag import match from beets.autotag.hooks import Distance, string_dist @@ -47,7 +47,7 @@ class PluralityTest(_common.TestCase): def test_plurality_conflict(self): objs = [1, 1, 2, 2, 3] obj, freq = plurality(objs) - self.assert_(obj in (1, 2)) + self.assertTrue(obj in (1, 2)) self.assertEqual(freq, 2) def test_plurality_empty_sequence_raises_error(self): @@ -611,17 +611,18 @@ class AssignmentTest(unittest.TestCase): match.assign_items(items, trackinfo) self.assertEqual(extra_items, []) self.assertEqual(extra_tracks, []) - for item, info in mapping.iteritems(): + for item, info in mapping.items(): self.assertEqual(items.index(item), trackinfo.index(info)) class ApplyTestUtil(object): - def _apply(self, info=None, per_disc_numbering=False): + def _apply(self, info=None, per_disc_numbering=False, artist_credit=False): info = info or self.info mapping = {} for i, t in zip(self.items, info.tracks): mapping[i] = t config['per_disc_numbering'] = per_disc_numbering + config['artist_credit'] = artist_credit autotag.apply_metadata(info, mapping) @@ -635,7 +636,7 @@ class ApplyTest(_common.TestCase, ApplyTestUtil): trackinfo = [] trackinfo.append(TrackInfo( u'oneNew', - 'dfa939ec-118c-4d0f-84a0-60f3d1e6522c', + u'dfa939ec-118c-4d0f-84a0-60f3d1e6522c', medium=1, medium_index=1, medium_total=1, @@ -645,7 +646,7 @@ class ApplyTest(_common.TestCase, ApplyTestUtil): )) trackinfo.append(TrackInfo( u'twoNew', - '40130ed1-a27c-42fd-a328-1ebefb6caef4', + u'40130ed1-a27c-42fd-a328-1ebefb6caef4', medium=2, medium_index=1, index=2, @@ -706,6 +707,24 @@ class ApplyTest(_common.TestCase, ApplyTestUtil): self.assertEqual(self.items[0].tracktotal, 1) self.assertEqual(self.items[1].tracktotal, 1) + def test_artist_credit(self): + self._apply(artist_credit=True) + self.assertEqual(self.items[0].artist, 'trackArtistCredit') + self.assertEqual(self.items[1].artist, 'albumArtistCredit') + self.assertEqual(self.items[0].albumartist, 'albumArtistCredit') + self.assertEqual(self.items[1].albumartist, 'albumArtistCredit') + + def test_artist_credit_prefers_artist_over_albumartist_credit(self): + self.info.tracks[0].artist = 'oldArtist' + self.info.tracks[0].artist_credit = None + self._apply(artist_credit=True) + self.assertEqual(self.items[0].artist, 'oldArtist') + + def test_artist_credit_falls_back_to_albumartist(self): + self.info.artist_credit = None + self._apply(artist_credit=True) + self.assertEqual(self.items[1].artist, 'artistNew') + def test_mb_trackid_applied(self): self._apply() self.assertEqual(self.items[0].mb_trackid, @@ -807,16 +826,16 @@ class ApplyCompilationTest(_common.TestCase, ApplyTestUtil): trackinfo = [] trackinfo.append(TrackInfo( u'oneNew', - 'dfa939ec-118c-4d0f-84a0-60f3d1e6522c', + u'dfa939ec-118c-4d0f-84a0-60f3d1e6522c', u'artistOneNew', - 'a05686fc-9db2-4c23-b99e-77f5db3e5282', + u'a05686fc-9db2-4c23-b99e-77f5db3e5282', index=1, )) trackinfo.append(TrackInfo( u'twoNew', - '40130ed1-a27c-42fd-a328-1ebefb6caef4', + u'40130ed1-a27c-42fd-a328-1ebefb6caef4', u'artistTwoNew', - '80b3cf5e-18fe-4c59-98c7-e5bb87210710', + u'80b3cf5e-18fe-4c59-98c7-e5bb87210710', index=2, )) self.info = AlbumInfo( @@ -879,17 +898,17 @@ class StringDistanceTest(unittest.TestCase): def test_leading_the_has_lower_weight(self): dist1 = string_dist(u'XXX Band Name', u'Band Name') dist2 = string_dist(u'The Band Name', u'Band Name') - self.assert_(dist2 < dist1) + self.assertTrue(dist2 < dist1) def test_parens_have_lower_weight(self): dist1 = string_dist(u'One .Two.', u'One') dist2 = string_dist(u'One (Two)', u'One') - self.assert_(dist2 < dist1) + self.assertTrue(dist2 < dist1) def test_brackets_have_lower_weight(self): dist1 = string_dist(u'One .Two.', u'One') dist2 = string_dist(u'One [Two]', u'One') - self.assert_(dist2 < dist1) + self.assertTrue(dist2 < dist1) def test_ep_label_has_zero_weight(self): dist = string_dist(u'My Song (EP)', u'My Song') @@ -898,7 +917,7 @@ class StringDistanceTest(unittest.TestCase): def test_featured_has_lower_weight(self): dist1 = string_dist(u'My Song blah Someone', u'My Song') dist2 = string_dist(u'My Song feat Someone', u'My Song') - self.assert_(dist2 < dist1) + self.assertTrue(dist2 < dist1) def test_postfix_the(self): dist = string_dist(u'The Song Title', u'Song Title, The') @@ -940,17 +959,17 @@ class EnumTest(_common.TestCase): Test Enum Subclasses defined in beets.util.enumeration """ def test_ordered_enum(self): - OrderedEnumTest = match.OrderedEnum('OrderedEnumTest', ['a', 'b', 'c']) - self.assertLess(OrderedEnumTest.a, OrderedEnumTest.b) - self.assertLess(OrderedEnumTest.a, OrderedEnumTest.c) - self.assertLess(OrderedEnumTest.b, OrderedEnumTest.c) - self.assertGreater(OrderedEnumTest.b, OrderedEnumTest.a) - self.assertGreater(OrderedEnumTest.c, OrderedEnumTest.a) - self.assertGreater(OrderedEnumTest.c, OrderedEnumTest.b) + OrderedEnumClass = match.OrderedEnum('OrderedEnumTest', ['a', 'b', 'c']) # noqa + self.assertLess(OrderedEnumClass.a, OrderedEnumClass.b) + self.assertLess(OrderedEnumClass.a, OrderedEnumClass.c) + self.assertLess(OrderedEnumClass.b, OrderedEnumClass.c) + self.assertGreater(OrderedEnumClass.b, OrderedEnumClass.a) + self.assertGreater(OrderedEnumClass.c, OrderedEnumClass.a) + self.assertGreater(OrderedEnumClass.c, OrderedEnumClass.b) def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_bucket.py b/test/test_bucket.py index 05b2a2a1f..61f6cfe24 100644 --- a/test/test_bucket.py +++ b/test/test_bucket.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Fabrice Laporte. +# Copyright 2016, Fabrice Laporte. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,10 +15,9 @@ """Tests for the 'bucket' plugin.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function -from test._common import unittest +import unittest from beetsplug import bucket from beets import config, ui @@ -165,5 +164,5 @@ class BucketPluginTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_config_command.py b/test/test_config_command.py index 18463cb2a..35ba6ca0e 100644 --- a/test/test_config_command.py +++ b/test/test_config_command.py @@ -1,23 +1,26 @@ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +# -*- coding: utf-8 -*- + +from __future__ import division, absolute_import, print_function import os import yaml from mock import patch from tempfile import mkdtemp from shutil import rmtree +import unittest from beets import ui from beets import config -from test._common import unittest -from test.helper import TestHelper, capture_stdout +from test.helper import TestHelper from beets.library import Library +import six class ConfigCommandTest(unittest.TestCase, TestHelper): def setUp(self): + self.lib = Library(':memory:') self.temp_dir = mkdtemp() if 'EDITOR' in os.environ: del os.environ['EDITOR'] @@ -40,55 +43,55 @@ class ConfigCommandTest(unittest.TestCase, TestHelper): def tearDown(self): rmtree(self.temp_dir) + def _run_with_yaml_output(self, *args): + output = self.run_with_output(*args) + return yaml.load(output) + def test_show_user_config(self): - with capture_stdout() as output: - self.run_command('config', '-c') - output = yaml.load(output.getvalue()) + output = self._run_with_yaml_output('config', '-c') + self.assertEqual(output['option'], 'value') self.assertEqual(output['password'], 'password_value') def test_show_user_config_with_defaults(self): - with capture_stdout() as output: - self.run_command('config', '-dc') - output = yaml.load(output.getvalue()) + output = self._run_with_yaml_output('config', '-dc') + self.assertEqual(output['option'], 'value') self.assertEqual(output['password'], 'password_value') self.assertEqual(output['library'], 'lib') self.assertEqual(output['import']['timid'], False) def test_show_user_config_with_cli(self): - with capture_stdout() as output: - self.run_command('--config', self.cli_config_path, 'config') - output = yaml.load(output.getvalue()) + output = self._run_with_yaml_output('--config', self.cli_config_path, + 'config') + self.assertEqual(output['library'], 'lib') self.assertEqual(output['option'], 'cli overwrite') def test_show_redacted_user_config(self): - with capture_stdout() as output: - self.run_command('config') - output = yaml.load(output.getvalue()) + output = self._run_with_yaml_output('config') + self.assertEqual(output['option'], 'value') self.assertEqual(output['password'], 'REDACTED') def test_show_redacted_user_config_with_defaults(self): - with capture_stdout() as output: - self.run_command('config', '-d') - output = yaml.load(output.getvalue()) + output = self._run_with_yaml_output('config', '-d') + self.assertEqual(output['option'], 'value') self.assertEqual(output['password'], 'REDACTED') self.assertEqual(output['import']['timid'], False) def test_config_paths(self): - with capture_stdout() as output: - self.run_command('config', '-p') - paths = output.getvalue().split('\n') + output = self.run_with_output('config', '-p') + + paths = output.split('\n') self.assertEqual(len(paths), 2) self.assertEqual(paths[0], self.config_path) def test_config_paths_with_cli(self): - with capture_stdout() as output: - self.run_command('--config', self.cli_config_path, 'config', '-p') - paths = output.getvalue().split('\n') + output = self.run_with_output('--config', self.cli_config_path, + 'config', '-p') + paths = output.split('\n') self.assertEqual(len(paths), 3) self.assertEqual(paths[0], self.cli_config_path) @@ -113,11 +116,10 @@ class ConfigCommandTest(unittest.TestCase, TestHelper): execlp.side_effect = OSError('here is problem') self.run_command('config', '-e') self.assertIn('Could not edit configuration', - unicode(user_error.exception)) - self.assertIn('here is problem', unicode(user_error.exception)) + six.text_type(user_error.exception)) + self.assertIn('here is problem', six.text_type(user_error.exception)) def test_edit_invalid_config_file(self): - self.lib = Library(':memory:') with open(self.config_path, 'w') as file: file.write('invalid: [') config.clear() @@ -133,5 +135,5 @@ class ConfigCommandTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_convert.py b/test/test_convert.py index 034d8a465..aa0cd0a34 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,20 +13,30 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function +import sys import re import os.path +import unittest + from test import _common -from test._common import unittest from test import helper -from test.helper import control_stdin +from test.helper import control_stdin, capture_log from beets.mediafile import MediaFile from beets import util +def shell_quote(text): + if sys.version_info[0] < 3: + import pipes + return pipes.quote(text) + else: + import shlex + return shlex.quote(text) + + class TestHelper(helper.TestHelper): def tagged_copy_cmd(self, tag): @@ -35,34 +46,47 @@ class TestHelper(helper.TestHelper): if re.search('[^a-zA-Z0-9]', tag): raise ValueError(u"tag '{0}' must only contain letters and digits" .format(tag)) - # FIXME This is not portable. For windows we need to use our own - # python script that performs the same task. - return u'sh -c "cp \'$source\' \'$dest\'; ' \ - u'printf {0} >> \'$dest\'"'.format(tag) - def assertFileTag(self, path, tag): + # A Python script that copies the file and appends a tag. + stub = os.path.join(_common.RSRC, b'convert_stub.py').decode('utf-8') + return u"{} {} $source $dest {}".format(shell_quote(sys.executable), + shell_quote(stub), tag) + + def assertFileTag(self, path, tag): # noqa """Assert that the path is a file and the files content ends with `tag`. """ + display_tag = tag + tag = tag.encode('utf-8') self.assertTrue(os.path.isfile(path), - u'{0} is not a file'.format(path)) - with open(path) as f: - f.seek(-len(tag), os.SEEK_END) + u'{0} is not a file'.format( + util.displayable_path(path))) + with open(path, 'rb') as f: + f.seek(-len(display_tag), os.SEEK_END) self.assertEqual(f.read(), tag, - u'{0} is not tagged with {1}'.format(path, tag)) + u'{0} is not tagged with {1}' + .format( + util.displayable_path(path), + display_tag)) - def assertNoFileTag(self, path, tag): + def assertNoFileTag(self, path, tag): # noqa """Assert that the path is a file and the files content does not end with `tag`. """ + display_tag = tag + tag = tag.encode('utf-8') self.assertTrue(os.path.isfile(path), - u'{0} is not a file'.format(path)) - with open(path) as f: + u'{0} is not a file'.format( + util.displayable_path(path))) + with open(path, 'rb') as f: f.seek(-len(tag), os.SEEK_END) self.assertNotEqual(f.read(), tag, u'{0} is unexpectedly tagged with {1}' - .format(path, tag)) + .format( + util.displayable_path(path), + display_tag)) +@_common.slow_test() class ImportConvertTest(unittest.TestCase, TestHelper): def setUp(self): @@ -71,7 +95,7 @@ class ImportConvertTest(unittest.TestCase, TestHelper): self.load_plugins('convert') self.config['convert'] = { - 'dest': os.path.join(self.temp_dir, 'convert'), + 'dest': os.path.join(self.temp_dir, b'convert'), 'command': self.tagged_copy_cmd('convert'), # Enforce running convert 'max_bitrate': 1, @@ -98,7 +122,26 @@ class ImportConvertTest(unittest.TestCase, TestHelper): self.assertTrue(os.path.isfile(item.path)) -class ConvertCliTest(unittest.TestCase, TestHelper): +class ConvertCommand(object): + """A mixin providing a utility method to run the `convert`command + in tests. + """ + def run_convert_path(self, path, *args): + """Run the `convert` command on a given path.""" + # The path is currently a filesystem bytestring. Convert it to + # an argument bytestring. + path = path.decode(util._fsencoding()).encode(util.arg_encoding()) + + args = args + (b'path:' + path,) + return self.run_command('convert', *args) + + def run_convert(self, *args): + """Run the `convert` command on `self.item`.""" + return self.run_convert_path(self.item.path, *args) + + +@_common.slow_test() +class ConvertCliTest(unittest.TestCase, TestHelper, ConvertCommand): def setUp(self): self.setup_beets(disk=True) # Converter is threaded @@ -107,7 +150,7 @@ class ConvertCliTest(unittest.TestCase, TestHelper): self.load_plugins('convert') self.convert_dest = util.bytestring_path( - os.path.join(self.temp_dir, 'convert_dest') + os.path.join(self.temp_dir, b'convert_dest') ) self.config['convert'] = { 'dest': self.convert_dest, @@ -128,59 +171,71 @@ class ConvertCliTest(unittest.TestCase, TestHelper): def test_convert(self): with control_stdin('y'): - self.run_command('convert', self.item.path) - converted = os.path.join(self.convert_dest, 'converted.mp3') + self.run_convert() + converted = os.path.join(self.convert_dest, b'converted.mp3') self.assertFileTag(converted, 'mp3') def test_convert_with_auto_confirmation(self): - self.run_command('convert', '--yes', self.item.path) - converted = os.path.join(self.convert_dest, 'converted.mp3') + self.run_convert('--yes') + converted = os.path.join(self.convert_dest, b'converted.mp3') self.assertFileTag(converted, 'mp3') - def test_rejecet_confirmation(self): + def test_reject_confirmation(self): with control_stdin('n'): - self.run_command('convert', self.item.path) - converted = os.path.join(self.convert_dest, 'converted.mp3') + self.run_convert() + converted = os.path.join(self.convert_dest, b'converted.mp3') self.assertFalse(os.path.isfile(converted)) def test_convert_keep_new(self): - self.assertEqual(os.path.splitext(self.item.path)[1], '.ogg') + self.assertEqual(os.path.splitext(self.item.path)[1], b'.ogg') with control_stdin('y'): - self.run_command('convert', '--keep-new', self.item.path) + self.run_convert('--keep-new') self.item.load() - self.assertEqual(os.path.splitext(self.item.path)[1], '.mp3') + self.assertEqual(os.path.splitext(self.item.path)[1], b'.mp3') def test_format_option(self): with control_stdin('y'): - self.run_command('convert', '--format', 'opus', self.item.path) - converted = os.path.join(self.convert_dest, 'converted.ops') + self.run_convert('--format', 'opus') + converted = os.path.join(self.convert_dest, b'converted.ops') self.assertFileTag(converted, 'opus') def test_embed_album_art(self): self.config['convert']['embed'] = True - image_path = os.path.join(_common.RSRC, 'image-2x3.jpg') + image_path = os.path.join(_common.RSRC, b'image-2x3.jpg') self.album.artpath = image_path self.album.store() - with open(os.path.join(image_path)) as f: + with open(os.path.join(image_path), 'rb') as f: image_data = f.read() with control_stdin('y'): - self.run_command('convert', self.item.path) - converted = os.path.join(self.convert_dest, 'converted.mp3') + self.run_convert() + converted = os.path.join(self.convert_dest, b'converted.mp3') mediafile = MediaFile(converted) self.assertEqual(mediafile.images[0].data, image_data) def test_skip_existing(self): - converted = os.path.join(self.convert_dest, 'converted.mp3') + converted = os.path.join(self.convert_dest, b'converted.mp3') self.touch(converted, content='XXX') - self.run_command('convert', '--yes', self.item.path) + self.run_convert('--yes') with open(converted, 'r') as f: self.assertEqual(f.read(), 'XXX') + def test_pretend(self): + self.run_convert('--pretend') + converted = os.path.join(self.convert_dest, b'converted.mp3') + self.assertFalse(os.path.exists(converted)) -class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper): + def test_empty_query(self): + with capture_log('beets.convert') as logs: + self.run_convert('An impossible query') + self.assertEqual(logs[0], u'convert: Empty query result.') + + +@_common.slow_test() +class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper, + ConvertCommand): """Test the effect of the `never_convert_lossy_files` option. """ @@ -188,7 +243,7 @@ class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper): self.setup_beets(disk=True) # Converter is threaded self.load_plugins('convert') - self.convert_dest = os.path.join(self.temp_dir, 'convert_dest') + self.convert_dest = os.path.join(self.temp_dir, b'convert_dest') self.config['convert'] = { 'dest': self.convert_dest, 'paths': {'default': 'converted'}, @@ -206,28 +261,29 @@ class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper): def test_transcode_from_lossles(self): [item] = self.add_item_fixtures(ext='flac') with control_stdin('y'): - self.run_command('convert', item.path) - converted = os.path.join(self.convert_dest, 'converted.mp3') + self.run_convert_path(item.path) + converted = os.path.join(self.convert_dest, b'converted.mp3') self.assertFileTag(converted, 'mp3') def test_transcode_from_lossy(self): self.config['convert']['never_convert_lossy_files'] = False [item] = self.add_item_fixtures(ext='ogg') with control_stdin('y'): - self.run_command('convert', item.path) - converted = os.path.join(self.convert_dest, 'converted.mp3') + self.run_convert_path(item.path) + converted = os.path.join(self.convert_dest, b'converted.mp3') self.assertFileTag(converted, 'mp3') def test_transcode_from_lossy_prevented(self): [item] = self.add_item_fixtures(ext='ogg') with control_stdin('y'): - self.run_command('convert', item.path) - converted = os.path.join(self.convert_dest, 'converted.ogg') + self.run_convert_path(item.path) + converted = os.path.join(self.convert_dest, b'converted.ogg') self.assertNoFileTag(converted, 'mp3') def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': + +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_datequery.py b/test/test_datequery.py index 0533846bf..b8348ca53 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,20 +15,24 @@ """Test for dbcore's date-based queries. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from test import _common -from test._common import unittest -from datetime import datetime +from datetime import datetime, timedelta +import unittest import time -from beets.dbcore.query import _parse_periods, DateInterval, DateQuery +from beets.dbcore.query import _parse_periods, DateInterval, DateQuery,\ + InvalidQueryArgumentValueError def _date(string): return datetime.strptime(string, '%Y-%m-%dT%H:%M:%S') +def _datepattern(datetimedate): + return datetimedate.strftime('%Y-%m-%dT%H:%M:%S') + + class DateIntervalTest(unittest.TestCase): def test_year_precision_intervals(self): self.assertContains('2000..2001', '2000-01-01T00:00:00') @@ -43,6 +48,9 @@ class DateIntervalTest(unittest.TestCase): self.assertContains('..2001', '2001-12-31T23:59:59') self.assertExcludes('..2001', '2002-01-01T00:00:00') + self.assertContains('-1d..1d', _datepattern(datetime.now())) + self.assertExcludes('-2d..-1d', _datepattern(datetime.now())) + def test_day_precision_intervals(self): self.assertContains('2000-06-20..2000-06-20', '2000-06-20T00:00:00') self.assertContains('2000-06-20..2000-06-20', '2000-06-20T10:20:30') @@ -57,19 +65,64 @@ class DateIntervalTest(unittest.TestCase): self.assertExcludes('1999-12..2000-02', '1999-11-30T23:59:59') self.assertExcludes('1999-12..2000-02', '2000-03-01T00:00:00') + def test_hour_precision_intervals(self): + # test with 'T' separator + self.assertExcludes('2000-01-01T12..2000-01-01T13', + '2000-01-01T11:59:59') + self.assertContains('2000-01-01T12..2000-01-01T13', + '2000-01-01T12:00:00') + self.assertContains('2000-01-01T12..2000-01-01T13', + '2000-01-01T12:30:00') + self.assertContains('2000-01-01T12..2000-01-01T13', + '2000-01-01T13:30:00') + self.assertContains('2000-01-01T12..2000-01-01T13', + '2000-01-01T13:59:59') + self.assertExcludes('2000-01-01T12..2000-01-01T13', + '2000-01-01T14:00:00') + self.assertExcludes('2000-01-01T12..2000-01-01T13', + '2000-01-01T14:30:00') + + # test non-range query + self.assertContains('2008-12-01T22', + '2008-12-01T22:30:00') + self.assertExcludes('2008-12-01T22', + '2008-12-01T23:30:00') + + def test_minute_precision_intervals(self): + self.assertExcludes('2000-01-01T12:30..2000-01-01T12:31', + '2000-01-01T12:29:59') + self.assertContains('2000-01-01T12:30..2000-01-01T12:31', + '2000-01-01T12:30:00') + self.assertContains('2000-01-01T12:30..2000-01-01T12:31', + '2000-01-01T12:30:30') + self.assertContains('2000-01-01T12:30..2000-01-01T12:31', + '2000-01-01T12:31:59') + self.assertExcludes('2000-01-01T12:30..2000-01-01T12:31', + '2000-01-01T12:32:00') + + def test_second_precision_intervals(self): + self.assertExcludes('2000-01-01T12:30:50..2000-01-01T12:30:55', + '2000-01-01T12:30:49') + self.assertContains('2000-01-01T12:30:50..2000-01-01T12:30:55', + '2000-01-01T12:30:50') + self.assertContains('2000-01-01T12:30:50..2000-01-01T12:30:55', + '2000-01-01T12:30:55') + self.assertExcludes('2000-01-01T12:30:50..2000-01-01T12:30:55', + '2000-01-01T12:30:56') + def test_unbounded_endpoints(self): self.assertContains('..', date=datetime.max) self.assertContains('..', date=datetime.min) self.assertContains('..', '1000-01-01T00:00:00') - def assertContains(self, interval_pattern, date_pattern=None, date=None): + def assertContains(self, interval_pattern, date_pattern=None, date=None): # noqa if date is None: date = _date(date_pattern) (start, end) = _parse_periods(interval_pattern) interval = DateInterval.from_periods(start, end) self.assertTrue(interval.contains(date)) - def assertExcludes(self, interval_pattern, date_pattern): + def assertExcludes(self, interval_pattern, date_pattern): # noqa date = _date(date_pattern) (start, end) = _parse_periods(interval_pattern) interval = DateInterval.from_periods(start, end) @@ -115,17 +168,139 @@ class DateQueryTest(_common.LibTestCase): self.assertEqual(len(matched), 0) +class DateQueryTestRelative(_common.LibTestCase): + def setUp(self): + super(DateQueryTestRelative, self).setUp() + + # We pick a date near a month changeover, which can reveal some time + # zone bugs. + self._now = datetime(2017, 12, 31, 22, 55, 4, 101332) + + self.i.added = _parsetime(self._now.strftime('%Y-%m-%d %H:%M')) + self.i.store() + + def test_single_month_match_fast(self): + query = DateQuery('added', self._now.strftime('%Y-%m')) + matched = self.lib.items(query) + self.assertEqual(len(matched), 1) + + def test_single_month_nonmatch_fast(self): + query = DateQuery('added', (self._now + timedelta(days=30)) + .strftime('%Y-%m')) + matched = self.lib.items(query) + self.assertEqual(len(matched), 0) + + def test_single_month_match_slow(self): + query = DateQuery('added', self._now.strftime('%Y-%m')) + self.assertTrue(query.match(self.i)) + + def test_single_month_nonmatch_slow(self): + query = DateQuery('added', (self._now + timedelta(days=30)) + .strftime('%Y-%m')) + self.assertFalse(query.match(self.i)) + + def test_single_day_match_fast(self): + query = DateQuery('added', self._now.strftime('%Y-%m-%d')) + matched = self.lib.items(query) + self.assertEqual(len(matched), 1) + + def test_single_day_nonmatch_fast(self): + query = DateQuery('added', (self._now + timedelta(days=1)) + .strftime('%Y-%m-%d')) + matched = self.lib.items(query) + self.assertEqual(len(matched), 0) + + +class DateQueryTestRelativeMore(_common.LibTestCase): + def setUp(self): + super(DateQueryTestRelativeMore, self).setUp() + self.i.added = _parsetime(datetime.now().strftime('%Y-%m-%d %H:%M')) + self.i.store() + + def test_relative(self): + for timespan in ['d', 'w', 'm', 'y']: + query = DateQuery('added', '-4' + timespan + '..+4' + timespan) + matched = self.lib.items(query) + self.assertEqual(len(matched), 1) + + def test_relative_fail(self): + for timespan in ['d', 'w', 'm', 'y']: + query = DateQuery('added', '-2' + timespan + '..-1' + timespan) + matched = self.lib.items(query) + self.assertEqual(len(matched), 0) + + def test_start_relative(self): + for timespan in ['d', 'w', 'm', 'y']: + query = DateQuery('added', '-4' + timespan + '..') + matched = self.lib.items(query) + self.assertEqual(len(matched), 1) + + def test_start_relative_fail(self): + for timespan in ['d', 'w', 'm', 'y']: + query = DateQuery('added', '4' + timespan + '..') + matched = self.lib.items(query) + self.assertEqual(len(matched), 0) + + def test_end_relative(self): + for timespan in ['d', 'w', 'm', 'y']: + query = DateQuery('added', '..+4' + timespan) + matched = self.lib.items(query) + self.assertEqual(len(matched), 1) + + def test_end_relative_fail(self): + for timespan in ['d', 'w', 'm', 'y']: + query = DateQuery('added', '..-4' + timespan) + matched = self.lib.items(query) + self.assertEqual(len(matched), 0) + + class DateQueryConstructTest(unittest.TestCase): def test_long_numbers(self): - DateQuery('added', '1409830085..1412422089') + with self.assertRaises(InvalidQueryArgumentValueError): + DateQuery('added', '1409830085..1412422089') def test_too_many_components(self): - DateQuery('added', '12-34-56-78') + with self.assertRaises(InvalidQueryArgumentValueError): + DateQuery('added', '12-34-56-78') + + def test_invalid_date_query(self): + q_list = [ + '2001-01-0a', + '2001-0a', + '200a', + '2001-01-01..2001-01-0a', + '2001-0a..2001-01', + '200a..2002', + '20aa..', + '..2aa' + ] + for q in q_list: + with self.assertRaises(InvalidQueryArgumentValueError): + DateQuery('added', q) + + def test_datetime_uppercase_t_separator(self): + date_query = DateQuery('added', '2000-01-01T12') + self.assertEqual(date_query.interval.start, datetime(2000, 1, 1, 12)) + self.assertEqual(date_query.interval.end, datetime(2000, 1, 1, 13)) + + def test_datetime_lowercase_t_separator(self): + date_query = DateQuery('added', '2000-01-01t12') + self.assertEqual(date_query.interval.start, datetime(2000, 1, 1, 12)) + self.assertEqual(date_query.interval.end, datetime(2000, 1, 1, 13)) + + def test_datetime_space_separator(self): + date_query = DateQuery('added', '2000-01-01 12') + self.assertEqual(date_query.interval.start, datetime(2000, 1, 1, 12)) + self.assertEqual(date_query.interval.end, datetime(2000, 1, 1, 13)) + + def test_datetime_invalid_separator(self): + with self.assertRaises(InvalidQueryArgumentValueError): + DateQuery('added', '2000-01-01x12') def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_dbcore.py b/test/test_dbcore.py index 6fc07d0f6..d2d97d4b3 100644 --- a/test/test_dbcore.py +++ b/test/test_dbcore.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,15 +15,18 @@ """Tests for the DBCore database abstraction. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import os +import shutil import sqlite3 +import unittest +from six import assertRaisesRegex -from test._common import unittest +from test import _common from beets import dbcore from tempfile import mkstemp +import six # Fixture: concrete database and model classes. For migration tests, we @@ -115,15 +119,28 @@ class TestDatabaseTwoModels(dbcore.Database): pass +class TestModelWithGetters(dbcore.Model): + + @classmethod + def _getters(cls): + return {'aComputedField': (lambda s: 'thing')} + + def _template_funcs(self): + return {} + + +@_common.slow_test() class MigrationTest(unittest.TestCase): """Tests the ability to change the database schema between versions. """ - def setUp(self): - handle, self.libfile = mkstemp('db') + + @classmethod + def setUpClass(cls): + handle, cls.orig_libfile = mkstemp('orig_db') os.close(handle) # Set up a database with the two-field schema. - old_lib = TestDatabase2(self.libfile) + old_lib = TestDatabase2(cls.orig_libfile) # Add an item to the old library. old_lib._connection().execute( @@ -132,6 +149,15 @@ class MigrationTest(unittest.TestCase): old_lib._connection().commit() del old_lib + @classmethod + def tearDownClass(cls): + os.remove(cls.orig_libfile) + + def setUp(self): + handle, self.libfile = mkstemp('db') + os.close(handle) + shutil.copyfile(self.orig_libfile, self.libfile) + def tearDown(self): os.remove(self.libfile) @@ -190,7 +216,7 @@ class ModelTest(unittest.TestCase): model.field_one = 123 model.store() row = self.db._connection().execute('select * from test').fetchone() - self.assertEqual(row[b'field_one'], 123) + self.assertEqual(row['field_one'], 123) def test_retrieve_by_id(self): model = TestModel1() @@ -273,6 +299,40 @@ class ModelTest(unittest.TestCase): model2.load() self.assertNotIn('flex_field', model2) + def test_check_db_fails(self): + with assertRaisesRegex(self, ValueError, 'no database'): + dbcore.Model()._check_db() + with assertRaisesRegex(self, ValueError, 'no id'): + TestModel1(self.db)._check_db() + + dbcore.Model(self.db)._check_db(need_id=False) + + def test_missing_field(self): + with self.assertRaises(AttributeError): + TestModel1(self.db).nonExistingKey + + def test_computed_field(self): + model = TestModelWithGetters() + self.assertEqual(model.aComputedField, 'thing') + with assertRaisesRegex(self, KeyError, u'computed field .+ deleted'): + del model.aComputedField + + def test_items(self): + model = TestModel1(self.db) + model.id = 5 + self.assertEqual({('id', 5), ('field_one', 0)}, + set(model.items())) + + def test_delete_internal_field(self): + model = dbcore.Model() + del model._db + with self.assertRaises(AttributeError): + model._db + + def test_parse_nonstring(self): + with assertRaisesRegex(self, TypeError, u"must be a string"): + dbcore.Model._parse(None, 42) + class FormatTest(unittest.TestCase): def test_format_fixed_field(self): @@ -289,9 +349,9 @@ class FormatTest(unittest.TestCase): def test_format_flex_field_bytes(self): model = TestModel1() - model.other_field = u'caf\xe9'.encode('utf8') + model.other_field = u'caf\xe9'.encode('utf-8') value = model.formatted().get('other_field') - self.assertTrue(isinstance(value, unicode)) + self.assertTrue(isinstance(value, six.text_type)) self.assertEqual(value, u'caf\xe9') def test_format_unset_field(self): @@ -351,7 +411,7 @@ class QueryParseTest(unittest.TestCase): part, {'year': dbcore.query.NumericQuery}, {':': dbcore.query.RegexpQuery}, - ) + )[:-1] # remove the negate flag def test_one_basic_term(self): q = 'test' @@ -551,7 +611,7 @@ class ResultsIteratorTest(unittest.TestCase): results = self.db._fetch(TestModel1) it1 = iter(results) it2 = iter(results) - it1.next() + next(it1) list(it2) self.assertEqual(len(list(it1)), 1) @@ -587,9 +647,18 @@ class ResultsIteratorTest(unittest.TestCase): objs = self.db._fetch(TestModel1) self.assertEqual(len(objs), 2) + def test_out_of_range(self): + objs = self.db._fetch(TestModel1) + with self.assertRaises(IndexError): + objs[100] + + def test_no_results(self): + self.assertIsNone(self.db._fetch( + TestModel1, dbcore.query.FalseQuery()).get()) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_discogs.py b/test/test_discogs.py new file mode 100644 index 000000000..8b2eff9f1 --- /dev/null +++ b/test/test_discogs.py @@ -0,0 +1,359 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Adrian Sampson. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Tests for discogs plugin. +""" +from __future__ import division, absolute_import, print_function + +import unittest +from test import _common +from test._common import Bag +from test.helper import capture_log + +from beetsplug.discogs import DiscogsPlugin + + +class DGAlbumInfoTest(_common.TestCase): + def _make_release(self, tracks=None): + """Returns a Bag that mimics a discogs_client.Release. The list + of elements on the returned Bag is incomplete, including just + those required for the tests on this class.""" + data = { + 'id': 'ALBUM ID', + 'uri': 'ALBUM URI', + 'title': 'ALBUM TITLE', + 'year': '3001', + 'artists': [{ + 'name': 'ARTIST NAME', + 'id': 'ARTIST ID', + 'join': ',' + }], + 'formats': [{ + 'descriptions': ['FORMAT DESC 1', 'FORMAT DESC 2'], + 'name': 'FORMAT', + 'qty': 1 + }], + 'labels': [{ + 'name': 'LABEL NAME', + 'catno': 'CATALOG NUMBER', + }], + 'tracklist': [] + } + + if tracks: + for recording in tracks: + data['tracklist'].append(recording) + + return Bag(data=data, + # Make some fields available as properties, as they are + # accessed by DiscogsPlugin methods. + title=data['title'], + artists=[Bag(data=d) for d in data['artists']]) + + def _make_track(self, title, position='', duration='', type_=None): + track = { + 'title': title, + 'position': position, + 'duration': duration + } + if type_ is not None: + # Test samples on discogs_client do not have a 'type_' field, but + # the API seems to return it. Values: 'track' for regular tracks, + # 'heading' for descriptive texts (ie. not real tracks - 12.13.2). + track['type_'] = type_ + + return track + + def _make_release_from_positions(self, positions): + """Return a Bag that mimics a discogs_client.Release with a + tracklist where tracks have the specified `positions`.""" + tracks = [self._make_track('TITLE%s' % i, position) for + (i, position) in enumerate(positions, start=1)] + return self._make_release(tracks) + + def test_parse_media_for_tracks(self): + tracks = [self._make_track('TITLE ONE', '1', '01:01'), + self._make_track('TITLE TWO', '2', '02:02')] + release = self._make_release(tracks=tracks) + + d = DiscogsPlugin().get_album_info(release) + t = d.tracks + self.assertEqual(d.media, 'FORMAT') + self.assertEqual(t[0].media, d.media) + self.assertEqual(t[1].media, d.media) + + def test_parse_medium_numbers_single_medium(self): + release = self._make_release_from_positions(['1', '2']) + d = DiscogsPlugin().get_album_info(release) + t = d.tracks + + self.assertEqual(d.mediums, 1) + self.assertEqual(t[0].medium, 1) + self.assertEqual(t[0].medium_total, 2) + self.assertEqual(t[1].medium, 1) + self.assertEqual(t[0].medium_total, 2) + + def test_parse_medium_numbers_two_mediums(self): + release = self._make_release_from_positions(['1-1', '2-1']) + d = DiscogsPlugin().get_album_info(release) + t = d.tracks + + self.assertEqual(d.mediums, 2) + self.assertEqual(t[0].medium, 1) + self.assertEqual(t[0].medium_total, 1) + self.assertEqual(t[1].medium, 2) + self.assertEqual(t[1].medium_total, 1) + + def test_parse_medium_numbers_two_mediums_two_sided(self): + release = self._make_release_from_positions(['A1', 'B1', 'C1']) + d = DiscogsPlugin().get_album_info(release) + t = d.tracks + + self.assertEqual(d.mediums, 2) + self.assertEqual(t[0].medium, 1) + self.assertEqual(t[0].medium_total, 2) + self.assertEqual(t[0].medium_index, 1) + self.assertEqual(t[1].medium, 1) + self.assertEqual(t[1].medium_total, 2) + self.assertEqual(t[1].medium_index, 2) + self.assertEqual(t[2].medium, 2) + self.assertEqual(t[2].medium_total, 1) + self.assertEqual(t[2].medium_index, 1) + + def test_parse_track_indices(self): + release = self._make_release_from_positions(['1', '2']) + d = DiscogsPlugin().get_album_info(release) + t = d.tracks + + self.assertEqual(t[0].medium_index, 1) + self.assertEqual(t[0].index, 1) + self.assertEqual(t[0].medium_total, 2) + self.assertEqual(t[1].medium_index, 2) + self.assertEqual(t[1].index, 2) + self.assertEqual(t[1].medium_total, 2) + + def test_parse_track_indices_several_media(self): + release = self._make_release_from_positions(['1-1', '1-2', '2-1', + '3-1']) + d = DiscogsPlugin().get_album_info(release) + t = d.tracks + + self.assertEqual(d.mediums, 3) + self.assertEqual(t[0].medium_index, 1) + self.assertEqual(t[0].index, 1) + self.assertEqual(t[0].medium_total, 2) + self.assertEqual(t[1].medium_index, 2) + self.assertEqual(t[1].index, 2) + self.assertEqual(t[1].medium_total, 2) + self.assertEqual(t[2].medium_index, 1) + self.assertEqual(t[2].index, 3) + self.assertEqual(t[2].medium_total, 1) + self.assertEqual(t[3].medium_index, 1) + self.assertEqual(t[3].index, 4) + self.assertEqual(t[3].medium_total, 1) + + def test_parse_position(self): + """Test the conversion of discogs `position` to medium, medium_index + and subtrack_index.""" + # List of tuples (discogs_position, (medium, medium_index, subindex) + positions = [('1', (None, '1', None)), + ('A12', ('A', '12', None)), + ('12-34', ('12-', '34', None)), + ('CD1-1', ('CD1-', '1', None)), + ('1.12', (None, '1', '12')), + ('12.a', (None, '12', 'A')), + ('12.34', (None, '12', '34')), + ('1ab', (None, '1', 'AB')), + # Non-standard + ('IV', ('IV', None, None)), + ] + + d = DiscogsPlugin() + for position, expected in positions: + self.assertEqual(d.get_track_index(position), expected) + + def test_parse_tracklist_without_sides(self): + """Test standard Discogs position 12.2.9#1: "without sides".""" + release = self._make_release_from_positions(['1', '2', '3']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 1) + self.assertEqual(len(d.tracks), 3) + + def test_parse_tracklist_with_sides(self): + """Test standard Discogs position 12.2.9#2: "with sides".""" + release = self._make_release_from_positions(['A1', 'A2', 'B1', 'B2']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 1) # 2 sides = 1 LP + self.assertEqual(len(d.tracks), 4) + + def test_parse_tracklist_multiple_lp(self): + """Test standard Discogs position 12.2.9#3: "multiple LP".""" + release = self._make_release_from_positions(['A1', 'A2', 'B1', 'C1']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 2) # 3 sides = 1 LP + 1 LP + self.assertEqual(len(d.tracks), 4) + + def test_parse_tracklist_multiple_cd(self): + """Test standard Discogs position 12.2.9#4: "multiple CDs".""" + release = self._make_release_from_positions(['1-1', '1-2', '2-1', + '3-1']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 3) + self.assertEqual(len(d.tracks), 4) + + def test_parse_tracklist_non_standard(self): + """Test non standard Discogs position.""" + release = self._make_release_from_positions(['I', 'II', 'III', 'IV']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 1) + self.assertEqual(len(d.tracks), 4) + + def test_parse_tracklist_subtracks_dot(self): + """Test standard Discogs position 12.2.9#5: "sub tracks, dots".""" + release = self._make_release_from_positions(['1', '2.1', '2.2', '3']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 1) + self.assertEqual(len(d.tracks), 3) + + release = self._make_release_from_positions(['A1', 'A2.1', 'A2.2', + 'A3']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 1) + self.assertEqual(len(d.tracks), 3) + + def test_parse_tracklist_subtracks_letter(self): + """Test standard Discogs position 12.2.9#5: "sub tracks, letter".""" + release = self._make_release_from_positions(['A1', 'A2a', 'A2b', 'A3']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 1) + self.assertEqual(len(d.tracks), 3) + + release = self._make_release_from_positions(['A1', 'A2.a', 'A2.b', + 'A3']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 1) + self.assertEqual(len(d.tracks), 3) + + def test_parse_tracklist_subtracks_extra_material(self): + """Test standard Discogs position 12.2.9#6: "extra material".""" + release = self._make_release_from_positions(['1', '2', 'Video 1']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 2) + self.assertEqual(len(d.tracks), 3) + + def test_parse_tracklist_subtracks_indices(self): + """Test parsing of subtracks that include index tracks.""" + release = self._make_release_from_positions(['', '', '1.1', '1.2']) + # Track 1: Index track with medium title + release.data['tracklist'][0]['title'] = 'MEDIUM TITLE' + # Track 2: Index track with track group title + release.data['tracklist'][1]['title'] = 'TRACK GROUP TITLE' + + d = DiscogsPlugin().get_album_info(release) + self.assertEqual(d.mediums, 1) + self.assertEqual(d.tracks[0].disctitle, 'MEDIUM TITLE') + self.assertEqual(len(d.tracks), 1) + self.assertEqual(d.tracks[0].title, 'TRACK GROUP TITLE') + + def test_parse_tracklist_subtracks_nested_logical(self): + """Test parsing of subtracks defined inside a index track that are + logical subtracks (ie. should be grouped together into a single track). + """ + release = self._make_release_from_positions(['1', '', '3']) + # Track 2: Index track with track group title, and sub_tracks + release.data['tracklist'][1]['title'] = 'TRACK GROUP TITLE' + release.data['tracklist'][1]['sub_tracks'] = [ + self._make_track('TITLE ONE', '2.1', '01:01'), + self._make_track('TITLE TWO', '2.2', '02:02') + ] + + d = DiscogsPlugin().get_album_info(release) + self.assertEqual(d.mediums, 1) + self.assertEqual(len(d.tracks), 3) + self.assertEqual(d.tracks[1].title, 'TRACK GROUP TITLE') + + def test_parse_tracklist_subtracks_nested_physical(self): + """Test parsing of subtracks defined inside a index track that are + physical subtracks (ie. should not be grouped together). + """ + release = self._make_release_from_positions(['1', '', '4']) + # Track 2: Index track with track group title, and sub_tracks + release.data['tracklist'][1]['title'] = 'TRACK GROUP TITLE' + release.data['tracklist'][1]['sub_tracks'] = [ + self._make_track('TITLE ONE', '2', '01:01'), + self._make_track('TITLE TWO', '3', '02:02') + ] + + d = DiscogsPlugin().get_album_info(release) + self.assertEqual(d.mediums, 1) + self.assertEqual(len(d.tracks), 4) + self.assertEqual(d.tracks[1].title, 'TITLE ONE') + self.assertEqual(d.tracks[2].title, 'TITLE TWO') + + def test_parse_tracklist_disctitles(self): + """Test parsing of index tracks that act as disc titles.""" + release = self._make_release_from_positions(['', '1-1', '1-2', '', + '2-1']) + # Track 1: Index track with medium title (Cd1) + release.data['tracklist'][0]['title'] = 'MEDIUM TITLE CD1' + # Track 4: Index track with medium title (Cd2) + release.data['tracklist'][3]['title'] = 'MEDIUM TITLE CD2' + + d = DiscogsPlugin().get_album_info(release) + self.assertEqual(d.mediums, 2) + self.assertEqual(d.tracks[0].disctitle, 'MEDIUM TITLE CD1') + self.assertEqual(d.tracks[1].disctitle, 'MEDIUM TITLE CD1') + self.assertEqual(d.tracks[2].disctitle, 'MEDIUM TITLE CD2') + self.assertEqual(len(d.tracks), 3) + + def test_parse_minimal_release(self): + """Test parsing of a release with the minimal amount of information.""" + data = {'id': 123, + 'tracklist': [self._make_track('A', '1', '01:01')], + 'artists': [{'name': 'ARTIST NAME', 'id': 321, 'join': ''}], + 'title': 'TITLE'} + release = Bag(data=data, + title=data['title'], + artists=[Bag(data=d) for d in data['artists']]) + d = DiscogsPlugin().get_album_info(release) + self.assertEqual(d.artist, 'ARTIST NAME') + self.assertEqual(d.album, 'TITLE') + self.assertEqual(len(d.tracks), 1) + + def test_parse_release_without_required_fields(self): + """Test parsing of a release that does not have the required fields.""" + release = Bag(data={}, refresh=lambda *args: None) + with capture_log() as logs: + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d, None) + self.assertIn('Release does not contain the required fields', logs[0]) + + +def suite(): + return unittest.TestLoader().loadTestsFromName(__name__) + +if __name__ == '__main__': + unittest.main(defaultTest='suite') diff --git a/test/test_echonest.py b/test/test_echonest.py deleted file mode 100644 index 1289decd2..000000000 --- a/test/test_echonest.py +++ /dev/null @@ -1,193 +0,0 @@ -# This file is part of beets. -# Copyright 2015, Thomas Scholtes -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. - - -from __future__ import (division, absolute_import, print_function, - unicode_literals) - -import os.path -from mock import Mock, patch - -from test._common import unittest, RSRC -from test.helper import TestHelper - -from beets.library import Item - - -class EchonestCliTest(unittest.TestCase, TestHelper): - def setUp(self): - try: - __import__('pyechonest') - except ImportError: - self.skipTest('pyechonest not available') - - self.setup_beets() - self.load_plugins('echonest') - # Prevent 'beet echonest' from writing files - self.config['import']['write'] = False - - def tearDown(self): - self.teardown_beets() - self.unload_plugins() - - @patch.object(Item, 'write') - @patch('pyechonest.song.profile') - @patch('pyechonest.track.track_from_id') - def test_mbid_profile(self, echonest_track, echonest_profile, item_write): - """Retrieve song info from MusicBrainz ID.""" - item = self.add_item(title='title', length=10, mb_trackid='1') - profile = self.profile(item, energy=0.5, tempo=120, key=2, mode=0) - echonest_profile.return_value = [profile] - echonest_track.return_value = Mock(song_id='echonestid') - - self.assertNotIn('energy', item) - self.assertNotEqual(item['bpm'], 120) - self.assertNotIn('initialkey', item) - - self.run_command('echonest') - item.load() - self.assertEqual(item['energy'], 0.5) - self.assertEqual(item['bpm'], 120) - self.assertEqual(item['initial_key'], 'C#m') - - @patch('pyechonest.track.track_from_id') - @patch('pyechonest.song.search') - def test_song_search(self, echonest_search, echonest_track): - item = self.add_item(title='title', length=10, mb_trackid='1') - echonest_search.return_value = [self.profile(item, energy=0.1)] - echonest_track.return_value = [] - - self.run_command('echonest') - item.load() - self.assertEqual(item['energy'], 0.1) - self.assertEqual(1, echonest_track.call_count) - - @patch('pyechonest.song.profile') - @patch('pyechonest.song.search') - @patch('pyechonest.track.track_from_filename') - def test_analyze(self, echonest_track, echonest_search, echonest_profile): - item = self.add_item(title='title', length=10, - path=os.path.join(RSRC, 'min.mp3')) - echonest_search.return_value = [] - echonest_profile.return_value = [self.profile(item, energy=0.2)] - echonest_track.return_value = self.track(item) - - self.run_command('echonest') - item.load() - self.assertEqual(item['energy'], 0.2) - self.assertEqual(1, echonest_search.call_count) - self.assertEqual(item.path, - echonest_track.call_args[1]['filename']) - - @patch('pyechonest.song.profile') - @patch('pyechonest.song.search') - @patch('pyechonest.track.track_from_filename') - @patch('beetsplug.echonest.CONVERT_COMMAND', 'cp $source $dest') - def test_analyze_convert(self, echonest_track, echonest_search, - echonest_profile): - item = self.add_item(title='title', length=10, format='FLAC', - path=os.path.join(RSRC, 'min.flac')) - echonest_search.return_value = [] - echonest_profile.return_value = [self.profile(item, energy=0.2)] - echonest_track.return_value = self.track(item) - - self.run_command('echonest') - item.load() - self.assertEqual(item['energy'], 0.2) - # Assert uploaded file was converted - self.assertNotEqual(item.path, - echonest_track.call_args[1]['filename']) - - @patch('pyechonest.song.search') - @patch('beetsplug.echonest.CONVERT_COMMAND', 'cp $source $dest') - def test_analyze_convert2(self, echonest_search): - self.add_item(format='FLAC', path=b'm\xc3\xacn.flac') - self.run_command('echonest') - - @patch('pyechonest.song.profile') - @patch('pyechonest.song.search') - @patch('pyechonest.track.track_from_filename') - @patch('beetsplug.echonest.CONVERT_COMMAND', 'false') - def test_analyze_convert_fail(self, echonest_track, echonest_search, - echonest_profile): - item = self.add_item(title='title', length=10, format='FLAC', - path=os.path.join(RSRC, 'min.flac')) - echonest_search.return_value = [] - echonest_profile.return_value = [self.profile(item, energy=0.2)] - echonest_track.return_value = self.track(item) - - self.run_command('echonest') - item.load() - self.assertNotIn('energy', item) - self.assertEqual(0, echonest_track.call_count) - - @patch('pyechonest.song.profile') - @patch('pyechonest.song.search') - @patch('pyechonest.track.track_from_filename') - # Force truncation - @patch('beetsplug.echonest.UPLOAD_MAX_SIZE', 0) - @patch('beetsplug.echonest.TRUNCATE_COMMAND', 'cp $source $dest') - def test_analyze_truncate(self, echonest_track, echonest_search, - echonest_profile): - item = self.add_item(title='title', length=10, format='MP3', - path=os.path.join(RSRC, 'min.mp3')) - echonest_search.return_value = [] - echonest_profile.return_value = [self.profile(item, energy=0.2)] - echonest_track.return_value = self.track(item) - - self.run_command('echonest') - item.load() - self.assertEqual(item['energy'], 0.2) - self.assertEqual(1, echonest_search.call_count) - self.assertNotEqual(item.path, - echonest_track.call_args[1]['filename']) - - def test_custom_field_range_query(self): - item = Item(liveness=2.2) - item.add(self.lib) - item = self.lib.items('liveness:2.2..3').get() - self.assertEqual(item['liveness'], 2.2) - - def profile(self, item, **values): - """Return a mock Echonest Profile object. - - The fields are set to match the item. Additional values are - passed to the `audio_summary` dictionary of the profile. - """ - audio_summary = {'duration': item.length} - audio_summary.update(values) - return Mock( - artist_name=item.artist, - title=item.title, - id='echonestid', - audio_summary=audio_summary - ) - - def track(self, item, **values): - """Return a mock Echonest Track object. - """ - values.update( - duration=item.length, - artist_name=item.artist, - title=item.title, - song_id='echonestid', - ) - return Mock(**values) - - -def suite(): - return unittest.TestLoader().loadTestsFromName(__name__) - -if __name__ == b'__main__': - unittest.main(defaultTest='suite') diff --git a/test/test_edit.py b/test/test_edit.py new file mode 100644 index 000000000..1b627939c --- /dev/null +++ b/test/test_edit.py @@ -0,0 +1,458 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Adrian Sampson and Diego Moreda. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +from __future__ import division, absolute_import, print_function +import codecs +import unittest + +from mock import patch +from test import _common +from test.helper import TestHelper, control_stdin +from test.test_ui_importer import TerminalImportSessionSetup +from test.test_importer import ImportHelper, AutotagStub +from beets.dbcore.query import TrueQuery +from beets.library import Item +from beetsplug.edit import EditPlugin + + +class ModifyFileMocker(object): + """Helper for modifying a file, replacing or editing its contents. Used for + mocking the calls to the external editor during testing. + """ + + def __init__(self, contents=None, replacements=None): + """ `self.contents` and `self.replacements` are initialized here, in + order to keep the rest of the functions of this class with the same + signature as `EditPlugin.get_editor()`, making mocking easier. + - `contents`: string with the contents of the file to be used for + `overwrite_contents()` + - `replacement`: dict with the in-place replacements to be used for + `replace_contents()`, in the form {'previous string': 'new string'} + + TODO: check if it can be solved more elegantly with a decorator + """ + self.contents = contents + self.replacements = replacements + self.action = self.overwrite_contents + if replacements: + self.action = self.replace_contents + + # The two methods below mock the `edit` utility function in the plugin. + + def overwrite_contents(self, filename, log): + """Modify `filename`, replacing its contents with `self.contents`. If + `self.contents` is empty, the file remains unchanged. + """ + if self.contents: + with codecs.open(filename, 'w', encoding='utf-8') as f: + f.write(self.contents) + + def replace_contents(self, filename, log): + """Modify `filename`, reading its contents and replacing the strings + specified in `self.replacements`. + """ + with codecs.open(filename, 'r', encoding='utf-8') as f: + contents = f.read() + for old, new_ in self.replacements.items(): + contents = contents.replace(old, new_) + with codecs.open(filename, 'w', encoding='utf-8') as f: + f.write(contents) + + +class EditMixin(object): + """Helper containing some common functionality used for the Edit tests.""" + def assertItemFieldsModified(self, library_items, items, fields=[], # noqa + allowed=['path']): + """Assert that items in the library (`lib_items`) have different values + on the specified `fields` (and *only* on those fields), compared to + `items`. + + An empty `fields` list results in asserting that no modifications have + been performed. `allowed` is a list of field changes that are ignored + (they may or may not have changed; the assertion doesn't care). + """ + for lib_item, item in zip(library_items, items): + diff_fields = [field for field in lib_item._fields + if lib_item[field] != item[field]] + self.assertEqual(set(diff_fields).difference(allowed), + set(fields)) + + def run_mocked_interpreter(self, modify_file_args={}, stdin=[]): + """Run the edit command during an import session, with mocked stdin and + yaml writing. + """ + m = ModifyFileMocker(**modify_file_args) + with patch('beetsplug.edit.edit', side_effect=m.action): + with control_stdin('\n'.join(stdin)): + self.importer.run() + + def run_mocked_command(self, modify_file_args={}, stdin=[], args=[]): + """Run the edit command, with mocked stdin and yaml writing, and + passing `args` to `run_command`.""" + m = ModifyFileMocker(**modify_file_args) + with patch('beetsplug.edit.edit', side_effect=m.action): + with control_stdin('\n'.join(stdin)): + self.run_command('edit', *args) + + +@_common.slow_test() +@patch('beets.library.Item.write') +class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): + """Black box tests for `beetsplug.edit`. Command line interaction is + simulated using `test.helper.control_stdin()`, and yaml editing via an + external editor is simulated using `ModifyFileMocker`. + """ + ALBUM_COUNT = 1 + TRACK_COUNT = 10 + + def setUp(self): + self.setup_beets() + self.load_plugins('edit') + # Add an album, storing the original fields for comparison. + self.album = self.add_album_fixture(track_count=self.TRACK_COUNT) + self.album_orig = {f: self.album[f] for f in self.album._fields} + self.items_orig = [{f: item[f] for f in item._fields} for + item in self.album.items()] + + def tearDown(self): + EditPlugin.listeners = None + self.teardown_beets() + self.unload_plugins() + + def assertCounts(self, mock_write, album_count=ALBUM_COUNT, track_count=TRACK_COUNT, # noqa + write_call_count=TRACK_COUNT, title_starts_with=''): + """Several common assertions on Album, Track and call counts.""" + self.assertEqual(len(self.lib.albums()), album_count) + self.assertEqual(len(self.lib.items()), track_count) + self.assertEqual(mock_write.call_count, write_call_count) + self.assertTrue(all(i.title.startswith(title_starts_with) + for i in self.lib.items())) + + def test_title_edit_discard(self, mock_write): + """Edit title for all items in the library, then discard changes.""" + # Edit track titles. + self.run_mocked_command({'replacements': {u't\u00eftle': + u'modified t\u00eftle'}}, + # Cancel. + ['c']) + + self.assertCounts(mock_write, write_call_count=0, + title_starts_with=u't\u00eftle') + self.assertItemFieldsModified(self.album.items(), self.items_orig, []) + + def test_title_edit_apply(self, mock_write): + """Edit title for all items in the library, then apply changes.""" + # Edit track titles. + self.run_mocked_command({'replacements': {u't\u00eftle': + u'modified t\u00eftle'}}, + # Apply changes. + ['a']) + + self.assertCounts(mock_write, write_call_count=self.TRACK_COUNT, + title_starts_with=u'modified t\u00eftle') + self.assertItemFieldsModified(self.album.items(), self.items_orig, + ['title', 'mtime']) + + def test_single_title_edit_apply(self, mock_write): + """Edit title for one item in the library, then apply changes.""" + # Edit one track title. + self.run_mocked_command({'replacements': {u't\u00eftle 9': + u'modified t\u00eftle 9'}}, + # Apply changes. + ['a']) + + self.assertCounts(mock_write, write_call_count=1,) + # No changes except on last item. + self.assertItemFieldsModified(list(self.album.items())[:-1], + self.items_orig[:-1], []) + self.assertEqual(list(self.album.items())[-1].title, + u'modified t\u00eftle 9') + + def test_noedit(self, mock_write): + """Do not edit anything.""" + # Do not edit anything. + self.run_mocked_command({'contents': None}, + # No stdin. + []) + + self.assertCounts(mock_write, write_call_count=0, + title_starts_with=u't\u00eftle') + self.assertItemFieldsModified(self.album.items(), self.items_orig, []) + + def test_album_edit_apply(self, mock_write): + """Edit the album field for all items in the library, apply changes. + By design, the album should not be updated."" + """ + # Edit album. + self.run_mocked_command({'replacements': {u'\u00e4lbum': + u'modified \u00e4lbum'}}, + # Apply changes. + ['a']) + + self.assertCounts(mock_write, write_call_count=self.TRACK_COUNT) + self.assertItemFieldsModified(self.album.items(), self.items_orig, + ['album', 'mtime']) + # Ensure album is *not* modified. + self.album.load() + self.assertEqual(self.album.album, u'\u00e4lbum') + + def test_single_edit_add_field(self, mock_write): + """Edit the yaml file appending an extra field to the first item, then + apply changes.""" + # Append "foo: bar" to item with id == 2. ("id: 1" would match both + # "id: 1" and "id: 10") + self.run_mocked_command({'replacements': {u"id: 2": + u"id: 2\nfoo: bar"}}, + # Apply changes. + ['a']) + + self.assertEqual(self.lib.items(u'id:2')[0].foo, 'bar') + # Even though a flexible attribute was written (which is not directly + # written to the tags), write should still be called since templates + # might use it. + self.assertCounts(mock_write, write_call_count=1, + title_starts_with=u't\u00eftle') + + def test_a_album_edit_apply(self, mock_write): + """Album query (-a), edit album field, apply changes.""" + self.run_mocked_command({'replacements': {u'\u00e4lbum': + u'modified \u00e4lbum'}}, + # Apply changes. + ['a'], + args=['-a']) + + self.album.load() + self.assertCounts(mock_write, write_call_count=self.TRACK_COUNT) + self.assertEqual(self.album.album, u'modified \u00e4lbum') + self.assertItemFieldsModified(self.album.items(), self.items_orig, + ['album', 'mtime']) + + def test_a_albumartist_edit_apply(self, mock_write): + """Album query (-a), edit albumartist field, apply changes.""" + self.run_mocked_command({'replacements': {u'album artist': + u'modified album artist'}}, + # Apply changes. + ['a'], + args=['-a']) + + self.album.load() + self.assertCounts(mock_write, write_call_count=self.TRACK_COUNT) + self.assertEqual(self.album.albumartist, u'the modified album artist') + self.assertItemFieldsModified(self.album.items(), self.items_orig, + ['albumartist', 'mtime']) + + def test_malformed_yaml(self, mock_write): + """Edit the yaml file incorrectly (resulting in a malformed yaml + document).""" + # Edit the yaml file to an invalid file. + self.run_mocked_command({'contents': '!MALFORMED'}, + # Edit again to fix? No. + ['n']) + + self.assertCounts(mock_write, write_call_count=0, + title_starts_with=u't\u00eftle') + + def test_invalid_yaml(self, mock_write): + """Edit the yaml file incorrectly (resulting in a well-formed but + invalid yaml document).""" + # Edit the yaml file to an invalid but parseable file. + self.run_mocked_command({'contents': u'wellformed: yes, but invalid'}, + # No stdin. + []) + + self.assertCounts(mock_write, write_call_count=0, + title_starts_with=u't\u00eftle') + + +@_common.slow_test() +class EditDuringImporterTest(TerminalImportSessionSetup, unittest.TestCase, + ImportHelper, TestHelper, EditMixin): + """TODO + """ + IGNORED = ['added', 'album_id', 'id', 'mtime', 'path'] + + def setUp(self): + self.setup_beets() + self.load_plugins('edit') + # Create some mediafiles, and store them for comparison. + self._create_import_dir(3) + self.items_orig = [Item.from_path(f.path) for f in self.media_files] + self.matcher = AutotagStub().install() + self.matcher.matching = AutotagStub.GOOD + self.config['import']['timid'] = True + + def tearDown(self): + EditPlugin.listeners = None + self.unload_plugins() + self.teardown_beets() + self.matcher.restore() + + def test_edit_apply_asis(self): + """Edit the album field for all items in the library, apply changes, + using the original item tags. + """ + self._setup_import_session() + # Edit track titles. + self.run_mocked_interpreter({'replacements': {u'Tag Title': + u'Edited Title'}}, + # eDit, Apply changes. + ['d', 'a']) + + # Check that only the 'title' field is modified. + self.assertItemFieldsModified(self.lib.items(), self.items_orig, + ['title'], + self.IGNORED + ['albumartist', + 'mb_albumartistid']) + self.assertTrue(all('Edited Title' in i.title + for i in self.lib.items())) + + # Ensure album is *not* fetched from a candidate. + self.assertEqual(self.lib.albums()[0].mb_albumid, u'') + + def test_edit_discard_asis(self): + """Edit the album field for all items in the library, discard changes, + using the original item tags. + """ + self._setup_import_session() + # Edit track titles. + self.run_mocked_interpreter({'replacements': {u'Tag Title': + u'Edited Title'}}, + # eDit, Cancel, Use as-is. + ['d', 'c', 'u']) + + # Check that nothing is modified, the album is imported ASIS. + self.assertItemFieldsModified(self.lib.items(), self.items_orig, + [], + self.IGNORED + ['albumartist', + 'mb_albumartistid']) + self.assertTrue(all('Tag Title' in i.title + for i in self.lib.items())) + + # Ensure album is *not* fetched from a candidate. + self.assertEqual(self.lib.albums()[0].mb_albumid, u'') + + def test_edit_apply_candidate(self): + """Edit the album field for all items in the library, apply changes, + using a candidate. + """ + self._setup_import_session() + # Edit track titles. + self.run_mocked_interpreter({'replacements': {u'Applied Title': + u'Edited Title'}}, + # edit Candidates, 1, Apply changes. + ['c', '1', 'a']) + + # Check that 'title' field is modified, and other fields come from + # the candidate. + self.assertTrue(all('Edited Title ' in i.title + for i in self.lib.items())) + self.assertTrue(all('match ' in i.mb_trackid + for i in self.lib.items())) + + # Ensure album is fetched from a candidate. + self.assertIn('albumid', self.lib.albums()[0].mb_albumid) + + def test_edit_retag_apply(self): + """Import the album using a candidate, then retag and edit and apply + changes. + """ + self._setup_import_session() + self.run_mocked_interpreter({}, + # 1, Apply changes. + ['1', 'a']) + + # Retag and edit track titles. On retag, the importer will reset items + # ids but not the db connections. + self.importer.paths = [] + self.importer.query = TrueQuery() + self.run_mocked_interpreter({'replacements': {u'Applied Title': + u'Edited Title'}}, + # eDit, Apply changes. + ['d', 'a']) + + # Check that 'title' field is modified, and other fields come from + # the candidate. + self.assertTrue(all('Edited Title ' in i.title + for i in self.lib.items())) + self.assertTrue(all('match ' in i.mb_trackid + for i in self.lib.items())) + + # Ensure album is fetched from a candidate. + self.assertIn('albumid', self.lib.albums()[0].mb_albumid) + + def test_edit_discard_candidate(self): + """Edit the album field for all items in the library, discard changes, + using a candidate. + """ + self._setup_import_session() + # Edit track titles. + self.run_mocked_interpreter({'replacements': {u'Applied Title': + u'Edited Title'}}, + # edit Candidates, 1, Apply changes. + ['c', '1', 'a']) + + # Check that 'title' field is modified, and other fields come from + # the candidate. + self.assertTrue(all('Edited Title ' in i.title + for i in self.lib.items())) + self.assertTrue(all('match ' in i.mb_trackid + for i in self.lib.items())) + + # Ensure album is fetched from a candidate. + self.assertIn('albumid', self.lib.albums()[0].mb_albumid) + + def test_edit_apply_asis_singleton(self): + """Edit the album field for all items in the library, apply changes, + using the original item tags and singleton mode. + """ + self._setup_import_session(singletons=True) + # Edit track titles. + self.run_mocked_interpreter({'replacements': {u'Tag Title': + u'Edited Title'}}, + # eDit, Apply changes, aBort. + ['d', 'a', 'b']) + + # Check that only the 'title' field is modified. + self.assertItemFieldsModified(self.lib.items(), self.items_orig, + ['title'], + self.IGNORED + ['albumartist', + 'mb_albumartistid']) + self.assertTrue(all('Edited Title' in i.title + for i in self.lib.items())) + + def test_edit_apply_candidate_singleton(self): + """Edit the album field for all items in the library, apply changes, + using a candidate and singleton mode. + """ + self._setup_import_session() + # Edit track titles. + self.run_mocked_interpreter({'replacements': {u'Applied Title': + u'Edited Title'}}, + # edit Candidates, 1, Apply changes, aBort. + ['c', '1', 'a', 'b']) + + # Check that 'title' field is modified, and other fields come from + # the candidate. + self.assertTrue(all('Edited Title ' in i.title + for i in self.lib.items())) + self.assertTrue(all('match ' in i.mb_trackid + for i in self.lib.items())) + + +def suite(): + return unittest.TestLoader().loadTestsFromName(__name__) + +if __name__ == '__main__': + unittest.main(defaultTest='suite') diff --git a/test/test_embedart.py b/test/test_embedart.py index a4c88a429..049e4694d 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,21 +13,20 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import os.path import shutil -from mock import patch +from mock import patch, MagicMock import tempfile +import unittest from test import _common -from test._common import unittest from test.helper import TestHelper from beets.mediafile import MediaFile from beets import config, logging, ui -from beets.util import syspath +from beets.util import syspath, displayable_path from beets.util.artresizer import ArtResizer from beets import art @@ -35,7 +35,7 @@ def require_artresizer_compare(test): def wrapper(*args, **kwargs): if not ArtResizer.shared.can_compare: - raise unittest.SkipTest() + raise unittest.SkipTest("compare not available") else: return test(*args, **kwargs) @@ -45,30 +45,51 @@ def require_artresizer_compare(test): class EmbedartCliTest(_common.TestCase, TestHelper): - small_artpath = os.path.join(_common.RSRC, 'image-2x3.jpg') - abbey_artpath = os.path.join(_common.RSRC, 'abbey.jpg') - abbey_similarpath = os.path.join(_common.RSRC, 'abbey-similar.jpg') - abbey_differentpath = os.path.join(_common.RSRC, 'abbey-different.jpg') + small_artpath = os.path.join(_common.RSRC, b'image-2x3.jpg') + abbey_artpath = os.path.join(_common.RSRC, b'abbey.jpg') + abbey_similarpath = os.path.join(_common.RSRC, b'abbey-similar.jpg') + abbey_differentpath = os.path.join(_common.RSRC, b'abbey-different.jpg') def setUp(self): + super(EmbedartCliTest, self).setUp() + self.io.install() self.setup_beets() # Converter is threaded self.load_plugins('embedart') def _setup_data(self, artpath=None): if not artpath: artpath = self.small_artpath - with open(syspath(artpath)) as f: + with open(syspath(artpath), 'rb') as f: self.image_data = f.read() def tearDown(self): self.unload_plugins() self.teardown_beets() + def test_embed_art_from_file_with_yes_input(self): + self._setup_data() + album = self.add_album_fixture() + item = album.items()[0] + self.io.addinput('y') + self.run_command('embedart', '-f', self.small_artpath) + mediafile = MediaFile(syspath(item.path)) + self.assertEqual(mediafile.images[0].data, self.image_data) + + def test_embed_art_from_file_with_no_input(self): + self._setup_data() + album = self.add_album_fixture() + item = album.items()[0] + self.io.addinput('n') + self.run_command('embedart', '-f', self.small_artpath) + mediafile = MediaFile(syspath(item.path)) + # make sure that images array is empty (nothing embedded) + self.assertEqual(len(mediafile.images), 0) + def test_embed_art_from_file(self): self._setup_data() album = self.add_album_fixture() item = album.items()[0] - self.run_command('embedart', '-f', self.small_artpath) + self.run_command('embedart', '-y', '-f', self.small_artpath) mediafile = MediaFile(syspath(item.path)) self.assertEqual(mediafile.images[0].data, self.image_data) @@ -78,7 +99,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): item = album.items()[0] album.artpath = self.small_artpath album.store() - self.run_command('embedart') + self.run_command('embedart', '-y') mediafile = MediaFile(syspath(item.path)) self.assertEqual(mediafile.images[0].data, self.image_data) @@ -96,28 +117,28 @@ class EmbedartCliTest(_common.TestCase, TestHelper): album.store() config['embedart']['remove_art_file'] = True - self.run_command('embedart') + self.run_command('embedart', '-y') if os.path.isfile(tmp_path): os.remove(tmp_path) - self.fail('Artwork file {0} was not deleted'.format(tmp_path)) + self.fail(u'Artwork file {0} was not deleted'.format(tmp_path)) def test_art_file_missing(self): self.add_album_fixture() logging.getLogger('beets.embedart').setLevel(logging.DEBUG) with self.assertRaises(ui.UserError): - self.run_command('embedart', '-f', '/doesnotexist') + self.run_command('embedart', '-y', '-f', '/doesnotexist') def test_embed_non_image_file(self): album = self.add_album_fixture() logging.getLogger('beets.embedart').setLevel(logging.DEBUG) handle, tmp_path = tempfile.mkstemp() - os.write(handle, 'I am not an image.') + os.write(handle, b'I am not an image.') os.close(handle) try: - self.run_command('embedart', '-f', tmp_path) + self.run_command('embedart', '-y', '-f', tmp_path) finally: os.remove(tmp_path) @@ -129,31 +150,31 @@ class EmbedartCliTest(_common.TestCase, TestHelper): self._setup_data(self.abbey_artpath) album = self.add_album_fixture() item = album.items()[0] - self.run_command('embedart', '-f', self.abbey_artpath) + self.run_command('embedart', '-y', '-f', self.abbey_artpath) config['embedart']['compare_threshold'] = 20 - self.run_command('embedart', '-f', self.abbey_differentpath) + self.run_command('embedart', '-y', '-f', self.abbey_differentpath) mediafile = MediaFile(syspath(item.path)) self.assertEqual(mediafile.images[0].data, self.image_data, - 'Image written is not {0}'.format( - self.abbey_artpath)) + u'Image written is not {0}'.format( + displayable_path(self.abbey_artpath))) @require_artresizer_compare def test_accept_similar_art(self): self._setup_data(self.abbey_similarpath) album = self.add_album_fixture() item = album.items()[0] - self.run_command('embedart', '-f', self.abbey_artpath) + self.run_command('embedart', '-y', '-f', self.abbey_artpath) config['embedart']['compare_threshold'] = 20 - self.run_command('embedart', '-f', self.abbey_similarpath) + self.run_command('embedart', '-y', '-f', self.abbey_similarpath) mediafile = MediaFile(syspath(item.path)) self.assertEqual(mediafile.images[0].data, self.image_data, - 'Image written is not {0}'.format( - self.abbey_similarpath)) + u'Image written is not {0}'.format( + displayable_path(self.abbey_similarpath))) def test_non_ascii_album_path(self): - resource_path = os.path.join(_common.RSRC, 'image.mp3').encode('utf8') + resource_path = os.path.join(_common.RSRC, b'image.mp3') album = self.add_album_fixture() trackpath = album.items()[0].path albumpath = album.path @@ -161,44 +182,105 @@ class EmbedartCliTest(_common.TestCase, TestHelper): self.run_command('extractart', '-n', 'extracted') - self.assertExists(syspath(os.path.join(albumpath, b'extracted.png'))) + self.assertExists(os.path.join(albumpath, b'extracted.png')) + + def test_extracted_extension(self): + resource_path = os.path.join(_common.RSRC, b'image-jpeg.mp3') + album = self.add_album_fixture() + trackpath = album.items()[0].path + albumpath = album.path + shutil.copy(syspath(resource_path), syspath(trackpath)) + + self.run_command('extractart', '-n', 'extracted') + + self.assertExists(os.path.join(albumpath, b'extracted.jpg')) + + def test_clear_art_with_yes_input(self): + self._setup_data() + album = self.add_album_fixture() + item = album.items()[0] + self.io.addinput('y') + self.run_command('embedart', '-f', self.small_artpath) + self.io.addinput('y') + self.run_command('clearart') + mediafile = MediaFile(syspath(item.path)) + self.assertEqual(len(mediafile.images), 0) + + def test_clear_art_with_no_input(self): + self._setup_data() + album = self.add_album_fixture() + item = album.items()[0] + self.io.addinput('y') + self.run_command('embedart', '-f', self.small_artpath) + self.io.addinput('n') + self.run_command('clearart') + mediafile = MediaFile(syspath(item.path)) + self.assertEqual(mediafile.images[0].data, self.image_data) @patch('beets.art.subprocess') @patch('beets.art.extract') class ArtSimilarityTest(unittest.TestCase): - def test_imagemagick_response(self, mock_extract, mock_subprocess): - mock_extract.return_value = True - proc = mock_subprocess.Popen.return_value - log = logging.getLogger('beets.embedart') + def setUp(self): + self.item = _common.item() + self.log = logging.getLogger('beets.embedart') - # everything is fine - proc.returncode = 0 - proc.communicate.return_value = "10", "tagada" - self.assertTrue(art.check_art_similarity(log, None, None, 20)) - self.assertFalse(art.check_art_similarity(log, None, None, 5)) + def _similarity(self, threshold): + return art.check_art_similarity(self.log, self.item, b'path', + threshold) - # small failure - proc.returncode = 1 - proc.communicate.return_value = "tagada", "10" - self.assertTrue(art.check_art_similarity(log, None, None, 20)) - self.assertFalse(art.check_art_similarity(log, None, None, 5)) + def _popen(self, status=0, stdout="", stderr=""): + """Create a mock `Popen` object.""" + popen = MagicMock(returncode=status) + popen.communicate.return_value = stdout, stderr + return popen - # bigger failure - proc.returncode = 2 - self.assertIsNone(art.check_art_similarity(log, None, None, 20)) + def _mock_popens(self, mock_extract, mock_subprocess, compare_status=0, + compare_stdout="", compare_stderr="", convert_status=0): + mock_extract.return_value = b'extracted_path' + mock_subprocess.Popen.side_effect = [ + # The `convert` call. + self._popen(convert_status), + # The `compare` call. + self._popen(compare_status, compare_stdout, compare_stderr), + ] - # IM result parsing problems - proc.returncode = 0 - proc.communicate.return_value = "foo", "bar" - self.assertIsNone(art.check_art_similarity(log, None, None, 20)) + def test_compare_success_similar(self, mock_extract, mock_subprocess): + self._mock_popens(mock_extract, mock_subprocess, 0, "10", "err") + self.assertTrue(self._similarity(20)) - proc.returncode = 1 - self.assertIsNone(art.check_art_similarity(log, None, None, 20)) + def test_compare_success_different(self, mock_extract, mock_subprocess): + self._mock_popens(mock_extract, mock_subprocess, 0, "10", "err") + self.assertFalse(self._similarity(5)) + + def test_compare_status1_similar(self, mock_extract, mock_subprocess): + self._mock_popens(mock_extract, mock_subprocess, 1, "out", "10") + self.assertTrue(self._similarity(20)) + + def test_compare_status1_different(self, mock_extract, mock_subprocess): + self._mock_popens(mock_extract, mock_subprocess, 1, "out", "10") + self.assertFalse(self._similarity(5)) + + def test_compare_failed(self, mock_extract, mock_subprocess): + self._mock_popens(mock_extract, mock_subprocess, 2, "out", "10") + self.assertIsNone(self._similarity(20)) + + def test_compare_parsing_error(self, mock_extract, mock_subprocess): + self._mock_popens(mock_extract, mock_subprocess, 0, "foo", "bar") + self.assertIsNone(self._similarity(20)) + + def test_compare_parsing_error_and_failure(self, mock_extract, + mock_subprocess): + self._mock_popens(mock_extract, mock_subprocess, 1, "foo", "bar") + self.assertIsNone(self._similarity(20)) + + def test_convert_failure(self, mock_extract, mock_subprocess): + self._mock_popens(mock_extract, mock_subprocess, convert_status=1) + self.assertIsNone(self._similarity(20)) def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_embyupdate.py b/test/test_embyupdate.py new file mode 100644 index 000000000..2b83a4896 --- /dev/null +++ b/test/test_embyupdate.py @@ -0,0 +1,235 @@ +# -*- coding: utf-8 -*- + +from __future__ import division, absolute_import, print_function + +from test.helper import TestHelper +from beetsplug import embyupdate +import unittest +import responses + + +class EmbyUpdateTest(unittest.TestCase, TestHelper): + def setUp(self): + self.setup_beets() + self.load_plugins('embyupdate') + + self.config['emby'] = { + u'host': u'localhost', + u'port': 8096, + u'username': u'username', + u'password': u'password' + } + + def tearDown(self): + self.teardown_beets() + self.unload_plugins() + + def test_api_url_only_name(self): + self.assertEqual( + embyupdate.api_url(self.config['emby']['host'].get(), + self.config['emby']['port'].get(), + '/Library/Refresh'), + 'http://localhost:8096/Library/Refresh?format=json' + ) + + def test_api_url_http(self): + self.assertEqual( + embyupdate.api_url(u'http://localhost', + self.config['emby']['port'].get(), + '/Library/Refresh'), + 'http://localhost:8096/Library/Refresh?format=json' + ) + + def test_api_url_https(self): + self.assertEqual( + embyupdate.api_url(u'https://localhost', + self.config['emby']['port'].get(), + '/Library/Refresh'), + 'https://localhost:8096/Library/Refresh?format=json' + ) + + def test_password_data(self): + self.assertEqual( + embyupdate.password_data(self.config['emby']['username'].get(), + self.config['emby']['password'].get()), + { + 'username': 'username', + 'password': '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8', + 'passwordMd5': '5f4dcc3b5aa765d61d8327deb882cf99' + } + ) + + def test_create_header_no_token(self): + self.assertEqual( + embyupdate.create_headers('e8837bc1-ad67-520e-8cd2-f629e3155721'), + { + 'x-emby-authorization': ( + 'MediaBrowser ' + 'UserId="e8837bc1-ad67-520e-8cd2-f629e3155721", ' + 'Client="other", ' + 'Device="beets", ' + 'DeviceId="beets", ' + 'Version="0.0.0"' + ) + } + ) + + def test_create_header_with_token(self): + self.assertEqual( + embyupdate.create_headers('e8837bc1-ad67-520e-8cd2-f629e3155721', + token='abc123'), + { + 'x-emby-authorization': ( + 'MediaBrowser ' + 'UserId="e8837bc1-ad67-520e-8cd2-f629e3155721", ' + 'Client="other", ' + 'Device="beets", ' + 'DeviceId="beets", ' + 'Version="0.0.0"' + ), + 'x-mediabrowser-token': 'abc123' + } + ) + + @responses.activate + def test_get_token(self): + body = ('{"User":{"Name":"username", ' + '"ServerId":"1efa5077976bfa92bc71652404f646ec",' + '"Id":"2ec276a2642e54a19b612b9418a8bd3b","HasPassword":true,' + '"HasConfiguredPassword":true,' + '"HasConfiguredEasyPassword":false,' + '"LastLoginDate":"2015-11-09T08:35:03.6357440Z",' + '"LastActivityDate":"2015-11-09T08:35:03.6665060Z",' + '"Configuration":{"AudioLanguagePreference":"",' + '"PlayDefaultAudioTrack":true,"SubtitleLanguagePreference":"",' + '"DisplayMissingEpisodes":false,' + '"DisplayUnairedEpisodes":false,' + '"GroupMoviesIntoBoxSets":false,' + '"DisplayChannelsWithinViews":[],' + '"ExcludeFoldersFromGrouping":[],"GroupedFolders":[],' + '"SubtitleMode":"Default","DisplayCollectionsView":true,' + '"DisplayFoldersView":false,"EnableLocalPassword":false,' + '"OrderedViews":[],"IncludeTrailersInSuggestions":true,' + '"EnableCinemaMode":true,"LatestItemsExcludes":[],' + '"PlainFolderViews":[],"HidePlayedInLatest":true,' + '"DisplayChannelsInline":false},' + '"Policy":{"IsAdministrator":true,"IsHidden":false,' + '"IsDisabled":false,"BlockedTags":[],' + '"EnableUserPreferenceAccess":true,"AccessSchedules":[],' + '"BlockUnratedItems":[],' + '"EnableRemoteControlOfOtherUsers":false,' + '"EnableSharedDeviceControl":true,' + '"EnableLiveTvManagement":true,"EnableLiveTvAccess":true,' + '"EnableMediaPlayback":true,' + '"EnableAudioPlaybackTranscoding":true,' + '"EnableVideoPlaybackTranscoding":true,' + '"EnableContentDeletion":false,' + '"EnableContentDownloading":true,"EnableSync":true,' + '"EnableSyncTranscoding":true,"EnabledDevices":[],' + '"EnableAllDevices":true,"EnabledChannels":[],' + '"EnableAllChannels":true,"EnabledFolders":[],' + '"EnableAllFolders":true,"InvalidLoginAttemptCount":0,' + '"EnablePublicSharing":true}},' + '"SessionInfo":{"SupportedCommands":[],' + '"QueueableMediaTypes":[],"PlayableMediaTypes":[],' + '"Id":"89f3b33f8b3a56af22088733ad1d76b3",' + '"UserId":"2ec276a2642e54a19b612b9418a8bd3b",' + '"UserName":"username","AdditionalUsers":[],' + '"ApplicationVersion":"Unknown version",' + '"Client":"Unknown app",' + '"LastActivityDate":"2015-11-09T08:35:03.6665060Z",' + '"DeviceName":"Unknown device","DeviceId":"Unknown device id",' + '"SupportsRemoteControl":false,"PlayState":{"CanSeek":false,' + '"IsPaused":false,"IsMuted":false,"RepeatMode":"RepeatNone"}},' + '"AccessToken":"4b19180cf02748f7b95c7e8e76562fc8",' + '"ServerId":"1efa5077976bfa92bc71652404f646ec"}') + + responses.add(responses.POST, + ('http://localhost:8096' + '/Users/AuthenticateByName'), + body=body, + status=200, + content_type='application/json') + + headers = { + 'x-emby-authorization': ( + 'MediaBrowser ' + 'UserId="e8837bc1-ad67-520e-8cd2-f629e3155721", ' + 'Client="other", ' + 'Device="beets", ' + 'DeviceId="beets", ' + 'Version="0.0.0"' + ) + } + + auth_data = { + 'username': 'username', + 'password': '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8', + 'passwordMd5': '5f4dcc3b5aa765d61d8327deb882cf99' + } + + self.assertEqual( + embyupdate.get_token('http://localhost', 8096, headers, auth_data), + '4b19180cf02748f7b95c7e8e76562fc8') + + @responses.activate + def test_get_user(self): + body = ('[{"Name":"username",' + '"ServerId":"1efa5077976bfa92bc71652404f646ec",' + '"Id":"2ec276a2642e54a19b612b9418a8bd3b","HasPassword":true,' + '"HasConfiguredPassword":true,' + '"HasConfiguredEasyPassword":false,' + '"LastLoginDate":"2015-11-09T08:35:03.6357440Z",' + '"LastActivityDate":"2015-11-09T08:42:39.3693220Z",' + '"Configuration":{"AudioLanguagePreference":"",' + '"PlayDefaultAudioTrack":true,"SubtitleLanguagePreference":"",' + '"DisplayMissingEpisodes":false,' + '"DisplayUnairedEpisodes":false,' + '"GroupMoviesIntoBoxSets":false,' + '"DisplayChannelsWithinViews":[],' + '"ExcludeFoldersFromGrouping":[],"GroupedFolders":[],' + '"SubtitleMode":"Default","DisplayCollectionsView":true,' + '"DisplayFoldersView":false,"EnableLocalPassword":false,' + '"OrderedViews":[],"IncludeTrailersInSuggestions":true,' + '"EnableCinemaMode":true,"LatestItemsExcludes":[],' + '"PlainFolderViews":[],"HidePlayedInLatest":true,' + '"DisplayChannelsInline":false},' + '"Policy":{"IsAdministrator":true,"IsHidden":false,' + '"IsDisabled":false,"BlockedTags":[],' + '"EnableUserPreferenceAccess":true,"AccessSchedules":[],' + '"BlockUnratedItems":[],' + '"EnableRemoteControlOfOtherUsers":false,' + '"EnableSharedDeviceControl":true,' + '"EnableLiveTvManagement":true,"EnableLiveTvAccess":true,' + '"EnableMediaPlayback":true,' + '"EnableAudioPlaybackTranscoding":true,' + '"EnableVideoPlaybackTranscoding":true,' + '"EnableContentDeletion":false,' + '"EnableContentDownloading":true,' + '"EnableSync":true,"EnableSyncTranscoding":true,' + '"EnabledDevices":[],"EnableAllDevices":true,' + '"EnabledChannels":[],"EnableAllChannels":true,' + '"EnabledFolders":[],"EnableAllFolders":true,' + '"InvalidLoginAttemptCount":0,"EnablePublicSharing":true}}]') + + responses.add(responses.GET, + 'http://localhost:8096/Users/Public', + body=body, + status=200, + content_type='application/json') + + response = embyupdate.get_user('http://localhost', 8096, 'username') + + self.assertEqual(response[0]['Id'], + '2ec276a2642e54a19b612b9418a8bd3b') + + self.assertEqual(response[0]['Name'], + 'username') + + +def suite(): + return unittest.TestLoader().loadTestsFromName(__name__) + + +if __name__ == '__main__': + unittest.main(defaultTest='suite') diff --git a/test/test_fetchart.py b/test/test_fetchart.py index b199e7139..91bc34101 100644 --- a/test/test_fetchart.py +++ b/test/test_fetchart.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,12 +13,12 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import os -from test._common import unittest +import unittest from test.helper import TestHelper +from beets import util class FetchartCliTest(unittest.TestCase, TestHelper): @@ -25,7 +26,7 @@ class FetchartCliTest(unittest.TestCase, TestHelper): def setUp(self): self.setup_beets() self.load_plugins('fetchart') - self.config['fetchart']['cover_names'] = b'c\xc3\xb6ver.jpg' + self.config['fetchart']['cover_names'] = 'c\xc3\xb6ver.jpg' self.config['art_filename'] = 'mycover' self.album = self.add_album() @@ -41,7 +42,7 @@ class FetchartCliTest(unittest.TestCase, TestHelper): self.album.load() self.assertEqual(self.album['artpath'], cover_path) - with open(cover_path, 'r') as f: + with open(util.syspath(cover_path), 'r') as f: self.assertEqual(f.read(), 'IMAGE') def test_filesystem_does_not_pick_up_folder(self): @@ -54,5 +55,5 @@ class FetchartCliTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_filefilter.py b/test/test_filefilter.py index a8a046a37..e7a4119d4 100644 --- a/test/test_filefilter.py +++ b/test/test_filefilter.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Malte Ried. +# Copyright 2016, Malte Ried. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,17 +15,20 @@ """Tests for the `filefilter` plugin. """ + +from __future__ import division, absolute_import, print_function + import os import shutil +import unittest -from _common import unittest -from beets import config -from beets.mediafile import MediaFile -from beets.util import displayable_path -from beetsplug.filefilter import FileFilterPlugin from test import _common from test.helper import capture_log from test.test_importer import ImportHelper +from beets import config +from beets.mediafile import MediaFile +from beets.util import displayable_path, bytestring_path +from beetsplug.filefilter import FileFilterPlugin class FileFilterPluginTest(unittest.TestCase, ImportHelper): @@ -39,7 +43,7 @@ class FileFilterPluginTest(unittest.TestCase, ImportHelper): def __copy_file(self, dest_path, metadata): # Copy files - resource_path = os.path.join(_common.RSRC, 'full.mp3') + resource_path = os.path.join(_common.RSRC, b'full.mp3') shutil.copy(resource_path, dest_path) medium = MediaFile(dest_path) # Set metadata @@ -48,13 +52,13 @@ class FileFilterPluginTest(unittest.TestCase, ImportHelper): medium.save() def __create_import_dir(self, count): - self.import_dir = os.path.join(self.temp_dir, 'testsrcdir') + self.import_dir = os.path.join(self.temp_dir, b'testsrcdir') if os.path.isdir(self.import_dir): shutil.rmtree(self.import_dir) - self.artist_path = os.path.join(self.import_dir, 'artist') - self.album_path = os.path.join(self.artist_path, 'album') - self.misc_path = os.path.join(self.import_dir, 'misc') + self.artist_path = os.path.join(self.import_dir, b'artist') + self.album_path = os.path.join(self.artist_path, b'album') + self.misc_path = os.path.join(self.import_dir, b'misc') os.makedirs(self.album_path) os.makedirs(self.misc_path) @@ -70,8 +74,8 @@ class FileFilterPluginTest(unittest.TestCase, ImportHelper): for i in range(count): metadata['track'] = i + 1 metadata['title'] = 'Tag Title Album %d' % (i + 1) - dest_path = os.path.join(self.album_path, - '%02d - track.mp3' % (i + 1)) + track_file = bytestring_path('%02d - track.mp3' % (i + 1)) + dest_path = os.path.join(self.album_path, track_file) self.__copy_file(dest_path, metadata) self.album_paths.append(dest_path) @@ -80,8 +84,8 @@ class FileFilterPluginTest(unittest.TestCase, ImportHelper): for i in range(count): metadata['track'] = i + 10 metadata['title'] = 'Tag Title Artist %d' % (i + 1) - dest_path = os.path.join(self.artist_path, - 'track_%d.mp3' % (i + 1)) + track_file = bytestring_path('track_%d.mp3' % (i + 1)) + dest_path = os.path.join(self.artist_path, track_file) self.__copy_file(dest_path, metadata) self.artist_paths.append(dest_path) @@ -90,7 +94,8 @@ class FileFilterPluginTest(unittest.TestCase, ImportHelper): metadata['artist'] = 'Artist %d' % (i + 42) metadata['track'] = i + 5 metadata['title'] = 'Tag Title Misc %d' % (i + 1) - dest_path = os.path.join(self.misc_path, 'track_%d.mp3' % (i + 1)) + track_file = bytestring_path('track_%d.mp3' % (i + 1)) + dest_path = os.path.join(self.misc_path, track_file) self.__copy_file(dest_path, metadata) self.misc_paths.append(dest_path) @@ -127,7 +132,8 @@ class FileFilterPluginTest(unittest.TestCase, ImportHelper): def test_import_nothing(self): config['filefilter']['path'] = 'not_there' - self.__run(['No files imported from %s' % self.import_dir]) + self.__run(['No files imported from %s' % displayable_path( + self.import_dir)]) # Global options def test_import_global(self): diff --git a/test/test_files.py b/test/test_files.py index 27aa93cd8..ff055ac6f 100644 --- a/test/test_files.py +++ b/test/test_files.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,19 +15,19 @@ """Test file manipulation functionality of Item. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import shutil import os import stat from os.path import join +import unittest from test import _common -from test._common import unittest from test._common import item, touch import beets.library from beets import util +from beets.util import MoveOperation class MoveTest(_common.TestCase): @@ -34,8 +35,8 @@ class MoveTest(_common.TestCase): super(MoveTest, self).setUp() # make a temporary file - self.path = join(self.temp_dir, 'temp.mp3') - shutil.copy(join(_common.RSRC, 'full.mp3'), self.path) + self.path = join(self.temp_dir, b'temp.mp3') + shutil.copy(join(_common.RSRC, b'full.mp3'), self.path) # add it to a temporary library self.lib = beets.library.Library(':memory:') @@ -43,7 +44,7 @@ class MoveTest(_common.TestCase): self.lib.add(self.i) # set up the destination - self.libdir = join(self.temp_dir, 'testlibdir') + self.libdir = join(self.temp_dir, b'testlibdir') os.mkdir(self.libdir) self.lib.directory = self.libdir self.lib.path_formats = [('default', @@ -51,9 +52,9 @@ class MoveTest(_common.TestCase): self.i.artist = 'one' self.i.album = 'two' self.i.title = 'three' - self.dest = join(self.libdir, 'one', 'two', 'three.mp3') + self.dest = join(self.libdir, b'one', b'two', b'three.mp3') - self.otherdir = join(self.temp_dir, 'testotherdir') + self.otherdir = join(self.temp_dir, b'testotherdir') def test_move_arrives(self): self.i.move() @@ -61,7 +62,7 @@ class MoveTest(_common.TestCase): def test_move_to_custom_dir(self): self.i.move(basedir=self.otherdir) - self.assertExists(join(self.otherdir, 'one', 'two', 'three.mp3')) + self.assertExists(join(self.otherdir, b'one', b'two', b'three.mp3')) def test_move_departs(self): self.i.move() @@ -72,17 +73,17 @@ class MoveTest(_common.TestCase): old_path = self.i.path self.assertExists(old_path) - self.i.artist = 'newArtist' + self.i.artist = u'newArtist' self.i.move() self.assertNotExists(old_path) self.assertNotExists(os.path.dirname(old_path)) def test_copy_arrives(self): - self.i.move(copy=True) + self.i.move(operation=MoveOperation.COPY) self.assertExists(self.dest) def test_copy_does_not_depart(self): - self.i.move(copy=True) + self.i.move(operation=MoveOperation.COPY) self.assertExists(self.path) def test_move_changes_path(self): @@ -92,26 +93,26 @@ class MoveTest(_common.TestCase): def test_copy_already_at_destination(self): self.i.move() old_path = self.i.path - self.i.move(copy=True) + self.i.move(operation=MoveOperation.COPY) self.assertEqual(self.i.path, old_path) def test_move_already_at_destination(self): self.i.move() old_path = self.i.path - self.i.move(copy=False) + self.i.move() self.assertEqual(self.i.path, old_path) def test_read_only_file_copied_writable(self): # Make the source file read-only. - os.chmod(self.path, 0444) + os.chmod(self.path, 0o444) try: - self.i.move(copy=True) + self.i.move(operation=MoveOperation.COPY) self.assertTrue(os.access(self.i.path, os.W_OK)) finally: # Make everything writable so it can be cleaned up. - os.chmod(self.path, 0777) - os.chmod(self.i.path, 0777) + os.chmod(self.path, 0o777) + os.chmod(self.i.path, 0o777) def test_move_avoids_collision_with_existing_file(self): # Make a conflicting file at the destination. @@ -126,19 +127,40 @@ class MoveTest(_common.TestCase): @unittest.skipUnless(_common.HAVE_SYMLINK, "need symlinks") def test_link_arrives(self): - self.i.move(link=True) + self.i.move(operation=MoveOperation.LINK) self.assertExists(self.dest) self.assertTrue(os.path.islink(self.dest)) self.assertEqual(os.readlink(self.dest), self.path) @unittest.skipUnless(_common.HAVE_SYMLINK, "need symlinks") def test_link_does_not_depart(self): - self.i.move(link=True) + self.i.move(operation=MoveOperation.LINK) self.assertExists(self.path) @unittest.skipUnless(_common.HAVE_SYMLINK, "need symlinks") def test_link_changes_path(self): - self.i.move(link=True) + self.i.move(operation=MoveOperation.LINK) + self.assertEqual(self.i.path, util.normpath(self.dest)) + + @unittest.skipUnless(_common.HAVE_HARDLINK, "need hardlinks") + def test_hardlink_arrives(self): + self.i.move(operation=MoveOperation.HARDLINK) + self.assertExists(self.dest) + s1 = os.stat(self.path) + s2 = os.stat(self.dest) + self.assertTrue( + (s1[stat.ST_INO], s1[stat.ST_DEV]) == + (s2[stat.ST_INO], s2[stat.ST_DEV]) + ) + + @unittest.skipUnless(_common.HAVE_HARDLINK, "need hardlinks") + def test_hardlink_does_not_depart(self): + self.i.move(operation=MoveOperation.HARDLINK) + self.assertExists(self.path) + + @unittest.skipUnless(_common.HAVE_HARDLINK, "need hardlinks") + def test_hardlink_changes_path(self): + self.i.move(operation=MoveOperation.HARDLINK) self.assertEqual(self.i.path, util.normpath(self.dest)) @@ -182,7 +204,7 @@ class AlbumFileTest(_common.TestCase): self.lib = beets.library.Library(':memory:') self.lib.path_formats = \ [('default', join('$albumartist', '$album', '$title'))] - self.libdir = os.path.join(self.temp_dir, 'testlibdir') + self.libdir = os.path.join(self.temp_dir, b'testlibdir') self.lib.directory = self.libdir self.i = item(self.lib) # Make a file for the item. @@ -192,19 +214,19 @@ class AlbumFileTest(_common.TestCase): # Make an album. self.ai = self.lib.add_album((self.i,)) # Alternate destination dir. - self.otherdir = os.path.join(self.temp_dir, 'testotherdir') + self.otherdir = os.path.join(self.temp_dir, b'testotherdir') def test_albuminfo_move_changes_paths(self): - self.ai.album = 'newAlbumName' + self.ai.album = u'newAlbumName' self.ai.move() self.ai.store() self.i.load() - self.assert_('newAlbumName' in self.i.path) + self.assertTrue(b'newAlbumName' in self.i.path) def test_albuminfo_move_moves_file(self): oldpath = self.i.path - self.ai.album = 'newAlbumName' + self.ai.album = u'newAlbumName' self.ai.move() self.ai.store() self.i.load() @@ -214,8 +236,8 @@ class AlbumFileTest(_common.TestCase): def test_albuminfo_move_copies_file(self): oldpath = self.i.path - self.ai.album = 'newAlbumName' - self.ai.move(True) + self.ai.album = u'newAlbumName' + self.ai.move(operation=MoveOperation.COPY) self.ai.store() self.i.load() @@ -226,7 +248,7 @@ class AlbumFileTest(_common.TestCase): self.ai.move(basedir=self.otherdir) self.i.load() self.ai.store() - self.assertTrue('testotherdir' in self.i.path) + self.assertTrue(b'testotherdir' in self.i.path) class ArtFileTest(_common.TestCase): @@ -235,7 +257,7 @@ class ArtFileTest(_common.TestCase): # Make library and item. self.lib = beets.library.Library(':memory:') - self.libdir = os.path.join(self.temp_dir, 'testlibdir') + self.libdir = os.path.join(self.temp_dir, b'testlibdir') self.lib.directory = self.libdir self.i = item(self.lib) self.i.path = self.i.destination() @@ -250,7 +272,7 @@ class ArtFileTest(_common.TestCase): self.ai.artpath = self.art self.ai.store() # Alternate destination dir. - self.otherdir = os.path.join(self.temp_dir, 'testotherdir') + self.otherdir = os.path.join(self.temp_dir, b'testotherdir') def test_art_deleted_when_items_deleted(self): self.assertTrue(os.path.exists(self.art)) @@ -260,7 +282,7 @@ class ArtFileTest(_common.TestCase): def test_art_moves_with_album(self): self.assertTrue(os.path.exists(self.art)) oldpath = self.i.path - self.ai.album = 'newAlbum' + self.ai.album = u'newAlbum' self.ai.move() self.i.load() @@ -279,18 +301,18 @@ class ArtFileTest(_common.TestCase): self.assertNotExists(self.art) newart = self.lib.get_album(self.i).artpath self.assertExists(newart) - self.assertTrue('testotherdir' in newart) + self.assertTrue(b'testotherdir' in newart) def test_setart_copies_image(self): os.remove(self.art) - newart = os.path.join(self.libdir, 'newart.jpg') + newart = os.path.join(self.libdir, b'newart.jpg') touch(newart) i2 = item() i2.path = self.i.path - i2.artist = 'someArtist' + i2.artist = u'someArtist' ai = self.lib.add_album((i2,)) - i2.move(True) + i2.move(operation=MoveOperation.COPY) self.assertEqual(ai.artpath, None) ai.set_art(newart) @@ -300,13 +322,13 @@ class ArtFileTest(_common.TestCase): os.remove(self.art) # Original art. - newart = os.path.join(self.libdir, 'newart.jpg') + newart = os.path.join(self.libdir, b'newart.jpg') touch(newart) i2 = item() i2.path = self.i.path - i2.artist = 'someArtist' + i2.artist = u'someArtist' ai = self.lib.add_album((i2,)) - i2.move(True) + i2.move(operation=MoveOperation.COPY) ai.set_art(newart) # Set the art again. @@ -314,13 +336,13 @@ class ArtFileTest(_common.TestCase): self.assertTrue(os.path.exists(ai.artpath)) def test_setart_to_existing_but_unset_art_works(self): - newart = os.path.join(self.libdir, 'newart.jpg') + newart = os.path.join(self.libdir, b'newart.jpg') touch(newart) i2 = item() i2.path = self.i.path - i2.artist = 'someArtist' + i2.artist = u'someArtist' ai = self.lib.add_album((i2,)) - i2.move(True) + i2.move(operation=MoveOperation.COPY) # Copy the art to the destination. artdest = ai.art_destination(newart) @@ -331,13 +353,13 @@ class ArtFileTest(_common.TestCase): self.assertTrue(os.path.exists(ai.artpath)) def test_setart_to_conflicting_file_gets_new_path(self): - newart = os.path.join(self.libdir, 'newart.jpg') + newart = os.path.join(self.libdir, b'newart.jpg') touch(newart) i2 = item() i2.path = self.i.path - i2.artist = 'someArtist' + i2.artist = u'someArtist' ai = self.lib.add_album((i2,)) - i2.move(True) + i2.move(operation=MoveOperation.COPY) # Make a file at the destination. artdest = ai.art_destination(newart) @@ -352,16 +374,16 @@ class ArtFileTest(_common.TestCase): def test_setart_sets_permissions(self): os.remove(self.art) - newart = os.path.join(self.libdir, 'newart.jpg') + newart = os.path.join(self.libdir, b'newart.jpg') touch(newart) - os.chmod(newart, 0400) # read-only + os.chmod(newart, 0o400) # read-only try: i2 = item() i2.path = self.i.path - i2.artist = 'someArtist' + i2.artist = u'someArtist' ai = self.lib.add_album((i2,)) - i2.move(True) + i2.move(operation=MoveOperation.COPY) ai.set_art(newart) mode = stat.S_IMODE(os.stat(ai.artpath).st_mode) @@ -370,19 +392,19 @@ class ArtFileTest(_common.TestCase): finally: # Make everything writable so it can be cleaned up. - os.chmod(newart, 0777) - os.chmod(ai.artpath, 0777) + os.chmod(newart, 0o777) + os.chmod(ai.artpath, 0o777) def test_move_last_file_moves_albumart(self): oldartpath = self.lib.albums()[0].artpath self.assertExists(oldartpath) - self.ai.album = 'different_album' + self.ai.album = u'different_album' self.ai.store() self.ai.items()[0].move() artpath = self.lib.albums()[0].artpath - self.assertTrue('different_album' in artpath) + self.assertTrue(b'different_album' in artpath) self.assertExists(artpath) self.assertNotExists(oldartpath) @@ -394,12 +416,12 @@ class ArtFileTest(_common.TestCase): oldartpath = self.lib.albums()[0].artpath self.assertExists(oldartpath) - self.i.album = 'different_album' + self.i.album = u'different_album' self.i.album_id = None # detach from album self.i.move() artpath = self.lib.albums()[0].artpath - self.assertFalse('different_album' in artpath) + self.assertFalse(b'different_album' in artpath) self.assertEqual(artpath, oldartpath) self.assertExists(oldartpath) @@ -410,7 +432,7 @@ class RemoveTest(_common.TestCase): # Make library and item. self.lib = beets.library.Library(':memory:') - self.libdir = os.path.join(self.temp_dir, 'testlibdir') + self.libdir = os.path.join(self.temp_dir, b'testlibdir') self.lib.directory = self.libdir self.i = item(self.lib) self.i.path = self.i.destination() @@ -428,13 +450,13 @@ class RemoveTest(_common.TestCase): def test_removing_last_item_preserves_nonempty_dir(self): parent = os.path.dirname(self.i.path) - touch(os.path.join(parent, 'dummy.txt')) + touch(os.path.join(parent, b'dummy.txt')) self.i.remove(True) self.assertExists(parent) def test_removing_last_item_prunes_dir_with_blacklisted_file(self): parent = os.path.dirname(self.i.path) - touch(os.path.join(parent, '.DS_Store')) + touch(os.path.join(parent, b'.DS_Store')) self.i.remove(True) self.assertNotExists(parent) @@ -448,13 +470,13 @@ class RemoveTest(_common.TestCase): self.assertExists(self.libdir) def test_removing_item_outside_of_library_deletes_nothing(self): - self.lib.directory = os.path.join(self.temp_dir, 'xxx') + self.lib.directory = os.path.join(self.temp_dir, b'xxx') parent = os.path.dirname(self.i.path) self.i.remove(True) self.assertExists(parent) def test_removing_last_item_in_album_with_albumart_prunes_dir(self): - artfile = os.path.join(self.temp_dir, 'testart.jpg') + artfile = os.path.join(self.temp_dir, b'testart.jpg') touch(artfile) self.ai.set_art(artfile) self.ai.store() @@ -469,7 +491,7 @@ class SoftRemoveTest(_common.TestCase): def setUp(self): super(SoftRemoveTest, self).setUp() - self.path = os.path.join(self.temp_dir, 'testfile') + self.path = os.path.join(self.temp_dir, b'testfile') touch(self.path) def test_soft_remove_deletes_file(self): @@ -478,20 +500,20 @@ class SoftRemoveTest(_common.TestCase): def test_soft_remove_silent_on_no_file(self): try: - util.remove(self.path + 'XXX', True) + util.remove(self.path + b'XXX', True) except OSError: - self.fail('OSError when removing path') + self.fail(u'OSError when removing path') class SafeMoveCopyTest(_common.TestCase): def setUp(self): super(SafeMoveCopyTest, self).setUp() - self.path = os.path.join(self.temp_dir, 'testfile') + self.path = os.path.join(self.temp_dir, b'testfile') touch(self.path) - self.otherpath = os.path.join(self.temp_dir, 'testfile2') + self.otherpath = os.path.join(self.temp_dir, b'testfile2') touch(self.otherpath) - self.dest = self.path + '.dest' + self.dest = self.path + b'.dest' def test_successful_move(self): util.move(self.path, self.dest) @@ -524,9 +546,9 @@ class PruneTest(_common.TestCase): def setUp(self): super(PruneTest, self).setUp() - self.base = os.path.join(self.temp_dir, 'testdir') + self.base = os.path.join(self.temp_dir, b'testdir') os.mkdir(self.base) - self.sub = os.path.join(self.base, 'subdir') + self.sub = os.path.join(self.base, b'subdir') os.mkdir(self.sub) def test_prune_existent_directory(self): @@ -535,7 +557,7 @@ class PruneTest(_common.TestCase): self.assertNotExists(self.sub) def test_prune_nonexistent_directory(self): - util.prune_dirs(os.path.join(self.sub, 'another'), self.base) + util.prune_dirs(os.path.join(self.sub, b'another'), self.base) self.assertExists(self.base) self.assertNotExists(self.sub) @@ -544,37 +566,37 @@ class WalkTest(_common.TestCase): def setUp(self): super(WalkTest, self).setUp() - self.base = os.path.join(self.temp_dir, 'testdir') + self.base = os.path.join(self.temp_dir, b'testdir') os.mkdir(self.base) - touch(os.path.join(self.base, 'y')) - touch(os.path.join(self.base, 'x')) - os.mkdir(os.path.join(self.base, 'd')) - touch(os.path.join(self.base, 'd', 'z')) + touch(os.path.join(self.base, b'y')) + touch(os.path.join(self.base, b'x')) + os.mkdir(os.path.join(self.base, b'd')) + touch(os.path.join(self.base, b'd', b'z')) def test_sorted_files(self): res = list(util.sorted_walk(self.base)) self.assertEqual(len(res), 2) self.assertEqual(res[0], - (self.base, ['d'], ['x', 'y'])) + (self.base, [b'd'], [b'x', b'y'])) self.assertEqual(res[1], - (os.path.join(self.base, 'd'), [], ['z'])) + (os.path.join(self.base, b'd'), [], [b'z'])) def test_ignore_file(self): - res = list(util.sorted_walk(self.base, ('x',))) + res = list(util.sorted_walk(self.base, (b'x',))) self.assertEqual(len(res), 2) self.assertEqual(res[0], - (self.base, ['d'], ['y'])) + (self.base, [b'd'], [b'y'])) self.assertEqual(res[1], - (os.path.join(self.base, 'd'), [], ['z'])) + (os.path.join(self.base, b'd'), [], [b'z'])) def test_ignore_directory(self): - res = list(util.sorted_walk(self.base, ('d',))) + res = list(util.sorted_walk(self.base, (b'd',))) self.assertEqual(len(res), 1) self.assertEqual(res[0], - (self.base, [], ['x', 'y'])) + (self.base, [], [b'x', b'y'])) def test_ignore_everything(self): - res = list(util.sorted_walk(self.base, ('*',))) + res = list(util.sorted_walk(self.base, (b'*',))) self.assertEqual(len(res), 1) self.assertEqual(res[0], (self.base, [], [])) @@ -584,48 +606,48 @@ class UniquePathTest(_common.TestCase): def setUp(self): super(UniquePathTest, self).setUp() - self.base = os.path.join(self.temp_dir, 'testdir') + self.base = os.path.join(self.temp_dir, b'testdir') os.mkdir(self.base) - touch(os.path.join(self.base, 'x.mp3')) - touch(os.path.join(self.base, 'x.1.mp3')) - touch(os.path.join(self.base, 'x.2.mp3')) - touch(os.path.join(self.base, 'y.mp3')) + touch(os.path.join(self.base, b'x.mp3')) + touch(os.path.join(self.base, b'x.1.mp3')) + touch(os.path.join(self.base, b'x.2.mp3')) + touch(os.path.join(self.base, b'y.mp3')) def test_new_file_unchanged(self): - path = util.unique_path(os.path.join(self.base, 'z.mp3')) - self.assertEqual(path, os.path.join(self.base, 'z.mp3')) + path = util.unique_path(os.path.join(self.base, b'z.mp3')) + self.assertEqual(path, os.path.join(self.base, b'z.mp3')) def test_conflicting_file_appends_1(self): - path = util.unique_path(os.path.join(self.base, 'y.mp3')) - self.assertEqual(path, os.path.join(self.base, 'y.1.mp3')) + path = util.unique_path(os.path.join(self.base, b'y.mp3')) + self.assertEqual(path, os.path.join(self.base, b'y.1.mp3')) def test_conflicting_file_appends_higher_number(self): - path = util.unique_path(os.path.join(self.base, 'x.mp3')) - self.assertEqual(path, os.path.join(self.base, 'x.3.mp3')) + path = util.unique_path(os.path.join(self.base, b'x.mp3')) + self.assertEqual(path, os.path.join(self.base, b'x.3.mp3')) def test_conflicting_file_with_number_increases_number(self): - path = util.unique_path(os.path.join(self.base, 'x.1.mp3')) - self.assertEqual(path, os.path.join(self.base, 'x.3.mp3')) + path = util.unique_path(os.path.join(self.base, b'x.1.mp3')) + self.assertEqual(path, os.path.join(self.base, b'x.3.mp3')) class MkDirAllTest(_common.TestCase): def test_parent_exists(self): - path = os.path.join(self.temp_dir, 'foo', 'bar', 'baz', 'qux.mp3') + path = os.path.join(self.temp_dir, b'foo', b'bar', b'baz', b'qux.mp3') util.mkdirall(path) self.assertTrue(os.path.isdir( - os.path.join(self.temp_dir, 'foo', 'bar', 'baz') + os.path.join(self.temp_dir, b'foo', b'bar', b'baz') )) def test_child_does_not_exist(self): - path = os.path.join(self.temp_dir, 'foo', 'bar', 'baz', 'qux.mp3') + path = os.path.join(self.temp_dir, b'foo', b'bar', b'baz', b'qux.mp3') util.mkdirall(path) self.assertTrue(not os.path.exists( - os.path.join(self.temp_dir, 'foo', 'bar', 'baz', 'qux.mp3') + os.path.join(self.temp_dir, b'foo', b'bar', b'baz', b'qux.mp3') )) def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_ftintitle.py b/test/test_ftintitle.py index 67b952a51..d698263be 100644 --- a/test/test_ftintitle.py +++ b/test/test_ftintitle.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Fabrice Laporte. +# Copyright 2016, Fabrice Laporte. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,10 +15,9 @@ """Tests for the 'ftintitle' plugin.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function -from test._common import unittest +import unittest from test.helper import TestHelper from beetsplug import ftintitle @@ -35,6 +35,7 @@ class FtInTitlePluginFunctional(unittest.TestCase, TestHelper): def _ft_add_item(self, path, artist, title, aartist): return self.add_item(path=path, artist=artist, + artist_sort=artist, title=title, albumartist=aartist) @@ -50,6 +51,14 @@ class FtInTitlePluginFunctional(unittest.TestCase, TestHelper): self.assertEqual(item['artist'], u'Alice') self.assertEqual(item['title'], u'Song 1') + def test_functional_not_found(self): + item = self._ft_add_item('/', u'Alice ft Bob', u'Song 1', u'George') + self.run_command('ftintitle', '-d') + item.load() + # item should be unchanged + self.assertEqual(item['artist'], u'Alice ft Bob') + self.assertEqual(item['title'], u'Song 1') + def test_functional_custom_format(self): self._ft_set_config('feat. {0}') item = self._ft_add_item('/', u'Alice ft Bob', u'Song 1', u'Alice') @@ -125,6 +134,11 @@ class FtInTitlePluginTest(unittest.TestCase): 'album_artist': 'Bob', 'feat_part': 'Alice' }, + { + 'artist': 'Alice ft. Carol', + 'album_artist': 'Bob', + 'feat_part': None + }, ] for test_case in test_cases: @@ -135,37 +149,37 @@ class FtInTitlePluginTest(unittest.TestCase): self.assertEqual(feat_part, test_case['feat_part']) def test_split_on_feat(self): - parts = ftintitle.split_on_feat('Alice ft. Bob') - self.assertEqual(parts, ('Alice', 'Bob')) - parts = ftintitle.split_on_feat('Alice feat Bob') - self.assertEqual(parts, ('Alice', 'Bob')) - parts = ftintitle.split_on_feat('Alice feat. Bob') - self.assertEqual(parts, ('Alice', 'Bob')) - parts = ftintitle.split_on_feat('Alice featuring Bob') - self.assertEqual(parts, ('Alice', 'Bob')) - parts = ftintitle.split_on_feat('Alice & Bob') - self.assertEqual(parts, ('Alice', 'Bob')) - parts = ftintitle.split_on_feat('Alice and Bob') - self.assertEqual(parts, ('Alice', 'Bob')) - parts = ftintitle.split_on_feat('Alice With Bob') - self.assertEqual(parts, ('Alice', 'Bob')) - parts = ftintitle.split_on_feat('Alice defeat Bob') - self.assertEqual(parts, ('Alice defeat Bob', None)) + parts = ftintitle.split_on_feat(u'Alice ft. Bob') + self.assertEqual(parts, (u'Alice', u'Bob')) + parts = ftintitle.split_on_feat(u'Alice feat Bob') + self.assertEqual(parts, (u'Alice', u'Bob')) + parts = ftintitle.split_on_feat(u'Alice feat. Bob') + self.assertEqual(parts, (u'Alice', u'Bob')) + parts = ftintitle.split_on_feat(u'Alice featuring Bob') + self.assertEqual(parts, (u'Alice', u'Bob')) + parts = ftintitle.split_on_feat(u'Alice & Bob') + self.assertEqual(parts, (u'Alice', u'Bob')) + parts = ftintitle.split_on_feat(u'Alice and Bob') + self.assertEqual(parts, (u'Alice', u'Bob')) + parts = ftintitle.split_on_feat(u'Alice With Bob') + self.assertEqual(parts, (u'Alice', u'Bob')) + parts = ftintitle.split_on_feat(u'Alice defeat Bob') + self.assertEqual(parts, (u'Alice defeat Bob', None)) def test_contains_feat(self): - self.assertTrue(ftintitle.contains_feat('Alice ft. Bob')) - self.assertTrue(ftintitle.contains_feat('Alice feat. Bob')) - self.assertTrue(ftintitle.contains_feat('Alice feat Bob')) - self.assertTrue(ftintitle.contains_feat('Alice featuring Bob')) - self.assertTrue(ftintitle.contains_feat('Alice & Bob')) - self.assertTrue(ftintitle.contains_feat('Alice and Bob')) - self.assertTrue(ftintitle.contains_feat('Alice With Bob')) - self.assertFalse(ftintitle.contains_feat('Alice defeat Bob')) - self.assertFalse(ftintitle.contains_feat('Aliceft.Bob')) + self.assertTrue(ftintitle.contains_feat(u'Alice ft. Bob')) + self.assertTrue(ftintitle.contains_feat(u'Alice feat. Bob')) + self.assertTrue(ftintitle.contains_feat(u'Alice feat Bob')) + self.assertTrue(ftintitle.contains_feat(u'Alice featuring Bob')) + self.assertTrue(ftintitle.contains_feat(u'Alice & Bob')) + self.assertTrue(ftintitle.contains_feat(u'Alice and Bob')) + self.assertTrue(ftintitle.contains_feat(u'Alice With Bob')) + self.assertFalse(ftintitle.contains_feat(u'Alice defeat Bob')) + self.assertFalse(ftintitle.contains_feat(u'Aliceft.Bob')) def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_hidden.py b/test/test_hidden.py new file mode 100644 index 000000000..e2dd1afb3 --- /dev/null +++ b/test/test_hidden.py @@ -0,0 +1,83 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Fabrice Laporte. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Tests for the 'hidden' utility.""" + +from __future__ import division, absolute_import, print_function + +import unittest +import sys +import tempfile +from beets.util import hidden +from beets import util +import subprocess +import errno +import ctypes + + +class HiddenFileTest(unittest.TestCase): + def setUp(self): + pass + + def test_osx_hidden(self): + if not sys.platform == 'darwin': + self.skipTest('sys.platform is not darwin') + return + + with tempfile.NamedTemporaryFile(delete=False) as f: + try: + command = ["chflags", "hidden", f.name] + subprocess.Popen(command).wait() + except OSError as e: + if e.errno == errno.ENOENT: + self.skipTest("unable to find chflags") + else: + raise e + + self.assertTrue(hidden.is_hidden(f.name)) + + def test_windows_hidden(self): + if not sys.platform == 'win32': + self.skipTest('sys.platform is not windows') + return + + # FILE_ATTRIBUTE_HIDDEN = 2 (0x2) from GetFileAttributes documentation. + hidden_mask = 2 + + with tempfile.NamedTemporaryFile() as f: + # Hide the file using + success = ctypes.windll.kernel32.SetFileAttributesW(f.name, + hidden_mask) + + if not success: + self.skipTest("unable to set file attributes") + + self.assertTrue(hidden.is_hidden(f.name)) + + def test_other_hidden(self): + if sys.platform == 'darwin' or sys.platform == 'win32': + self.skipTest('sys.platform is known') + return + + with tempfile.NamedTemporaryFile(prefix='.tmp') as f: + fn = util.bytestring_path(f.name) + self.assertTrue(hidden.is_hidden(fn)) + + +def suite(): + return unittest.TestLoader().loadTestsFromName(__name__) + +if __name__ == '__main__': + unittest.main(defaultTest='suite') diff --git a/test/test_hook.py b/test/test_hook.py new file mode 100644 index 000000000..39fd08959 --- /dev/null +++ b/test/test_hook.py @@ -0,0 +1,118 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2015, Thomas Scholtes. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +from __future__ import division, absolute_import, print_function + +import os.path +import tempfile +import unittest + +from test import _common +from test.helper import TestHelper + +from beets import config +from beets import plugins + + +def get_temporary_path(): + temporary_directory = tempfile._get_default_tempdir() + temporary_name = next(tempfile._get_candidate_names()) + + return os.path.join(temporary_directory, temporary_name) + + +class HookTest(_common.TestCase, TestHelper): + TEST_HOOK_COUNT = 5 + + def setUp(self): + self.setup_beets() # Converter is threaded + + def tearDown(self): + self.unload_plugins() + self.teardown_beets() + + def _add_hook(self, event, command): + hook = { + 'event': event, + 'command': command + } + + hooks = config['hook']['hooks'].get(list) if 'hook' in config else [] + hooks.append(hook) + + config['hook']['hooks'] = hooks + + def test_hook_no_arguments(self): + temporary_paths = [ + get_temporary_path() for i in range(self.TEST_HOOK_COUNT) + ] + + for index, path in enumerate(temporary_paths): + self._add_hook('test_no_argument_event_{0}'.format(index), + 'touch "{0}"'.format(path)) + + self.load_plugins('hook') + + for index in range(len(temporary_paths)): + plugins.send('test_no_argument_event_{0}'.format(index)) + + for path in temporary_paths: + self.assertTrue(os.path.isfile(path)) + os.remove(path) + + def test_hook_event_substitution(self): + temporary_directory = tempfile._get_default_tempdir() + event_names = ['test_event_event_{0}'.format(i) for i in + range(self.TEST_HOOK_COUNT)] + + for event in event_names: + self._add_hook(event, + 'touch "{0}/{{event}}"'.format(temporary_directory)) + + self.load_plugins('hook') + + for event in event_names: + plugins.send(event) + + for event in event_names: + path = os.path.join(temporary_directory, event) + + self.assertTrue(os.path.isfile(path)) + os.remove(path) + + def test_hook_argument_substitution(self): + temporary_paths = [ + get_temporary_path() for i in range(self.TEST_HOOK_COUNT) + ] + + for index, path in enumerate(temporary_paths): + self._add_hook('test_argument_event_{0}'.format(index), + 'touch "{path}"') + + self.load_plugins('hook') + + for index, path in enumerate(temporary_paths): + plugins.send('test_argument_event_{0}'.format(index), path=path) + + for path in temporary_paths: + self.assertTrue(os.path.isfile(path)) + os.remove(path) + + +def suite(): + return unittest.TestLoader().loadTestsFromName(__name__) + +if __name__ == '__main__': + unittest.main(defaultTest='suite') diff --git a/test/test_ihate.py b/test/test_ihate.py index eb14ccdc3..f52617481 100644 --- a/test/test_ihate.py +++ b/test/test_ihate.py @@ -1,9 +1,10 @@ +# -*- coding: utf-8 -*- + """Tests for the 'ihate' plugin""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function -from test._common import unittest +import unittest from beets import importer from beets.library import Item from beetsplug.ihate import IHatePlugin @@ -15,7 +16,7 @@ class IHatePluginTest(unittest.TestCase): match_pattern = {} test_item = Item( - genre='TestGenre', + genre=u'TestGenre', album=u'TestAlbum', artist=u'TestArtist') task = importer.SingletonImportTask(None, test_item) @@ -24,30 +25,30 @@ class IHatePluginTest(unittest.TestCase): self.assertFalse(IHatePlugin.do_i_hate_this(task, match_pattern)) # 1 query match. - match_pattern = ["artist:bad_artist", "artist:TestArtist"] + match_pattern = [u"artist:bad_artist", u"artist:TestArtist"] self.assertTrue(IHatePlugin.do_i_hate_this(task, match_pattern)) # 2 query matches, either should trigger. - match_pattern = ["album:test", "artist:testartist"] + match_pattern = [u"album:test", u"artist:testartist"] self.assertTrue(IHatePlugin.do_i_hate_this(task, match_pattern)) # Query is blocked by AND clause. - match_pattern = ["album:notthis genre:testgenre"] + match_pattern = [u"album:notthis genre:testgenre"] self.assertFalse(IHatePlugin.do_i_hate_this(task, match_pattern)) # Both queries are blocked by AND clause with unmatched condition. - match_pattern = ["album:notthis genre:testgenre", - "artist:testartist album:notthis"] + match_pattern = [u"album:notthis genre:testgenre", + u"artist:testartist album:notthis"] self.assertFalse(IHatePlugin.do_i_hate_this(task, match_pattern)) # Only one query should fire. - match_pattern = ["album:testalbum genre:testgenre", - "artist:testartist album:notthis"] + match_pattern = [u"album:testalbum genre:testgenre", + u"artist:testartist album:notthis"] self.assertTrue(IHatePlugin.do_i_hate_this(task, match_pattern)) def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_importadded.py b/test/test_importadded.py index f070b1e60..dd933c3c8 100644 --- a/test/test_importadded.py +++ b/test/test_importadded.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Stig Inge Lea Bjornsen. +# Copyright 2016, Stig Inge Lea Bjornsen. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,14 +13,13 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function """Tests for the `importadded` plugin.""" import os +import unittest -from test._common import unittest from test.test_importer import ImportHelper, AutotagStub from beets import importer from beets import util @@ -67,19 +67,19 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): self.teardown_beets() self.matcher.restore() - def findMediaFile(self, item): + def find_media_file(self, item): """Find the pre-import MediaFile for an Item""" for m in self.media_files: if m.title.replace('Tag', 'Applied') == item.title: return m - raise AssertionError("No MediaFile found for Item " + + raise AssertionError(u"No MediaFile found for Item " + util.displayable_path(item.path)) - def assertEqualTimes(self, first, second, msg=None): + def assertEqualTimes(self, first, second, msg=None): # noqa """For comparing file modification times at a sufficient precision""" self.assertAlmostEqual(first, second, places=4, msg=msg) - def assertAlbumImport(self): + def assertAlbumImport(self): # noqa self.importer.run() album = self.lib.albums().get() self.assertEqual(album.added, self.min_mtime) @@ -93,6 +93,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): self.config['import']['copy'] = False self.config['import']['move'] = False self.config['import']['link'] = False + self.config['import']['hardlink'] = False self.assertAlbumImport() def test_import_album_with_preserved_mtimes(self): @@ -102,7 +103,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): self.assertEqual(album.added, self.min_mtime) for item in album.items(): self.assertEqualTimes(item.added, self.min_mtime) - mediafile_mtime = os.path.getmtime(self.findMediaFile(item).path) + mediafile_mtime = os.path.getmtime(self.find_media_file(item).path) self.assertEqualTimes(item.mtime, mediafile_mtime) self.assertEqualTimes(os.path.getmtime(item.path), mediafile_mtime) @@ -124,16 +125,16 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): self.assertEqualTimes(album.added, album_added_before) items_added_after = dict((item.path, item.added) for item in album.items()) - for item_path, added_after in items_added_after.iteritems(): + for item_path, added_after in items_added_after.items(): self.assertEqualTimes(items_added_before[item_path], added_after, - "reimport modified Item.added for " + - item_path) + u"reimport modified Item.added for " + + util.displayable_path(item_path)) def test_import_singletons_with_added_dates(self): self.config['import']['singletons'] = True self.importer.run() for item in self.lib.items(): - mfile = self.findMediaFile(item) + mfile = self.find_media_file(item) self.assertEqualTimes(item.added, os.path.getmtime(mfile.path)) def test_import_singletons_with_preserved_mtimes(self): @@ -141,7 +142,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): self.config['importadded']['preserve_mtimes'] = True self.importer.run() for item in self.lib.items(): - mediafile_mtime = os.path.getmtime(self.findMediaFile(item).path) + mediafile_mtime = os.path.getmtime(self.find_media_file(item).path) self.assertEqualTimes(item.added, mediafile_mtime) self.assertEqualTimes(item.mtime, mediafile_mtime) self.assertEqualTimes(os.path.getmtime(item.path), @@ -156,20 +157,20 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): # Newer Item path mtimes as if Beets had modified them modify_mtimes(items_added_before.keys(), offset=10000) # Reimport - import_dir = os.path.dirname(items_added_before.keys()[0]) + import_dir = os.path.dirname(list(items_added_before.keys())[0]) self._setup_import_session(import_dir=import_dir, singletons=True) self.importer.run() # Verify the reimported items items_added_after = dict((item.path, item.added) for item in self.lib.items()) - for item_path, added_after in items_added_after.iteritems(): + for item_path, added_after in items_added_after.items(): self.assertEqualTimes(items_added_before[item_path], added_after, - "reimport modified Item.added for " + - item_path) + u"reimport modified Item.added for " + + util.displayable_path(item_path)) def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_importer.py b/test/test_importer.py index 7b07ea331..e30f5609c 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,25 +13,25 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function """Tests for the general importer functionality. """ import os import re import shutil -import StringIO import unicodedata import sys +import stat +from six import StringIO from tempfile import mkstemp from zipfile import ZipFile from tarfile import TarFile -from mock import patch +from mock import patch, Mock +import unittest from test import _common -from test._common import unittest -from beets.util import displayable_path +from beets.util import displayable_path, bytestring_path, py3_path from test.helper import TestImportSession, TestHelper, has_program, capture_log from beets import importer from beets.importer import albums_in_dir @@ -39,6 +40,7 @@ from beets import autotag from beets.autotag import AlbumInfo, TrackInfo, AlbumMatch from beets import config from beets import logging +from beets import util class AutotagStub(object): @@ -97,7 +99,8 @@ class AutotagStub(object): track_id=u'trackid', artist=artist.replace('Tag', 'Applied'), artist_id=u'artistid', - length=1 + length=1, + index=0, ) def album_for_id(self, mbid): @@ -111,7 +114,8 @@ class AutotagStub(object): title=u'Applied Title %d' % number, track_id=u'match %d' % number, artist=artist, - length=1 + length=1, + index=0, ) def _make_album_match(self, artist, album, tracks, distance=0, missing=0): @@ -120,19 +124,19 @@ class AutotagStub(object): else: id = '' if artist is None: - artist = "Various Artists" + artist = u"Various Artists" else: artist = artist.replace('Tag', 'Applied') + id album = album.replace('Tag', 'Applied') + id - trackInfos = [] + track_infos = [] for i in range(tracks - missing): - trackInfos.append(self._make_track_match(artist, album, i + 1)) + track_infos.append(self._make_track_match(artist, album, i + 1)) return AlbumInfo( artist=artist, album=album, - tracks=trackInfos, + tracks=track_infos, va=False, album_id=u'albumid' + id, artist_id=u'artistid' + id, @@ -149,9 +153,9 @@ class ImportHelper(TestHelper): def setup_beets(self, disk=False): super(ImportHelper, self).setup_beets(disk) self.lib.path_formats = [ - ('default', os.path.join('$artist', '$album', '$title')), - ('singleton:true', os.path.join('singletons', '$title')), - ('comp:true', os.path.join('compilations', '$album', '$title')), + (u'default', os.path.join('$artist', '$album', '$title')), + (u'singleton:true', os.path.join('singletons', '$title')), + (u'comp:true', os.path.join('compilations', '$album', '$title')), ] def _create_import_dir(self, count=3): @@ -168,18 +172,18 @@ class ImportHelper(TestHelper): :param count: Number of files to create """ - self.import_dir = os.path.join(self.temp_dir, 'testsrcdir') + self.import_dir = os.path.join(self.temp_dir, b'testsrcdir') if os.path.isdir(self.import_dir): shutil.rmtree(self.import_dir) - album_path = os.path.join(self.import_dir, 'the_album') + album_path = os.path.join(self.import_dir, b'the_album') os.makedirs(album_path) - resource_path = os.path.join(_common.RSRC, 'full.mp3') + resource_path = os.path.join(_common.RSRC, b'full.mp3') metadata = { - 'artist': 'Tag Artist', - 'album': 'Tag Album', + 'artist': u'Tag Artist', + 'album': u'Tag Album', 'albumartist': None, 'mb_trackid': None, 'mb_albumid': None, @@ -188,13 +192,16 @@ class ImportHelper(TestHelper): self.media_files = [] for i in range(count): # Copy files - medium_path = os.path.join(album_path, 'track_%d.mp3' % (i + 1)) + medium_path = os.path.join( + album_path, + bytestring_path('track_%d.mp3' % (i + 1)) + ) shutil.copy(resource_path, medium_path) medium = MediaFile(medium_path) # Set metadata metadata['track'] = i + 1 - metadata['title'] = 'Tag Title %d' % (i + 1) + metadata['title'] = u'Tag Title %d' % (i + 1) for attr in metadata: setattr(medium, attr, metadata[attr]) medium.save() @@ -203,7 +210,8 @@ class ImportHelper(TestHelper): def _setup_import_session(self, import_dir=None, delete=False, threaded=False, copy=True, singletons=False, - move=False, autotag=True, link=False): + move=False, autotag=True, link=False, + hardlink=False): config['import']['copy'] = copy config['import']['delete'] = delete config['import']['timid'] = True @@ -213,6 +221,7 @@ class ImportHelper(TestHelper): config['import']['autotag'] = autotag config['import']['resume'] = False config['import']['link'] = link + config['import']['hardlink'] = hardlink self.importer = TestImportSession( self.lib, loghandler=None, query=None, @@ -235,6 +244,7 @@ class ImportHelper(TestHelper): self.assertEqual(len(os.listdir(self.libdir)), 0) +@_common.slow_test() class NonAutotaggedImportTest(_common.TestCase, ImportHelper): def setUp(self): self.setup_beets(disk=True) @@ -248,14 +258,14 @@ class NonAutotaggedImportTest(_common.TestCase, ImportHelper): self.importer.run() albums = self.lib.albums() self.assertEqual(len(albums), 1) - self.assertEqual(albums[0].albumartist, 'Tag Artist') + self.assertEqual(albums[0].albumartist, u'Tag Artist') def test_import_copy_arrives(self): self.importer.run() for mediafile in self.import_media: self.assert_file_in_lib( - 'Tag Artist', 'Tag Album', '%s.mp3' % mediafile.title - ) + b'Tag Artist', b'Tag Album', + util.bytestring_path('{0}.mp3'.format(mediafile.title))) def test_threaded_import_copy_arrives(self): config['threaded'] = True @@ -263,8 +273,8 @@ class NonAutotaggedImportTest(_common.TestCase, ImportHelper): self.importer.run() for mediafile in self.import_media: self.assert_file_in_lib( - 'Tag Artist', 'Tag Album', '%s.mp3' % mediafile.title - ) + b'Tag Artist', b'Tag Album', + util.bytestring_path('{0}.mp3'.format(mediafile.title))) def test_import_with_move_deletes_import_files(self): config['import']['move'] = True @@ -278,19 +288,19 @@ class NonAutotaggedImportTest(_common.TestCase, ImportHelper): def test_import_with_move_prunes_directory_empty(self): config['import']['move'] = True - self.assertExists(os.path.join(self.import_dir, 'the_album')) + self.assertExists(os.path.join(self.import_dir, b'the_album')) self.importer.run() - self.assertNotExists(os.path.join(self.import_dir, 'the_album')) + self.assertNotExists(os.path.join(self.import_dir, b'the_album')) def test_import_with_move_prunes_with_extra_clutter(self): - f = open(os.path.join(self.import_dir, 'the_album', 'alog.log'), 'w') + f = open(os.path.join(self.import_dir, b'the_album', b'alog.log'), 'w') f.close() config['clutter'] = ['*.log'] config['import']['move'] = True - self.assertExists(os.path.join(self.import_dir, 'the_album')) + self.assertExists(os.path.join(self.import_dir, b'the_album')) self.importer.run() - self.assertNotExists(os.path.join(self.import_dir, 'the_album')) + self.assertNotExists(os.path.join(self.import_dir, b'the_album')) def test_threaded_import_move_arrives(self): config['import']['move'] = True @@ -299,8 +309,8 @@ class NonAutotaggedImportTest(_common.TestCase, ImportHelper): self.importer.run() for mediafile in self.import_media: self.assert_file_in_lib( - 'Tag Artist', 'Tag Album', '%s.mp3' % mediafile.title - ) + b'Tag Artist', b'Tag Album', + util.bytestring_path('{0}.mp3'.format(mediafile.title))) def test_threaded_import_move_deletes_import(self): config['import']['move'] = True @@ -325,9 +335,9 @@ class NonAutotaggedImportTest(_common.TestCase, ImportHelper): def test_import_with_delete_prunes_directory_empty(self): config['import']['delete'] = True - self.assertExists(os.path.join(self.import_dir, 'the_album')) + self.assertExists(os.path.join(self.import_dir, b'the_album')) self.importer.run() - self.assertNotExists(os.path.join(self.import_dir, 'the_album')) + self.assertNotExists(os.path.join(self.import_dir, b'the_album')) @unittest.skipUnless(_common.HAVE_SYMLINK, "need symlinks") def test_import_link_arrives(self): @@ -336,24 +346,47 @@ class NonAutotaggedImportTest(_common.TestCase, ImportHelper): for mediafile in self.import_media: filename = os.path.join( self.libdir, - 'Tag Artist', 'Tag Album', '%s.mp3' % mediafile.title + b'Tag Artist', b'Tag Album', + util.bytestring_path('{0}.mp3'.format(mediafile.title)) ) self.assertExists(filename) self.assertTrue(os.path.islink(filename)) - self.assertEqual(os.readlink(filename), mediafile.path) + self.assert_equal_path( + util.bytestring_path(os.readlink(filename)), + mediafile.path + ) + + @unittest.skipUnless(_common.HAVE_HARDLINK, "need hardlinks") + def test_import_hardlink_arrives(self): + config['import']['hardlink'] = True + self.importer.run() + for mediafile in self.import_media: + filename = os.path.join( + self.libdir, + b'Tag Artist', b'Tag Album', + util.bytestring_path('{0}.mp3'.format(mediafile.title)) + ) + self.assertExists(filename) + s1 = os.stat(mediafile.path) + s2 = os.stat(filename) + self.assertTrue( + (s1[stat.ST_INO], s1[stat.ST_DEV]) == + (s2[stat.ST_INO], s2[stat.ST_DEV]) + ) def create_archive(session): - (handle, path) = mkstemp(dir=session.temp_dir) + (handle, path) = mkstemp(dir=py3_path(session.temp_dir)) os.close(handle) - archive = ZipFile(path, mode='w') - archive.write(os.path.join(_common.RSRC, 'full.mp3'), + archive = ZipFile(py3_path(path), mode='w') + archive.write(os.path.join(_common.RSRC, b'full.mp3'), 'full.mp3') archive.close() + path = bytestring_path(path) return path -class RmTempTest(unittest.TestCase, ImportHelper): +class RmTempTest(unittest.TestCase, ImportHelper, _common.Assertions): """Tests that temporarily extracted archives are properly removed after usage. """ @@ -373,9 +406,9 @@ class RmTempTest(unittest.TestCase, ImportHelper): archive_task.extract() tmp_path = archive_task.toppath self._setup_import_session(autotag=False, import_dir=tmp_path) - self.assertTrue(os.path.exists(tmp_path)) + self.assertExists(tmp_path) archive_task.finalize(self) - self.assertFalse(os.path.exists(tmp_path)) + self.assertNotExists(tmp_path) class ImportZipTest(unittest.TestCase, ImportHelper): @@ -402,25 +435,25 @@ class ImportTarTest(ImportZipTest): def create_archive(self): (handle, path) = mkstemp(dir=self.temp_dir) os.close(handle) - archive = TarFile(path, mode='w') - archive.add(os.path.join(_common.RSRC, 'full.mp3'), + archive = TarFile(py3_path(path), mode='w') + archive.add(os.path.join(_common.RSRC, b'full.mp3'), 'full.mp3') archive.close() return path -@unittest.skipIf(not has_program('unrar'), 'unrar program not found') +@unittest.skipIf(not has_program('unrar'), u'unrar program not found') class ImportRarTest(ImportZipTest): def create_archive(self): - return os.path.join(_common.RSRC, 'archive.rar') + return os.path.join(_common.RSRC, b'archive.rar') @unittest.skip('Implement me!') class ImportPasswordRarTest(ImportZipTest): def create_archive(self): - return os.path.join(_common.RSRC, 'password.rar') + return os.path.join(_common.RSRC, b'password.rar') class ImportSingletonTest(_common.TestCase, ImportHelper): @@ -444,7 +477,7 @@ class ImportSingletonTest(_common.TestCase, ImportHelper): self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assertEqual(self.lib.items().get().title, 'Tag Title 1') + self.assertEqual(self.lib.items().get().title, u'Tag Title 1') def test_apply_asis_does_not_add_album(self): self.assertEqual(self.lib.albums().get(), None) @@ -458,14 +491,14 @@ class ImportSingletonTest(_common.TestCase, ImportHelper): self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assert_file_in_lib('singletons', 'Tag Title 1.mp3') + self.assert_file_in_lib(b'singletons', b'Tag Title 1.mp3') def test_apply_candidate_adds_track(self): self.assertEqual(self.lib.items().get(), None) self.importer.add_choice(importer.action.APPLY) self.importer.run() - self.assertEqual(self.lib.items().get().title, 'Applied Title 1') + self.assertEqual(self.lib.items().get().title, u'Applied Title 1') def test_apply_candidate_does_not_add_album(self): self.importer.add_choice(importer.action.APPLY) @@ -477,7 +510,7 @@ class ImportSingletonTest(_common.TestCase, ImportHelper): self.importer.add_choice(importer.action.APPLY) self.importer.run() - self.assert_file_in_lib('singletons', 'Applied Title 1.mp3') + self.assert_file_in_lib(b'singletons', b'Applied Title 1.mp3') def test_skip_does_not_add_first_track(self): self.importer.add_choice(importer.action.SKIP) @@ -492,12 +525,12 @@ class ImportSingletonTest(_common.TestCase, ImportHelper): self.assertEqual(len(self.lib.items()), 1) def test_import_single_files(self): - resource_path = os.path.join(_common.RSRC, u'empty.mp3') - single_path = os.path.join(self.import_dir, u'track_2.mp3') + resource_path = os.path.join(_common.RSRC, b'empty.mp3') + single_path = os.path.join(self.import_dir, b'track_2.mp3') shutil.copy(resource_path, single_path) import_files = [ - os.path.join(self.import_dir, u'the_album'), + os.path.join(self.import_dir, b'the_album'), single_path ] self._setup_import_session(singletons=False) @@ -510,6 +543,38 @@ class ImportSingletonTest(_common.TestCase, ImportHelper): self.assertEqual(len(self.lib.items()), 2) self.assertEqual(len(self.lib.albums()), 2) + def test_set_fields(self): + genre = u"\U0001F3B7 Jazz" + collection = u"To Listen" + + config['import']['set_fields'] = { + u'collection': collection, + u'genre': genre + } + + # As-is item import. + self.assertEqual(self.lib.albums().get(), None) + self.importer.add_choice(importer.action.ASIS) + self.importer.run() + + for item in self.lib.items(): + item.load() # TODO: Not sure this is necessary. + self.assertEqual(item.genre, genre) + self.assertEqual(item.collection, collection) + # Remove item from library to test again with APPLY choice. + item.remove() + + # Autotagged. + self.assertEqual(self.lib.albums().get(), None) + self.importer.clear_choices() + self.importer.add_choice(importer.action.APPLY) + self.importer.run() + + for item in self.lib.items(): + item.load() + self.assertEqual(item.genre, genre) + self.assertEqual(item.collection, collection) + class ImportTest(_common.TestCase, ImportHelper): """Test APPLY, ASIS and SKIP choices. @@ -530,34 +595,35 @@ class ImportTest(_common.TestCase, ImportHelper): self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assertEqual(self.lib.albums().get().album, 'Tag Album') + self.assertEqual(self.lib.albums().get().album, u'Tag Album') def test_apply_asis_adds_tracks(self): self.assertEqual(self.lib.items().get(), None) self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assertEqual(self.lib.items().get().title, 'Tag Title 1') + self.assertEqual(self.lib.items().get().title, u'Tag Title 1') def test_apply_asis_adds_album_path(self): self.assert_lib_dir_empty() self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assert_file_in_lib('Tag Artist', 'Tag Album', 'Tag Title 1.mp3') + self.assert_file_in_lib( + b'Tag Artist', b'Tag Album', b'Tag Title 1.mp3') def test_apply_candidate_adds_album(self): self.assertEqual(self.lib.albums().get(), None) self.importer.add_choice(importer.action.APPLY) self.importer.run() - self.assertEqual(self.lib.albums().get().album, 'Applied Album') + self.assertEqual(self.lib.albums().get().album, u'Applied Album') def test_apply_candidate_adds_tracks(self): self.assertEqual(self.lib.items().get(), None) self.importer.add_choice(importer.action.APPLY) self.importer.run() - self.assertEqual(self.lib.items().get().title, 'Applied Title 1') + self.assertEqual(self.lib.items().get().title, u'Applied Title 1') def test_apply_candidate_adds_album_path(self): self.assert_lib_dir_empty() @@ -565,13 +631,24 @@ class ImportTest(_common.TestCase, ImportHelper): self.importer.add_choice(importer.action.APPLY) self.importer.run() self.assert_file_in_lib( - 'Applied Artist', 'Applied Album', 'Applied Title 1.mp3' - ) + b'Applied Artist', b'Applied Album', b'Applied Title 1.mp3') + + def test_apply_from_scratch_removes_other_metadata(self): + config['import']['from_scratch'] = True + + for mediafile in self.import_media: + mediafile.genre = u'Tag Genre' + mediafile.save() + + self.importer.add_choice(importer.action.APPLY) + self.importer.run() + self.assertEqual(self.lib.items().get().genre, u'') def test_apply_with_move_deletes_import(self): config['import']['move'] = True - import_file = os.path.join(self.import_dir, 'the_album', 'track_1.mp3') + import_file = os.path.join( + self.import_dir, b'the_album', b'track_1.mp3') self.assertExists(import_file) self.importer.add_choice(importer.action.APPLY) @@ -581,7 +658,8 @@ class ImportTest(_common.TestCase, ImportHelper): def test_apply_with_delete_deletes_import(self): config['import']['delete'] = True - import_file = os.path.join(self.import_dir, 'the_album', 'track_1.mp3') + import_file = os.path.join(self.import_dir, + b'the_album', b'track_1.mp3') self.assertExists(import_file) self.importer.add_choice(importer.action.APPLY) @@ -595,8 +673,8 @@ class ImportTest(_common.TestCase, ImportHelper): def test_skip_non_album_dirs(self): self.assertTrue(os.path.isdir( - os.path.join(self.import_dir, 'the_album'))) - self.touch('cruft', dir=self.import_dir) + os.path.join(self.import_dir, b'the_album'))) + self.touch(b'cruft', dir=self.import_dir) self.importer.add_choice(importer.action.APPLY) self.importer.run() self.assertEqual(len(self.lib.albums()), 1) @@ -609,22 +687,24 @@ class ImportTest(_common.TestCase, ImportHelper): self.assertEqual(len(self.lib.items()), 1) def test_empty_directory_warning(self): - import_dir = os.path.join(self.temp_dir, 'empty') - self.touch('non-audio', dir=import_dir) + import_dir = os.path.join(self.temp_dir, b'empty') + self.touch(b'non-audio', dir=import_dir) self._setup_import_session(import_dir=import_dir) with capture_log() as logs: self.importer.run() - self.assertIn('No files imported from {0}'.format(import_dir), logs) + import_dir = displayable_path(import_dir) + self.assertIn(u'No files imported from {0}'.format(import_dir), logs) def test_empty_directory_singleton_warning(self): - import_dir = os.path.join(self.temp_dir, 'empty') - self.touch('non-audio', dir=import_dir) + import_dir = os.path.join(self.temp_dir, b'empty') + self.touch(b'non-audio', dir=import_dir) self._setup_import_session(import_dir=import_dir, singletons=True) with capture_log() as logs: self.importer.run() - self.assertIn('No files imported from {0}'.format(import_dir), logs) + import_dir = displayable_path(import_dir) + self.assertIn(u'No files imported from {0}'.format(import_dir), logs) def test_asis_no_data_source(self): self.assertEqual(self.lib.items().get(), None) @@ -635,6 +715,38 @@ class ImportTest(_common.TestCase, ImportHelper): with self.assertRaises(AttributeError): self.lib.items().get().data_source + def test_set_fields(self): + genre = u"\U0001F3B7 Jazz" + collection = u"To Listen" + + config['import']['set_fields'] = { + u'collection': collection, + u'genre': genre + } + + # As-is album import. + self.assertEqual(self.lib.albums().get(), None) + self.importer.add_choice(importer.action.ASIS) + self.importer.run() + + for album in self.lib.albums(): + album.load() # TODO: Not sure this is necessary. + self.assertEqual(album.genre, genre) + self.assertEqual(album.collection, collection) + # Remove album from library to test again with APPLY choice. + album.remove() + + # Autotagged. + self.assertEqual(self.lib.albums().get(), None) + self.importer.clear_choices() + self.importer.add_choice(importer.action.APPLY) + self.importer.run() + + for album in self.lib.albums(): + album.load() + self.assertEqual(album.genre, genre) + self.assertEqual(album.collection, collection) + class ImportTracksTest(_common.TestCase, ImportHelper): """Test TRACKS and APPLY choice. @@ -657,7 +769,7 @@ class ImportTracksTest(_common.TestCase, ImportHelper): self.importer.add_choice(importer.action.APPLY) self.importer.add_choice(importer.action.APPLY) self.importer.run() - self.assertEqual(self.lib.items().get().title, 'Applied Title 1') + self.assertEqual(self.lib.items().get().title, u'Applied Title 1') self.assertEqual(self.lib.albums().get(), None) def test_apply_tracks_adds_singleton_path(self): @@ -667,7 +779,7 @@ class ImportTracksTest(_common.TestCase, ImportHelper): self.importer.add_choice(importer.action.APPLY) self.importer.add_choice(importer.action.APPLY) self.importer.run() - self.assert_file_in_lib('singletons', 'Applied Title 1.mp3') + self.assert_file_in_lib(b'singletons', b'Applied Title 1.mp3') class ImportCompilationTest(_common.TestCase, ImportHelper): @@ -686,27 +798,27 @@ class ImportCompilationTest(_common.TestCase, ImportHelper): def test_asis_homogenous_sets_albumartist(self): self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assertEqual(self.lib.albums().get().albumartist, 'Tag Artist') + self.assertEqual(self.lib.albums().get().albumartist, u'Tag Artist') for item in self.lib.items(): - self.assertEqual(item.albumartist, 'Tag Artist') + self.assertEqual(item.albumartist, u'Tag Artist') def test_asis_heterogenous_sets_various_albumartist(self): - self.import_media[0].artist = 'Other Artist' + self.import_media[0].artist = u'Other Artist' self.import_media[0].save() - self.import_media[1].artist = 'Another Artist' + self.import_media[1].artist = u'Another Artist' self.import_media[1].save() self.importer.add_choice(importer.action.ASIS) self.importer.run() self.assertEqual(self.lib.albums().get().albumartist, - 'Various Artists') + u'Various Artists') for item in self.lib.items(): - self.assertEqual(item.albumartist, 'Various Artists') + self.assertEqual(item.albumartist, u'Various Artists') def test_asis_heterogenous_sets_sompilation(self): - self.import_media[0].artist = 'Other Artist' + self.import_media[0].artist = u'Other Artist' self.import_media[0].save() - self.import_media[1].artist = 'Another Artist' + self.import_media[1].artist = u'Another Artist' self.import_media[1].save() self.importer.add_choice(importer.action.ASIS) @@ -715,33 +827,33 @@ class ImportCompilationTest(_common.TestCase, ImportHelper): self.assertTrue(item.comp) def test_asis_sets_majority_albumartist(self): - self.import_media[0].artist = 'Other Artist' + self.import_media[0].artist = u'Other Artist' self.import_media[0].save() - self.import_media[1].artist = 'Other Artist' + self.import_media[1].artist = u'Other Artist' self.import_media[1].save() self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assertEqual(self.lib.albums().get().albumartist, 'Other Artist') + self.assertEqual(self.lib.albums().get().albumartist, u'Other Artist') for item in self.lib.items(): - self.assertEqual(item.albumartist, 'Other Artist') + self.assertEqual(item.albumartist, u'Other Artist') def test_asis_albumartist_tag_sets_albumartist(self): - self.import_media[0].artist = 'Other Artist' - self.import_media[1].artist = 'Another Artist' + self.import_media[0].artist = u'Other Artist' + self.import_media[1].artist = u'Another Artist' for mediafile in self.import_media: - mediafile.albumartist = 'Album Artist' - mediafile.mb_albumartistid = 'Album Artist ID' + mediafile.albumartist = u'Album Artist' + mediafile.mb_albumartistid = u'Album Artist ID' mediafile.save() self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assertEqual(self.lib.albums().get().albumartist, 'Album Artist') + self.assertEqual(self.lib.albums().get().albumartist, u'Album Artist') self.assertEqual(self.lib.albums().get().mb_albumartistid, - 'Album Artist ID') + u'Album Artist ID') for item in self.lib.items(): - self.assertEqual(item.albumartist, 'Album Artist') - self.assertEqual(item.mb_albumartistid, 'Album Artist ID') + self.assertEqual(item.albumartist, u'Album Artist') + self.assertEqual(item.mb_albumartistid, u'Album Artist ID') class ImportExistingTest(_common.TestCase, ImportHelper): @@ -792,68 +904,68 @@ class ImportExistingTest(_common.TestCase, ImportHelper): def test_asis_updates_metadata(self): self.setup_importer.run() medium = MediaFile(self.lib.items().get().path) - medium.title = 'New Title' + medium.title = u'New Title' medium.save() self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assertEqual(self.lib.items().get().title, 'New Title') + self.assertEqual(self.lib.items().get().title, u'New Title') def test_asis_updated_moves_file(self): self.setup_importer.run() medium = MediaFile(self.lib.items().get().path) - medium.title = 'New Title' + medium.title = u'New Title' medium.save() - old_path = os.path.join('Applied Artist', 'Applied Album', - 'Applied Title 1.mp3') + old_path = os.path.join(b'Applied Artist', b'Applied Album', + b'Applied Title 1.mp3') self.assert_file_in_lib(old_path) self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assert_file_in_lib('Applied Artist', 'Applied Album', - 'New Title.mp3') + self.assert_file_in_lib(b'Applied Artist', b'Applied Album', + b'New Title.mp3') self.assert_file_not_in_lib(old_path) def test_asis_updated_without_copy_does_not_move_file(self): self.setup_importer.run() medium = MediaFile(self.lib.items().get().path) - medium.title = 'New Title' + medium.title = u'New Title' medium.save() - old_path = os.path.join('Applied Artist', 'Applied Album', - 'Applied Title 1.mp3') + old_path = os.path.join(b'Applied Artist', b'Applied Album', + b'Applied Title 1.mp3') self.assert_file_in_lib(old_path) config['import']['copy'] = False self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assert_file_not_in_lib('Applied Artist', 'Applied Album', - 'New Title.mp3') + self.assert_file_not_in_lib(b'Applied Artist', b'Applied Album', + b'New Title.mp3') self.assert_file_in_lib(old_path) def test_outside_file_is_copied(self): config['import']['copy'] = False self.setup_importer.run() - self.assertEqual(self.lib.items().get().path, - self.import_media[0].path) + self.assert_equal_path(self.lib.items().get().path, + self.import_media[0].path) config['import']['copy'] = True self._setup_import_session() self.importer.add_choice(importer.action.APPLY) self.importer.run() - new_path = os.path.join('Applied Artist', 'Applied Album', - 'Applied Title 1.mp3') + new_path = os.path.join(b'Applied Artist', b'Applied Album', + b'Applied Title 1.mp3') self.assert_file_in_lib(new_path) - self.assertEqual(self.lib.items().get().path, - os.path.join(self.libdir, new_path)) + self.assert_equal_path(self.lib.items().get().path, + os.path.join(self.libdir, new_path)) def test_outside_file_is_moved(self): config['import']['copy'] = False self.setup_importer.run() - self.assertEqual(self.lib.items().get().path, - self.import_media[0].path) + self.assert_equal_path(self.lib.items().get().path, + self.import_media[0].path) self._setup_import_session(move=True) self.importer.add_choice(importer.action.APPLY) @@ -879,8 +991,8 @@ class GroupAlbumsImportTest(_common.TestCase, ImportHelper): self.matcher.restore() def test_add_album_for_different_artist_and_different_album(self): - self.import_media[0].artist = "Artist B" - self.import_media[0].album = "Album B" + self.import_media[0].artist = u"Artist B" + self.import_media[0].album = u"Album B" self.import_media[0].save() self.importer.run() @@ -888,11 +1000,11 @@ class GroupAlbumsImportTest(_common.TestCase, ImportHelper): self.assertEqual(albums, set(['Album B', 'Tag Album'])) def test_add_album_for_different_artist_and_same_albumartist(self): - self.import_media[0].artist = "Artist B" - self.import_media[0].albumartist = "Album Artist" + self.import_media[0].artist = u"Artist B" + self.import_media[0].albumartist = u"Album Artist" self.import_media[0].save() - self.import_media[1].artist = "Artist C" - self.import_media[1].albumartist = "Album Artist" + self.import_media[1].artist = u"Artist C" + self.import_media[1].albumartist = u"Album Artist" self.import_media[1].save() self.importer.run() @@ -900,7 +1012,7 @@ class GroupAlbumsImportTest(_common.TestCase, ImportHelper): self.assertEqual(artists, set(['Album Artist', 'Tag Artist'])) def test_add_album_for_same_artist_and_different_album(self): - self.import_media[0].album = "Album B" + self.import_media[0].album = u"Album B" self.import_media[0].save() self.importer.run() @@ -908,7 +1020,7 @@ class GroupAlbumsImportTest(_common.TestCase, ImportHelper): self.assertEqual(albums, set(['Album B', 'Tag Album'])) def test_add_album_for_same_album_and_different_artist(self): - self.import_media[0].artist = "Artist B" + self.import_media[0].artist = u"Artist B" self.import_media[0].save() self.importer.run() @@ -917,7 +1029,7 @@ class GroupAlbumsImportTest(_common.TestCase, ImportHelper): def test_incremental(self): config['import']['incremental'] = True - self.import_media[0].album = "Album B" + self.import_media[0].album = u"Album B" self.import_media[0].save() self.importer.run() @@ -949,12 +1061,12 @@ class ChooseCandidateTest(_common.TestCase, ImportHelper): def test_choose_first_candidate(self): self.importer.add_choice(1) self.importer.run() - self.assertEqual(self.lib.albums().get().album, 'Applied Album M') + self.assertEqual(self.lib.albums().get().album, u'Applied Album M') def test_choose_second_candidate(self): self.importer.add_choice(2) self.importer.run() - self.assertEqual(self.lib.albums().get().album, 'Applied Album MM') + self.assertEqual(self.lib.albums().get().album, u'Applied Album MM') class InferAlbumDataTest(_common.TestCase): @@ -964,9 +1076,9 @@ class InferAlbumDataTest(_common.TestCase): i1 = _common.item() i2 = _common.item() i3 = _common.item() - i1.title = 'first item' - i2.title = 'second item' - i3.title = 'third item' + i1.title = u'first item' + i2.title = u'second item' + i3.title = u'third item' i1.comp = i2.comp = i3.comp = False i1.albumartist = i2.albumartist = i3.albumartist = '' i1.mb_albumartistid = i2.mb_albumartistid = i3.mb_albumartistid = '' @@ -982,28 +1094,28 @@ class InferAlbumDataTest(_common.TestCase): self.assertEqual(self.items[0].albumartist, self.items[2].artist) def test_asis_heterogenous_va(self): - self.items[0].artist = 'another artist' - self.items[1].artist = 'some other artist' + self.items[0].artist = u'another artist' + self.items[1].artist = u'some other artist' self.task.set_choice(importer.action.ASIS) self.task.align_album_level_fields() self.assertTrue(self.items[0].comp) - self.assertEqual(self.items[0].albumartist, 'Various Artists') + self.assertEqual(self.items[0].albumartist, u'Various Artists') def test_asis_comp_applied_to_all_items(self): - self.items[0].artist = 'another artist' - self.items[1].artist = 'some other artist' + self.items[0].artist = u'another artist' + self.items[1].artist = u'some other artist' self.task.set_choice(importer.action.ASIS) self.task.align_album_level_fields() for item in self.items: self.assertTrue(item.comp) - self.assertEqual(item.albumartist, 'Various Artists') + self.assertEqual(item.albumartist, u'Various Artists') def test_asis_majority_artist_single_artist(self): - self.items[0].artist = 'another artist' + self.items[0].artist = u'another artist' self.task.set_choice(importer.action.ASIS) self.task.align_album_level_fields() @@ -1012,19 +1124,19 @@ class InferAlbumDataTest(_common.TestCase): self.assertEqual(self.items[0].albumartist, self.items[2].artist) def test_asis_track_albumartist_override(self): - self.items[0].artist = 'another artist' - self.items[1].artist = 'some other artist' + self.items[0].artist = u'another artist' + self.items[1].artist = u'some other artist' for item in self.items: - item.albumartist = 'some album artist' - item.mb_albumartistid = 'some album artist id' + item.albumartist = u'some album artist' + item.mb_albumartistid = u'some album artist id' self.task.set_choice(importer.action.ASIS) self.task.align_album_level_fields() self.assertEqual(self.items[0].albumartist, - 'some album artist') + u'some album artist') self.assertEqual(self.items[0].mb_albumartistid, - 'some album artist id') + u'some album artist id') def test_apply_gets_artist_and_id(self): self.task.set_choice(AlbumMatch(0, None, {}, set(), set())) # APPLY @@ -1037,16 +1149,16 @@ class InferAlbumDataTest(_common.TestCase): def test_apply_lets_album_values_override(self): for item in self.items: - item.albumartist = 'some album artist' - item.mb_albumartistid = 'some album artist id' + item.albumartist = u'some album artist' + item.mb_albumartistid = u'some album artist id' self.task.set_choice(AlbumMatch(0, None, {}, set(), set())) # APPLY self.task.align_album_level_fields() self.assertEqual(self.items[0].albumartist, - 'some album artist') + u'some album artist') self.assertEqual(self.items[0].mb_albumartistid, - 'some album artist id') + u'some album artist id') def test_small_single_artist_album(self): self.items = [self.items[0]] @@ -1056,12 +1168,13 @@ class InferAlbumDataTest(_common.TestCase): self.assertFalse(self.items[0].comp) -def test_album_info(): +def test_album_info(*args, **kwargs): """Create an AlbumInfo object for testing. """ track_info = TrackInfo( title=u'new title', track_id=u'trackid', + index=0, ) album_info = AlbumInfo( artist=u'artist', @@ -1070,10 +1183,12 @@ def test_album_info(): album_id=u'albumid', artist_id=u'artistid', ) - return album_info + return iter([album_info]) -class ImportDuplicateAlbumTest(unittest.TestCase, TestHelper): +@patch('beets.autotag.mb.match_album', Mock(side_effect=test_album_info)) +class ImportDuplicateAlbumTest(unittest.TestCase, TestHelper, + _common.Assertions): def setUp(self): self.setup_beets() @@ -1081,28 +1196,22 @@ class ImportDuplicateAlbumTest(unittest.TestCase, TestHelper): # Original album self.add_album_fixture(albumartist=u'artist', album=u'album') - # Create duplicate through autotagger - self.match_album_patcher = patch('beets.autotag.mb.match_album') - self.match_album = self.match_album_patcher.start() - self.match_album.return_value = iter([test_album_info()]) - # Create import session self.importer = self.create_importer() config['import']['autotag'] = True def tearDown(self): - self.match_album_patcher.stop() self.teardown_beets() def test_remove_duplicate_album(self): item = self.lib.items().get() self.assertEqual(item.title, u't\xeftle 0') - self.assertTrue(os.path.isfile(item.path)) + self.assertExists(item.path) self.importer.default_resolution = self.importer.Resolution.REMOVE self.importer.run() - self.assertFalse(os.path.isfile(item.path)) + self.assertNotExists(item.path) self.assertEqual(len(self.lib.albums()), 1) self.assertEqual(len(self.lib.items()), 1) item = self.lib.items().get() @@ -1112,12 +1221,12 @@ class ImportDuplicateAlbumTest(unittest.TestCase, TestHelper): config['import']['autotag'] = False item = self.lib.items().get() self.assertEqual(item.title, u't\xeftle 0') - self.assertTrue(os.path.isfile(item.path)) + self.assertExists(item.path) # Imported item has the same artist and album as the one in the # library. import_file = os.path.join(self.importer.paths[0], - 'album 0', 'track 0.mp3') + b'album 0', b'track 0.mp3') import_file = MediaFile(import_file) import_file.artist = item['artist'] import_file.albumartist = item['artist'] @@ -1127,7 +1236,7 @@ class ImportDuplicateAlbumTest(unittest.TestCase, TestHelper): self.importer.default_resolution = self.importer.Resolution.REMOVE self.importer.run() - self.assertTrue(os.path.isfile(item.path)) + self.assertExists(item.path) self.assertEqual(len(self.lib.albums()), 2) self.assertEqual(len(self.lib.items()), 2) @@ -1150,6 +1259,12 @@ class ImportDuplicateAlbumTest(unittest.TestCase, TestHelper): item = self.lib.items().get() self.assertEqual(item.title, u't\xeftle 0') + def test_merge_duplicate_album(self): + self.importer.default_resolution = self.importer.Resolution.MERGE + self.importer.run() + + self.assertEqual(len(self.lib.albums()), 1) + def test_twice_in_import_dir(self): self.skipTest('write me') @@ -1161,7 +1276,15 @@ class ImportDuplicateAlbumTest(unittest.TestCase, TestHelper): return album -class ImportDuplicateSingletonTest(unittest.TestCase, TestHelper): +def test_track_info(*args, **kwargs): + return iter([TrackInfo( + artist=u'artist', title=u'title', + track_id=u'new trackid', index=0,)]) + + +@patch('beets.autotag.mb.match_track', Mock(side_effect=test_track_info)) +class ImportDuplicateSingletonTest(unittest.TestCase, TestHelper, + _common.Assertions): def setUp(self): self.setup_beets() @@ -1170,34 +1293,23 @@ class ImportDuplicateSingletonTest(unittest.TestCase, TestHelper): self.add_item_fixture(artist=u'artist', title=u'title', mb_trackid='old trackid') - # Create duplicate through autotagger - self.match_track_patcher = patch('beets.autotag.mb.match_track') - self.match_track = self.match_track_patcher.start() - track_info = TrackInfo( - artist=u'artist', - title=u'title', - track_id=u'new trackid', - ) - self.match_track.return_value = iter([track_info]) - # Import session self.importer = self.create_importer() config['import']['autotag'] = True config['import']['singletons'] = True def tearDown(self): - self.match_track_patcher.stop() self.teardown_beets() def test_remove_duplicate(self): item = self.lib.items().get() self.assertEqual(item.mb_trackid, u'old trackid') - self.assertTrue(os.path.isfile(item.path)) + self.assertExists(item.path) self.importer.default_resolution = self.importer.Resolution.REMOVE self.importer.run() - self.assertFalse(os.path.isfile(item.path)) + self.assertNotExists(item.path) self.assertEqual(len(self.lib.items()), 1) item = self.lib.items().get() self.assertEqual(item.mb_trackid, u'new trackid') @@ -1234,14 +1346,14 @@ class ImportDuplicateSingletonTest(unittest.TestCase, TestHelper): class TagLogTest(_common.TestCase): def test_tag_log_line(self): - sio = StringIO.StringIO() + sio = StringIO() handler = logging.StreamHandler(sio) session = _common.import_session(loghandler=handler) session.tag_log('status', 'path') self.assertIn('status path', sio.getvalue()) def test_tag_log_unicode(self): - sio = StringIO.StringIO() + sio = StringIO() handler = logging.StreamHandler(sio) session = _common.import_session(loghandler=handler) session.tag_log('status', u'caf\xe9') # send unicode @@ -1270,11 +1382,11 @@ class ResumeImportTest(unittest.TestCase, TestHelper): self.importer.run() self.assertEqual(len(self.lib.albums()), 1) - self.assertIsNotNone(self.lib.albums('album:album 0').get()) + self.assertIsNotNone(self.lib.albums(u'album:album 0').get()) self.importer.run() self.assertEqual(len(self.lib.albums()), 2) - self.assertIsNotNone(self.lib.albums('album:album 1').get()) + self.assertIsNotNone(self.lib.albums(u'album:album 1').get()) @patch('beets.plugins.send') def test_resume_singleton(self, plugins_send): @@ -1291,11 +1403,11 @@ class ResumeImportTest(unittest.TestCase, TestHelper): self.importer.run() self.assertEqual(len(self.lib.items()), 1) - self.assertIsNotNone(self.lib.items('title:track 0').get()) + self.assertIsNotNone(self.lib.items(u'title:track 0').get()) self.importer.run() self.assertEqual(len(self.lib.items()), 2) - self.assertIsNotNone(self.lib.items('title:track 1').get()) + self.assertIsNotNone(self.lib.items(u'title:track 1').get()) class IncrementalImportTest(unittest.TestCase, TestHelper): @@ -1338,14 +1450,14 @@ class IncrementalImportTest(unittest.TestCase, TestHelper): def test_invalid_state_file(self): importer = self.create_importer() - with open(self.config['statefile'].as_filename(), 'w') as f: - f.write('000') + with open(self.config['statefile'].as_filename(), 'wb') as f: + f.write(b'000') importer.run() self.assertEqual(len(self.lib.albums()), 1) def _mkmp3(path): - shutil.copyfile(os.path.join(_common.RSRC, 'min.mp3'), path) + shutil.copyfile(os.path.join(_common.RSRC, b'min.mp3'), path) class AlbumsInDirTest(_common.TestCase): @@ -1353,20 +1465,20 @@ class AlbumsInDirTest(_common.TestCase): super(AlbumsInDirTest, self).setUp() # create a directory structure for testing - self.base = os.path.abspath(os.path.join(self.temp_dir, 'tempdir')) + self.base = os.path.abspath(os.path.join(self.temp_dir, b'tempdir')) os.mkdir(self.base) - os.mkdir(os.path.join(self.base, 'album1')) - os.mkdir(os.path.join(self.base, 'album2')) - os.mkdir(os.path.join(self.base, 'more')) - os.mkdir(os.path.join(self.base, 'more', 'album3')) - os.mkdir(os.path.join(self.base, 'more', 'album4')) + os.mkdir(os.path.join(self.base, b'album1')) + os.mkdir(os.path.join(self.base, b'album2')) + os.mkdir(os.path.join(self.base, b'more')) + os.mkdir(os.path.join(self.base, b'more', b'album3')) + os.mkdir(os.path.join(self.base, b'more', b'album4')) - _mkmp3(os.path.join(self.base, 'album1', 'album1song1.mp3')) - _mkmp3(os.path.join(self.base, 'album1', 'album1song2.mp3')) - _mkmp3(os.path.join(self.base, 'album2', 'album2song.mp3')) - _mkmp3(os.path.join(self.base, 'more', 'album3', 'album3song.mp3')) - _mkmp3(os.path.join(self.base, 'more', 'album4', 'album4song.mp3')) + _mkmp3(os.path.join(self.base, b'album1', b'album1song1.mp3')) + _mkmp3(os.path.join(self.base, b'album1', b'album1song2.mp3')) + _mkmp3(os.path.join(self.base, b'album2', b'album2song.mp3')) + _mkmp3(os.path.join(self.base, b'more', b'album3', b'album3song.mp3')) + _mkmp3(os.path.join(self.base, b'more', b'album4', b'album4song.mp3')) def test_finds_all_albums(self): albums = list(albums_in_dir(self.base)) @@ -1375,16 +1487,16 @@ class AlbumsInDirTest(_common.TestCase): def test_separates_contents(self): found = [] for _, album in albums_in_dir(self.base): - found.append(re.search(r'album(.)song', album[0]).group(1)) - self.assertTrue('1' in found) - self.assertTrue('2' in found) - self.assertTrue('3' in found) - self.assertTrue('4' in found) + found.append(re.search(br'album(.)song', album[0]).group(1)) + self.assertTrue(b'1' in found) + self.assertTrue(b'2' in found) + self.assertTrue(b'3' in found) + self.assertTrue(b'4' in found) def test_finds_multiple_songs(self): for _, album in albums_in_dir(self.base): - n = re.search(r'album(.)song', album[0]).group(1) - if n == '1': + n = re.search(br'album(.)song', album[0]).group(1) + if n == b'1': self.assertEqual(len(album), 2) else: self.assertEqual(len(album), 1) @@ -1401,8 +1513,8 @@ class MultiDiscAlbumsInDirTest(_common.TestCase): self.base = os.path.abspath(os.path.join(self.temp_dir, b'tempdir')) os.mkdir(self.base) - name = b'CAT' if ascii else u'C\xc1T'.encode('utf8') - name_alt_case = b'CAt' if ascii else u'C\xc1t'.encode('utf8') + name = b'CAT' if ascii else util.bytestring_path(u'C\xc1T') + name_alt_case = b'CAt' if ascii else util.bytestring_path(u'C\xc1t') self.dirs = [ # Nested album, multiple subdirs. @@ -1446,19 +1558,19 @@ class MultiDiscAlbumsInDirTest(_common.TestCase): self.files = [self._normalize_path(p) for p in self.files] for path in self.dirs: - os.mkdir(path) + os.mkdir(util.syspath(path)) if files: for path in self.files: - _mkmp3(path) + _mkmp3(util.syspath(path)) def _normalize_path(self, path): """Normalize a path's Unicode combining form according to the platform. """ - path = path.decode('utf8') + path = path.decode('utf-8') norm_form = 'NFD' if sys.platform == 'darwin' else 'NFC' path = unicodedata.normalize(norm_form, path) - return path.encode('utf8') + return path.encode('utf-8') def test_coalesce_nested_album_multiple_subdirs(self): self.create_music() @@ -1510,7 +1622,7 @@ class MultiDiscAlbumsInDirTest(_common.TestCase): self.assertEqual(len(items), 3) -class ReimportTest(unittest.TestCase, ImportHelper): +class ReimportTest(unittest.TestCase, ImportHelper, _common.Assertions): """Test "re-imports", in which the autotagging machinery is used for music that's already in the library. @@ -1592,6 +1704,21 @@ class ReimportTest(unittest.TestCase, ImportHelper): self.importer.run() self.assertEqual(self._item().added, 4747.0) + def test_reimported_item_preserves_art(self): + self._setup_session() + art_source = os.path.join(_common.RSRC, b'abbey.jpg') + replaced_album = self._album() + replaced_album.set_art(art_source) + replaced_album.store() + old_artpath = replaced_album.artpath + self.importer.run() + new_album = self._album() + new_artpath = new_album.art_destination(art_source) + self.assertEqual(new_album.artpath, new_artpath) + self.assertExists(new_artpath) + if new_artpath != old_artpath: + self.assertNotExists(old_artpath) + class ImportPretendTest(_common.TestCase, ImportHelper): """ Test the pretend commandline option @@ -1617,21 +1744,21 @@ class ImportPretendTest(_common.TestCase, ImportHelper): def __create_import_dir(self): self._create_import_dir(1) - resource_path = os.path.join(_common.RSRC, u'empty.mp3') - single_path = os.path.join(self.import_dir, u'track_2.mp3') + resource_path = os.path.join(_common.RSRC, b'empty.mp3') + single_path = os.path.join(self.import_dir, b'track_2.mp3') shutil.copy(resource_path, single_path) self.import_paths = [ - os.path.join(self.import_dir, u'the_album'), + os.path.join(self.import_dir, b'the_album'), single_path ] self.import_files = [ displayable_path( - os.path.join(self.import_paths[0], u'track_1.mp3')), + os.path.join(self.import_paths[0], b'track_1.mp3')), displayable_path(single_path) ] def __create_empty_import_dir(self): - path = os.path.join(self.temp_dir, 'empty') + path = os.path.join(self.temp_dir, b'empty') os.makedirs(path) self.empty_path = path @@ -1653,27 +1780,184 @@ class ImportPretendTest(_common.TestCase, ImportHelper): logs = self.__run(self.import_paths) self.assertEqual(logs, [ - 'Singleton: %s' % self.import_files[0], - 'Singleton: %s' % self.import_paths[1]]) + 'Singleton: %s' % displayable_path(self.import_files[0]), + 'Singleton: %s' % displayable_path(self.import_paths[1])]) def test_import_album_pretend(self): logs = self.__run(self.import_paths, singletons=False) self.assertEqual(logs, [ 'Album: %s' % displayable_path(self.import_paths[0]), - ' %s' % self.import_files[0], + ' %s' % displayable_path(self.import_files[0]), 'Album: %s' % displayable_path(self.import_paths[1]), - ' %s' % self.import_paths[1]]) + ' %s' % displayable_path(self.import_paths[1])]) def test_import_pretend_empty(self): logs = self.__run([self.empty_path]) - self.assertEqual(logs, ['No files imported from {0}' + self.assertEqual(logs, [u'No files imported from {0}' .format(displayable_path(self.empty_path))]) +# Helpers for ImportMusicBrainzIdTest. + + +def mocked_get_release_by_id(id_, includes=[], release_status=[], + release_type=[]): + """Mimic musicbrainzngs.get_release_by_id, accepting only a restricted list + of MB ids (ID_RELEASE_0, ID_RELEASE_1). The returned dict differs only in + the release title and artist name, so that ID_RELEASE_0 is a closer match + to the items created by ImportHelper._create_import_dir().""" + # Map IDs to (release title, artist), so the distances are different. + releases = {ImportMusicBrainzIdTest.ID_RELEASE_0: ('VALID_RELEASE_0', + 'TAG ARTIST'), + ImportMusicBrainzIdTest.ID_RELEASE_1: ('VALID_RELEASE_1', + 'DISTANT_MATCH')} + + return { + 'release': { + 'title': releases[id_][0], + 'id': id_, + 'medium-list': [{ + 'track-list': [{ + 'recording': { + 'title': 'foo', + 'id': 'bar', + 'length': 59, + }, + 'position': 9, + 'number': 'A2' + }], + 'position': 5, + }], + 'artist-credit': [{ + 'artist': { + 'name': releases[id_][1], + 'id': 'some-id', + }, + }], + 'release-group': { + 'id': 'another-id', + } + } + } + + +def mocked_get_recording_by_id(id_, includes=[], release_status=[], + release_type=[]): + """Mimic musicbrainzngs.get_recording_by_id, accepting only a restricted + list of MB ids (ID_RECORDING_0, ID_RECORDING_1). The returned dict differs + only in the recording title and artist name, so that ID_RECORDING_0 is a + closer match to the items created by ImportHelper._create_import_dir().""" + # Map IDs to (recording title, artist), so the distances are different. + releases = {ImportMusicBrainzIdTest.ID_RECORDING_0: ('VALID_RECORDING_0', + 'TAG ARTIST'), + ImportMusicBrainzIdTest.ID_RECORDING_1: ('VALID_RECORDING_1', + 'DISTANT_MATCH')} + + return { + 'recording': { + 'title': releases[id_][0], + 'id': id_, + 'length': 59, + 'artist-credit': [{ + 'artist': { + 'name': releases[id_][1], + 'id': 'some-id', + }, + }], + } + } + + +@patch('musicbrainzngs.get_recording_by_id', + Mock(side_effect=mocked_get_recording_by_id)) +@patch('musicbrainzngs.get_release_by_id', + Mock(side_effect=mocked_get_release_by_id)) +class ImportMusicBrainzIdTest(_common.TestCase, ImportHelper): + """Test the --musicbrainzid argument.""" + + MB_RELEASE_PREFIX = 'https://musicbrainz.org/release/' + MB_RECORDING_PREFIX = 'https://musicbrainz.org/recording/' + ID_RELEASE_0 = '00000000-0000-0000-0000-000000000000' + ID_RELEASE_1 = '11111111-1111-1111-1111-111111111111' + ID_RECORDING_0 = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' + ID_RECORDING_1 = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb' + + def setUp(self): + self.setup_beets() + self._create_import_dir(1) + + def tearDown(self): + self.teardown_beets() + + def test_one_mbid_one_album(self): + self.config['import']['search_ids'] = \ + [self.MB_RELEASE_PREFIX + self.ID_RELEASE_0] + self._setup_import_session() + + self.importer.add_choice(importer.action.APPLY) + self.importer.run() + self.assertEqual(self.lib.albums().get().album, 'VALID_RELEASE_0') + + def test_several_mbid_one_album(self): + self.config['import']['search_ids'] = \ + [self.MB_RELEASE_PREFIX + self.ID_RELEASE_0, + self.MB_RELEASE_PREFIX + self.ID_RELEASE_1] + self._setup_import_session() + + self.importer.add_choice(2) # Pick the 2nd best match (release 1). + self.importer.add_choice(importer.action.APPLY) + self.importer.run() + self.assertEqual(self.lib.albums().get().album, 'VALID_RELEASE_1') + + def test_one_mbid_one_singleton(self): + self.config['import']['search_ids'] = \ + [self.MB_RECORDING_PREFIX + self.ID_RECORDING_0] + self._setup_import_session(singletons=True) + + self.importer.add_choice(importer.action.APPLY) + self.importer.run() + self.assertEqual(self.lib.items().get().title, 'VALID_RECORDING_0') + + def test_several_mbid_one_singleton(self): + self.config['import']['search_ids'] = \ + [self.MB_RECORDING_PREFIX + self.ID_RECORDING_0, + self.MB_RECORDING_PREFIX + self.ID_RECORDING_1] + self._setup_import_session(singletons=True) + + self.importer.add_choice(2) # Pick the 2nd best match (recording 1). + self.importer.add_choice(importer.action.APPLY) + self.importer.run() + self.assertEqual(self.lib.items().get().title, 'VALID_RECORDING_1') + + def test_candidates_album(self): + """Test directly ImportTask.lookup_candidates().""" + task = importer.ImportTask(paths=self.import_dir, + toppath='top path', + items=[_common.item()]) + task.search_ids = [self.MB_RELEASE_PREFIX + self.ID_RELEASE_0, + self.MB_RELEASE_PREFIX + self.ID_RELEASE_1, + 'an invalid and discarded id'] + + task.lookup_candidates() + self.assertEqual(set(['VALID_RELEASE_0', 'VALID_RELEASE_1']), + set([c.info.album for c in task.candidates])) + + def test_candidates_singleton(self): + """Test directly SingletonImportTask.lookup_candidates().""" + task = importer.SingletonImportTask(toppath='top path', + item=_common.item()) + task.search_ids = [self.MB_RECORDING_PREFIX + self.ID_RECORDING_0, + self.MB_RECORDING_PREFIX + self.ID_RECORDING_1, + 'an invalid and discarded id'] + + task.lookup_candidates() + self.assertEqual(set(['VALID_RECORDING_0', 'VALID_RECORDING_1']), + set([c.info.title for c in task.candidates])) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_importfeeds.py b/test/test_importfeeds.py index 061f7a7a4..064f5eee5 100644 --- a/test/test_importfeeds.py +++ b/test/test_importfeeds.py @@ -1,12 +1,13 @@ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +# -*- coding: utf-8 -*- + +from __future__ import division, absolute_import, print_function import os import os.path import tempfile import shutil +import unittest -from test._common import unittest from beets import config from beets.library import Item, Album, Library from beetsplug.importfeeds import ImportFeedsPlugin @@ -42,7 +43,8 @@ class ImportfeedsTestTest(unittest.TestCase): def test_playlist_in_subdir(self): config['importfeeds']['formats'] = 'm3u' - config['importfeeds']['m3u_name'] = 'subdir/imported.m3u' + config['importfeeds']['m3u_name'] = \ + os.path.join('subdir', 'imported.m3u') album = Album(album='album/name', id=1) item_path = os.path.join('path', 'to', 'item') item = Item(title='song', album_id=1, path=item_path) @@ -60,5 +62,5 @@ class ImportfeedsTestTest(unittest.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_info.py b/test/test_info.py index e382f4872..f5375e2f6 100644 --- a/test/test_info.py +++ b/test/test_info.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,10 +13,9 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function -from test._common import unittest +import unittest from test.helper import TestHelper from beets.mediafile import MediaFile @@ -32,9 +32,6 @@ class InfoTest(unittest.TestCase, TestHelper): self.unload_plugins() self.teardown_beets() - def run_command(self, *args): - super(InfoTest, self).run_command('info', *args) - def test_path(self): path = self.create_mediafile_fixture() @@ -45,12 +42,13 @@ class InfoTest(unittest.TestCase, TestHelper): mediafile.composer = None mediafile.save() - out = self.run_with_output(path) + out = self.run_with_output('info', path) self.assertIn(path, out) self.assertIn('albumartist: AAA', out) self.assertIn('disctitle: DDD', out) self.assertIn('genres: a; b; c', out) self.assertNotIn('composer:', out) + self.remove_mediafile_fixtures() def test_item_query(self): item1, item2 = self.add_item_fixtures(count=2) @@ -59,7 +57,7 @@ class InfoTest(unittest.TestCase, TestHelper): item1.album = 'yyyy' item1.store() - out = self.run_with_output('album:yyyy') + out = self.run_with_output('info', 'album:yyyy') self.assertIn(displayable_path(item1.path), out) self.assertIn(u'album: xxxx', out) @@ -70,7 +68,7 @@ class InfoTest(unittest.TestCase, TestHelper): item.album = 'xxxx' item.store() - out = self.run_with_output('--library', 'album:xxxx') + out = self.run_with_output('info', '--library', 'album:xxxx') self.assertIn(displayable_path(item.path), out) self.assertIn(u'album: xxxx', out) @@ -88,25 +86,32 @@ class InfoTest(unittest.TestCase, TestHelper): item.store() mediafile.save() - out = self.run_with_output('--summarize', 'album:AAA', path) + out = self.run_with_output('info', '--summarize', 'album:AAA', path) self.assertIn(u'album: AAA', out) self.assertIn(u'tracktotal: 5', out) self.assertIn(u'title: [various]', out) + self.remove_mediafile_fixtures() def test_include_pattern(self): item, = self.add_item_fixtures() item.album = 'xxxx' item.store() - out = self.run_with_output('--library', 'album:xxxx', + out = self.run_with_output('info', '--library', 'album:xxxx', '--include-keys', '*lbu*') self.assertIn(displayable_path(item.path), out) self.assertNotIn(u'title:', out) self.assertIn(u'album: xxxx', out) + def test_custom_format(self): + self.add_item_fixtures() + out = self.run_with_output('info', '--library', '--format', + '$track. $title - $artist ($length)') + self.assertEqual(u'02. tïtle 0 - the artist (0:01)\n', out) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_ipfs.py b/test/test_ipfs.py index cfb74f203..d670bfc25 100644 --- a/test/test_ipfs.py +++ b/test/test_ipfs.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # # Permission is hereby granted, free of charge, to any person obtaining @@ -11,30 +12,32 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from mock import patch +from __future__ import division, absolute_import, print_function + +from mock import patch, Mock from beets import library +from beets.util import bytestring_path, _fsencoding from beetsplug.ipfs import IPFSPlugin -from test import _common -from test._common import unittest -from test.helper import TestHelper +import unittest import os +from test import _common +from test.helper import TestHelper + +@patch('beets.util.command_output', Mock()) class IPFSPluginTest(unittest.TestCase, TestHelper): def setUp(self): self.setup_beets() self.load_plugins('ipfs') - self.patcher = patch('beets.util.command_output') - self.command_output = self.patcher.start() self.lib = library.Library(":memory:") def tearDown(self): self.unload_plugins() self.teardown_beets() - self.patcher.stop() def test_stored_hashes(self): test_album = self.mk_test_album() @@ -47,9 +50,12 @@ class IPFSPluginTest(unittest.TestCase, TestHelper): for check_item in added_album.items(): try: if check_item.ipfs: + ipfs_item = os.path.basename(want_item.path).decode( + _fsencoding(), + ) want_path = '/ipfs/{0}/{1}'.format(test_album.ipfs, - os.path.basename( - want_item.path)) + ipfs_item) + want_path = bytestring_path(want_path) self.assertEqual(check_item.path, want_path) self.assertEqual(check_item.ipfs, want_item.ipfs) self.assertEqual(check_item.title, want_item.title) @@ -61,17 +67,17 @@ class IPFSPluginTest(unittest.TestCase, TestHelper): def mk_test_album(self): items = [_common.item() for _ in range(3)] items[0].title = 'foo bar' - items[0].artist = 'one' + items[0].artist = '1one' items[0].album = 'baz' items[0].year = 2001 items[0].comp = True items[1].title = 'baz qux' - items[1].artist = 'two' + items[1].artist = '2two' items[1].album = 'baz' items[1].year = 2002 items[1].comp = True items[2].title = 'beets 4 eva' - items[2].artist = 'three' + items[2].artist = '3three' items[2].album = 'foo' items[2].year = 2003 items[2].comp = False @@ -90,5 +96,5 @@ class IPFSPluginTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_keyfinder.py b/test/test_keyfinder.py index 95c06754a..c2b4227d7 100644 --- a/test/test_keyfinder.py +++ b/test/test_keyfinder.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,66 +13,64 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from mock import patch -from test._common import unittest +import unittest from test.helper import TestHelper from beets.library import Item +from beets import util +@patch('beets.util.command_output') class KeyFinderTest(unittest.TestCase, TestHelper): def setUp(self): self.setup_beets() self.load_plugins('keyfinder') - self.patcher = patch('beets.util.command_output') - self.command_output = self.patcher.start() def tearDown(self): self.teardown_beets() self.unload_plugins() - self.patcher.stop() - def test_add_key(self): + def test_add_key(self, command_output): item = Item(path='/file') item.add(self.lib) - self.command_output.return_value = 'dbm' + command_output.return_value = 'dbm' self.run_command('keyfinder') item.load() self.assertEqual(item['initial_key'], 'C#m') - self.command_output.assert_called_with( - ['KeyFinder', '-f', item.path]) + command_output.assert_called_with( + ['KeyFinder', '-f', util.syspath(item.path)]) - def test_add_key_on_import(self): - self.command_output.return_value = 'dbm' + def test_add_key_on_import(self, command_output): + command_output.return_value = 'dbm' importer = self.create_importer() importer.run() item = self.lib.items().get() self.assertEqual(item['initial_key'], 'C#m') - def test_force_overwrite(self): + def test_force_overwrite(self, command_output): self.config['keyfinder']['overwrite'] = True item = Item(path='/file', initial_key='F') item.add(self.lib) - self.command_output.return_value = 'C#m' + command_output.return_value = 'C#m' self.run_command('keyfinder') item.load() self.assertEqual(item['initial_key'], 'C#m') - def test_do_not_overwrite(self): + def test_do_not_overwrite(self, command_output): item = Item(path='/file', initial_key='F') item.add(self.lib) - self.command_output.return_value = 'dbm' + command_output.return_value = 'dbm' self.run_command('keyfinder') item.load() @@ -81,5 +80,5 @@ class KeyFinderTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_lastgenre.py b/test/test_lastgenre.py index 4b1a50207..a70c65ca1 100644 --- a/test/test_lastgenre.py +++ b/test/test_lastgenre.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Fabrice Laporte. +# Copyright 2016, Fabrice Laporte. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,17 +15,17 @@ """Tests for the 'lastgenre' plugin.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function +import unittest from mock import Mock from test import _common -from test._common import unittest from beetsplug import lastgenre from beets import config from test.helper import TestHelper +import six class LastGenrePluginTest(unittest.TestCase, TestHelper): @@ -38,11 +39,11 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): def _setup_config(self, whitelist=False, canonical=False, count=1): config['lastgenre']['canonical'] = canonical config['lastgenre']['count'] = count - if isinstance(whitelist, (bool, basestring)): + if isinstance(whitelist, (bool, six.string_types)): # Filename, default, or disabled. config['lastgenre']['whitelist'] = whitelist self.plugin.setup() - if not isinstance(whitelist, (bool, basestring)): + if not isinstance(whitelist, (bool, six.string_types)): # Explicit list of genres. self.plugin.whitelist = whitelist @@ -51,7 +52,7 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): """ self._setup_config() self.assertEqual(self.plugin._resolve_genres(['delta blues']), - 'Delta Blues') + u'Delta Blues') def test_c14n_only(self): """Default c14n tree funnels up to most common genre except for *wrong* @@ -59,16 +60,16 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): """ self._setup_config(canonical=True, count=99) self.assertEqual(self.plugin._resolve_genres(['delta blues']), - 'Blues') + u'Blues') self.assertEqual(self.plugin._resolve_genres(['iota blues']), - 'Iota Blues') + u'Iota Blues') def test_whitelist_only(self): """Default whitelist rejects *wrong* (non existing) genres. """ self._setup_config(whitelist=True) self.assertEqual(self.plugin._resolve_genres(['iota blues']), - '') + u'') def test_whitelist_c14n(self): """Default whitelist and c14n both activated result in all parents @@ -76,7 +77,7 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): """ self._setup_config(canonical=True, whitelist=True, count=99) self.assertEqual(self.plugin._resolve_genres(['delta blues']), - 'Delta Blues, Blues') + u'Delta Blues, Blues') def test_whitelist_custom(self): """Keep only genres that are in the whitelist. @@ -84,11 +85,11 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): self._setup_config(whitelist=set(['blues', 'rock', 'jazz']), count=2) self.assertEqual(self.plugin._resolve_genres(['pop', 'blues']), - 'Blues') + u'Blues') self._setup_config(canonical='', whitelist=set(['rock'])) self.assertEqual(self.plugin._resolve_genres(['delta blues']), - '') + u'') def test_count(self): """Keep the n first genres, as we expect them to be sorted from more to @@ -98,7 +99,7 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): count=2) self.assertEqual(self.plugin._resolve_genres( ['jazz', 'pop', 'rock', 'blues']), - 'Jazz, Rock') + u'Jazz, Rock') def test_count_c14n(self): """Keep the n first genres, after having applied c14n when necessary @@ -110,14 +111,14 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): # second slot self.assertEqual(self.plugin._resolve_genres( ['jazz', 'pop', 'country blues', 'rock']), - 'Jazz, Blues') + u'Jazz, Blues') def test_c14n_whitelist(self): """Genres first pass through c14n and are then filtered """ self._setup_config(canonical=True, whitelist=set(['rock'])) self.assertEqual(self.plugin._resolve_genres(['delta blues']), - '') + u'') def test_empty_string_enables_canonical(self): """For backwards compatibility, setting the `canonical` option @@ -125,7 +126,7 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): """ self._setup_config(canonical='', count=99) self.assertEqual(self.plugin._resolve_genres(['delta blues']), - 'Blues') + u'Blues') def test_empty_string_enables_whitelist(self): """Again for backwards compatibility, setting the `whitelist` @@ -133,14 +134,14 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): """ self._setup_config(whitelist='') self.assertEqual(self.plugin._resolve_genres(['iota blues']), - '') + u'') def test_no_duplicate(self): """Remove duplicated genres. """ self._setup_config(count=99) self.assertEqual(self.plugin._resolve_genres(['blues', 'blues']), - 'Blues') + u'Blues') def test_tags_for(self): class MockPylastElem(object): @@ -167,16 +168,16 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): self.assertEqual(res, [u'pop']) def test_get_genre(self): - MOCK_GENRES = {'track': u'1', 'album': u'2', 'artist': u'3'} + mock_genres = {'track': u'1', 'album': u'2', 'artist': u'3'} def mock_fetch_track_genre(self, obj=None): - return MOCK_GENRES['track'] + return mock_genres['track'] def mock_fetch_album_genre(self, obj): - return MOCK_GENRES['album'] + return mock_genres['album'] def mock_fetch_artist_genre(self, obj): - return MOCK_GENRES['artist'] + return mock_genres['artist'] lastgenre.LastGenrePlugin.fetch_track_genre = mock_fetch_track_genre lastgenre.LastGenrePlugin.fetch_album_genre = mock_fetch_album_genre @@ -184,37 +185,49 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): self._setup_config(whitelist=False) item = _common.item() - item.genre = MOCK_GENRES['track'] + item.genre = mock_genres['track'] config['lastgenre'] = {'force': False} res = self.plugin._get_genre(item) - self.assertEqual(res, (item.genre, 'keep')) + self.assertEqual(res, (item.genre, u'keep')) - config['lastgenre'] = {'force': True, 'source': 'track'} + config['lastgenre'] = {'force': True, 'source': u'track'} res = self.plugin._get_genre(item) - self.assertEqual(res, (MOCK_GENRES['track'], 'track')) + self.assertEqual(res, (mock_genres['track'], u'track')) - config['lastgenre'] = {'source': 'album'} + config['lastgenre'] = {'source': u'album'} res = self.plugin._get_genre(item) - self.assertEqual(res, (MOCK_GENRES['album'], 'album')) + self.assertEqual(res, (mock_genres['album'], u'album')) - config['lastgenre'] = {'source': 'artist'} + config['lastgenre'] = {'source': u'artist'} res = self.plugin._get_genre(item) - self.assertEqual(res, (MOCK_GENRES['artist'], 'artist')) + self.assertEqual(res, (mock_genres['artist'], u'artist')) - MOCK_GENRES['artist'] = None + mock_genres['artist'] = None res = self.plugin._get_genre(item) - self.assertEqual(res, (item.genre, 'original')) + self.assertEqual(res, (item.genre, u'original')) - config['lastgenre'] = {'fallback': 'rap'} + config['lastgenre'] = {'fallback': u'rap'} item.genre = None res = self.plugin._get_genre(item) self.assertEqual(res, (config['lastgenre']['fallback'].get(), - 'fallback')) + u'fallback')) + + def test_sort_by_depth(self): + self._setup_config(canonical=True) + # Normal case. + tags = ('electronic', 'ambient', 'post-rock', 'downtempo') + res = self.plugin._sort_by_depth(tags) + self.assertEqual( + res, ['post-rock', 'downtempo', 'ambient', 'electronic']) + # Non-canonical tag ('chillout') present. + tags = ('electronic', 'ambient', 'chillout') + res = self.plugin._sort_by_depth(tags) + self.assertEqual(res, ['ambient', 'electronic']) def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_library.py b/test/test_library.py index 30b0d6fc4..ea566965e 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,8 +15,7 @@ """Tests for non-query database functions of Item. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import os import os.path @@ -25,9 +24,10 @@ import shutil import re import unicodedata import sys +import time +import unittest from test import _common -from test._common import unittest from test._common import item import beets.library import beets.mediafile @@ -36,7 +36,9 @@ from beets import util from beets import plugins from beets import config from beets.mediafile import MediaFile +from beets.util import syspath, bytestring_path from test.helper import TestHelper +import six # Shortcut to path normalization. np = util.normpath @@ -45,12 +47,12 @@ np = util.normpath class LoadTest(_common.LibTestCase): def test_load_restores_data_from_db(self): original_title = self.i.title - self.i.title = 'something' + self.i.title = u'something' self.i.load() self.assertEqual(original_title, self.i.title) def test_load_clears_dirty_flags(self): - self.i.artist = 'something' + self.i.artist = u'something' self.assertTrue('artist' in self.i._dirty) self.i.load() self.assertTrue('artist' not in self.i._dirty) @@ -62,20 +64,20 @@ class StoreTest(_common.LibTestCase): self.i.store() new_year = self.lib._connection().execute( 'select year from items where ' - 'title="the title"').fetchone()[b'year'] + 'title="the title"').fetchone()['year'] self.assertEqual(new_year, 1987) def test_store_only_writes_dirty_fields(self): original_genre = self.i.genre - self.i._values_fixed['genre'] = 'beatboxing' # change w/o dirtying + self.i._values_fixed['genre'] = u'beatboxing' # change w/o dirtying self.i.store() new_genre = self.lib._connection().execute( 'select genre from items where ' - 'title="the title"').fetchone()[b'genre'] + 'title="the title"').fetchone()['genre'] self.assertEqual(new_genre, original_genre) def test_store_clears_dirty_flags(self): - self.i.composer = 'tvp' + self.i.composer = u'tvp' self.i.store() self.assertTrue('composer' not in self.i._dirty) @@ -90,17 +92,17 @@ class AddTest(_common.TestCase): self.lib.add(self.i) new_grouping = self.lib._connection().execute( 'select grouping from items ' - 'where composer="the composer"').fetchone()[b'grouping'] + 'where composer="the composer"').fetchone()['grouping'] self.assertEqual(new_grouping, self.i.grouping) def test_library_add_path_inserts_row(self): i = beets.library.Item.from_path( - os.path.join(_common.RSRC, 'full.mp3') + os.path.join(_common.RSRC, b'full.mp3') ) self.lib.add(i) new_grouping = self.lib._connection().execute( 'select grouping from items ' - 'where composer="the composer"').fetchone()[b'grouping'] + 'where composer="the composer"').fetchone()['grouping'] self.assertEqual(new_grouping, self.i.grouping) @@ -129,7 +131,7 @@ class GetSetTest(_common.TestCase): self.assertTrue('title' not in self.i._dirty) def test_invalid_field_raises_attributeerror(self): - self.assertRaises(AttributeError, getattr, self.i, 'xyzzy') + self.assertRaises(AttributeError, getattr, self.i, u'xyzzy') class DestinationTest(_common.TestCase): @@ -147,18 +149,18 @@ class DestinationTest(_common.TestCase): config.read(user=False, defaults=True) def test_directory_works_with_trailing_slash(self): - self.lib.directory = 'one/' - self.lib.path_formats = [('default', 'two')] + self.lib.directory = b'one/' + self.lib.path_formats = [(u'default', u'two')] self.assertEqual(self.i.destination(), np('one/two')) def test_directory_works_without_trailing_slash(self): - self.lib.directory = 'one' - self.lib.path_formats = [('default', 'two')] + self.lib.directory = b'one' + self.lib.path_formats = [(u'default', u'two')] self.assertEqual(self.i.destination(), np('one/two')) def test_destination_substitues_metadata_values(self): - self.lib.directory = 'base' - self.lib.path_formats = [('default', '$album/$artist $title')] + self.lib.directory = b'base' + self.lib.path_formats = [(u'default', u'$album/$artist $title')] self.i.title = 'three' self.i.artist = 'two' self.i.album = 'one' @@ -166,23 +168,23 @@ class DestinationTest(_common.TestCase): np('base/one/two three')) def test_destination_preserves_extension(self): - self.lib.directory = 'base' - self.lib.path_formats = [('default', '$title')] + self.lib.directory = b'base' + self.lib.path_formats = [(u'default', u'$title')] self.i.path = 'hey.audioformat' self.assertEqual(self.i.destination(), np('base/the title.audioformat')) def test_lower_case_extension(self): - self.lib.directory = 'base' - self.lib.path_formats = [('default', '$title')] + self.lib.directory = b'base' + self.lib.path_formats = [(u'default', u'$title')] self.i.path = 'hey.MP3' self.assertEqual(self.i.destination(), np('base/the title.mp3')) def test_destination_pads_some_indices(self): - self.lib.directory = 'base' - self.lib.path_formats = [('default', - '$track $tracktotal $disc $disctotal $bpm')] + self.lib.directory = b'base' + self.lib.path_formats = [(u'default', + u'$track $tracktotal $disc $disctotal $bpm')] self.i.track = 1 self.i.tracktotal = 2 self.i.disc = 3 @@ -192,8 +194,8 @@ class DestinationTest(_common.TestCase): np('base/01 02 03 04 5')) def test_destination_pads_date_values(self): - self.lib.directory = 'base' - self.lib.path_formats = [('default', '$year-$month-$day')] + self.lib.directory = b'base' + self.lib.path_formats = [(u'default', u'$year-$month-$day')] self.i.year = 1 self.i.month = 2 self.i.day = 3 @@ -203,116 +205,116 @@ class DestinationTest(_common.TestCase): def test_destination_escapes_slashes(self): self.i.album = 'one/two' dest = self.i.destination() - self.assertTrue('one' in dest) - self.assertTrue('two' in dest) - self.assertFalse('one/two' in dest) + self.assertTrue(b'one' in dest) + self.assertTrue(b'two' in dest) + self.assertFalse(b'one/two' in dest) def test_destination_escapes_leading_dot(self): self.i.album = '.something' dest = self.i.destination() - self.assertTrue('something' in dest) - self.assertFalse('/.' in dest) + self.assertTrue(b'something' in dest) + self.assertFalse(b'/.' in dest) def test_destination_preserves_legitimate_slashes(self): self.i.artist = 'one' self.i.album = 'two' dest = self.i.destination() - self.assertTrue(os.path.join('one', 'two') in dest) + self.assertTrue(os.path.join(b'one', b'two') in dest) def test_destination_long_names_truncated(self): - self.i.title = 'X' * 300 - self.i.artist = 'Y' * 300 - for c in self.i.destination().split(os.path.sep): + self.i.title = u'X' * 300 + self.i.artist = u'Y' * 300 + for c in self.i.destination().split(util.PATH_SEP): self.assertTrue(len(c) <= 255) def test_destination_long_names_keep_extension(self): - self.i.title = 'X' * 300 - self.i.path = 'something.extn' + self.i.title = u'X' * 300 + self.i.path = b'something.extn' dest = self.i.destination() - self.assertEqual(dest[-5:], '.extn') + self.assertEqual(dest[-5:], b'.extn') def test_distination_windows_removes_both_separators(self): self.i.title = 'one \\ two / three.mp3' with _common.platform_windows(): p = self.i.destination() - self.assertFalse('one \\ two' in p) - self.assertFalse('one / two' in p) - self.assertFalse('two \\ three' in p) - self.assertFalse('two / three' in p) + self.assertFalse(b'one \\ two' in p) + self.assertFalse(b'one / two' in p) + self.assertFalse(b'two \\ three' in p) + self.assertFalse(b'two / three' in p) def test_path_with_format(self): - self.lib.path_formats = [('default', '$artist/$album ($format)')] + self.lib.path_formats = [(u'default', u'$artist/$album ($format)')] p = self.i.destination() - self.assert_('(FLAC)' in p) + self.assertTrue(b'(FLAC)' in p) def test_heterogeneous_album_gets_single_directory(self): i1, i2 = item(), item() self.lib.add_album([i1, i2]) i1.year, i2.year = 2009, 2010 - self.lib.path_formats = [('default', '$album ($year)/$track $title')] + self.lib.path_formats = [(u'default', u'$album ($year)/$track $title')] dest1, dest2 = i1.destination(), i2.destination() self.assertEqual(os.path.dirname(dest1), os.path.dirname(dest2)) def test_default_path_for_non_compilations(self): self.i.comp = False self.lib.add_album([self.i]) - self.lib.directory = 'one' - self.lib.path_formats = [('default', 'two'), - ('comp:true', 'three')] + self.lib.directory = b'one' + self.lib.path_formats = [(u'default', u'two'), + (u'comp:true', u'three')] self.assertEqual(self.i.destination(), np('one/two')) def test_singleton_path(self): i = item(self.lib) - self.lib.directory = 'one' + self.lib.directory = b'one' self.lib.path_formats = [ - ('default', 'two'), - ('singleton:true', 'four'), - ('comp:true', 'three'), + (u'default', u'two'), + (u'singleton:true', u'four'), + (u'comp:true', u'three'), ] self.assertEqual(i.destination(), np('one/four')) def test_comp_before_singleton_path(self): i = item(self.lib) i.comp = True - self.lib.directory = 'one' + self.lib.directory = b'one' self.lib.path_formats = [ - ('default', 'two'), - ('comp:true', 'three'), - ('singleton:true', 'four'), + (u'default', u'two'), + (u'comp:true', u'three'), + (u'singleton:true', u'four'), ] self.assertEqual(i.destination(), np('one/three')) def test_comp_path(self): self.i.comp = True self.lib.add_album([self.i]) - self.lib.directory = 'one' + self.lib.directory = b'one' self.lib.path_formats = [ - ('default', 'two'), - ('comp:true', 'three'), + (u'default', u'two'), + (u'comp:true', u'three'), ] self.assertEqual(self.i.destination(), np('one/three')) def test_albumtype_query_path(self): self.i.comp = True self.lib.add_album([self.i]) - self.i.albumtype = 'sometype' - self.lib.directory = 'one' + self.i.albumtype = u'sometype' + self.lib.directory = b'one' self.lib.path_formats = [ - ('default', 'two'), - ('albumtype:sometype', 'four'), - ('comp:true', 'three'), + (u'default', u'two'), + (u'albumtype:sometype', u'four'), + (u'comp:true', u'three'), ] self.assertEqual(self.i.destination(), np('one/four')) def test_albumtype_path_fallback_to_comp(self): self.i.comp = True self.lib.add_album([self.i]) - self.i.albumtype = 'sometype' - self.lib.directory = 'one' + self.i.albumtype = u'sometype' + self.lib.directory = b'one' self.lib.path_formats = [ - ('default', 'two'), - ('albumtype:anothertype', 'four'), - ('comp:true', 'three'), + (u'default', u'two'), + (u'albumtype:anothertype', u'four'), + (u'comp:true', u'three'), ] self.assertEqual(self.i.destination(), np('one/three')) @@ -354,43 +356,43 @@ class DestinationTest(_common.TestCase): self.assertEqual(val, u'') def test_artist_falls_back_to_albumartist(self): - self.i.artist = '' - self.i.albumartist = 'something' - self.lib.path_formats = [('default', '$artist')] + self.i.artist = u'' + self.i.albumartist = u'something' + self.lib.path_formats = [(u'default', u'$artist')] p = self.i.destination() - self.assertEqual(p.rsplit(os.path.sep, 1)[1], 'something') + self.assertEqual(p.rsplit(util.PATH_SEP, 1)[1], b'something') def test_albumartist_falls_back_to_artist(self): - self.i.artist = 'trackartist' - self.i.albumartist = '' - self.lib.path_formats = [('default', '$albumartist')] + self.i.artist = u'trackartist' + self.i.albumartist = u'' + self.lib.path_formats = [(u'default', u'$albumartist')] p = self.i.destination() - self.assertEqual(p.rsplit(os.path.sep, 1)[1], 'trackartist') + self.assertEqual(p.rsplit(util.PATH_SEP, 1)[1], b'trackartist') def test_artist_overrides_albumartist(self): - self.i.artist = 'theartist' - self.i.albumartist = 'something' - self.lib.path_formats = [('default', '$artist')] + self.i.artist = u'theartist' + self.i.albumartist = u'something' + self.lib.path_formats = [(u'default', u'$artist')] p = self.i.destination() - self.assertEqual(p.rsplit(os.path.sep, 1)[1], 'theartist') + self.assertEqual(p.rsplit(util.PATH_SEP, 1)[1], b'theartist') def test_albumartist_overrides_artist(self): - self.i.artist = 'theartist' - self.i.albumartist = 'something' - self.lib.path_formats = [('default', '$albumartist')] + self.i.artist = u'theartist' + self.i.albumartist = u'something' + self.lib.path_formats = [(u'default', u'$albumartist')] p = self.i.destination() - self.assertEqual(p.rsplit(os.path.sep, 1)[1], 'something') + self.assertEqual(p.rsplit(util.PATH_SEP, 1)[1], b'something') def test_unicode_normalized_nfd_on_mac(self): instr = unicodedata.normalize('NFC', u'caf\xe9') - self.lib.path_formats = [('default', instr)] + self.lib.path_formats = [(u'default', instr)] dest = self.i.destination(platform='darwin', fragment=True) self.assertEqual(dest, unicodedata.normalize('NFD', instr)) def test_unicode_normalized_nfc_on_linux(self): instr = unicodedata.normalize('NFD', u'caf\xe9') - self.lib.path_formats = [('default', instr)] - dest = self.i.destination(platform='linux2', fragment=True) + self.lib.path_formats = [(u'default', instr)] + dest = self.i.destination(platform='linux', fragment=True) self.assertEqual(dest, unicodedata.normalize('NFC', instr)) def test_non_mbcs_characters_on_windows(self): @@ -398,56 +400,63 @@ class DestinationTest(_common.TestCase): sys.getfilesystemencoding = lambda: 'mbcs' try: self.i.title = u'h\u0259d' - self.lib.path_formats = [('default', '$title')] + self.lib.path_formats = [(u'default', u'$title')] p = self.i.destination() self.assertFalse(b'?' in p) # We use UTF-8 to encode Windows paths now. - self.assertTrue(u'h\u0259d'.encode('utf8') in p) + self.assertTrue(u'h\u0259d'.encode('utf-8') in p) finally: sys.getfilesystemencoding = oldfunc def test_unicode_extension_in_fragment(self): - self.lib.path_formats = [('default', u'foo')] + self.lib.path_formats = [(u'default', u'foo')] self.i.path = util.bytestring_path(u'bar.caf\xe9') - dest = self.i.destination(platform='linux2', fragment=True) + dest = self.i.destination(platform='linux', fragment=True) self.assertEqual(dest, u'foo.caf\xe9') def test_asciify_and_replace(self): config['asciify_paths'] = True self.lib.replacements = [(re.compile(u'"'), u'q')] - self.lib.directory = 'lib' - self.lib.path_formats = [('default', '$title')] + self.lib.directory = b'lib' + self.lib.path_formats = [(u'default', u'$title')] self.i.title = u'\u201c\u00f6\u2014\u00cf\u201d' self.assertEqual(self.i.destination(), np('lib/qo--Iq')) + def test_asciify_character_expanding_to_slash(self): + config['asciify_paths'] = True + self.lib.directory = b'lib' + self.lib.path_formats = [(u'default', u'$title')] + self.i.title = u'ab\xa2\xbdd' + self.assertEqual(self.i.destination(), np('lib/abC_ 1_2 d')) + def test_destination_with_replacements(self): - self.lib.directory = 'base' + self.lib.directory = b'base' self.lib.replacements = [(re.compile(r'a'), u'e')] - self.lib.path_formats = [('default', '$album/$title')] - self.i.title = 'foo' - self.i.album = 'bar' + self.lib.path_formats = [(u'default', u'$album/$title')] + self.i.title = u'foo' + self.i.album = u'bar' self.assertEqual(self.i.destination(), np('base/ber/foo')) @unittest.skip('unimplemented: #359') def test_destination_with_empty_component(self): - self.lib.directory = 'base' + self.lib.directory = b'base' self.lib.replacements = [(re.compile(r'^$'), u'_')] - self.lib.path_formats = [('default', '$album/$artist/$title')] - self.i.title = 'three' - self.i.artist = '' - self.i.albumartist = '' - self.i.album = 'one' + self.lib.path_formats = [(u'default', u'$album/$artist/$title')] + self.i.title = u'three' + self.i.artist = u'' + self.i.albumartist = u'' + self.i.album = u'one' self.assertEqual(self.i.destination(), np('base/one/_/three')) @unittest.skip('unimplemented: #359') def test_destination_with_empty_final_component(self): - self.lib.directory = 'base' + self.lib.directory = b'base' self.lib.replacements = [(re.compile(r'^$'), u'_')] - self.lib.path_formats = [('default', '$album/$title')] - self.i.title = '' - self.i.album = 'one' + self.lib.path_formats = [(u'default', u'$album/$title')] + self.i.title = u'' + self.i.album = u'one' self.i.path = 'foo.mp3' self.assertEqual(self.i.destination(), np('base/one/_.mp3')) @@ -461,11 +470,11 @@ class DestinationTest(_common.TestCase): # Construct an item whose untruncated path ends with a Y but whose # truncated version ends with an X. - self.i.title = 'X' * 300 + 'Y' + self.i.title = u'X' * 300 + u'Y' # The final path should reflect the replacement. dest = self.i.destination() - self.assertEqual(dest[-2:], 'XZ') + self.assertEqual(dest[-2:], b'XZ') def test_legalize_path_one_for_many_replacement(self): # Use a replacement that should always replace the last X in any @@ -476,18 +485,18 @@ class DestinationTest(_common.TestCase): # Construct an item whose untruncated path ends with a Y but whose # truncated version ends with an X. - self.i.title = 'X' * 300 + 'Y' + self.i.title = u'X' * 300 + u'Y' # The final path should ignore the user replacement and create a path # of the correct length, containing Xs. dest = self.i.destination() - self.assertEqual(dest[-2:], 'XX') + self.assertEqual(dest[-2:], b'XX') class ItemFormattedMappingTest(_common.LibTestCase): def test_formatted_item_value(self): formatted = self.i.formatted() - self.assertEqual(formatted['artist'], 'the artist') + self.assertEqual(formatted['artist'], u'the artist') def test_get_unset_field(self): formatted = self.i.formatted() @@ -500,53 +509,53 @@ class ItemFormattedMappingTest(_common.LibTestCase): def test_get_method_with_specified_default(self): formatted = self.i.formatted() - self.assertEqual(formatted.get('other_field', 'default'), 'default') + self.assertEqual(formatted.get('other_field', u'default'), u'default') def test_item_precedence(self): album = self.lib.add_album([self.i]) - album['artist'] = 'foo' + album['artist'] = u'foo' album.store() - self.assertNotEqual('foo', self.i.formatted().get('artist')) + self.assertNotEqual(u'foo', self.i.formatted().get('artist')) def test_album_flex_field(self): album = self.lib.add_album([self.i]) - album['flex'] = 'foo' + album['flex'] = u'foo' album.store() - self.assertEqual('foo', self.i.formatted().get('flex')) + self.assertEqual(u'foo', self.i.formatted().get('flex')) def test_album_field_overrides_item_field_for_path(self): # Make the album inconsistent with the item. album = self.lib.add_album([self.i]) - album.album = 'foo' + album.album = u'foo' album.store() - self.i.album = 'bar' + self.i.album = u'bar' self.i.store() # Ensure the album takes precedence. formatted = self.i.formatted(for_path=True) - self.assertEqual(formatted['album'], 'foo') + self.assertEqual(formatted['album'], u'foo') def test_artist_falls_back_to_albumartist(self): - self.i.artist = '' + self.i.artist = u'' formatted = self.i.formatted() - self.assertEqual(formatted['artist'], 'the album artist') + self.assertEqual(formatted['artist'], u'the album artist') def test_albumartist_falls_back_to_artist(self): - self.i.albumartist = '' + self.i.albumartist = u'' formatted = self.i.formatted() - self.assertEqual(formatted['albumartist'], 'the artist') + self.assertEqual(formatted['albumartist'], u'the artist') def test_both_artist_and_albumartist_empty(self): - self.i.artist = '' - self.i.albumartist = '' + self.i.artist = u'' + self.i.albumartist = u'' formatted = self.i.formatted() - self.assertEqual(formatted['albumartist'], '') + self.assertEqual(formatted['albumartist'], u'') class PathFormattingMixin(object): """Utilities for testing path formatting.""" def _setf(self, fmt): - self.lib.path_formats.insert(0, ('default', fmt)) + self.lib.path_formats.insert(0, (u'default', fmt)) def _assert_dest(self, dest, i=None): if i is None: @@ -560,8 +569,8 @@ class DestinationFunctionTest(_common.TestCase, PathFormattingMixin): def setUp(self): super(DestinationFunctionTest, self).setUp() self.lib = beets.library.Library(':memory:') - self.lib.directory = '/base' - self.lib.path_formats = [('default', u'path')] + self.lib.directory = b'/base' + self.lib.path_formats = [(u'default', u'path')] self.i = item(self.lib) def tearDown(self): @@ -570,59 +579,103 @@ class DestinationFunctionTest(_common.TestCase, PathFormattingMixin): def test_upper_case_literal(self): self._setf(u'%upper{foo}') - self._assert_dest('/base/FOO') + self._assert_dest(b'/base/FOO') def test_upper_case_variable(self): self._setf(u'%upper{$title}') - self._assert_dest('/base/THE TITLE') + self._assert_dest(b'/base/THE TITLE') def test_title_case_variable(self): self._setf(u'%title{$title}') - self._assert_dest('/base/The Title') + self._assert_dest(b'/base/The Title') + + def test_asciify_variable(self): + self._setf(u'%asciify{ab\xa2\xbdd}') + self._assert_dest(b'/base/abC_ 1_2 d') def test_left_variable(self): self._setf(u'%left{$title, 3}') - self._assert_dest('/base/the') + self._assert_dest(b'/base/the') def test_right_variable(self): self._setf(u'%right{$title,3}') - self._assert_dest('/base/tle') + self._assert_dest(b'/base/tle') def test_if_false(self): self._setf(u'x%if{,foo}') - self._assert_dest('/base/x') + self._assert_dest(b'/base/x') def test_if_false_value(self): self._setf(u'x%if{false,foo}') - self._assert_dest('/base/x') + self._assert_dest(b'/base/x') def test_if_true(self): self._setf(u'%if{bar,foo}') - self._assert_dest('/base/foo') + self._assert_dest(b'/base/foo') def test_if_else_false(self): self._setf(u'%if{,foo,baz}') - self._assert_dest('/base/baz') + self._assert_dest(b'/base/baz') def test_if_else_false_value(self): self._setf(u'%if{false,foo,baz}') - self._assert_dest('/base/baz') + self._assert_dest(b'/base/baz') def test_if_int_value(self): self._setf(u'%if{0,foo,baz}') - self._assert_dest('/base/baz') + self._assert_dest(b'/base/baz') def test_nonexistent_function(self): self._setf(u'%foo{bar}') - self._assert_dest('/base/%foo{bar}') + self._assert_dest(b'/base/%foo{bar}') + + def test_if_def_field_return_self(self): + self.i.bar = 3 + self._setf(u'%ifdef{bar}') + self._assert_dest(b'/base/3') + + def test_if_def_field_not_defined(self): + self._setf(u' %ifdef{bar}/$artist') + self._assert_dest(b'/base/the artist') + + def test_if_def_field_not_defined_2(self): + self._setf(u'$artist/%ifdef{bar}') + self._assert_dest(b'/base/the artist') + + def test_if_def_true(self): + self._setf(u'%ifdef{artist,cool}') + self._assert_dest(b'/base/cool') + + def test_if_def_true_complete(self): + self.i.series = "Now" + self._setf(u'%ifdef{series,$series Series,Albums}/$album') + self._assert_dest(b'/base/Now Series/the album') + + def test_if_def_false_complete(self): + self._setf(u'%ifdef{plays,$plays,not_played}') + self._assert_dest(b'/base/not_played') + + def test_first(self): + self.i.genres = "Pop; Rock; Classical Crossover" + self._setf(u'%first{$genres}') + self._assert_dest(b'/base/Pop') + + def test_first_skip(self): + self.i.genres = "Pop; Rock; Classical Crossover" + self._setf(u'%first{$genres,1,2}') + self._assert_dest(b'/base/Classical Crossover') + + def test_first_different_sep(self): + self._setf(u'%first{Alice / Bob / Eve,2,0, / , & }') + self._assert_dest(b'/base/Alice & Bob') class DisambiguationTest(_common.TestCase, PathFormattingMixin): def setUp(self): super(DisambiguationTest, self).setUp() self.lib = beets.library.Library(':memory:') - self.lib.directory = '/base' - self.lib.path_formats = [('default', u'path')] + self.lib.directory = b'/base' + self.lib.path_formats = [(u'default', u'path')] self.i1 = item() self.i1.year = 2001 @@ -639,43 +692,61 @@ class DisambiguationTest(_common.TestCase, PathFormattingMixin): self.lib._connection().close() def test_unique_expands_to_disambiguating_year(self): - self._assert_dest('/base/foo [2001]/the title', self.i1) + self._assert_dest(b'/base/foo [2001]/the title', self.i1) def test_unique_with_default_arguments_uses_albumtype(self): album2 = self.lib.get_album(self.i1) - album2.albumtype = 'bar' + album2.albumtype = u'bar' album2.store() self._setf(u'foo%aunique{}/$title') - self._assert_dest('/base/foo [bar]/the title', self.i1) + self._assert_dest(b'/base/foo [bar]/the title', self.i1) def test_unique_expands_to_nothing_for_distinct_albums(self): album2 = self.lib.get_album(self.i2) - album2.album = 'different album' + album2.album = u'different album' album2.store() - self._assert_dest('/base/foo/the title', self.i1) + self._assert_dest(b'/base/foo/the title', self.i1) def test_use_fallback_numbers_when_identical(self): album2 = self.lib.get_album(self.i2) album2.year = 2001 album2.store() - self._assert_dest('/base/foo 1/the title', self.i1) - self._assert_dest('/base/foo 2/the title', self.i2) + self._assert_dest(b'/base/foo [1]/the title', self.i1) + self._assert_dest(b'/base/foo [2]/the title', self.i2) def test_unique_falls_back_to_second_distinguishing_field(self): self._setf(u'foo%aunique{albumartist album,month year}/$title') - self._assert_dest('/base/foo [2001]/the title', self.i1) + self._assert_dest(b'/base/foo [2001]/the title', self.i1) def test_unique_sanitized(self): album2 = self.lib.get_album(self.i2) album2.year = 2001 album1 = self.lib.get_album(self.i1) - album1.albumtype = 'foo/bar' + album1.albumtype = u'foo/bar' album2.store() album1.store() self._setf(u'foo%aunique{albumartist album,albumtype}/$title') - self._assert_dest('/base/foo [foo_bar]/the title', self.i1) + self._assert_dest(b'/base/foo [foo_bar]/the title', self.i1) + + def test_drop_empty_disambig_string(self): + album1 = self.lib.get_album(self.i1) + album1.albumdisambig = None + album2 = self.lib.get_album(self.i2) + album2.albumdisambig = u'foo' + album1.store() + album2.store() + self._setf(u'foo%aunique{albumartist album,albumdisambig}/$title') + self._assert_dest(b'/base/foo/the title', self.i1) + + def test_change_brackets(self): + self._setf(u'foo%aunique{albumartist album,year,()}/$title') + self._assert_dest(b'/base/foo (2001)/the title', self.i1) + + def test_remove_brackets(self): + self._setf(u'foo%aunique{albumartist album,year,}/$title') + self._assert_dest(b'/base/foo 2001/the title', self.i1) class PluginDestinationTest(_common.TestCase): @@ -695,8 +766,8 @@ class PluginDestinationTest(_common.TestCase): plugins.item_field_getters = field_getters self.lib = beets.library.Library(':memory:') - self.lib.directory = '/base' - self.lib.path_formats = [('default', u'$artist $foo')] + self.lib.directory = b'/base' + self.lib.path_formats = [(u'default', u'$artist $foo')] self.i = item(self.lib) def tearDown(self): @@ -706,28 +777,28 @@ class PluginDestinationTest(_common.TestCase): def _assert_dest(self, dest): with _common.platform_posix(): the_dest = self.i.destination() - self.assertEqual(the_dest, '/base/' + dest) + self.assertEqual(the_dest, b'/base/' + dest) def test_undefined_value_not_substituted(self): - self._assert_dest('the artist $foo') + self._assert_dest(b'the artist $foo') def test_plugin_value_not_substituted(self): self._tv_map = { 'foo': 'bar', } - self._assert_dest('the artist bar') + self._assert_dest(b'the artist bar') def test_plugin_value_overrides_attribute(self): self._tv_map = { 'artist': 'bar', } - self._assert_dest('bar $foo') + self._assert_dest(b'bar $foo') def test_plugin_value_sanitized(self): self._tv_map = { 'foo': 'bar/baz', } - self._assert_dest('the artist bar_baz') + self._assert_dest(b'the artist bar_baz') class AlbumInfoTest(_common.TestCase): @@ -749,7 +820,7 @@ class AlbumInfoTest(_common.TestCase): ai.artpath = '/my/great/art' ai.store() new_ai = self.lib.get_album(self.i) - self.assertEqual(new_ai.artpath, '/my/great/art') + self.assertEqual(new_ai.artpath, b'/my/great/art') def test_albuminfo_for_two_items_doesnt_duplicate_row(self): i2 = item(self.lib) @@ -764,7 +835,7 @@ class AlbumInfoTest(_common.TestCase): def test_individual_tracks_have_no_albuminfo(self): i2 = item() - i2.album = 'aTotallyDifferentAlbum' + i2.album = u'aTotallyDifferentAlbum' self.lib.add(i2) ai = self.lib.get_album(i2) self.assertEqual(ai, None) @@ -780,29 +851,29 @@ class AlbumInfoTest(_common.TestCase): if i.id == self.i.id: break else: - self.fail("item not found") + self.fail(u"item not found") def test_albuminfo_changes_affect_items(self): ai = self.lib.get_album(self.i) - ai.album = 'myNewAlbum' + ai.album = u'myNewAlbum' ai.store() i = self.lib.items()[0] - self.assertEqual(i.album, 'myNewAlbum') + self.assertEqual(i.album, u'myNewAlbum') def test_albuminfo_change_albumartist_changes_items(self): ai = self.lib.get_album(self.i) - ai.albumartist = 'myNewArtist' + ai.albumartist = u'myNewArtist' ai.store() i = self.lib.items()[0] - self.assertEqual(i.albumartist, 'myNewArtist') - self.assertNotEqual(i.artist, 'myNewArtist') + self.assertEqual(i.albumartist, u'myNewArtist') + self.assertNotEqual(i.artist, u'myNewArtist') def test_albuminfo_change_artist_does_not_change_items(self): ai = self.lib.get_album(self.i) - ai.artist = 'myNewArtist' + ai.artist = u'myNewArtist' ai.store() i = self.lib.items()[0] - self.assertNotEqual(i.artist, 'myNewArtist') + self.assertNotEqual(i.artist, u'myNewArtist') def test_albuminfo_remove_removes_items(self): item_id = self.i.id @@ -819,7 +890,7 @@ class AlbumInfoTest(_common.TestCase): def test_noop_albuminfo_changes_affect_items(self): i = self.lib.items()[0] - i.album = 'foobar' + i.album = u'foobar' i.store() ai = self.lib.get_album(self.i) ai.album = ai.album @@ -842,7 +913,8 @@ class ArtDestinationTest(_common.TestCase): def test_art_filename_respects_setting(self): art = self.ai.art_destination('something.jpg') - self.assert_('%sartimage.jpg' % os.path.sep in art) + new_art = bytestring_path('%sartimage.jpg' % os.path.sep) + self.assertTrue(new_art in art) def test_art_path_in_item_dir(self): art = self.ai.art_destination('something.jpg') @@ -852,7 +924,7 @@ class ArtDestinationTest(_common.TestCase): def test_art_path_sanitized(self): config['art_filename'] = u'artXimage' art = self.ai.art_destination('something.jpg') - self.assert_('artYimage' in art) + self.assertTrue(b'artYimage' in art) class PathStringTest(_common.TestCase): @@ -862,25 +934,25 @@ class PathStringTest(_common.TestCase): self.i = item(self.lib) def test_item_path_is_bytestring(self): - self.assert_(isinstance(self.i.path, bytes)) + self.assertTrue(isinstance(self.i.path, bytes)) def test_fetched_item_path_is_bytestring(self): i = list(self.lib.items())[0] - self.assert_(isinstance(i.path, bytes)) + self.assertTrue(isinstance(i.path, bytes)) def test_unicode_path_becomes_bytestring(self): self.i.path = u'unicodepath' - self.assert_(isinstance(self.i.path, bytes)) + self.assertTrue(isinstance(self.i.path, bytes)) def test_unicode_in_database_becomes_bytestring(self): self.lib._connection().execute(""" update items set path=? where id=? """, (self.i.id, u'somepath')) i = list(self.lib.items())[0] - self.assert_(isinstance(i.path, bytes)) + self.assertTrue(isinstance(i.path, bytes)) def test_special_chars_preserved_in_database(self): - path = 'b\xe1r'.encode('utf8') + path = u'b\xe1r'.encode('utf-8') self.i.path = path self.i.store() i = list(self.lib.items())[0] @@ -888,7 +960,7 @@ class PathStringTest(_common.TestCase): def test_special_char_path_added_to_database(self): self.i.remove() - path = 'b\xe1r'.encode('utf8') + path = u'b\xe1r'.encode('utf-8') i = item() i.path = path self.lib.add(i) @@ -898,13 +970,13 @@ class PathStringTest(_common.TestCase): def test_destination_returns_bytestring(self): self.i.artist = u'b\xe1r' dest = self.i.destination() - self.assert_(isinstance(dest, bytes)) + self.assertTrue(isinstance(dest, bytes)) def test_art_destination_returns_bytestring(self): self.i.artist = u'b\xe1r' alb = self.lib.add_album([self.i]) dest = alb.art_destination(u'image.jpg') - self.assert_(isinstance(dest, bytes)) + self.assertTrue(isinstance(dest, bytes)) def test_artpath_stores_special_chars(self): path = b'b\xe1r' @@ -917,17 +989,17 @@ class PathStringTest(_common.TestCase): def test_sanitize_path_with_special_chars(self): path = u'b\xe1r?' new_path = util.sanitize_path(path) - self.assert_(new_path.startswith(u'b\xe1r')) + self.assertTrue(new_path.startswith(u'b\xe1r')) def test_sanitize_path_returns_unicode(self): path = u'b\xe1r?' new_path = util.sanitize_path(path) - self.assert_(isinstance(new_path, unicode)) + self.assertTrue(isinstance(new_path, six.text_type)) def test_unicode_artpath_becomes_bytestring(self): alb = self.lib.add_album([self.i]) alb.artpath = u'somep\xe1th' - self.assert_(isinstance(alb.artpath, bytes)) + self.assertTrue(isinstance(alb.artpath, bytes)) def test_unicode_artpath_in_database_decoded(self): alb = self.lib.add_album([self.i]) @@ -936,14 +1008,14 @@ class PathStringTest(_common.TestCase): (u'somep\xe1th', alb.id) ) alb = self.lib.get_album(alb.id) - self.assert_(isinstance(alb.artpath, bytes)) + self.assertTrue(isinstance(alb.artpath, bytes)) class MtimeTest(_common.TestCase): def setUp(self): super(MtimeTest, self).setUp() - self.ipath = os.path.join(self.temp_dir, 'testfile.mp3') - shutil.copy(os.path.join(_common.RSRC, 'full.mp3'), self.ipath) + self.ipath = os.path.join(self.temp_dir, b'testfile.mp3') + shutil.copy(os.path.join(_common.RSRC, b'full.mp3'), self.ipath) self.i = beets.library.Item.from_path(self.ipath) self.lib = beets.library.Library(':memory:') self.lib.add(self.i) @@ -960,16 +1032,16 @@ class MtimeTest(_common.TestCase): self.assertGreaterEqual(self.i.mtime, self._mtime()) def test_mtime_reset_on_db_modify(self): - self.i.title = 'something else' + self.i.title = u'something else' self.assertLess(self.i.mtime, self._mtime()) def test_mtime_up_to_date_after_write(self): - self.i.title = 'something else' + self.i.title = u'something else' self.i.write() self.assertGreaterEqual(self.i.mtime, self._mtime()) def test_mtime_up_to_date_after_read(self): - self.i.title = 'something else' + self.i.title = u'something else' self.i.read() self.assertGreaterEqual(self.i.mtime, self._mtime()) @@ -994,35 +1066,36 @@ class TemplateTest(_common.LibTestCase): def test_year_formatted_in_template(self): self.i.year = 123 self.i.store() - self.assertEqual(self.i.evaluate_template('$year'), '0123') + self.assertEqual(self.i.evaluate_template('$year'), u'0123') def test_album_flexattr_appears_in_item_template(self): self.album = self.lib.add_album([self.i]) - self.album.foo = 'baz' + self.album.foo = u'baz' self.album.store() - self.assertEqual(self.i.evaluate_template('$foo'), 'baz') + self.assertEqual(self.i.evaluate_template('$foo'), u'baz') def test_album_and_item_format(self): config['format_album'] = u'foö $foo' album = beets.library.Album() - album.foo = 'bar' - album.tagada = 'togodo' + album.foo = u'bar' + album.tagada = u'togodo' self.assertEqual(u"{0}".format(album), u"foö bar") self.assertEqual(u"{0:$tagada}".format(album), u"togodo") - self.assertEqual(unicode(album), u"foö bar") - self.assertEqual(str(album), b"fo\xc3\xb6 bar") + self.assertEqual(six.text_type(album), u"foö bar") + self.assertEqual(bytes(album), b"fo\xc3\xb6 bar") - config['format_item'] = 'bar $foo' + config['format_item'] = u'bar $foo' item = beets.library.Item() - item.foo = 'bar' - item.tagada = 'togodo' - self.assertEqual("{0}".format(item), "bar bar") - self.assertEqual("{0:$tagada}".format(item), "togodo") + item.foo = u'bar' + item.tagada = u'togodo' + self.assertEqual(u"{0}".format(item), u"bar bar") + self.assertEqual(u"{0:$tagada}".format(item), u"togodo") class UnicodePathTest(_common.LibTestCase): def test_unicode_path(self): - self.i.path = os.path.join(_common.RSRC, u'unicode\u2019d.mp3') + self.i.path = os.path.join(_common.RSRC, + u'unicode\u2019d.mp3'.encode('utf-8')) # If there are any problems with unicode paths, we will raise # here and fail. self.i.read() @@ -1038,13 +1111,13 @@ class WriteTest(unittest.TestCase, TestHelper): def test_write_nonexistant(self): item = self.create_item() - item.path = '/path/does/not/exist' + item.path = b'/path/does/not/exist' with self.assertRaises(beets.library.ReadError): item.write() def test_no_write_permission(self): item = self.add_item_fixture() - path = item.path + path = syspath(item.path) os.chmod(path, stat.S_IRUSR) try: @@ -1056,36 +1129,38 @@ class WriteTest(unittest.TestCase, TestHelper): def test_write_with_custom_path(self): item = self.add_item_fixture() - custom_path = os.path.join(self.temp_dir, 'custom.mp3') - shutil.copy(item.path, custom_path) + custom_path = os.path.join(self.temp_dir, b'custom.mp3') + shutil.copy(syspath(item.path), syspath(custom_path)) item['artist'] = 'new artist' - self.assertNotEqual(MediaFile(custom_path).artist, 'new artist') - self.assertNotEqual(MediaFile(item.path).artist, 'new artist') + self.assertNotEqual(MediaFile(syspath(custom_path)).artist, + 'new artist') + self.assertNotEqual(MediaFile(syspath(item.path)).artist, + 'new artist') item.write(custom_path) - self.assertEqual(MediaFile(custom_path).artist, 'new artist') - self.assertNotEqual(MediaFile(item.path).artist, 'new artist') + self.assertEqual(MediaFile(syspath(custom_path)).artist, 'new artist') + self.assertNotEqual(MediaFile(syspath(item.path)).artist, 'new artist') def test_write_custom_tags(self): item = self.add_item_fixture(artist='old artist') item.write(tags={'artist': 'new artist'}) self.assertNotEqual(item.artist, 'new artist') - self.assertEqual(MediaFile(item.path).artist, 'new artist') + self.assertEqual(MediaFile(syspath(item.path)).artist, 'new artist') def test_write_date_field(self): # Since `date` is not a MediaField, this should do nothing. item = self.add_item_fixture() clean_year = item.year - item.date = 'foo' + item.date = u'foo' item.write() - self.assertEqual(MediaFile(item.path).year, clean_year) + self.assertEqual(MediaFile(syspath(item.path)).year, clean_year) class ItemReadTest(unittest.TestCase): def test_unreadable_raise_read_error(self): - unreadable = os.path.join(_common.RSRC, 'image-2x3.png') + unreadable = os.path.join(_common.RSRC, b'image-2x3.png') item = beets.library.Item() with self.assertRaises(beets.library.ReadError) as cm: item.read(unreadable) @@ -1107,7 +1182,7 @@ class FilesizeTest(unittest.TestCase, TestHelper): def test_filesize(self): item = self.add_item_fixture() - self.assertNotEquals(item.filesize, 0) + self.assertNotEqual(item.filesize, 0) def test_nonexistent_file(self): item = beets.library.Item() @@ -1117,7 +1192,7 @@ class FilesizeTest(unittest.TestCase, TestHelper): class ParseQueryTest(unittest.TestCase): def test_parse_invalid_query_string(self): with self.assertRaises(beets.dbcore.InvalidQueryError) as raised: - beets.library.parse_query_string('foo"', None) + beets.library.parse_query_string(u'foo"', None) self.assertIsInstance(raised.exception, beets.dbcore.query.ParsingError) @@ -1126,9 +1201,63 @@ class ParseQueryTest(unittest.TestCase): beets.library.parse_query_string(b"query", None) +class LibraryFieldTypesTest(unittest.TestCase): + """Test format() and parse() for library-specific field types""" + def test_datetype(self): + t = beets.library.DateType() + + # format + time_format = beets.config['time_format'].as_str() + time_local = time.strftime(time_format, + time.localtime(123456789)) + self.assertEqual(time_local, t.format(123456789)) + # parse + self.assertEqual(123456789.0, t.parse(time_local)) + self.assertEqual(123456789.0, t.parse(u'123456789.0')) + self.assertEqual(t.null, t.parse(u'not123456789.0')) + self.assertEqual(t.null, t.parse(u'1973-11-29')) + + def test_pathtype(self): + t = beets.library.PathType() + + # format + self.assertEqual('/tmp', t.format('/tmp')) + self.assertEqual(u'/tmp/\xe4lbum', t.format(u'/tmp/\u00e4lbum')) + # parse + self.assertEqual(np(b'/tmp'), t.parse('/tmp')) + self.assertEqual(np(b'/tmp/\xc3\xa4lbum'), + t.parse(u'/tmp/\u00e4lbum/')) + + def test_musicalkey(self): + t = beets.library.MusicalKey() + + # parse + self.assertEqual(u'C#m', t.parse(u'c#m')) + self.assertEqual(u'Gm', t.parse(u'g minor')) + self.assertEqual(u'Not c#m', t.parse(u'not C#m')) + + def test_durationtype(self): + t = beets.library.DurationType() + + # format + self.assertEqual(u'1:01', t.format(61.23)) + self.assertEqual(u'60:01', t.format(3601.23)) + self.assertEqual(u'0:00', t.format(None)) + # parse + self.assertEqual(61.0, t.parse(u'1:01')) + self.assertEqual(61.23, t.parse(u'61.23')) + self.assertEqual(3601.0, t.parse(u'60:01')) + self.assertEqual(t.null, t.parse(u'1:00:01')) + self.assertEqual(t.null, t.parse(u'not61.23')) + # config format_raw_length + beets.config['format_raw_length'] = True + self.assertEqual(61.23, t.format(61.23)) + self.assertEqual(3601.23, t.format(3601.23)) + + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_logging.py b/test/test_logging.py index bc52edf59..826b2447b 100644 --- a/test/test_logging.py +++ b/test/test_logging.py @@ -1,17 +1,21 @@ +# -*- coding: utf-8 -*- + """Stupid tests that ensure logging works as expected""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import sys import threading import logging as log -from StringIO import StringIO +from six import StringIO +import unittest import beets.logging as blog from beets import plugins, ui import beetsplug -from test._common import unittest, TestCase +from test import _common +from test._common import TestCase from test import helper +import six class LoggingTest(TestCase): @@ -42,9 +46,9 @@ class LoggingTest(TestCase): l.addHandler(handler) l.propagate = False - l.warning("foo {0} {bar}", "oof", bar="baz") + l.warning(u"foo {0} {bar}", "oof", bar=u"baz") handler.flush() - self.assertTrue(stream.getvalue(), "foo oof baz") + self.assertTrue(stream.getvalue(), u"foo oof baz") class LoggingLevelTest(unittest.TestCase, helper.TestHelper): @@ -56,9 +60,9 @@ class LoggingLevelTest(unittest.TestCase, helper.TestHelper): self.register_listener('dummy_event', self.listener) def log_all(self, name): - self._log.debug('debug ' + name) - self._log.info('info ' + name) - self._log.warning('warning ' + name) + self._log.debug(u'debug ' + name) + self._log.info(u'info ' + name) + self._log.warning(u'warning ' + name) def commands(self): cmd = ui.Subcommand('dummy') @@ -89,78 +93,79 @@ class LoggingLevelTest(unittest.TestCase, helper.TestHelper): self.config['verbose'] = 0 with helper.capture_log() as logs: self.run_command('dummy') - self.assertIn('dummy: warning cmd', logs) - self.assertIn('dummy: info cmd', logs) - self.assertNotIn('dummy: debug cmd', logs) + self.assertIn(u'dummy: warning cmd', logs) + self.assertIn(u'dummy: info cmd', logs) + self.assertNotIn(u'dummy: debug cmd', logs) def test_command_level1(self): self.config['verbose'] = 1 with helper.capture_log() as logs: self.run_command('dummy') - self.assertIn('dummy: warning cmd', logs) - self.assertIn('dummy: info cmd', logs) - self.assertIn('dummy: debug cmd', logs) + self.assertIn(u'dummy: warning cmd', logs) + self.assertIn(u'dummy: info cmd', logs) + self.assertIn(u'dummy: debug cmd', logs) def test_command_level2(self): self.config['verbose'] = 2 with helper.capture_log() as logs: self.run_command('dummy') - self.assertIn('dummy: warning cmd', logs) - self.assertIn('dummy: info cmd', logs) - self.assertIn('dummy: debug cmd', logs) + self.assertIn(u'dummy: warning cmd', logs) + self.assertIn(u'dummy: info cmd', logs) + self.assertIn(u'dummy: debug cmd', logs) def test_listener_level0(self): self.config['verbose'] = 0 with helper.capture_log() as logs: plugins.send('dummy_event') - self.assertIn('dummy: warning listener', logs) - self.assertNotIn('dummy: info listener', logs) - self.assertNotIn('dummy: debug listener', logs) + self.assertIn(u'dummy: warning listener', logs) + self.assertNotIn(u'dummy: info listener', logs) + self.assertNotIn(u'dummy: debug listener', logs) def test_listener_level1(self): self.config['verbose'] = 1 with helper.capture_log() as logs: plugins.send('dummy_event') - self.assertIn('dummy: warning listener', logs) - self.assertIn('dummy: info listener', logs) - self.assertNotIn('dummy: debug listener', logs) + self.assertIn(u'dummy: warning listener', logs) + self.assertIn(u'dummy: info listener', logs) + self.assertNotIn(u'dummy: debug listener', logs) def test_listener_level2(self): self.config['verbose'] = 2 with helper.capture_log() as logs: plugins.send('dummy_event') - self.assertIn('dummy: warning listener', logs) - self.assertIn('dummy: info listener', logs) - self.assertIn('dummy: debug listener', logs) + self.assertIn(u'dummy: warning listener', logs) + self.assertIn(u'dummy: info listener', logs) + self.assertIn(u'dummy: debug listener', logs) def test_import_stage_level0(self): self.config['verbose'] = 0 with helper.capture_log() as logs: importer = self.create_importer() importer.run() - self.assertIn('dummy: warning import_stage', logs) - self.assertNotIn('dummy: info import_stage', logs) - self.assertNotIn('dummy: debug import_stage', logs) + self.assertIn(u'dummy: warning import_stage', logs) + self.assertNotIn(u'dummy: info import_stage', logs) + self.assertNotIn(u'dummy: debug import_stage', logs) def test_import_stage_level1(self): self.config['verbose'] = 1 with helper.capture_log() as logs: importer = self.create_importer() importer.run() - self.assertIn('dummy: warning import_stage', logs) - self.assertIn('dummy: info import_stage', logs) - self.assertNotIn('dummy: debug import_stage', logs) + self.assertIn(u'dummy: warning import_stage', logs) + self.assertIn(u'dummy: info import_stage', logs) + self.assertNotIn(u'dummy: debug import_stage', logs) def test_import_stage_level2(self): self.config['verbose'] = 2 with helper.capture_log() as logs: importer = self.create_importer() importer.run() - self.assertIn('dummy: warning import_stage', logs) - self.assertIn('dummy: info import_stage', logs) - self.assertIn('dummy: debug import_stage', logs) + self.assertIn(u'dummy: warning import_stage', logs) + self.assertIn(u'dummy: info import_stage', logs) + self.assertIn(u'dummy: debug import_stage', logs) +@_common.slow_test() class ConcurrentEventsTest(TestCase, helper.TestHelper): """Similar to LoggingLevelTest but lower-level and focused on multiple events interaction. Since this is a bit heavy we don't do it in @@ -178,9 +183,9 @@ class ConcurrentEventsTest(TestCase, helper.TestHelper): self.t1_step = self.t2_step = 0 def log_all(self, name): - self._log.debug('debug ' + name) - self._log.info('info ' + name) - self._log.warning('warning ' + name) + self._log.debug(u'debug ' + name) + self._log.info(u'info ' + name) + self._log.warning(u'warning ' + name) def listener1(self): try: @@ -215,7 +220,7 @@ class ConcurrentEventsTest(TestCase, helper.TestHelper): def check_dp_exc(): if dp.exc_info: - raise dp.exc_info[1], None, dp.exc_info[2] + six.reraise(dp.exc_info[1], None, dp.exc_info[2]) try: dp.lock1.acquire() @@ -252,15 +257,15 @@ class ConcurrentEventsTest(TestCase, helper.TestHelper): t2.join(.1) self.assertFalse(t2.is_alive()) - except: - print("Alive threads:", threading.enumerate()) + except Exception: + print(u"Alive threads:", threading.enumerate()) if dp.lock1.locked(): - print("Releasing lock1 after exception in test") + print(u"Releasing lock1 after exception in test") dp.lock1.release() if dp.lock2.locked(): - print("Releasing lock2 after exception in test") + print(u"Releasing lock2 after exception in test") dp.lock2.release() - print("Alive threads:", threading.enumerate()) + print(u"Alive threads:", threading.enumerate()) raise def test_root_logger_levels(self): @@ -279,19 +284,19 @@ class ConcurrentEventsTest(TestCase, helper.TestHelper): importer = self.create_importer() importer.run() for l in logs: - self.assertIn("import", l) - self.assertIn("album", l) + self.assertIn(u"import", l) + self.assertIn(u"album", l) blog.getLogger('beets').set_global_level(blog.DEBUG) with helper.capture_log() as logs: importer = self.create_importer() importer.run() - self.assertIn("Sending event: database_change", logs) + self.assertIn(u"Sending event: database_change", logs) def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_lyrics.py b/test/test_lyrics.py index 960a94e33..398314ba6 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Fabrice Laporte. +# Copyright 2016, Fabrice Laporte. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,21 +15,25 @@ """Tests for the 'lyrics' plugin.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import absolute_import, division, print_function import os -from test import _common -import sys import re +import six +import sys +import unittest + +from mock import patch +from test import _common + +from beets import logging +from beets.library import Item +from beets.util import bytestring_path, confit + +from beetsplug import lyrics from mock import MagicMock -from test._common import unittest -from beetsplug import lyrics -from beets.library import Item -from beets.util import confit -from beets import logging log = logging.getLogger('beets.test_lyrics') raw_backend = lyrics.Backend({}, log) @@ -36,8 +41,9 @@ google = lyrics.Google(MagicMock(), log) class LyricsPluginTest(unittest.TestCase): + def setUp(self): - """Set up configuration""" + """Set up configuration.""" lyrics.LyricsPlugin() def test_search_artist(self): @@ -83,6 +89,10 @@ class LyricsPluginTest(unittest.TestCase): self.assertIn(('Alice', ['song']), lyrics.search_pairs(item)) + item = Item(artist='Alice and Bob', title='song') + self.assertEqual(('Alice and Bob', ['song']), + list(lyrics.search_pairs(item))[0]) + def test_search_pairs_multi_titles(self): item = Item(title='1 / 2', artist='A') self.assertIn(('A', ['1 / 2']), lyrics.search_pairs(item)) @@ -117,6 +127,10 @@ class LyricsPluginTest(unittest.TestCase): self.assertNotIn(('A', ['Song']), lyrics.search_pairs(item)) self.assertIn(('A', ['Song and B']), lyrics.search_pairs(item)) + item = Item(title='Song: B', artist='A') + self.assertIn(('A', ['Song']), lyrics.search_pairs(item)) + self.assertIn(('A', ['Song: B']), lyrics.search_pairs(item)) + def test_remove_credits(self): self.assertEqual( lyrics.remove_credits("""It's close to midnight @@ -179,20 +193,14 @@ def url_to_filename(url): url = re.sub(r'https?://|www.', '', url) fn = "".join(x for x in url if (x.isalnum() or x == '/')) fn = fn.split('/') - fn = os.path.join(LYRICS_ROOT_DIR, fn[0], fn[-1]) + '.txt' + fn = os.path.join(LYRICS_ROOT_DIR, + bytestring_path(fn[0]), + bytestring_path(fn[-1] + '.txt')) return fn -def check_lyrics_fetched(): - """Return True if lyrics_download_samples.py has been runned and lyrics - pages are present in resources directory""" - lyrics_dirs = len([d for d in os.listdir(LYRICS_ROOT_DIR) if - os.path.isdir(os.path.join(LYRICS_ROOT_DIR, d))]) - # example.com is the only lyrics dir added to repo - return lyrics_dirs > 1 - - class MockFetchUrl(object): + def __init__(self, pathval='fetched_path'): self.pathval = pathval self.fetched = None @@ -206,178 +214,207 @@ class MockFetchUrl(object): def is_lyrics_content_ok(title, text): - """Compare lyrics text to expected lyrics for given title""" + """Compare lyrics text to expected lyrics for given title.""" + if not text: + return + keywords = set(LYRICS_TEXTS[google.slugify(title)].split()) + words = set(x.strip(".?, ") for x in text.lower().split()) + return keywords <= words - keywords = LYRICS_TEXTS[google.slugify(title)] - return all(x in text.lower() for x in keywords) - -LYRICS_ROOT_DIR = os.path.join(_common.RSRC, 'lyrics') -LYRICS_TEXTS = confit.load_yaml(os.path.join(_common.RSRC, 'lyricstext.yaml')) -DEFAULT_SONG = dict(artist=u'The Beatles', title=u'Lady Madonna') - -DEFAULT_SOURCES = [ - dict(DEFAULT_SONG, url=u'http://lyrics.wikia.com/', - path=u'The_Beatles:Lady_Madonna'), - dict(artist=u'Santana', title=u'Black magic woman', - url='http://www.lyrics.com/', - path=u'black-magic-woman-lyrics-santana.html'), - dict(DEFAULT_SONG, url='https://www.musixmatch.com/', - path=u'lyrics/The-Beatles/Lady-Madonna'), -] - -# Every source entered in default beets google custom search engine -# must be listed below. -# Use default query when possible, or override artist and title fields -# if website don't have lyrics for default query. -GOOGLE_SOURCES = [ - dict(DEFAULT_SONG, - url=u'http://www.absolutelyrics.com', - path=u'/lyrics/view/the_beatles/lady_madonna'), - dict(DEFAULT_SONG, - url=u'http://www.azlyrics.com', - path=u'/lyrics/beatles/ladymadonna.html'), - dict(DEFAULT_SONG, - url=u'http://www.chartlyrics.com', - path=u'/_LsLsZ7P4EK-F-LD4dJgDQ/Lady+Madonna.aspx'), - dict(DEFAULT_SONG, - url=u'http://www.elyricsworld.com', - path=u'/lady_madonna_lyrics_beatles.html'), - dict(url=u'http://www.lacoccinelle.net', - artist=u'Jacques Brel', title=u"Amsterdam", - path=u'/paroles-officielles/275679.html'), - dict(DEFAULT_SONG, - url=u'http://letras.mus.br/', path=u'the-beatles/275/'), - dict(DEFAULT_SONG, - url='http://www.lyricsmania.com/', - path='lady_madonna_lyrics_the_beatles.html'), - dict(artist=u'Santana', title=u'Black magic woman', - url='http://www.lyrics.com/', - path=u'black-magic-woman-lyrics-santana.html'), - dict(DEFAULT_SONG, url=u'http://lyrics.wikia.com/', - path=u'The_Beatles:Lady_Madonna'), - dict(DEFAULT_SONG, - url=u'http://www.lyrics.net', path=u'/lyric/19110224'), - dict(DEFAULT_SONG, - url=u'http://www.lyricsmode.com', - path=u'/lyrics/b/beatles/lady_madonna.html'), - dict(url=u'http://www.lyricsontop.com', - artist=u'Amy Winehouse', title=u"Jazz'n'blues", - path=u'/amy-winehouse-songs/jazz-n-blues-lyrics.html'), - dict(DEFAULT_SONG, - url='http://www.metrolyrics.com/', - path='lady-madonna-lyrics-beatles.html'), - dict(url='http://www.musica.com/', path='letras.asp?letra=2738', - artist=u'Santana', title=u'Black magic woman'), - dict(DEFAULT_SONG, - url=u'http://www.onelyrics.net/', - artist=u'Ben & Ellen Harper', title=u'City of dreams', - path='ben-ellen-harper-city-of-dreams-lyrics'), - dict(url=u'http://www.paroles.net/', - artist=u'Lilly Wood & the prick', title=u"Hey it's ok", - path=u'lilly-wood-the-prick/paroles-hey-it-s-ok'), - dict(DEFAULT_SONG, - url='http://www.releaselyrics.com', - path=u'/346e/the-beatles-lady-madonna-(love-version)/'), - dict(DEFAULT_SONG, - url=u'http://www.smartlyrics.com', - path=u'/Song18148-The-Beatles-Lady-Madonna-lyrics.aspx'), - dict(DEFAULT_SONG, - url='http://www.songlyrics.com', - path=u'/the-beatles/lady-madonna-lyrics'), - dict(DEFAULT_SONG, - url=u'http://www.stlyrics.com', - path=u'/songs/r/richiehavens48961/ladymadonna2069109.html'), - dict(DEFAULT_SONG, - url=u'http://www.sweetslyrics.com', - path=u'/761696.The%20Beatles%20-%20Lady%20Madonna.html') -] +LYRICS_ROOT_DIR = os.path.join(_common.RSRC, b'lyrics') +LYRICS_TEXTS = confit.load_yaml(os.path.join(_common.RSRC, b'lyricstext.yaml')) -class LyricsGooglePluginTest(unittest.TestCase): - """Test scraping heuristics on a fake html page. - Or run lyrics_download_samples.py first to check that beets google - custom search engine sources are correctly scraped. - """ - source = dict(url=u'http://www.example.com', artist=u'John Doe', - title=u'Beets song', path=u'/lyrics/beetssong') +class LyricsGoogleBaseTest(unittest.TestCase): def setUp(self): - """Set up configuration""" + """Set up configuration.""" try: __import__('bs4') except ImportError: self.skipTest('Beautiful Soup 4 not available') if sys.version_info[:3] < (2, 7, 3): self.skipTest("Python's built-in HTML parser is not good enough") - lyrics.LyricsPlugin() - raw_backend.fetch_url = MockFetchUrl() + +class LyricsPluginSourcesTest(LyricsGoogleBaseTest): + """Check that beets google custom search engine sources are correctly + scraped. + """ + + DEFAULT_SONG = dict(artist=u'The Beatles', title=u'Lady Madonna') + + DEFAULT_SOURCES = [ + dict(DEFAULT_SONG, backend=lyrics.LyricsWiki), + dict(artist=u'Santana', title=u'Black magic woman', + backend=lyrics.MusiXmatch), + dict(DEFAULT_SONG, backend=lyrics.Genius), + ] + + GOOGLE_SOURCES = [ + dict(DEFAULT_SONG, + url=u'http://www.absolutelyrics.com', + path=u'/lyrics/view/the_beatles/lady_madonna'), + dict(DEFAULT_SONG, + url=u'http://www.azlyrics.com', + path=u'/lyrics/beatles/ladymadonna.html'), + dict(DEFAULT_SONG, + url=u'http://www.chartlyrics.com', + path=u'/_LsLsZ7P4EK-F-LD4dJgDQ/Lady+Madonna.aspx'), + dict(DEFAULT_SONG, + url=u'http://www.elyricsworld.com', + path=u'/lady_madonna_lyrics_beatles.html'), + dict(url=u'http://www.lacoccinelle.net', + artist=u'Jacques Brel', title=u"Amsterdam", + path=u'/paroles-officielles/275679.html'), + dict(DEFAULT_SONG, + url=u'http://letras.mus.br/', path=u'the-beatles/275/'), + dict(DEFAULT_SONG, + url='http://www.lyricsmania.com/', + path='lady_madonna_lyrics_the_beatles.html'), + dict(DEFAULT_SONG, url=u'http://lyrics.wikia.com/', + path=u'The_Beatles:Lady_Madonna'), + dict(DEFAULT_SONG, + url=u'http://www.lyricsmode.com', + path=u'/lyrics/b/beatles/lady_madonna.html'), + dict(url=u'http://www.lyricsontop.com', + artist=u'Amy Winehouse', title=u"Jazz'n'blues", + path=u'/amy-winehouse-songs/jazz-n-blues-lyrics.html'), + dict(DEFAULT_SONG, + url='http://www.metrolyrics.com/', + path='lady-madonna-lyrics-beatles.html'), + dict(url='http://www.musica.com/', path='letras.asp?letra=2738', + artist=u'Santana', title=u'Black magic woman'), + dict(url=u'http://www.paroles.net/', + artist=u'Lilly Wood & the prick', title=u"Hey it's ok", + path=u'lilly-wood-the-prick/paroles-hey-it-s-ok'), + dict(DEFAULT_SONG, + url='http://www.songlyrics.com', + path=u'/the-beatles/lady-madonna-lyrics'), + dict(DEFAULT_SONG, + url=u'http://www.sweetslyrics.com', + path=u'/761696.The%20Beatles%20-%20Lady%20Madonna.html') + ] + + def setUp(self): + LyricsGoogleBaseTest.setUp(self) + self.plugin = lyrics.LyricsPlugin() + + @unittest.skipUnless(os.environ.get( + 'BEETS_TEST_LYRICS_SOURCES', '0') == '1', + 'lyrics sources testing not enabled') + def test_backend_sources_ok(self): + """Test default backends with songs known to exist in respective databases. + """ + errors = [] + for s in self.DEFAULT_SOURCES: + res = s['backend'](self.plugin.config, self.plugin._log).fetch( + s['artist'], s['title']) + if not is_lyrics_content_ok(s['title'], res): + errors.append(s['backend'].__name__) + self.assertFalse(errors) + + @unittest.skipUnless(os.environ.get( + 'BEETS_TEST_LYRICS_SOURCES', '0') == '1', + 'lyrics sources testing not enabled') + def test_google_sources_ok(self): + """Test if lyrics present on websites registered in beets google custom + search engine are correctly scraped. + """ + for s in self.GOOGLE_SOURCES: + url = s['url'] + s['path'] + res = lyrics.scrape_lyrics_from_html( + raw_backend.fetch_url(url)) + self.assertTrue(google.is_lyrics(res), url) + self.assertTrue(is_lyrics_content_ok(s['title'], res), url) + + +class LyricsGooglePluginMachineryTest(LyricsGoogleBaseTest): + """Test scraping heuristics on a fake html page. + """ + + source = dict(url=u'http://www.example.com', artist=u'John Doe', + title=u'Beets song', path=u'/lyrics/beetssong') + + def setUp(self): + """Set up configuration""" + LyricsGoogleBaseTest.setUp(self) + self.plugin = lyrics.LyricsPlugin() + + @patch.object(lyrics.Backend, 'fetch_url', MockFetchUrl()) def test_mocked_source_ok(self): """Test that lyrics of the mocked page are correctly scraped""" url = self.source['url'] + self.source['path'] - if os.path.isfile(url_to_filename(url)): - res = lyrics.scrape_lyrics_from_html(raw_backend.fetch_url(url)) - self.assertTrue(google.is_lyrics(res), url) - self.assertTrue(is_lyrics_content_ok(self.source['title'], res), - url) - - def test_google_sources_ok(self): - """Test if lyrics present on websites registered in beets google custom - search engine are correctly scraped.""" - if not check_lyrics_fetched(): - self.skipTest("Run lyrics_download_samples.py script first.") - for s in GOOGLE_SOURCES: - url = s['url'] + s['path'] - if os.path.isfile(url_to_filename(url)): - res = lyrics.scrape_lyrics_from_html( - raw_backend.fetch_url(url)) - self.assertTrue(google.is_lyrics(res), url) - self.assertTrue(is_lyrics_content_ok(s['title'], res), url) - - def test_default_ok(self): - """Test default engines with the default query""" - if not check_lyrics_fetched(): - self.skipTest("Run lyrics_download_samples.py script first.") - for (source, s) in zip([lyrics.LyricsWiki, - lyrics.LyricsCom, - lyrics.MusiXmatch], DEFAULT_SOURCES): - url = s['url'] + s['path'] - if os.path.isfile(url_to_filename(url)): - res = source({}, log).fetch(s['artist'], s['title']) - self.assertTrue(google.is_lyrics(res), url) - self.assertTrue(is_lyrics_content_ok(s['title'], res), url) + res = lyrics.scrape_lyrics_from_html(raw_backend.fetch_url(url)) + self.assertTrue(google.is_lyrics(res), url) + self.assertTrue(is_lyrics_content_ok(self.source['title'], res), + url) + @patch.object(lyrics.Backend, 'fetch_url', MockFetchUrl()) def test_is_page_candidate_exact_match(self): """Test matching html page title with song infos -- when song infos are - present in the title.""" + present in the title. + """ from bs4 import SoupStrainer, BeautifulSoup s = self.source - url = unicode(s['url'] + s['path']) + url = six.text_type(s['url'] + s['path']) html = raw_backend.fetch_url(url) soup = BeautifulSoup(html, "html.parser", parse_only=SoupStrainer('title')) - self.assertEqual(google.is_page_candidate(url, soup.title.string, - s['title'], s['artist']), - True, url) + self.assertEqual( + google.is_page_candidate(url, soup.title.string, + s['title'], s['artist']), True, url) def test_is_page_candidate_fuzzy_match(self): """Test matching html page title with song infos -- when song infos are - not present in the title.""" + not present in the title. + """ s = self.source url = s['url'] + s['path'] - urlTitle = u'example.com | Beats song by John doe' + url_title = u'example.com | Beats song by John doe' # very small diffs (typo) are ok eg 'beats' vs 'beets' with same artist - self.assertEqual(google.is_page_candidate(url, urlTitle, s['title'], - s['artist']), True, url) + self.assertEqual(google.is_page_candidate(url, url_title, s['title'], + s['artist']), True, url) # reject different title - urlTitle = u'example.com | seets bong lyrics by John doe' - self.assertEqual(google.is_page_candidate(url, urlTitle, s['title'], - s['artist']), False, url) + url_title = u'example.com | seets bong lyrics by John doe' + self.assertEqual(google.is_page_candidate(url, url_title, s['title'], + s['artist']), False, url) + + def test_is_page_candidate_special_chars(self): + """Ensure that `is_page_candidate` doesn't crash when the artist + and such contain special regular expression characters. + """ + # https://github.com/beetbox/beets/issues/1673 + s = self.source + url = s['url'] + s['path'] + url_title = u'foo' + + google.is_page_candidate(url, url_title, s['title'], u'Sunn O)))') + + +class SlugTests(unittest.TestCase): + + def test_slug(self): + # plain ascii passthrough + text = u"test" + self.assertEqual(lyrics.slug(text), 'test') + # german unicode and capitals + text = u"Mørdag" + self.assertEqual(lyrics.slug(text), 'mordag') + # more accents and quotes + text = u"l'été c'est fait pour jouer" + self.assertEqual(lyrics.slug(text), 'l-ete-c-est-fait-pour-jouer') + # accents, parens and spaces + text = u"\xe7afe au lait (boisson)" + self.assertEqual(lyrics.slug(text), 'cafe-au-lait-boisson') + text = u"Multiple spaces -- and symbols! -- merged" + self.assertEqual(lyrics.slug(text), + 'multiple-spaces-and-symbols-merged') def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_mb.py b/test/test_mb.py index 7662e0722..644e7f5de 100644 --- a/test/test_mb.py +++ b/test/test_mb.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,19 +15,19 @@ """Tests for MusicBrainz API wrapper. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from test import _common -from test._common import unittest from beets.autotag import mb from beets import config + +import unittest import mock class MBAlbumInfoTest(_common.TestCase): def _make_release(self, date_str='2009', tracks=None, track_length=None, - track_artist=False): + track_artist=False, medium_format='FORMAT'): release = { 'title': 'ALBUM TITLE', 'id': 'ALBUM ID', @@ -66,7 +67,8 @@ class MBAlbumInfoTest(_common.TestCase): for i, recording in enumerate(tracks): track = { 'recording': recording, - 'position': bytes(i + 1), + 'position': i + 1, + 'number': 'A1', } if track_length: # Track lengths are distinct from recording lengths. @@ -88,12 +90,12 @@ class MBAlbumInfoTest(_common.TestCase): release['medium-list'].append({ 'position': '1', 'track-list': track_list, - 'format': 'FORMAT', + 'format': medium_format, 'title': 'MEDIUM TITLE', }) return release - def _make_track(self, title, tr_id, duration, artist=False): + def _make_track(self, title, tr_id, duration, artist=False, video=False): track = { 'title': title, 'id': tr_id, @@ -111,6 +113,8 @@ class MBAlbumInfoTest(_common.TestCase): 'name': 'RECORDING ARTIST CREDIT', } ] + if video: + track['video'] = 'true' return track def test_parse_release_with_year(self): @@ -181,6 +185,7 @@ class MBAlbumInfoTest(_common.TestCase): second_track_list = [{ 'recording': tracks[1], 'position': '1', + 'number': 'A1', }] release['medium-list'].append({ 'position': '2', @@ -321,6 +326,58 @@ class MBAlbumInfoTest(_common.TestCase): d = mb.album_info(release) self.assertEqual(d.data_source, 'MusicBrainz') + def test_ignored_media(self): + config['match']['ignored_media'] = ['IGNORED1', 'IGNORED2'] + tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0), + self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)] + release = self._make_release(tracks=tracks, medium_format="IGNORED1") + d = mb.album_info(release) + self.assertEqual(len(d.tracks), 0) + + def test_no_ignored_media(self): + config['match']['ignored_media'] = ['IGNORED1', 'IGNORED2'] + tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0), + self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)] + release = self._make_release(tracks=tracks, + medium_format="NON-IGNORED") + d = mb.album_info(release) + self.assertEqual(len(d.tracks), 2) + + def test_skip_data_track(self): + tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0), + self._make_track('[data track]', 'ID DATA TRACK', + 100.0 * 1000.0), + self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)] + release = self._make_release(tracks=tracks) + d = mb.album_info(release) + self.assertEqual(len(d.tracks), 2) + self.assertEqual(d.tracks[0].title, 'TITLE ONE') + self.assertEqual(d.tracks[1].title, 'TITLE TWO') + + def test_skip_video_tracks_by_default(self): + tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0), + self._make_track('TITLE VIDEO', 'ID VIDEO', 100.0 * 1000.0, + False, True), + self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)] + release = self._make_release(tracks=tracks) + d = mb.album_info(release) + self.assertEqual(len(d.tracks), 2) + self.assertEqual(d.tracks[0].title, 'TITLE ONE') + self.assertEqual(d.tracks[1].title, 'TITLE TWO') + + def test_no_skip_video_tracks_if_configured(self): + config['match']['ignore_video_tracks'] = False + tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0), + self._make_track('TITLE VIDEO', 'ID VIDEO', 100.0 * 1000.0, + False, True), + self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)] + release = self._make_release(tracks=tracks) + d = mb.album_info(release) + self.assertEqual(len(d.tracks), 3) + self.assertEqual(d.tracks[0].title, 'TITLE ONE') + self.assertEqual(d.tracks[1].title, 'TITLE VIDEO') + self.assertEqual(d.tracks[2].title, 'TITLE TWO') + class ParseIDTest(_common.TestCase): def test_parse_id_correct(self): @@ -453,6 +510,7 @@ class MBLibraryTest(unittest.TestCase): 'length': 42, }, 'position': 9, + 'number': 'A1', }], 'position': 5, }], @@ -491,5 +549,5 @@ class MBLibraryTest(unittest.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_mbsubmit.py b/test/test_mbsubmit.py new file mode 100644 index 000000000..3402c8464 --- /dev/null +++ b/test/test_mbsubmit.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Adrian Sampson and Diego Moreda. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +from __future__ import division, absolute_import, print_function + +import unittest +from test.helper import capture_stdout, control_stdin, TestHelper +from test.test_importer import ImportHelper, AutotagStub +from test.test_ui_importer import TerminalImportSessionSetup + + +class MBSubmitPluginTest(TerminalImportSessionSetup, unittest.TestCase, + ImportHelper, TestHelper): + def setUp(self): + self.setup_beets() + self.load_plugins('mbsubmit') + self._create_import_dir(2) + self._setup_import_session() + self.matcher = AutotagStub().install() + + def tearDown(self): + self.unload_plugins() + self.teardown_beets() + self.matcher.restore() + + def test_print_tracks_output(self): + """Test the output of the "print tracks" choice.""" + self.matcher.matching = AutotagStub.BAD + + with capture_stdout() as output: + with control_stdin('\n'.join(['p', 's'])): + # Print tracks; Skip + self.importer.run() + + # Manually build the string for comparing the output. + tracklist = (u'Print tracks? ' + u'01. Tag Title 1 - Tag Artist (0:01)\n' + u'02. Tag Title 2 - Tag Artist (0:01)') + self.assertIn(tracklist, output.getvalue()) + + def test_print_tracks_output_as_tracks(self): + """Test the output of the "print tracks" choice, as singletons.""" + self.matcher.matching = AutotagStub.BAD + + with capture_stdout() as output: + with control_stdin('\n'.join(['t', 's', 'p', 's'])): + # as Tracks; Skip; Print tracks; Skip + self.importer.run() + + # Manually build the string for comparing the output. + tracklist = (u'Print tracks? ' + u'02. Tag Title 2 - Tag Artist (0:01)') + self.assertIn(tracklist, output.getvalue()) + + +def suite(): + return unittest.TestLoader().loadTestsFromName(__name__) + +if __name__ == '__main__': + unittest.main(defaultTest='suite') diff --git a/test/test_mbsync.py b/test/test_mbsync.py index ff6e01cf3..411af8d0a 100644 --- a/test/test_mbsync.py +++ b/test/test_mbsync.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,12 +13,11 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function +import unittest from mock import patch -from test._common import unittest from test.helper import TestHelper,\ generate_album_info, \ generate_track_info, \ @@ -43,20 +43,20 @@ class MbsyncCliTest(unittest.TestCase, TestHelper): album_for_mbid.return_value = \ generate_album_info('album id', ['track id']) track_for_mbid.return_value = \ - generate_track_info('singleton track id', - {'title': 'singleton info'}) + generate_track_info(u'singleton track id', + {'title': u'singleton info'}) album_item = Item( - album='old title', - mb_albumid='album id', - mb_trackid='track id', + album=u'old title', + mb_albumid=u'album id', + mb_trackid=u'track id', path='' ) album = self.lib.add_album([album_item]) item = Item( - title='old title', - mb_trackid='singleton track id', + title=u'old title', + mb_trackid=u'singleton track id', path='', ) self.lib.add(item) @@ -64,24 +64,24 @@ class MbsyncCliTest(unittest.TestCase, TestHelper): self.run_command('mbsync') item.load() - self.assertEqual(item.title, 'singleton info') + self.assertEqual(item.title, u'singleton info') album_item.load() - self.assertEqual(album_item.title, 'track info') + self.assertEqual(album_item.title, u'track info') album.load() - self.assertEqual(album.album, 'album info') + self.assertEqual(album.album, u'album info') def test_message_when_skipping(self): - config['format_item'] = '$artist - $album - $title' - config['format_album'] = '$albumartist - $album' + config['format_item'] = u'$artist - $album - $title' + config['format_album'] = u'$albumartist - $album' # Test album with no mb_albumid. # The default format for an album include $albumartist so # set that here, too. album_invalid = Item( - albumartist='album info', - album='album info', + albumartist=u'album info', + album=u'album info', path='' ) self.lib.add_album([album_invalid]) @@ -89,27 +89,27 @@ class MbsyncCliTest(unittest.TestCase, TestHelper): # default format with capture_log('beets.mbsync') as logs: self.run_command('mbsync') - e = 'mbsync: Skipping album with no mb_albumid: ' + \ - 'album info - album info' + e = u'mbsync: Skipping album with no mb_albumid: ' + \ + u'album info - album info' self.assertEqual(e, logs[0]) # custom format with capture_log('beets.mbsync') as logs: self.run_command('mbsync', '-f', "'$album'") - e = "mbsync: Skipping album with no mb_albumid: 'album info'" + e = u"mbsync: Skipping album with no mb_albumid: 'album info'" self.assertEqual(e, logs[0]) # restore the config - config['format_item'] = '$artist - $album - $title' - config['format_album'] = '$albumartist - $album' + config['format_item'] = u'$artist - $album - $title' + config['format_album'] = u'$albumartist - $album' # Test singleton with no mb_trackid. # The default singleton format includes $artist and $album # so we need to stub them here item_invalid = Item( - artist='album info', - album='album info', - title='old title', + artist=u'album info', + album=u'album info', + title=u'old title', path='', ) self.lib.add(item_invalid) @@ -117,19 +117,19 @@ class MbsyncCliTest(unittest.TestCase, TestHelper): # default format with capture_log('beets.mbsync') as logs: self.run_command('mbsync') - e = 'mbsync: Skipping singleton with no mb_trackid: ' + \ - 'album info - album info - old title' + e = u'mbsync: Skipping singleton with no mb_trackid: ' + \ + u'album info - album info - old title' self.assertEqual(e, logs[0]) # custom format with capture_log('beets.mbsync') as logs: self.run_command('mbsync', '-f', "'$title'") - e = "mbsync: Skipping singleton with no mb_trackid: 'old title'" + e = u"mbsync: Skipping singleton with no mb_trackid: 'old title'" self.assertEqual(e, logs[0]) def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_mediafile.py b/test/test_mediafile.py index cd149e7e4..5a004b7e8 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,22 +16,18 @@ """Automatically-generated blanket testing for the MediaFile metadata layer. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import os import shutil -import tempfile import datetime import time +import unittest +from six import assertCountEqual from test import _common -from test._common import unittest -from beets.mediafile import MediaFile, MediaField, Image, \ - MP3DescStorageStyle, StorageStyle, MP4StorageStyle, \ - ASFStorageStyle, ImageType, CoverArtField -from beets.library import Item -from beets.plugins import BeetsPlugin +from beets.mediafile import MediaFile, Image, \ + ImageType, CoverArtField, UnreadableFileError class ArtTestMixin(object): @@ -40,7 +37,8 @@ class ArtTestMixin(object): @property def png_data(self): if not self._png_data: - with open(os.path.join(_common.RSRC, 'image-2x3.png'), 'rb') as f: + image_file = os.path.join(_common.RSRC, b'image-2x3.png') + with open(image_file, 'rb') as f: self._png_data = f.read() return self._png_data _png_data = None @@ -48,7 +46,8 @@ class ArtTestMixin(object): @property def jpg_data(self): if not self._jpg_data: - with open(os.path.join(_common.RSRC, 'image-2x3.jpg'), 'rb') as f: + image_file = os.path.join(_common.RSRC, b'image-2x3.jpg') + with open(image_file, 'rb') as f: self._jpg_data = f.read() return self._jpg_data _jpg_data = None @@ -56,7 +55,8 @@ class ArtTestMixin(object): @property def tiff_data(self): if not self._jpg_data: - with open(os.path.join(_common.RSRC, 'image-2x3.tiff'), 'rb') as f: + image_file = os.path.join(_common.RSRC, b'image-2x3.tiff') + with open(image_file, 'rb') as f: self._jpg_data = f.read() return self._jpg_data _jpg_data = None @@ -108,18 +108,18 @@ class ImageStructureTestMixin(ArtTestMixin): image = next(i for i in mediafile.images if i.mime_type == 'image/png') self.assertEqual(image.data, self.png_data) - self.assertExtendedImageAttributes(image, desc='album cover', + self.assertExtendedImageAttributes(image, desc=u'album cover', type=ImageType.front) image = next(i for i in mediafile.images if i.mime_type == 'image/jpeg') self.assertEqual(image.data, self.jpg_data) - self.assertExtendedImageAttributes(image, desc='the artist', + self.assertExtendedImageAttributes(image, desc=u'the artist', type=ImageType.artist) def test_set_image_structure(self): mediafile = self._mediafile_fixture('empty') - image = Image(data=self.png_data, desc='album cover', + image = Image(data=self.png_data, desc=u'album cover', type=ImageType.front) mediafile.images = [image] mediafile.save() @@ -130,14 +130,14 @@ class ImageStructureTestMixin(ArtTestMixin): image = mediafile.images[0] self.assertEqual(image.data, self.png_data) self.assertEqual(image.mime_type, 'image/png') - self.assertExtendedImageAttributes(image, desc='album cover', + self.assertExtendedImageAttributes(image, desc=u'album cover', type=ImageType.front) def test_add_image_structure(self): mediafile = self._mediafile_fixture('image') self.assertEqual(len(mediafile.images), 2) - image = Image(data=self.png_data, desc='the composer', + image = Image(data=self.png_data, desc=u'the composer', type=ImageType.composer) mediafile.images += [image] mediafile.save() @@ -145,10 +145,10 @@ class ImageStructureTestMixin(ArtTestMixin): mediafile = MediaFile(mediafile.path) self.assertEqual(len(mediafile.images), 3) - images = (i for i in mediafile.images if i.desc == 'the composer') + images = (i for i in mediafile.images if i.desc == u'the composer') image = next(images, None) self.assertExtendedImageAttributes( - image, desc='the composer', type=ImageType.composer + image, desc=u'the composer', type=ImageType.composer ) def test_delete_image_structures(self): @@ -165,19 +165,23 @@ class ImageStructureTestMixin(ArtTestMixin): mediafile = self._mediafile_fixture('image') self.assertEqual(len(mediafile.images), 2) cover = CoverArtField.guess_cover_image(mediafile.images) - self.assertEqual(cover.desc, 'album cover') + self.assertEqual(cover.desc, u'album cover') self.assertEqual(mediafile.art, cover.data) - def assertExtendedImageAttributes(self, image, **kwargs): + def assertExtendedImageAttributes(self, image, **kwargs): # noqa """Ignore extended image attributes in the base tests. """ pass class ExtendedImageStructureTestMixin(ImageStructureTestMixin): - """Checks for additional attributes in the image structure.""" + """Checks for additional attributes in the image structure. - def assertExtendedImageAttributes(self, image, desc=None, type=None): + Like the base `ImageStructureTestMixin`, per-format test classes + should include this mixin to add image-related tests. + """ + + def assertExtendedImageAttributes(self, image, desc=None, type=None): # noqa self.assertEqual(image.desc, desc) self.assertEqual(image.type, type) @@ -185,7 +189,7 @@ class ExtendedImageStructureTestMixin(ImageStructureTestMixin): mediafile = self._mediafile_fixture('image') self.assertEqual(len(mediafile.images), 2) - image = Image(data=self.tiff_data, desc='the composer', + image = Image(data=self.tiff_data, desc=u'the composer', type=ImageType.composer) mediafile.images += [image] mediafile.save() @@ -194,17 +198,17 @@ class ExtendedImageStructureTestMixin(ImageStructureTestMixin): self.assertEqual(len(mediafile.images), 3) # WMA does not preserve the order, so we have to work around this - image = filter(lambda i: i.mime_type == 'image/tiff', - mediafile.images)[0] + image = list(filter(lambda i: i.mime_type == 'image/tiff', + mediafile.images))[0] self.assertExtendedImageAttributes( - image, desc='the composer', type=ImageType.composer) + image, desc=u'the composer', type=ImageType.composer) class LazySaveTestMixin(object): """Mediafile should only write changes when tags have changed """ - @unittest.skip('not yet implemented') + @unittest.skip(u'not yet implemented') def test_unmodified(self): mediafile = self._mediafile_fixture('full') mtime = self._set_past_mtime(mediafile.path) @@ -213,7 +217,7 @@ class LazySaveTestMixin(object): mediafile.save() self.assertEqual(os.stat(mediafile.path).st_mtime, mtime) - @unittest.skip('not yet implemented') + @unittest.skip(u'not yet implemented') def test_same_tag_value(self): mediafile = self._mediafile_fixture('full') mtime = self._set_past_mtime(mediafile.path) @@ -232,14 +236,14 @@ class LazySaveTestMixin(object): mediafile.save() self.assertEqual(os.stat(mediafile.path).st_mtime, mtime) - @unittest.skip('not yet implemented') + @unittest.skip(u'not yet implemented') def test_tag_value_change(self): mediafile = self._mediafile_fixture('full') mtime = self._set_past_mtime(mediafile.path) self.assertEqual(os.stat(mediafile.path).st_mtime, mtime) mediafile.title = mediafile.title - mediafile.album = 'another' + mediafile.album = u'another' mediafile.save() self.assertNotEqual(os.stat(mediafile.path).st_mtime, mtime) @@ -248,7 +252,7 @@ class LazySaveTestMixin(object): mtime = self._set_past_mtime(mediafile.path) self.assertEqual(os.stat(mediafile.path).st_mtime, mtime) - mediafile.update({'title': mediafile.title, 'album': 'another'}) + mediafile.update({'title': mediafile.title, 'album': u'another'}) mediafile.save() self.assertNotEqual(os.stat(mediafile.path).st_mtime, mtime) @@ -264,7 +268,7 @@ class GenreListTestMixin(object): def test_read_genre_list(self): mediafile = self._mediafile_fixture('full') - self.assertItemsEqual(mediafile.genres, ['the genre']) + assertCountEqual(self, mediafile.genres, ['the genre']) def test_write_genre_list(self): mediafile = self._mediafile_fixture('empty') @@ -272,7 +276,7 @@ class GenreListTestMixin(object): mediafile.save() mediafile = MediaFile(mediafile.path) - self.assertItemsEqual(mediafile.genres, ['one', 'two']) + assertCountEqual(self, mediafile.genres, [u'one', u'two']) def test_write_genre_list_get_first(self): mediafile = self._mediafile_fixture('empty') @@ -280,87 +284,37 @@ class GenreListTestMixin(object): mediafile.save() mediafile = MediaFile(mediafile.path) - self.assertEqual(mediafile.genre, 'one') + self.assertEqual(mediafile.genre, u'one') def test_append_genre_list(self): mediafile = self._mediafile_fixture('full') - self.assertEqual(mediafile.genre, 'the genre') + self.assertEqual(mediafile.genre, u'the genre') mediafile.genres += [u'another'] mediafile.save() mediafile = MediaFile(mediafile.path) - self.assertItemsEqual(mediafile.genres, [u'the genre', u'another']) - - -field_extension = MediaField( - MP3DescStorageStyle(b'customtag'), - MP4StorageStyle(b'----:com.apple.iTunes:customtag'), - StorageStyle(b'customtag'), - ASFStorageStyle(b'customtag'), -) - - -class ExtendedFieldTestMixin(object): - - def test_extended_field_write(self): - plugin = BeetsPlugin() - plugin.add_media_field('customtag', field_extension) - - mediafile = self._mediafile_fixture('empty') - mediafile.customtag = 'F#' - mediafile.save() - - mediafile = MediaFile(mediafile.path) - self.assertEqual(mediafile.customtag, 'F#') - delattr(MediaFile, 'customtag') - Item._media_fields.remove('customtag') - - def test_write_extended_tag_from_item(self): - plugin = BeetsPlugin() - plugin.add_media_field('customtag', field_extension) - - mediafile = self._mediafile_fixture('empty') - self.assertIsNone(mediafile.customtag) - - item = Item(path=mediafile.path, customtag='Gb') - item.write() - mediafile = MediaFile(mediafile.path) - self.assertEqual(mediafile.customtag, 'Gb') - - delattr(MediaFile, 'customtag') - Item._media_fields.remove('customtag') - - def test_read_flexible_attribute_from_file(self): - plugin = BeetsPlugin() - plugin.add_media_field('customtag', field_extension) - - mediafile = self._mediafile_fixture('empty') - mediafile.update({'customtag': 'F#'}) - mediafile.save() - - item = Item.from_path(mediafile.path) - self.assertEqual(item['customtag'], 'F#') - - delattr(MediaFile, 'customtag') - Item._media_fields.remove('customtag') - - def test_invalid_descriptor(self): - with self.assertRaises(ValueError) as cm: - MediaFile.add_field('somekey', True) - self.assertIn('must be an instance of MediaField', - unicode(cm.exception)) - - def test_overwrite_property(self): - with self.assertRaises(ValueError) as cm: - MediaFile.add_field('artist', MediaField()) - self.assertIn('property "artist" already exists', - unicode(cm.exception)) + assertCountEqual(self, mediafile.genres, [u'the genre', u'another']) class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, - ExtendedFieldTestMixin): - """Test writing and reading tags. Subclasses must set ``extension`` and - ``audio_properties``. + _common.TempDirMixin): + """Test writing and reading tags. Subclasses must set ``extension`` + and ``audio_properties``. + + The basic tests for all audio formats encompass three files provided + in our `rsrc` folder: `full.*`, `empty.*`, and `unparseable.*`. + Respectively, they should contain a full slate of common fields + listed in `full_initial_tags` below; no fields contents at all; and + an unparseable release date field. + + To add support for a new file format to MediaFile, add these three + files and then create a `ReadWriteTestBase` subclass by copying n' + pasting one of the existing subclasses below. You will want to + update the `format` field in that subclass, and you will probably + need to fiddle with the `bitrate` and other format-specific fields. + + You can also add image tests (using an additional `image.*` fixture + file) by including one of the image-related mixins. """ full_initial_tags = { @@ -394,7 +348,10 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, 'artist', 'album', 'genre', + 'lyricist', 'composer', + 'composer_sort', + 'arranger', 'grouping', 'year', 'month', @@ -417,6 +374,8 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, 'rg_track_gain', 'rg_album_peak', 'rg_album_gain', + 'r128_track_gain', + 'r128_album_gain', 'albumartist', 'mb_albumartistid', 'artist_sort', @@ -443,11 +402,31 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, ] def setUp(self): - self.temp_dir = tempfile.mkdtemp() + self.create_temp_dir() def tearDown(self): - if os.path.isdir(self.temp_dir): - shutil.rmtree(self.temp_dir) + self.remove_temp_dir() + + def test_read_nonexisting(self): + mediafile = self._mediafile_fixture('full') + os.remove(mediafile.path) + self.assertRaises(UnreadableFileError, MediaFile, mediafile.path) + + def test_save_nonexisting(self): + mediafile = self._mediafile_fixture('full') + os.remove(mediafile.path) + try: + mediafile.save() + except UnreadableFileError: + pass + + def test_delete_nonexisting(self): + mediafile = self._mediafile_fixture('full') + os.remove(mediafile.path) + try: + mediafile.delete() + except UnreadableFileError: + pass def test_read_audio_properties(self): mediafile = self._mediafile_fixture('full') @@ -597,6 +576,9 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, self.assertEqual(mediafile.disctotal, None) def test_unparseable_date(self): + """The `unparseable.*` fixture should not crash but should return None + for all parts of the release date. + """ mediafile = self._mediafile_fixture('unparseable') self.assertIsNone(mediafile.date) @@ -660,22 +642,24 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, self.assertIsNone(mediafile.date) self.assertIsNone(mediafile.year) - def assertTags(self, mediafile, tags): + def assertTags(self, mediafile, tags): # noqa errors = [] for key, value in tags.items(): try: value2 = getattr(mediafile, key) except AttributeError: - errors.append('Tag %s does not exist' % key) + errors.append(u'Tag %s does not exist' % key) else: if value2 != value: - errors.append('Tag %s: %r != %r' % (key, value2, value)) + errors.append(u'Tag %s: %r != %r' % (key, value2, value)) if any(errors): - errors = ['Tags did not match'] + errors + errors = [u'Tags did not match'] + errors self.fail('\n '.join(errors)) def _mediafile_fixture(self, name): name = name + '.' + self.extension + if not isinstance(name, bytes): + name = name.encode('utf8') src = os.path.join(_common.RSRC, name) target = os.path.join(self.temp_dir, name) shutil.copy(src, target) @@ -690,8 +674,11 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, if key.startswith('rg_'): # ReplayGain is float tags[key] = 1.0 + elif key.startswith('r128_'): + # R128 is int + tags[key] = -1 else: - tags[key] = b'value\u2010%s' % key + tags[key] = 'value\u2010%s' % key for key in ['disc', 'disctotal', 'track', 'tracktotal', 'bpm']: tags[key] = 1 @@ -787,7 +774,7 @@ class MusepackTest(ReadWriteTestBase, unittest.TestCase): audio_properties = { 'length': 1.0, 'bitrate': 23458, - 'format': 'Musepack', + 'format': u'Musepack', 'samplerate': 44100, 'bitdepth': 0, 'channels': 2, @@ -800,7 +787,7 @@ class WMATest(ReadWriteTestBase, ExtendedImageStructureTestMixin, audio_properties = { 'length': 1.0, 'bitrate': 128000, - 'format': 'Windows Media', + 'format': u'Windows Media', 'samplerate': 44100, 'bitdepth': 0, 'channels': 1, @@ -817,9 +804,9 @@ class WMATest(ReadWriteTestBase, ExtendedImageStructureTestMixin, def test_read_pure_tags(self): mediafile = self._mediafile_fixture('pure') - self.assertEqual(mediafile.comments, 'the comments') - self.assertEqual(mediafile.title, 'the title') - self.assertEqual(mediafile.artist, 'the artist') + self.assertEqual(mediafile.comments, u'the comments') + self.assertEqual(mediafile.title, u'the title') + self.assertEqual(mediafile.artist, u'the artist') class OggTest(ReadWriteTestBase, ExtendedImageStructureTestMixin, @@ -828,7 +815,7 @@ class OggTest(ReadWriteTestBase, ExtendedImageStructureTestMixin, audio_properties = { 'length': 1.0, 'bitrate': 48000, - 'format': 'OGG', + 'format': u'OGG', 'samplerate': 44100, 'bitdepth': 0, 'channels': 1, @@ -871,8 +858,8 @@ class FlacTest(ReadWriteTestBase, PartialTestMixin, extension = 'flac' audio_properties = { 'length': 1.0, - 'bitrate': 175120, - 'format': 'FLAC', + 'bitrate': 108688, + 'format': u'FLAC', 'samplerate': 44100, 'bitdepth': 16, 'channels': 1, @@ -885,7 +872,7 @@ class ApeTest(ReadWriteTestBase, ExtendedImageStructureTestMixin, audio_properties = { 'length': 1.0, 'bitrate': 112040, - 'format': 'APE', + 'format': u'APE', 'samplerate': 44100, 'bitdepth': 16, 'channels': 1, @@ -897,7 +884,7 @@ class WavpackTest(ReadWriteTestBase, unittest.TestCase): audio_properties = { 'length': 1.0, 'bitrate': 108744, - 'format': 'WavPack', + 'format': u'WavPack', 'samplerate': 44100, 'bitdepth': 0, 'channels': 1, @@ -909,7 +896,7 @@ class OpusTest(ReadWriteTestBase, unittest.TestCase): audio_properties = { 'length': 1.0, 'bitrate': 57984, - 'format': 'Opus', + 'format': u'Opus', 'samplerate': 48000, 'bitdepth': 0, 'channels': 1, @@ -921,23 +908,46 @@ class AIFFTest(ReadWriteTestBase, unittest.TestCase): audio_properties = { 'length': 1.0, 'bitrate': 705600, - 'format': 'AIFF', + 'format': u'AIFF', 'samplerate': 44100, 'bitdepth': 0, 'channels': 1, } +# Check whether we have a Mutagen version with DSF support. We can +# remove this once we require a version that includes the feature. +try: + import mutagen.dsf # noqa +except ImportError: + HAVE_DSF = False +else: + HAVE_DSF = True + + +@unittest.skipIf(not HAVE_DSF, "Mutagen does not have DSF support") +class DSFTest(ReadWriteTestBase, unittest.TestCase): + extension = 'dsf' + audio_properties = { + 'length': 0.01, + 'bitrate': 11289600, + 'format': u'DSD Stream File', + 'samplerate': 5644800, + 'bitdepth': 1, + 'channels': 2, + } + + class MediaFieldTest(unittest.TestCase): def test_properties_from_fields(self): - path = os.path.join(_common.RSRC, 'full.mp3') + path = os.path.join(_common.RSRC, b'full.mp3') mediafile = MediaFile(path) for field in MediaFile.fields(): self.assertTrue(hasattr(mediafile, field)) def test_properties_from_readable_fields(self): - path = os.path.join(_common.RSRC, 'full.mp3') + path = os.path.join(_common.RSRC, b'full.mp3') mediafile = MediaFile(path) for field in MediaFile.readable_fields(): self.assertTrue(hasattr(mediafile, field)) @@ -945,7 +955,7 @@ class MediaFieldTest(unittest.TestCase): def test_known_fields(self): fields = list(ReadWriteTestBase.tag_fields) fields.extend(('encoder', 'images', 'genres', 'albumtype')) - self.assertItemsEqual(MediaFile.fields(), fields) + assertCountEqual(self, MediaFile.fields(), fields) def test_fields_in_readable_fields(self): readable = MediaFile.readable_fields() @@ -956,5 +966,5 @@ class MediaFieldTest(unittest.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 7a17fe86a..8bf9e1916 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,19 +15,20 @@ """Specific, edge-case tests for the MediaFile metadata layer. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import os import shutil +import unittest +import mutagen.id3 from test import _common -from test._common import unittest -from test.helper import TestHelper -import beets.mediafile + +from beets import mediafile +import six -_sc = beets.mediafile._safe_cast +_sc = mediafile._safe_cast class EdgeTest(unittest.TestCase): @@ -34,8 +36,8 @@ class EdgeTest(unittest.TestCase): # Some files have an ID3 frame that has a list with no elements. # This is very hard to produce, so this is just the first 8192 # bytes of a file found "in the wild". - emptylist = beets.mediafile.MediaFile( - os.path.join(_common.RSRC, 'emptylist.mp3') + emptylist = mediafile.MediaFile( + os.path.join(_common.RSRC, b'emptylist.mp3') ) genre = emptylist.genre self.assertEqual(genre, None) @@ -43,8 +45,8 @@ class EdgeTest(unittest.TestCase): def test_release_time_with_space(self): # Ensures that release times delimited by spaces are ignored. # Amie Street produces such files. - space_time = beets.mediafile.MediaFile( - os.path.join(_common.RSRC, 'space_time.mp3') + space_time = mediafile.MediaFile( + os.path.join(_common.RSRC, b'space_time.mp3') ) self.assertEqual(space_time.year, 2009) self.assertEqual(space_time.month, 9) @@ -53,8 +55,8 @@ class EdgeTest(unittest.TestCase): def test_release_time_with_t(self): # Ensures that release times delimited by Ts are ignored. # The iTunes Store produces such files. - t_time = beets.mediafile.MediaFile( - os.path.join(_common.RSRC, 't_time.m4a') + t_time = mediafile.MediaFile( + os.path.join(_common.RSRC, b't_time.m4a') ) self.assertEqual(t_time.year, 1987) self.assertEqual(t_time.month, 3) @@ -63,19 +65,20 @@ class EdgeTest(unittest.TestCase): def test_tempo_with_bpm(self): # Some files have a string like "128 BPM" in the tempo field # rather than just a number. - f = beets.mediafile.MediaFile(os.path.join(_common.RSRC, 'bpm.mp3')) + f = mediafile.MediaFile(os.path.join(_common.RSRC, b'bpm.mp3')) self.assertEqual(f.bpm, 128) def test_discc_alternate_field(self): # Different taggers use different vorbis comments to reflect # the disc and disc count fields: ensure that the alternative # style works. - f = beets.mediafile.MediaFile(os.path.join(_common.RSRC, 'discc.ogg')) + f = mediafile.MediaFile(os.path.join(_common.RSRC, b'discc.ogg')) self.assertEqual(f.disc, 4) self.assertEqual(f.disctotal, 5) def test_old_ape_version_bitrate(self): - f = beets.mediafile.MediaFile(os.path.join(_common.RSRC, 'oldape.ape')) + media_file = os.path.join(_common.RSRC, b'oldape.ape') + f = mediafile.MediaFile(media_file) self.assertEqual(f.bitrate, 0) def test_only_magic_bytes_jpeg(self): @@ -83,50 +86,68 @@ class EdgeTest(unittest.TestCase): # such aren't recognized by imghdr. Ensure that this still works thanks # to our own follow up mimetype detection based on # https://github.com/file/file/blob/master/magic/Magdir/jpeg#L12 - f = open(os.path.join(_common.RSRC, 'only-magic-bytes.jpg'), 'rb') - jpg_data = f.read() + magic_bytes_file = os.path.join(_common.RSRC, b'only-magic-bytes.jpg') + with open(magic_bytes_file, 'rb') as f: + jpg_data = f.read() self.assertEqual( - beets.mediafile._image_mime_type(jpg_data), - 'image/jpeg') + mediafile._imghdr_what_wrapper(jpg_data), 'jpeg') + + def test_soundcheck_non_ascii(self): + # Make sure we don't crash when the iTunes SoundCheck field contains + # non-ASCII binary data. + f = mediafile.MediaFile(os.path.join(_common.RSRC, + b'soundcheck-nonascii.m4a')) + self.assertEqual(f.rg_track_gain, 0.0) class InvalidValueToleranceTest(unittest.TestCase): def test_safe_cast_string_to_int(self): - self.assertEqual(_sc(int, 'something'), 0) + self.assertEqual(_sc(int, u'something'), 0) + + def test_safe_cast_string_to_int_with_no_numbers(self): + self.assertEqual(_sc(int, u'-'), 0) def test_safe_cast_int_string_to_int(self): - self.assertEqual(_sc(int, '20'), 20) + self.assertEqual(_sc(int, u'20'), 20) def test_safe_cast_string_to_bool(self): - self.assertEqual(_sc(bool, 'whatever'), False) + self.assertEqual(_sc(bool, u'whatever'), False) def test_safe_cast_intstring_to_bool(self): - self.assertEqual(_sc(bool, '5'), True) + self.assertEqual(_sc(bool, u'5'), True) def test_safe_cast_string_to_float(self): - self.assertAlmostEqual(_sc(float, '1.234'), 1.234) + self.assertAlmostEqual(_sc(float, u'1.234'), 1.234) def test_safe_cast_int_to_float(self): self.assertAlmostEqual(_sc(float, 2), 2.0) def test_safe_cast_string_with_cruft_to_float(self): - self.assertAlmostEqual(_sc(float, '1.234stuff'), 1.234) + self.assertAlmostEqual(_sc(float, u'1.234stuff'), 1.234) def test_safe_cast_negative_string_to_float(self): - self.assertAlmostEqual(_sc(float, '-1.234'), -1.234) + self.assertAlmostEqual(_sc(float, u'-1.234'), -1.234) def test_safe_cast_special_chars_to_unicode(self): - us = _sc(unicode, 'caf\xc3\xa9') - self.assertTrue(isinstance(us, unicode)) + us = _sc(six.text_type, 'caf\xc3\xa9') + self.assertTrue(isinstance(us, six.text_type)) self.assertTrue(us.startswith(u'caf')) def test_safe_cast_float_with_no_numbers(self): - v = _sc(float, '+') + v = _sc(float, u'+') self.assertEqual(v, 0.0) + def test_safe_cast_float_with_dot_only(self): + v = _sc(float, u'.') + self.assertEqual(v, 0.0) -class SafetyTest(unittest.TestCase, TestHelper): + def test_safe_cast_float_with_multiple_dots(self): + v = _sc(float, u'1.0.0') + self.assertEqual(v, 1.0) + + +class SafetyTest(unittest.TestCase, _common.TempDirMixin): def setUp(self): self.create_temp_dir() @@ -138,67 +159,67 @@ class SafetyTest(unittest.TestCase, TestHelper): with open(fn, 'w') as f: f.write(data) try: - self.assertRaises(exc, beets.mediafile.MediaFile, fn) + self.assertRaises(exc, mediafile.MediaFile, fn) finally: os.unlink(fn) # delete the temporary file def test_corrupt_mp3_raises_unreadablefileerror(self): # Make sure we catch Mutagen reading errors appropriately. - self._exccheck('corrupt.mp3', beets.mediafile.UnreadableFileError) + self._exccheck(b'corrupt.mp3', mediafile.UnreadableFileError) def test_corrupt_mp4_raises_unreadablefileerror(self): - self._exccheck('corrupt.m4a', beets.mediafile.UnreadableFileError) + self._exccheck(b'corrupt.m4a', mediafile.UnreadableFileError) def test_corrupt_flac_raises_unreadablefileerror(self): - self._exccheck('corrupt.flac', beets.mediafile.UnreadableFileError) + self._exccheck(b'corrupt.flac', mediafile.UnreadableFileError) def test_corrupt_ogg_raises_unreadablefileerror(self): - self._exccheck('corrupt.ogg', beets.mediafile.UnreadableFileError) + self._exccheck(b'corrupt.ogg', mediafile.UnreadableFileError) def test_invalid_ogg_header_raises_unreadablefileerror(self): - self._exccheck('corrupt.ogg', beets.mediafile.UnreadableFileError, + self._exccheck(b'corrupt.ogg', mediafile.UnreadableFileError, 'OggS\x01vorbis') def test_corrupt_monkeys_raises_unreadablefileerror(self): - self._exccheck('corrupt.ape', beets.mediafile.UnreadableFileError) + self._exccheck(b'corrupt.ape', mediafile.UnreadableFileError) def test_invalid_extension_raises_filetypeerror(self): - self._exccheck('something.unknown', beets.mediafile.FileTypeError) + self._exccheck(b'something.unknown', mediafile.FileTypeError) def test_magic_xml_raises_unreadablefileerror(self): - self._exccheck('nothing.xml', beets.mediafile.UnreadableFileError, + self._exccheck(b'nothing.xml', mediafile.UnreadableFileError, "ftyp") - @unittest.skipIf(not hasattr(os, 'symlink'), 'platform lacks symlink') + @unittest.skipUnless(_common.HAVE_SYMLINK, u'platform lacks symlink') def test_broken_symlink(self): - fn = os.path.join(_common.RSRC, 'brokenlink') + fn = os.path.join(_common.RSRC, b'brokenlink') os.symlink('does_not_exist', fn) try: - self.assertRaises(IOError, - beets.mediafile.MediaFile, fn) + self.assertRaises(mediafile.UnreadableFileError, + mediafile.MediaFile, fn) finally: os.unlink(fn) class SideEffectsTest(unittest.TestCase): def setUp(self): - self.empty = os.path.join(_common.RSRC, 'empty.mp3') + self.empty = os.path.join(_common.RSRC, b'empty.mp3') def test_opening_tagless_file_leaves_untouched(self): old_mtime = os.stat(self.empty).st_mtime - beets.mediafile.MediaFile(self.empty) + mediafile.MediaFile(self.empty) new_mtime = os.stat(self.empty).st_mtime self.assertEqual(old_mtime, new_mtime) -class EncodingTest(unittest.TestCase, TestHelper): +class MP4EncodingTest(unittest.TestCase, _common.TempDirMixin): def setUp(self): self.create_temp_dir() - src = os.path.join(_common.RSRC, 'full.m4a') - self.path = os.path.join(self.temp_dir, 'test.m4a') + src = os.path.join(_common.RSRC, b'full.m4a') + self.path = os.path.join(self.temp_dir, b'test.m4a') shutil.copy(src, self.path) - self.mf = beets.mediafile.MediaFile(self.path) + self.mf = mediafile.MediaFile(self.path) def tearDown(self): self.remove_temp_dir() @@ -206,11 +227,31 @@ class EncodingTest(unittest.TestCase, TestHelper): def test_unicode_label_in_m4a(self): self.mf.label = u'foo\xe8bar' self.mf.save() - new_mf = beets.mediafile.MediaFile(self.path) + new_mf = mediafile.MediaFile(self.path) self.assertEqual(new_mf.label, u'foo\xe8bar') -class ZeroLengthMediaFile(beets.mediafile.MediaFile): +class MP3EncodingTest(unittest.TestCase, _common.TempDirMixin): + def setUp(self): + self.create_temp_dir() + src = os.path.join(_common.RSRC, b'full.mp3') + self.path = os.path.join(self.temp_dir, b'test.mp3') + shutil.copy(src, self.path) + + self.mf = mediafile.MediaFile(self.path) + + def test_comment_with_latin1_encoding(self): + # Set up the test file with a Latin1-encoded COMM frame. The encoding + # indices defined by MP3 are listed here: + # http://id3.org/id3v2.4.0-structure + self.mf.mgfile['COMM::eng'].encoding = 0 + + # Try to store non-Latin1 text. + self.mf.comments = u'\u2028' + self.mf.save() + + +class ZeroLengthMediaFile(mediafile.MediaFile): @property def length(self): return 0.0 @@ -219,7 +260,7 @@ class ZeroLengthMediaFile(beets.mediafile.MediaFile): class MissingAudioDataTest(unittest.TestCase): def setUp(self): super(MissingAudioDataTest, self).setUp() - path = os.path.join(_common.RSRC, 'full.mp3') + path = os.path.join(_common.RSRC, b'full.mp3') self.mf = ZeroLengthMediaFile(path) def test_bitrate_with_zero_length(self): @@ -230,11 +271,11 @@ class MissingAudioDataTest(unittest.TestCase): class TypeTest(unittest.TestCase): def setUp(self): super(TypeTest, self).setUp() - path = os.path.join(_common.RSRC, 'full.mp3') - self.mf = beets.mediafile.MediaFile(path) + path = os.path.join(_common.RSRC, b'full.mp3') + self.mf = mediafile.MediaFile(path) def test_year_integer_in_string(self): - self.mf.year = '2009' + self.mf.year = u'2009' self.assertEqual(self.mf.year, 2009) def test_set_replaygain_gain_to_none(self): @@ -263,36 +304,45 @@ class TypeTest(unittest.TestCase): class SoundCheckTest(unittest.TestCase): def test_round_trip(self): - data = beets.mediafile._sc_encode(1.0, 1.0) - gain, peak = beets.mediafile._sc_decode(data) + data = mediafile._sc_encode(1.0, 1.0) + gain, peak = mediafile._sc_decode(data) self.assertEqual(gain, 1.0) self.assertEqual(peak, 1.0) def test_decode_zero(self): - data = u' 80000000 80000000 00000000 00000000 00000000 00000000 ' \ - u'00000000 00000000 00000000 00000000' - gain, peak = beets.mediafile._sc_decode(data) + data = b' 80000000 80000000 00000000 00000000 00000000 00000000 ' \ + b'00000000 00000000 00000000 00000000' + gain, peak = mediafile._sc_decode(data) self.assertEqual(gain, 0.0) self.assertEqual(peak, 0.0) def test_malformatted(self): - gain, peak = beets.mediafile._sc_decode(u'foo') + gain, peak = mediafile._sc_decode(b'foo') self.assertEqual(gain, 0.0) self.assertEqual(peak, 0.0) def test_special_characters(self): - gain, peak = beets.mediafile._sc_decode(u'caf\xe9') + gain, peak = mediafile._sc_decode(u'caf\xe9'.encode('utf-8')) + self.assertEqual(gain, 0.0) + self.assertEqual(peak, 0.0) + + def test_decode_handles_unicode(self): + # Most of the time, we expect to decode the raw bytes. But some formats + # might give us text strings, which we need to handle. + gain, peak = mediafile._sc_decode(u'caf\xe9') self.assertEqual(gain, 0.0) self.assertEqual(peak, 0.0) -class ID3v23Test(unittest.TestCase, TestHelper): - def _make_test(self, ext='mp3', id3v23=False): +class ID3v23Test(unittest.TestCase, _common.TempDirMixin): + def _make_test(self, ext=b'mp3', id3v23=False): self.create_temp_dir() - src = os.path.join(_common.RSRC, 'full.{0}'.format(ext)) - self.path = os.path.join(self.temp_dir, 'test.{0}'.format(ext)) + src = os.path.join(_common.RSRC, + b'full.' + ext) + self.path = os.path.join(self.temp_dir, + b'test.' + ext) shutil.copy(src, self.path) - return beets.mediafile.MediaFile(self.path, id3v23=id3v23) + return mediafile.MediaFile(self.path, id3v23=id3v23) def _delete_test(self): self.remove_temp_dir() @@ -303,7 +353,7 @@ class ID3v23Test(unittest.TestCase, TestHelper): mf.year = 2013 mf.save() frame = mf.mgfile['TDRC'] - self.assertTrue('2013' in unicode(frame)) + self.assertTrue('2013' in six.text_type(frame)) self.assertTrue('TYER' not in mf.mgfile) finally: self._delete_test() @@ -314,48 +364,48 @@ class ID3v23Test(unittest.TestCase, TestHelper): mf.year = 2013 mf.save() frame = mf.mgfile['TYER'] - self.assertTrue('2013' in unicode(frame)) + self.assertTrue('2013' in six.text_type(frame)) self.assertTrue('TDRC' not in mf.mgfile) finally: self._delete_test() def test_v23_on_non_mp3_is_noop(self): - mf = self._make_test('m4a', id3v23=True) + mf = self._make_test(b'm4a', id3v23=True) try: mf.year = 2013 mf.save() finally: self._delete_test() - def test_v24_image_encoding(self): - mf = self._make_test(id3v23=False) - try: - mf.images = [beets.mediafile.Image(b'test data')] - mf.save() - frame = mf.mgfile.tags.getall('APIC')[0] - self.assertEqual(frame.encoding, 3) - finally: - self._delete_test() + def test_image_encoding(self): + """For compatibility with OS X/iTunes. - @unittest.skip("a bug, see #899") - def test_v23_image_encoding(self): - """For compatibility with OS X/iTunes (and strict adherence to - the standard), ID3v2.3 tags need to use an inferior text - encoding: UTF-8 is not supported. + See https://github.com/beetbox/beets/issues/899#issuecomment-62437773 """ - mf = self._make_test(id3v23=True) - try: - mf.images = [beets.mediafile.Image(b'test data')] - mf.save() - frame = mf.mgfile.tags.getall('APIC')[0] - self.assertEqual(frame.encoding, 1) - finally: - self._delete_test() + + for v23 in [True, False]: + mf = self._make_test(id3v23=v23) + try: + mf.images = [ + mediafile.Image(b'data', desc=u""), + mediafile.Image(b'data', desc=u"foo"), + mediafile.Image(b'data', desc=u"\u0185"), + ] + mf.save() + apic_frames = mf.mgfile.tags.getall('APIC') + encodings = dict([(f.desc, f.encoding) for f in apic_frames]) + self.assertEqual(encodings, { + u"": mutagen.id3.Encoding.LATIN1, + u"foo": mutagen.id3.Encoding.LATIN1, + u"\u0185": mutagen.id3.Encoding.UTF16, + }) + finally: + self._delete_test() def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_metasync.py b/test/test_metasync.py index 8e2669c41..ef16c57a2 100644 --- a/test/test_metasync.py +++ b/test/test_metasync.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Tom Jaspers. +# Copyright 2016, Tom Jaspers. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -11,14 +12,18 @@ # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. + +from __future__ import division, absolute_import, print_function + import os import platform import time from datetime import datetime from beets.library import Item +from beets.util import py3_path +import unittest from test import _common -from test._common import unittest from test.helper import TestHelper @@ -32,9 +37,9 @@ def _is_windows(): class MetaSyncTest(_common.TestCase, TestHelper): itunes_library_unix = os.path.join(_common.RSRC, - 'itunes_library_unix.xml') + b'itunes_library_unix.xml') itunes_library_windows = os.path.join(_common.RSRC, - 'itunes_library_windows.xml') + b'itunes_library_windows.xml') def setUp(self): self.setup_beets() @@ -44,10 +49,10 @@ class MetaSyncTest(_common.TestCase, TestHelper): if _is_windows(): self.config['metasync']['itunes']['library'] = \ - self.itunes_library_windows + py3_path(self.itunes_library_windows) else: self.config['metasync']['itunes']['library'] = \ - self.itunes_library_unix + py3_path(self.itunes_library_unix) self._set_up_data() @@ -119,5 +124,5 @@ def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_mpdstats.py b/test/test_mpdstats.py index c2db78f1f..7452be86b 100644 --- a/test/test_mpdstats.py +++ b/test/test_mpdstats.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015 +# Copyright 2016 # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,16 +13,15 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function - -from mock import Mock -from test._common import unittest +import unittest +from mock import Mock, patch, call, ANY from test.helper import TestHelper from beets.library import Item from beetsplug.mpdstats import MPDStats +from beets import util class MPDStatsTest(unittest.TestCase, TestHelper): @@ -34,7 +34,7 @@ class MPDStatsTest(unittest.TestCase, TestHelper): self.unload_plugins() def test_update_rating(self): - item = Item(title='title', path='', id=1) + item = Item(title=u'title', path='', id=1) item.add(self.lib) log = Mock() @@ -43,9 +43,47 @@ class MPDStatsTest(unittest.TestCase, TestHelper): self.assertFalse(mpdstats.update_rating(item, True)) self.assertFalse(mpdstats.update_rating(None, True)) + def test_get_item(self): + item_path = util.normpath('/foo/bar.flac') + item = Item(title=u'title', path=item_path, id=1) + item.add(self.lib) + + log = Mock() + mpdstats = MPDStats(self.lib, log) + + self.assertEqual(str(mpdstats.get_item(item_path)), str(item)) + self.assertIsNone(mpdstats.get_item('/some/non-existing/path')) + self.assertIn(u'item not found:', log.info.call_args[0][0]) + + FAKE_UNKNOWN_STATE = 'some-unknown-one' + STATUSES = [{'state': FAKE_UNKNOWN_STATE}, + {'state': u'pause'}, + {'state': u'play', 'songid': 1, 'time': u'0:1'}, + {'state': u'stop'}] + EVENTS = [["player"]] * (len(STATUSES) - 1) + [KeyboardInterrupt] + item_path = util.normpath('/foo/bar.flac') + + @patch("beetsplug.mpdstats.MPDClientWrapper", return_value=Mock(**{ + "events.side_effect": EVENTS, "status.side_effect": STATUSES, + "playlist.return_value": {1: item_path}})) + def test_run_mpdstats(self, mpd_mock): + item = Item(title=u'title', path=self.item_path, id=1) + item.add(self.lib) + + log = Mock() + try: + MPDStats(self.lib, log).run() + except KeyboardInterrupt: + pass + + log.debug.assert_has_calls( + [call(u'unhandled status "{0}"', ANY)]) + log.info.assert_has_calls( + [call(u'pause'), call(u'playing {0}', ANY), call(u'stop')]) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_permissions.py b/test/test_permissions.py index b2a8adcb8..ed84798f1 100644 --- a/test/test_permissions.py +++ b/test/test_permissions.py @@ -1,10 +1,16 @@ +# -*- coding: utf-8 -*- + """Tests for the 'permissions' plugin. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function + +import os +import platform +import unittest +from mock import patch, Mock -from test._common import unittest from test.helper import TestHelper +from beets.util import displayable_path from beetsplug.permissions import (check_permissions, convert_perm, dirs_in_library) @@ -16,58 +22,70 @@ class PermissionsPluginTest(unittest.TestCase, TestHelper): self.load_plugins('permissions') self.config['permissions'] = { - 'file': 777, - 'dir': 777} + 'file': '777', + 'dir': '777'} def tearDown(self): self.teardown_beets() self.unload_plugins() def test_permissions_on_album_imported(self): - self.importer = self.create_importer() - self.importer.run() - item = self.lib.items().get() - - file_perm = self.config['permissions']['file'].get() - file_perm = convert_perm(file_perm) - - dir_perm = self.config['permissions']['dir'].get() - dir_perm = convert_perm(dir_perm) - - music_dirs = dirs_in_library(self.lib.directory, item.path) - - self.assertTrue(check_permissions(item.path, file_perm)) - self.assertFalse(check_permissions(item.path, convert_perm(644))) - - for path in music_dirs: - self.assertTrue(check_permissions(path, dir_perm)) - self.assertFalse(check_permissions(path, convert_perm(644))) + self.do_thing(True) def test_permissions_on_item_imported(self): self.config['import']['singletons'] = True + self.do_thing(True) + + @patch("os.chmod", Mock()) + def test_failing_to_set_permissions(self): + self.do_thing(False) + + def do_thing(self, expect_success): + if platform.system() == 'Windows': + self.skipTest('permissions not available on Windows') + + def get_stat(v): + return os.stat( + os.path.join(self.temp_dir, b'import', *v)).st_mode & 0o777 self.importer = self.create_importer() + typs = ['file', 'dir'] + + track_file = (b'album 0', b'track 0.mp3') + self.exp_perms = { + True: {k: convert_perm(self.config['permissions'][k].get()) + for k in typs}, + False: {k: get_stat(v) for (k, v) in zip(typs, (track_file, ()))} + } + self.importer.run() item = self.lib.items().get() - file_perm = self.config['permissions']['file'].get() - file_perm = convert_perm(file_perm) + self.assertPerms(item.path, 'file', expect_success) - dir_perm = self.config['permissions']['dir'].get() - dir_perm = convert_perm(dir_perm) + for path in dirs_in_library(self.lib.directory, item.path): + self.assertPerms(path, 'dir', expect_success) - music_dirs = dirs_in_library(self.lib.directory, item.path) + def assertPerms(self, path, typ, expect_success): # noqa + for x in [(True, self.exp_perms[expect_success][typ], '!='), + (False, self.exp_perms[not expect_success][typ], '==')]: + msg = u'{} : {} {} {}'.format( + displayable_path(path), + oct(os.stat(path).st_mode), + x[2], + oct(x[1]) + ) + self.assertEqual(x[0], check_permissions(path, x[1]), msg=msg) - self.assertTrue(check_permissions(item.path, file_perm)) - self.assertFalse(check_permissions(item.path, convert_perm(644))) + def test_convert_perm_from_string(self): + self.assertEqual(convert_perm('10'), 8) - for path in music_dirs: - self.assertTrue(check_permissions(path, dir_perm)) - self.assertFalse(check_permissions(path, convert_perm(644))) + def test_convert_perm_from_int(self): + self.assertEqual(convert_perm(10), 8) def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_pipeline.py b/test/test_pipeline.py index aaa12d2a3..228deb50e 100644 --- a/test/test_pipeline.py +++ b/test/test_pipeline.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,10 +15,11 @@ """Test the "pipeline.py" restricted parallel programming library. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function + +import six +import unittest -from test._common import unittest from beets.util import pipeline @@ -133,8 +135,11 @@ class ExceptionTest(unittest.TestCase): pl = pipeline.Pipeline((_produce(), _exc_work())) pull = pl.pull() for i in range(3): - pull.next() - self.assertRaises(TestException, pull.next) + next(pull) + if six.PY2: + self.assertRaises(TestException, pull.next) + else: + self.assertRaises(TestException, pull.__next__) class ParallelExceptionTest(unittest.TestCase): @@ -240,5 +245,5 @@ class StageDecoratorTest(unittest.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_play.py b/test/test_play.py new file mode 100644 index 000000000..9721143cc --- /dev/null +++ b/test/test_play.py @@ -0,0 +1,143 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Jesse Weinstein +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Tests for the play plugin""" + +from __future__ import division, absolute_import, print_function + +import os + +import unittest +from mock import patch, ANY + +from test.helper import TestHelper, control_stdin + +from beets.ui import UserError +from beets.util import open_anything + + +@patch('beetsplug.play.util.interactive_open') +class PlayPluginTest(unittest.TestCase, TestHelper): + def setUp(self): + self.setup_beets() + self.load_plugins('play') + self.item = self.add_item(album=u'a nice älbum', title=u'aNiceTitle') + self.lib.add_album([self.item]) + self.config['play']['command'] = 'echo' + + def tearDown(self): + self.teardown_beets() + self.unload_plugins() + + def run_and_assert(self, open_mock, args=('title:aNiceTitle',), + expected_cmd='echo', expected_playlist=None): + self.run_command('play', *args) + + open_mock.assert_called_once_with(ANY, expected_cmd) + expected_playlist = expected_playlist or self.item.path.decode('utf-8') + exp_playlist = expected_playlist + u'\n' + with open(open_mock.call_args[0][0][0], 'rb') as playlist: + self.assertEqual(exp_playlist, playlist.read().decode('utf-8')) + + def test_basic(self, open_mock): + self.run_and_assert(open_mock) + + def test_album_option(self, open_mock): + self.run_and_assert(open_mock, [u'-a', u'nice']) + + def test_args_option(self, open_mock): + self.run_and_assert( + open_mock, [u'-A', u'foo', u'title:aNiceTitle'], u'echo foo') + + def test_args_option_in_middle(self, open_mock): + self.config['play']['command'] = 'echo $args other' + + self.run_and_assert( + open_mock, [u'-A', u'foo', u'title:aNiceTitle'], u'echo foo other') + + def test_unset_args_option_in_middle(self, open_mock): + self.config['play']['command'] = 'echo $args other' + + self.run_and_assert( + open_mock, [u'title:aNiceTitle'], u'echo other') + + def test_relative_to(self, open_mock): + self.config['play']['command'] = 'echo' + self.config['play']['relative_to'] = '/something' + + path = os.path.relpath(self.item.path, b'/something') + playlist = path.decode('utf-8') + self.run_and_assert( + open_mock, expected_cmd='echo', expected_playlist=playlist) + + def test_use_folders(self, open_mock): + self.config['play']['command'] = None + self.config['play']['use_folders'] = True + self.run_command('play', '-a', 'nice') + + open_mock.assert_called_once_with(ANY, open_anything()) + with open(open_mock.call_args[0][0][0], 'rb') as f: + playlist = f.read().decode('utf-8') + self.assertEqual(u'{}\n'.format( + os.path.dirname(self.item.path.decode('utf-8'))), + playlist) + + def test_raw(self, open_mock): + self.config['play']['raw'] = True + + self.run_command(u'play', u'nice') + + open_mock.assert_called_once_with([self.item.path], 'echo') + + def test_not_found(self, open_mock): + self.run_command(u'play', u'not found') + + open_mock.assert_not_called() + + def test_warning_threshold(self, open_mock): + self.config['play']['warning_threshold'] = 1 + self.add_item(title='another NiceTitle') + + with control_stdin("a"): + self.run_command(u'play', u'nice') + + open_mock.assert_not_called() + + def test_skip_warning_threshold_bypass(self, open_mock): + self.config['play']['warning_threshold'] = 1 + self.other_item = self.add_item(title='another NiceTitle') + + expected_playlist = u'{0}\n{1}'.format( + self.item.path.decode('utf-8'), + self.other_item.path.decode('utf-8')) + + with control_stdin("a"): + self.run_and_assert( + open_mock, + [u'-y', u'NiceTitle'], + expected_playlist=expected_playlist) + + def test_command_failed(self, open_mock): + open_mock.side_effect = OSError(u"some reason") + + with self.assertRaises(UserError): + self.run_command(u'play', u'title:aNiceTitle') + + +def suite(): + return unittest.TestLoader().loadTestsFromName(__name__) + +if __name__ == '__main__': + unittest.main(defaultTest='suite') diff --git a/test/test_player.py b/test/test_player.py index 6115b92c2..0a576f0ba 100644 --- a/test/test_player.py +++ b/test/test_player.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,10 +15,9 @@ """Tests for BPD and music playing. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function -from test._common import unittest +import unittest from beetsplug import bpd @@ -66,5 +66,5 @@ class CommandParseTest(unittest.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_plexupdate.py b/test/test_plexupdate.py index 58388f728..f8b0bdcd9 100644 --- a/test/test_plexupdate.py +++ b/test/test_plexupdate.py @@ -1,9 +1,10 @@ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +# -*- coding: utf-8 -*- + +from __future__ import division, absolute_import, print_function -from test._common import unittest from test.helper import TestHelper from beetsplug.plexupdate import get_music_section, update_plex +import unittest import responses @@ -123,5 +124,5 @@ def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_plugin_mediafield.py b/test/test_plugin_mediafield.py new file mode 100644 index 000000000..983f6e2c8 --- /dev/null +++ b/test/test_plugin_mediafield.py @@ -0,0 +1,115 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Adrian Sampson. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Tests the facility that lets plugins add custom field to MediaFile. +""" +from __future__ import division, absolute_import, print_function + +import os +import six +import shutil +import unittest + +from test import _common +from beets.library import Item +from beets import mediafile +from beets.plugins import BeetsPlugin +from beets.util import bytestring_path + + +field_extension = mediafile.MediaField( + mediafile.MP3DescStorageStyle(u'customtag'), + mediafile.MP4StorageStyle('----:com.apple.iTunes:customtag'), + mediafile.StorageStyle('customtag'), + mediafile.ASFStorageStyle('customtag'), +) + + +class ExtendedFieldTestMixin(_common.TestCase): + + def _mediafile_fixture(self, name, extension='mp3'): + name = bytestring_path(name + '.' + extension) + src = os.path.join(_common.RSRC, name) + target = os.path.join(self.temp_dir, name) + shutil.copy(src, target) + return mediafile.MediaFile(target) + + def test_extended_field_write(self): + plugin = BeetsPlugin() + plugin.add_media_field('customtag', field_extension) + + try: + mf = self._mediafile_fixture('empty') + mf.customtag = u'F#' + mf.save() + + mf = mediafile.MediaFile(mf.path) + self.assertEqual(mf.customtag, u'F#') + + finally: + delattr(mediafile.MediaFile, 'customtag') + Item._media_fields.remove('customtag') + + def test_write_extended_tag_from_item(self): + plugin = BeetsPlugin() + plugin.add_media_field('customtag', field_extension) + + try: + mf = self._mediafile_fixture('empty') + self.assertIsNone(mf.customtag) + + item = Item(path=mf.path, customtag=u'Gb') + item.write() + mf = mediafile.MediaFile(mf.path) + self.assertEqual(mf.customtag, u'Gb') + + finally: + delattr(mediafile.MediaFile, 'customtag') + Item._media_fields.remove('customtag') + + def test_read_flexible_attribute_from_file(self): + plugin = BeetsPlugin() + plugin.add_media_field('customtag', field_extension) + + try: + mf = self._mediafile_fixture('empty') + mf.update({'customtag': u'F#'}) + mf.save() + + item = Item.from_path(mf.path) + self.assertEqual(item['customtag'], u'F#') + + finally: + delattr(mediafile.MediaFile, 'customtag') + Item._media_fields.remove('customtag') + + def test_invalid_descriptor(self): + with self.assertRaises(ValueError) as cm: + mediafile.MediaFile.add_field('somekey', True) + self.assertIn(u'must be an instance of MediaField', + six.text_type(cm.exception)) + + def test_overwrite_property(self): + with self.assertRaises(ValueError) as cm: + mediafile.MediaFile.add_field('artist', mediafile.MediaField()) + self.assertIn(u'property "artist" already exists', + six.text_type(cm.exception)) + + +def suite(): + return unittest.TestLoader().loadTestsFromName(__name__) + +if __name__ == '__main__': + unittest.main(defaultTest='suite') diff --git a/test/test_plugins.py b/test/test_plugins.py index 2e8bedca1..7c32e9aca 100644 --- a/test/test_plugins.py +++ b/test/test_plugins.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,22 +13,25 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import os -from mock import patch, Mock +from mock import patch, Mock, ANY import shutil import itertools +import unittest from beets.importer import SingletonImportTask, SentinelImportTask, \ - ArchiveImportTask -from beets import plugins, config + ArchiveImportTask, action +from beets import plugins, config, ui from beets.library import Item from beets.dbcore import types from beets.mediafile import MediaFile -from test.test_importer import ImportHelper -from test._common import unittest, RSRC +from beets.util import displayable_path, bytestring_path, syspath + +from test.test_importer import ImportHelper, AutotagStub +from test.test_ui_importer import TerminalImportSessionSetup +from test._common import RSRC from test import helper @@ -70,22 +74,22 @@ class ItemTypesTest(unittest.TestCase, TestHelper): self.register_plugin(RatingPlugin) self.config['plugins'] = 'rating' - item = Item(path='apath', artist='aaa') + item = Item(path=u'apath', artist=u'aaa') item.add(self.lib) # Do not match unset values - out = self.run_with_output('ls', 'rating:1..3') - self.assertNotIn('aaa', out) + out = self.run_with_output(u'ls', u'rating:1..3') + self.assertNotIn(u'aaa', out) - self.run_command('modify', 'rating=2', '--yes') + self.run_command(u'modify', u'rating=2', u'--yes') # Match in range - out = self.run_with_output('ls', 'rating:1..3') - self.assertIn('aaa', out) + out = self.run_with_output(u'ls', u'rating:1..3') + self.assertIn(u'aaa', out) # Don't match out of range - out = self.run_with_output('ls', 'rating:3..5') - self.assertNotIn('aaa', out) + out = self.run_with_output(u'ls', u'rating:3..5') + self.assertNotIn(u'aaa', out) class ItemWriteTest(unittest.TestCase, TestHelper): @@ -106,16 +110,16 @@ class ItemWriteTest(unittest.TestCase, TestHelper): def test_change_tags(self): def on_write(item=None, path=None, tags=None): - if tags['artist'] == 'XXX': - tags['artist'] = 'YYY' + if tags['artist'] == u'XXX': + tags['artist'] = u'YYY' self.register_listener('write', on_write) - item = self.add_item_fixture(artist='XXX') + item = self.add_item_fixture(artist=u'XXX') item.write() - mediafile = MediaFile(item.path) - self.assertEqual(mediafile.artist, 'YYY') + mediafile = MediaFile(syspath(item.path)) + self.assertEqual(mediafile.artist, u'YYY') def register_listener(self, event, func): self.event_listener_plugin.register_listener(event, func) @@ -174,7 +178,7 @@ class EventsTest(unittest.TestCase, ImportHelper, TestHelper): def __copy_file(self, dest_path, metadata): # Copy files - resource_path = os.path.join(RSRC, 'full.mp3') + resource_path = os.path.join(RSRC, b'full.mp3') shutil.copy(resource_path, dest_path) medium = MediaFile(dest_path) # Set metadata @@ -183,16 +187,16 @@ class EventsTest(unittest.TestCase, ImportHelper, TestHelper): medium.save() def __create_import_dir(self, count): - self.import_dir = os.path.join(self.temp_dir, 'testsrcdir') + self.import_dir = os.path.join(self.temp_dir, b'testsrcdir') if os.path.isdir(self.import_dir): shutil.rmtree(self.import_dir) - self.album_path = os.path.join(self.import_dir, 'album') + self.album_path = os.path.join(self.import_dir, b'album') os.makedirs(self.album_path) metadata = { - 'artist': 'Tag Artist', - 'album': 'Tag Album', + 'artist': u'Tag Artist', + 'album': u'Tag Album', 'albumartist': None, 'mb_trackid': None, 'mb_albumid': None, @@ -201,9 +205,9 @@ class EventsTest(unittest.TestCase, ImportHelper, TestHelper): self.file_paths = [] for i in range(count): metadata['track'] = i + 1 - metadata['title'] = 'Tag Title Album %d' % (i + 1) - dest_path = os.path.join(self.album_path, - '%02d - track.mp3' % (i + 1)) + metadata['title'] = u'Tag Title Album %d' % (i + 1) + track_file = bytestring_path('%02d - track.mp3' % (i + 1)) + dest_path = os.path.join(self.album_path, track_file) self.__copy_file(dest_path, metadata) self.file_paths.append(dest_path) @@ -218,13 +222,15 @@ class EventsTest(unittest.TestCase, ImportHelper, TestHelper): # Exactly one event should have been imported (for the album). # Sentinels do not get emitted. - self.assertEqual(logs.count('Sending event: import_task_created'), 1) + self.assertEqual(logs.count(u'Sending event: import_task_created'), 1) - logs = [line for line in logs if not line.startswith('Sending event:')] + logs = [line for line in logs if not line.startswith( + u'Sending event:')] self.assertEqual(logs, [ - 'Album: {0}'.format(os.path.join(self.import_dir, 'album')), - ' {0}'.format(self.file_paths[0]), - ' {0}'.format(self.file_paths[1]), + u'Album: {0}'.format(displayable_path( + os.path.join(self.import_dir, b'album'))), + u' {0}'.format(displayable_path(self.file_paths[0])), + u' {0}'.format(displayable_path(self.file_paths[1])), ]) def test_import_task_created_with_plugin(self): @@ -260,23 +266,27 @@ class EventsTest(unittest.TestCase, ImportHelper, TestHelper): # Exactly one event should have been imported (for the album). # Sentinels do not get emitted. - self.assertEqual(logs.count('Sending event: import_task_created'), 1) + self.assertEqual(logs.count(u'Sending event: import_task_created'), 1) - logs = [line for line in logs if not line.startswith('Sending event:')] + logs = [line for line in logs if not line.startswith( + u'Sending event:')] self.assertEqual(logs, [ - 'Singleton: {0}'.format(self.file_paths[0]), - 'Singleton: {0}'.format(self.file_paths[1]), + u'Singleton: {0}'.format(displayable_path(self.file_paths[0])), + u'Singleton: {0}'.format(displayable_path(self.file_paths[1])), ]) class HelpersTest(unittest.TestCase): def test_sanitize_choices(self): - self.assertEqual(plugins.sanitize_choices(['A', 'Z'], ('A', 'B')), - ['A']) - self.assertEqual(plugins.sanitize_choices(['A', 'A'], ('A')), ['A']) - self.assertEqual(plugins.sanitize_choices(['D', '*', 'A'], - ('A', 'B', 'C', 'D')), ['D', 'B', 'C', 'A']) + self.assertEqual( + plugins.sanitize_choices([u'A', u'Z'], (u'A', u'B')), [u'A']) + self.assertEqual( + plugins.sanitize_choices([u'A', u'A'], (u'A')), [u'A']) + self.assertEqual( + plugins.sanitize_choices([u'D', u'*', u'A'], + (u'A', u'B', u'C', u'D')), + [u'D', u'B', u'C', u'A']) class ListenersTest(unittest.TestCase, TestHelper): @@ -317,9 +327,9 @@ class ListenersTest(unittest.TestCase, TestHelper): class DummyPlugin(plugins.BeetsPlugin): def __init__(self): super(DummyPlugin, self).__init__() - self.foo = Mock(__name__=b'foo') + self.foo = Mock(__name__='foo') self.register_listener('event_foo', self.foo) - self.bar = Mock(__name__=b'bar') + self.bar = Mock(__name__='bar') self.register_listener('event_bar', self.bar) d = DummyPlugin() @@ -329,8 +339,8 @@ class ListenersTest(unittest.TestCase, TestHelper): d.foo.assert_has_calls([]) d.bar.assert_has_calls([]) - plugins.send('event_foo', var="tagada") - d.foo.assert_called_once_with(var="tagada") + plugins.send('event_foo', var=u"tagada") + d.foo.assert_called_once_with(var=u"tagada") d.bar.assert_has_calls([]) @patch('beets.plugins.find_plugins') @@ -400,8 +410,158 @@ class ListenersTest(unittest.TestCase, TestHelper): plugins.send('event9', foo=5) +class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, + ImportHelper, TestHelper): + def setUp(self): + self.setup_plugin_loader() + self.setup_beets() + self._create_import_dir(3) + self._setup_import_session() + self.matcher = AutotagStub().install() + # keep track of ui.input_option() calls + self.input_options_patcher = patch('beets.ui.input_options', + side_effect=ui.input_options) + self.mock_input_options = self.input_options_patcher.start() + + def tearDown(self): + self.input_options_patcher.stop() + self.teardown_plugin_loader() + self.teardown_beets() + self.matcher.restore() + + def test_plugin_choices_in_ui_input_options_album(self): + """Test the presence of plugin choices on the prompt (album).""" + class DummyPlugin(plugins.BeetsPlugin): + def __init__(self): + super(DummyPlugin, self).__init__() + self.register_listener('before_choose_candidate', + self.return_choices) + + def return_choices(self, session, task): + return [ui.commands.PromptChoice('f', u'Foo', None), + ui.commands.PromptChoice('r', u'baR', None)] + + self.register_plugin(DummyPlugin) + # Default options + extra choices by the plugin ('Foo', 'Bar') + opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is', + u'as Tracks', u'Group albums', u'Enter search', + u'enter Id', u'aBort') + (u'Foo', u'baR') + + self.importer.add_choice(action.SKIP) + self.importer.run() + self.mock_input_options.assert_called_once_with(opts, default='a', + require=ANY) + + def test_plugin_choices_in_ui_input_options_singleton(self): + """Test the presence of plugin choices on the prompt (singleton).""" + class DummyPlugin(plugins.BeetsPlugin): + def __init__(self): + super(DummyPlugin, self).__init__() + self.register_listener('before_choose_candidate', + self.return_choices) + + def return_choices(self, session, task): + return [ui.commands.PromptChoice('f', u'Foo', None), + ui.commands.PromptChoice('r', u'baR', None)] + + self.register_plugin(DummyPlugin) + # Default options + extra choices by the plugin ('Foo', 'Bar') + opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is', + u'Enter search', + u'enter Id', u'aBort') + (u'Foo', u'baR') + + config['import']['singletons'] = True + self.importer.add_choice(action.SKIP) + self.importer.run() + self.mock_input_options.assert_called_with(opts, default='a', + require=ANY) + + def test_choices_conflicts(self): + """Test the short letter conflict solving.""" + class DummyPlugin(plugins.BeetsPlugin): + def __init__(self): + super(DummyPlugin, self).__init__() + self.register_listener('before_choose_candidate', + self.return_choices) + + def return_choices(self, session, task): + return [ui.commands.PromptChoice('a', u'A foo', None), # dupe + ui.commands.PromptChoice('z', u'baZ', None), # ok + ui.commands.PromptChoice('z', u'Zupe', None), # dupe + ui.commands.PromptChoice('z', u'Zoo', None)] # dupe + + self.register_plugin(DummyPlugin) + # Default options + not dupe extra choices by the plugin ('baZ') + opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is', + u'as Tracks', u'Group albums', u'Enter search', + u'enter Id', u'aBort') + (u'baZ',) + self.importer.add_choice(action.SKIP) + self.importer.run() + self.mock_input_options.assert_called_once_with(opts, default='a', + require=ANY) + + def test_plugin_callback(self): + """Test that plugin callbacks are being called upon user choice.""" + class DummyPlugin(plugins.BeetsPlugin): + def __init__(self): + super(DummyPlugin, self).__init__() + self.register_listener('before_choose_candidate', + self.return_choices) + + def return_choices(self, session, task): + return [ui.commands.PromptChoice('f', u'Foo', self.foo)] + + def foo(self, session, task): + pass + + self.register_plugin(DummyPlugin) + # Default options + extra choices by the plugin ('Foo', 'Bar') + opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is', + u'as Tracks', u'Group albums', u'Enter search', + u'enter Id', u'aBort') + (u'Foo',) + + # DummyPlugin.foo() should be called once + with patch.object(DummyPlugin, 'foo', autospec=True) as mock_foo: + with helper.control_stdin('\n'.join(['f', 's'])): + self.importer.run() + self.assertEqual(mock_foo.call_count, 1) + + # input_options should be called twice, as foo() returns None + self.assertEqual(self.mock_input_options.call_count, 2) + self.mock_input_options.assert_called_with(opts, default='a', + require=ANY) + + def test_plugin_callback_return(self): + """Test that plugin callbacks that return a value exit the loop.""" + class DummyPlugin(plugins.BeetsPlugin): + def __init__(self): + super(DummyPlugin, self).__init__() + self.register_listener('before_choose_candidate', + self.return_choices) + + def return_choices(self, session, task): + return [ui.commands.PromptChoice('f', u'Foo', self.foo)] + + def foo(self, session, task): + return action.SKIP + + self.register_plugin(DummyPlugin) + # Default options + extra choices by the plugin ('Foo', 'Bar') + opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is', + u'as Tracks', u'Group albums', u'Enter search', + u'enter Id', u'aBort') + (u'Foo',) + + # DummyPlugin.foo() should be called once + with helper.control_stdin('f\n'): + self.importer.run() + + # input_options should be called once, as foo() returns SKIP + self.mock_input_options.assert_called_once_with(opts, default='a', + require=ANY) + + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_query.py b/test/test_query.py index 04235906d..c0ab2a171 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,33 +15,36 @@ """Various tests for querying the library database. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from functools import partial from mock import patch import os +import sys +import unittest from test import _common -from test._common import unittest from test import helper import beets.library from beets import dbcore from beets.dbcore import types from beets.dbcore.query import (NoneQuery, ParsingError, - InvalidQueryArgumentTypeError) + InvalidQueryArgumentValueError) from beets.library import Library, Item +from beets import util +import platform +import six class TestHelper(helper.TestHelper): - def assertInResult(self, item, results): - result_ids = map(lambda i: i.id, results) + def assertInResult(self, item, results): # noqa + result_ids = [i.id for i in results] self.assertIn(item.id, result_ids) - def assertNotInResult(self, item, results): - result_ids = map(lambda i: i.id, results) + def assertNotInResult(self, item, results): # noqa + result_ids = [i.id for i in results] self.assertNotIn(item.id, result_ids) @@ -53,19 +57,19 @@ class AnyFieldQueryTest(_common.LibTestCase): self.assertEqual(self.lib.items(q).get().title, 'the title') def test_restriction_completeness(self): - q = dbcore.query.AnyFieldQuery('title', ['title'], + q = dbcore.query.AnyFieldQuery('title', [u'title'], dbcore.query.SubstringQuery) - self.assertEqual(self.lib.items(q).get().title, 'the title') + self.assertEqual(self.lib.items(q).get().title, u'the title') def test_restriction_soundness(self): - q = dbcore.query.AnyFieldQuery('title', ['artist'], + q = dbcore.query.AnyFieldQuery('title', [u'artist'], dbcore.query.SubstringQuery) self.assertEqual(self.lib.items(q).get(), None) def test_eq(self): - q1 = dbcore.query.AnyFieldQuery('foo', ['bar'], + q1 = dbcore.query.AnyFieldQuery('foo', [u'bar'], dbcore.query.SubstringQuery) - q2 = dbcore.query.AnyFieldQuery('foo', ['bar'], + q2 = dbcore.query.AnyFieldQuery('foo', [u'bar'], dbcore.query.SubstringQuery) self.assertEqual(q1, q2) @@ -75,10 +79,10 @@ class AnyFieldQueryTest(_common.LibTestCase): class AssertsMixin(object): def assert_items_matched(self, results, titles): - self.assertEqual([i.title for i in results], titles) + self.assertEqual(set([i.title for i in results]), set(titles)) def assert_albums_matched(self, results, albums): - self.assertEqual([a.album for a in results], albums) + self.assertEqual(set([a.album for a in results]), set(albums)) # A test case class providing a library with some dummy data and some @@ -88,19 +92,19 @@ class DummyDataTestCase(_common.TestCase, AssertsMixin): super(DummyDataTestCase, self).setUp() self.lib = beets.library.Library(':memory:') items = [_common.item() for _ in range(3)] - items[0].title = 'foo bar' - items[0].artist = 'one' - items[0].album = 'baz' + items[0].title = u'foo bar' + items[0].artist = u'one' + items[0].album = u'baz' items[0].year = 2001 items[0].comp = True - items[1].title = 'baz qux' - items[1].artist = 'two' - items[1].album = 'baz' + items[1].title = u'baz qux' + items[1].artist = u'two' + items[1].album = u'baz' items[1].year = 2002 items[1].comp = True - items[2].title = 'beets 4 eva' - items[2].artist = 'three' - items[2].album = 'foo' + items[2].title = u'beets 4 eva' + items[2].artist = u'three' + items[2].album = u'foo' items[2].year = 2003 items[2].comp = False for item in items: @@ -109,15 +113,15 @@ class DummyDataTestCase(_common.TestCase, AssertsMixin): def assert_items_matched_all(self, results): self.assert_items_matched(results, [ - 'foo bar', - 'baz qux', - 'beets 4 eva', + u'foo bar', + u'baz qux', + u'beets 4 eva', ]) class GetTest(DummyDataTestCase): def test_get_empty(self): - q = '' + q = u'' results = self.lib.items(q) self.assert_items_matched_all(results) @@ -127,152 +131,152 @@ class GetTest(DummyDataTestCase): self.assert_items_matched_all(results) def test_get_one_keyed_term(self): - q = 'title:qux' + q = u'title:qux' results = self.lib.items(q) - self.assert_items_matched(results, ['baz qux']) + self.assert_items_matched(results, [u'baz qux']) def test_get_one_keyed_regexp(self): - q = r'artist::t.+r' + q = u'artist::t.+r' results = self.lib.items(q) - self.assert_items_matched(results, ['beets 4 eva']) + self.assert_items_matched(results, [u'beets 4 eva']) def test_get_one_unkeyed_term(self): - q = 'three' + q = u'three' results = self.lib.items(q) - self.assert_items_matched(results, ['beets 4 eva']) + self.assert_items_matched(results, [u'beets 4 eva']) def test_get_one_unkeyed_regexp(self): - q = r':x$' + q = u':x$' results = self.lib.items(q) - self.assert_items_matched(results, ['baz qux']) + self.assert_items_matched(results, [u'baz qux']) def test_get_no_matches(self): - q = 'popebear' + q = u'popebear' results = self.lib.items(q) self.assert_items_matched(results, []) def test_invalid_key(self): - q = 'pope:bear' + q = u'pope:bear' results = self.lib.items(q) # Matches nothing since the flexattr is not present on the # objects. self.assert_items_matched(results, []) def test_term_case_insensitive(self): - q = 'oNE' + q = u'oNE' results = self.lib.items(q) - self.assert_items_matched(results, ['foo bar']) + self.assert_items_matched(results, [u'foo bar']) def test_regexp_case_sensitive(self): - q = r':oNE' + q = u':oNE' results = self.lib.items(q) self.assert_items_matched(results, []) - q = r':one' + q = u':one' results = self.lib.items(q) - self.assert_items_matched(results, ['foo bar']) + self.assert_items_matched(results, [u'foo bar']) def test_term_case_insensitive_with_key(self): - q = 'artist:thrEE' + q = u'artist:thrEE' results = self.lib.items(q) - self.assert_items_matched(results, ['beets 4 eva']) + self.assert_items_matched(results, [u'beets 4 eva']) def test_key_case_insensitive(self): - q = 'ArTiST:three' + q = u'ArTiST:three' results = self.lib.items(q) - self.assert_items_matched(results, ['beets 4 eva']) + self.assert_items_matched(results, [u'beets 4 eva']) def test_unkeyed_term_matches_multiple_columns(self): - q = 'baz' + q = u'baz' results = self.lib.items(q) self.assert_items_matched(results, [ - 'foo bar', - 'baz qux', + u'foo bar', + u'baz qux', ]) def test_unkeyed_regexp_matches_multiple_columns(self): - q = r':z$' + q = u':z$' results = self.lib.items(q) self.assert_items_matched(results, [ - 'foo bar', - 'baz qux', + u'foo bar', + u'baz qux', ]) def test_keyed_term_matches_only_one_column(self): - q = 'title:baz' + q = u'title:baz' results = self.lib.items(q) - self.assert_items_matched(results, ['baz qux']) + self.assert_items_matched(results, [u'baz qux']) def test_keyed_regexp_matches_only_one_column(self): - q = r'title::baz' + q = u'title::baz' results = self.lib.items(q) self.assert_items_matched(results, [ - 'baz qux', + u'baz qux', ]) def test_multiple_terms_narrow_search(self): - q = 'qux baz' + q = u'qux baz' results = self.lib.items(q) self.assert_items_matched(results, [ - 'baz qux', + u'baz qux', ]) def test_multiple_regexps_narrow_search(self): - q = r':baz :qux' + q = u':baz :qux' results = self.lib.items(q) - self.assert_items_matched(results, ['baz qux']) + self.assert_items_matched(results, [u'baz qux']) def test_mixed_terms_regexps_narrow_search(self): - q = r':baz qux' + q = u':baz qux' results = self.lib.items(q) - self.assert_items_matched(results, ['baz qux']) + self.assert_items_matched(results, [u'baz qux']) def test_single_year(self): - q = 'year:2001' + q = u'year:2001' results = self.lib.items(q) - self.assert_items_matched(results, ['foo bar']) + self.assert_items_matched(results, [u'foo bar']) def test_year_range(self): - q = 'year:2000..2002' + q = u'year:2000..2002' results = self.lib.items(q) self.assert_items_matched(results, [ - 'foo bar', - 'baz qux', + u'foo bar', + u'baz qux', ]) def test_singleton_true(self): - q = 'singleton:true' + q = u'singleton:true' results = self.lib.items(q) - self.assert_items_matched(results, ['beets 4 eva']) + self.assert_items_matched(results, [u'beets 4 eva']) def test_singleton_false(self): - q = 'singleton:false' + q = u'singleton:false' results = self.lib.items(q) - self.assert_items_matched(results, ['foo bar', 'baz qux']) + self.assert_items_matched(results, [u'foo bar', u'baz qux']) def test_compilation_true(self): - q = 'comp:true' + q = u'comp:true' results = self.lib.items(q) - self.assert_items_matched(results, ['foo bar', 'baz qux']) + self.assert_items_matched(results, [u'foo bar', u'baz qux']) def test_compilation_false(self): - q = 'comp:false' + q = u'comp:false' results = self.lib.items(q) - self.assert_items_matched(results, ['beets 4 eva']) + self.assert_items_matched(results, [u'beets 4 eva']) def test_unknown_field_name_no_results(self): - q = 'xyzzy:nonsense' + q = u'xyzzy:nonsense' results = self.lib.items(q) titles = [i.title for i in results] self.assertEqual(titles, []) def test_unknown_field_name_no_results_in_album_query(self): - q = 'xyzzy:nonsense' + q = u'xyzzy:nonsense' results = self.lib.albums(q) names = [a.album for a in results] self.assertEqual(names, []) def test_item_field_name_matches_nothing_in_album_query(self): - q = 'format:nonsense' + q = u'format:nonsense' results = self.lib.albums(q) names = [a.album for a in results] self.assertEqual(names, []) @@ -287,24 +291,28 @@ class GetTest(DummyDataTestCase): self.assert_items_matched(results, [u'caf\xe9']) def test_numeric_search_positive(self): - q = dbcore.query.NumericQuery('year', '2001') + q = dbcore.query.NumericQuery('year', u'2001') results = self.lib.items(q) self.assertTrue(results) def test_numeric_search_negative(self): - q = dbcore.query.NumericQuery('year', '1999') + q = dbcore.query.NumericQuery('year', u'1999') results = self.lib.items(q) self.assertFalse(results) def test_invalid_query(self): - with self.assertRaises(InvalidQueryArgumentTypeError) as raised: - dbcore.query.NumericQuery('year', '199a') - self.assertIn('not an int', unicode(raised.exception)) + with self.assertRaises(InvalidQueryArgumentValueError) as raised: + dbcore.query.NumericQuery('year', u'199a') + self.assertIn(u'not an int', six.text_type(raised.exception)) - with self.assertRaises(InvalidQueryArgumentTypeError) as raised: - dbcore.query.RegexpQuery('year', '199(') - self.assertIn('not a regular expression', unicode(raised.exception)) - self.assertIn('unbalanced parenthesis', unicode(raised.exception)) + with self.assertRaises(InvalidQueryArgumentValueError) as raised: + dbcore.query.RegexpQuery('year', u'199(') + exception_text = six.text_type(raised.exception) + self.assertIn(u'not a regular expression', exception_text) + if sys.version_info >= (3, 5): + self.assertIn(u'unterminated subpattern', exception_text) + else: + self.assertIn(u'unbalanced parenthesis', exception_text) self.assertIsInstance(raised.exception, ParsingError) @@ -314,53 +322,53 @@ class MatchTest(_common.TestCase): self.item = _common.item() def test_regex_match_positive(self): - q = dbcore.query.RegexpQuery('album', '^the album$') + q = dbcore.query.RegexpQuery('album', u'^the album$') self.assertTrue(q.match(self.item)) def test_regex_match_negative(self): - q = dbcore.query.RegexpQuery('album', '^album$') + q = dbcore.query.RegexpQuery('album', u'^album$') self.assertFalse(q.match(self.item)) def test_regex_match_non_string_value(self): - q = dbcore.query.RegexpQuery('disc', '^6$') + q = dbcore.query.RegexpQuery('disc', u'^6$') self.assertTrue(q.match(self.item)) def test_substring_match_positive(self): - q = dbcore.query.SubstringQuery('album', 'album') + q = dbcore.query.SubstringQuery('album', u'album') self.assertTrue(q.match(self.item)) def test_substring_match_negative(self): - q = dbcore.query.SubstringQuery('album', 'ablum') + q = dbcore.query.SubstringQuery('album', u'ablum') self.assertFalse(q.match(self.item)) def test_substring_match_non_string_value(self): - q = dbcore.query.SubstringQuery('disc', '6') + q = dbcore.query.SubstringQuery('disc', u'6') self.assertTrue(q.match(self.item)) def test_year_match_positive(self): - q = dbcore.query.NumericQuery('year', '1') + q = dbcore.query.NumericQuery('year', u'1') self.assertTrue(q.match(self.item)) def test_year_match_negative(self): - q = dbcore.query.NumericQuery('year', '10') + q = dbcore.query.NumericQuery('year', u'10') self.assertFalse(q.match(self.item)) def test_bitrate_range_positive(self): - q = dbcore.query.NumericQuery('bitrate', '100000..200000') + q = dbcore.query.NumericQuery('bitrate', u'100000..200000') self.assertTrue(q.match(self.item)) def test_bitrate_range_negative(self): - q = dbcore.query.NumericQuery('bitrate', '200000..300000') + q = dbcore.query.NumericQuery('bitrate', u'200000..300000') self.assertFalse(q.match(self.item)) def test_open_range(self): - dbcore.query.NumericQuery('bitrate', '100000..') + dbcore.query.NumericQuery('bitrate', u'100000..') def test_eq(self): - q1 = dbcore.query.MatchQuery('foo', 'bar') - q2 = dbcore.query.MatchQuery('foo', 'bar') - q3 = dbcore.query.MatchQuery('foo', 'baz') - q4 = dbcore.query.StringFieldQuery('foo', 'bar') + q1 = dbcore.query.MatchQuery('foo', u'bar') + q2 = dbcore.query.MatchQuery('foo', u'bar') + q3 = dbcore.query.MatchQuery('foo', u'baz') + q4 = dbcore.query.StringFieldQuery('foo', u'bar') self.assertEqual(q1, q2) self.assertNotEqual(q1, q3) self.assertNotEqual(q1, q4) @@ -370,45 +378,66 @@ class MatchTest(_common.TestCase): class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): def setUp(self): super(PathQueryTest, self).setUp() - self.i.path = '/a/b/c.mp3' - self.i.title = 'path item' - self.i.album = 'path album' + + # This is the item we'll try to match. + self.i.path = util.normpath('/a/b/c.mp3') + self.i.title = u'path item' + self.i.album = u'path album' self.i.store() self.lib.add_album([self.i]) - self.patcher = patch('beets.library.os.path.exists') - self.patcher.start().return_value = True + # A second item for testing exclusion. + i2 = _common.item() + i2.path = util.normpath('/x/y/z.mp3') + i2.title = 'another item' + i2.album = 'another album' + self.lib.add(i2) + self.lib.add_album([i2]) + + # Unadorned path queries with path separators in them are considered + # path queries only when the path in question actually exists. So we + # mock the existence check to return true. + self.patcher_exists = patch('beets.library.os.path.exists') + self.patcher_exists.start().return_value = True + + # We have to create function samefile as it does not exist on + # Windows and python 2.7 + self.patcher_samefile = patch('beets.library.os.path.samefile', + create=True) + self.patcher_samefile.start().return_value = True def tearDown(self): super(PathQueryTest, self).tearDown() - self.patcher.stop() + + self.patcher_samefile.stop() + self.patcher_exists.stop() def test_path_exact_match(self): - q = 'path:/a/b/c.mp3' + q = u'path:/a/b/c.mp3' results = self.lib.items(q) - self.assert_items_matched(results, ['path item']) + self.assert_items_matched(results, [u'path item']) results = self.lib.albums(q) self.assert_albums_matched(results, []) def test_parent_directory_no_slash(self): - q = 'path:/a' + q = u'path:/a' results = self.lib.items(q) - self.assert_items_matched(results, ['path item']) + self.assert_items_matched(results, [u'path item']) results = self.lib.albums(q) - self.assert_albums_matched(results, ['path album']) + self.assert_albums_matched(results, [u'path album']) def test_parent_directory_with_slash(self): - q = 'path:/a/' + q = u'path:/a/' results = self.lib.items(q) - self.assert_items_matched(results, ['path item']) + self.assert_items_matched(results, [u'path item']) results = self.lib.albums(q) - self.assert_albums_matched(results, ['path album']) + self.assert_albums_matched(results, [u'path album']) def test_no_match(self): - q = 'path:/xyzzy/' + q = u'path:/xyzzy/' results = self.lib.items(q) self.assert_items_matched(results, []) @@ -416,7 +445,7 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.assert_albums_matched(results, []) def test_fragment_no_match(self): - q = 'path:/b/' + q = u'path:/b/' results = self.lib.items(q) self.assert_items_matched(results, []) @@ -424,23 +453,29 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.assert_albums_matched(results, []) def test_nonnorm_path(self): - q = 'path:/x/../a/b' + q = u'path:/x/../a/b' results = self.lib.items(q) - self.assert_items_matched(results, ['path item']) + self.assert_items_matched(results, [u'path item']) results = self.lib.albums(q) - self.assert_albums_matched(results, ['path album']) + self.assert_albums_matched(results, [u'path album']) def test_slashed_query_matches_path(self): - q = '/a/b' + q = u'/a/b' + results = self.lib.items(q) + self.assert_items_matched(results, [u'path item']) + + results = self.lib.albums(q) + self.assert_albums_matched(results, [u'path album']) + + @unittest.skip('unfixed (#1865)') + def test_path_query_in_or_query(self): + q = '/a/b , /a/b' results = self.lib.items(q) self.assert_items_matched(results, ['path item']) - results = self.lib.albums(q) - self.assert_albums_matched(results, ['path album']) - def test_non_slashed_does_not_match_path(self): - q = 'c.mp3' + q = u'c.mp3' results = self.lib.items(q) self.assert_items_matched(results, []) @@ -448,74 +483,103 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.assert_albums_matched(results, []) def test_slashes_in_explicit_field_does_not_match_path(self): - q = 'title:/a/b' + q = u'title:/a/b' results = self.lib.items(q) self.assert_items_matched(results, []) def test_path_item_regex(self): - q = 'path::\\.mp3$' + q = u'path::c\\.mp3$' results = self.lib.items(q) - self.assert_items_matched(results, ['path item']) + self.assert_items_matched(results, [u'path item']) def test_path_album_regex(self): - q = 'path::b' + q = u'path::b' results = self.lib.albums(q) - self.assert_albums_matched(results, ['path album']) + self.assert_albums_matched(results, [u'path album']) def test_escape_underscore(self): - self.add_album(path='/a/_/title.mp3', title='with underscore', - album='album with underscore') - q = 'path:/a/_' + self.add_album(path=b'/a/_/title.mp3', title=u'with underscore', + album=u'album with underscore') + q = u'path:/a/_' results = self.lib.items(q) - self.assert_items_matched(results, ['with underscore']) + self.assert_items_matched(results, [u'with underscore']) results = self.lib.albums(q) - self.assert_albums_matched(results, ['album with underscore']) + self.assert_albums_matched(results, [u'album with underscore']) def test_escape_percent(self): - self.add_album(path='/a/%/title.mp3', title='with percent', - album='album with percent') - q = 'path:/a/%' + self.add_album(path=b'/a/%/title.mp3', title=u'with percent', + album=u'album with percent') + q = u'path:/a/%' results = self.lib.items(q) - self.assert_items_matched(results, ['with percent']) + self.assert_items_matched(results, [u'with percent']) results = self.lib.albums(q) - self.assert_albums_matched(results, ['album with percent']) + self.assert_albums_matched(results, [u'album with percent']) def test_escape_backslash(self): - self.add_album(path=r'/a/\x/title.mp3', title='with backslash', - album='album with backslash') - q = r'path:/a/\\x' + self.add_album(path=br'/a/\x/title.mp3', title=u'with backslash', + album=u'album with backslash') + q = u'path:/a/\\\\x' results = self.lib.items(q) - self.assert_items_matched(results, ['with backslash']) + self.assert_items_matched(results, [u'with backslash']) results = self.lib.albums(q) - self.assert_albums_matched(results, ['album with backslash']) + self.assert_albums_matched(results, [u'album with backslash']) def test_case_sensitivity(self): - self.add_album(path='/A/B/C2.mp3', title='caps path') + self.add_album(path=b'/A/B/C2.mp3', title=u'caps path') - makeq = partial(beets.library.PathQuery, 'path', '/A/B') + makeq = partial(beets.library.PathQuery, u'path', '/A/B') results = self.lib.items(makeq(case_sensitive=True)) - self.assert_items_matched(results, ['caps path']) + self.assert_items_matched(results, [u'caps path']) results = self.lib.items(makeq(case_sensitive=False)) - self.assert_items_matched(results, ['path item', 'caps path']) + self.assert_items_matched(results, [u'path item', u'caps path']) - # test platform-aware default sensitivity + # Check for correct case sensitivity selection (this check + # only works on non-Windows OSes). with _common.system_mock('Darwin'): - q = makeq() - self.assertEqual(q.case_sensitive, True) - - with _common.system_mock('Windows'): + # exists = True and samefile = True => Case insensitive q = makeq() self.assertEqual(q.case_sensitive, False) + # exists = True and samefile = False => Case sensitive + self.patcher_samefile.stop() + self.patcher_samefile.start().return_value = False + try: + q = makeq() + self.assertEqual(q.case_sensitive, True) + finally: + self.patcher_samefile.stop() + self.patcher_samefile.start().return_value = True + + # Test platform-aware default sensitivity when the library path + # does not exist. For the duration of this check, we change the + # `os.path.exists` mock to return False. + self.patcher_exists.stop() + self.patcher_exists.start().return_value = False + try: + with _common.system_mock('Darwin'): + q = makeq() + self.assertEqual(q.case_sensitive, True) + + with _common.system_mock('Windows'): + q = makeq() + self.assertEqual(q.case_sensitive, False) + finally: + # Restore the `os.path.exists` mock to its original state. + self.patcher_exists.stop() + self.patcher_exists.start().return_value = True + @patch('beets.library.os') def test_path_sep_detection(self, mock_os): mock_os.sep = '/' + mock_os.altsep = None + mock_os.path.exists = lambda p: True is_path = beets.library.PathQuery.is_path_query + self.assertTrue(is_path('/foo/bar')) self.assertTrue(is_path('foo/bar')) self.assertTrue(is_path('foo/')) @@ -524,29 +588,55 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.assertFalse(is_path('foo:bar/')) self.assertFalse(is_path('foo:/bar')) - def test_path_detection(self): - # cover existence test - self.patcher.stop() + def test_detect_absolute_path(self): + if platform.system() == 'Windows': + # Because the absolute path begins with something like C:, we + # can't disambiguate it from an ordinary query. + self.skipTest('Windows absolute paths do not work as queries') + + # Don't patch `os.path.exists`; we'll actually create a file when + # it exists. + self.patcher_exists.stop() is_path = beets.library.PathQuery.is_path_query try: - self.touch(b'foo/bar') - # test absolute - self.assertTrue(is_path(os.path.join(self.temp_dir, b'foo/bar'))) - self.assertTrue(is_path(os.path.join(self.temp_dir, b'foo'))) - self.assertFalse(is_path(b'foo/bar')) + path = self.touch(os.path.join(b'foo', b'bar')) + path = path.decode('utf-8') + # The file itself. + self.assertTrue(is_path(path)) + + # The parent directory. + parent = os.path.dirname(path) + self.assertTrue(is_path(parent)) + + # Some non-existent path. + self.assertFalse(is_path(path + u'baz')) + + finally: + # Restart the `os.path.exists` patch. + self.patcher_exists.start() + + def test_detect_relative_path(self): + self.patcher_exists.stop() + is_path = beets.library.PathQuery.is_path_query + + try: + self.touch(os.path.join(b'foo', b'bar')) + + # Temporarily change directory so relative paths work. cur_dir = os.getcwd() try: os.chdir(self.temp_dir) - self.assertTrue(is_path(b'foo/')) - self.assertTrue(is_path(b'foo/bar')) - self.assertTrue(is_path(b'foo/bar:tagada')) - self.assertFalse(is_path(b'bar')) + self.assertTrue(is_path(u'foo/')) + self.assertTrue(is_path(u'foo/bar')) + self.assertTrue(is_path(u'foo/bar:tagada')) + self.assertFalse(is_path(u'bar')) finally: os.chdir(cur_dir) + finally: - self.patcher.start() + self.patcher_exists.start() class IntQueryTest(unittest.TestCase, TestHelper): @@ -559,32 +649,32 @@ class IntQueryTest(unittest.TestCase, TestHelper): def test_exact_value_match(self): item = self.add_item(bpm=120) - matched = self.lib.items('bpm:120').get() + matched = self.lib.items(u'bpm:120').get() self.assertEqual(item.id, matched.id) def test_range_match(self): item = self.add_item(bpm=120) self.add_item(bpm=130) - matched = self.lib.items('bpm:110..125') + matched = self.lib.items(u'bpm:110..125') self.assertEqual(1, len(matched)) self.assertEqual(item.id, matched.get().id) def test_flex_range_match(self): Item._types = {'myint': types.Integer()} item = self.add_item(myint=2) - matched = self.lib.items('myint:2').get() + matched = self.lib.items(u'myint:2').get() self.assertEqual(item.id, matched.id) def test_flex_dont_match_missing(self): Item._types = {'myint': types.Integer()} self.add_item() - matched = self.lib.items('myint:2').get() + matched = self.lib.items(u'myint:2').get() self.assertIsNone(matched) def test_no_substring_match(self): self.add_item(bpm=120) - matched = self.lib.items('bpm:12').get() + matched = self.lib.items(u'bpm:12').get() self.assertIsNone(matched) @@ -600,35 +690,35 @@ class BoolQueryTest(unittest.TestCase, TestHelper): def test_parse_true(self): item_true = self.add_item(comp=True) item_false = self.add_item(comp=False) - matched = self.lib.items('comp:true') + matched = self.lib.items(u'comp:true') self.assertInResult(item_true, matched) self.assertNotInResult(item_false, matched) def test_flex_parse_true(self): item_true = self.add_item(flexbool=True) item_false = self.add_item(flexbool=False) - matched = self.lib.items('flexbool:true') + matched = self.lib.items(u'flexbool:true') self.assertInResult(item_true, matched) self.assertNotInResult(item_false, matched) def test_flex_parse_false(self): item_true = self.add_item(flexbool=True) item_false = self.add_item(flexbool=False) - matched = self.lib.items('flexbool:false') + matched = self.lib.items(u'flexbool:false') self.assertInResult(item_false, matched) self.assertNotInResult(item_true, matched) def test_flex_parse_1(self): item_true = self.add_item(flexbool=True) item_false = self.add_item(flexbool=False) - matched = self.lib.items('flexbool:1') + matched = self.lib.items(u'flexbool:1') self.assertInResult(item_true, matched) self.assertNotInResult(item_false, matched) def test_flex_parse_0(self): item_true = self.add_item(flexbool=True) item_false = self.add_item(flexbool=False) - matched = self.lib.items('flexbool:0') + matched = self.lib.items(u'flexbool:0') self.assertInResult(item_false, matched) self.assertNotInResult(item_true, matched) @@ -636,26 +726,26 @@ class BoolQueryTest(unittest.TestCase, TestHelper): # TODO this should be the other way around item_true = self.add_item(flexbool=True) item_false = self.add_item(flexbool=False) - matched = self.lib.items('flexbool:something') + matched = self.lib.items(u'flexbool:something') self.assertInResult(item_false, matched) self.assertNotInResult(item_true, matched) class DefaultSearchFieldsTest(DummyDataTestCase): def test_albums_matches_album(self): - albums = list(self.lib.albums('baz')) + albums = list(self.lib.albums(u'baz')) self.assertEqual(len(albums), 1) def test_albums_matches_albumartist(self): - albums = list(self.lib.albums(['album artist'])) + albums = list(self.lib.albums([u'album artist'])) self.assertEqual(len(albums), 1) def test_items_matches_title(self): - items = self.lib.items('beets') - self.assert_items_matched(items, ['beets 4 eva']) + items = self.lib.items(u'beets') + self.assert_items_matched(items, [u'beets 4 eva']) def test_items_does_not_match_year(self): - items = self.lib.items('2001') + items = self.lib.items(u'2001') self.assert_items_matched(items, []) @@ -668,24 +758,266 @@ class NoneQueryTest(unittest.TestCase, TestHelper): singleton = self.add_item() album_item = self.add_album().items().get() - matched = self.lib.items(NoneQuery('album_id')) + matched = self.lib.items(NoneQuery(u'album_id')) self.assertInResult(singleton, matched) self.assertNotInResult(album_item, matched) def test_match_after_set_none(self): item = self.add_item(rg_track_gain=0) - matched = self.lib.items(NoneQuery('rg_track_gain')) + matched = self.lib.items(NoneQuery(u'rg_track_gain')) self.assertNotInResult(item, matched) item['rg_track_gain'] = None item.store() - matched = self.lib.items(NoneQuery('rg_track_gain')) + matched = self.lib.items(NoneQuery(u'rg_track_gain')) self.assertInResult(item, matched) +class NotQueryMatchTest(_common.TestCase): + """Test `query.NotQuery` matching against a single item, using the same + cases and assertions as on `MatchTest`, plus assertion on the negated + queries (ie. assertTrue(q) -> assertFalse(NotQuery(q))). + """ + def setUp(self): + super(NotQueryMatchTest, self).setUp() + self.item = _common.item() + + def test_regex_match_positive(self): + q = dbcore.query.RegexpQuery(u'album', u'^the album$') + self.assertTrue(q.match(self.item)) + self.assertFalse(dbcore.query.NotQuery(q).match(self.item)) + + def test_regex_match_negative(self): + q = dbcore.query.RegexpQuery(u'album', u'^album$') + self.assertFalse(q.match(self.item)) + self.assertTrue(dbcore.query.NotQuery(q).match(self.item)) + + def test_regex_match_non_string_value(self): + q = dbcore.query.RegexpQuery(u'disc', u'^6$') + self.assertTrue(q.match(self.item)) + self.assertFalse(dbcore.query.NotQuery(q).match(self.item)) + + def test_substring_match_positive(self): + q = dbcore.query.SubstringQuery(u'album', u'album') + self.assertTrue(q.match(self.item)) + self.assertFalse(dbcore.query.NotQuery(q).match(self.item)) + + def test_substring_match_negative(self): + q = dbcore.query.SubstringQuery(u'album', u'ablum') + self.assertFalse(q.match(self.item)) + self.assertTrue(dbcore.query.NotQuery(q).match(self.item)) + + def test_substring_match_non_string_value(self): + q = dbcore.query.SubstringQuery(u'disc', u'6') + self.assertTrue(q.match(self.item)) + self.assertFalse(dbcore.query.NotQuery(q).match(self.item)) + + def test_year_match_positive(self): + q = dbcore.query.NumericQuery(u'year', u'1') + self.assertTrue(q.match(self.item)) + self.assertFalse(dbcore.query.NotQuery(q).match(self.item)) + + def test_year_match_negative(self): + q = dbcore.query.NumericQuery(u'year', u'10') + self.assertFalse(q.match(self.item)) + self.assertTrue(dbcore.query.NotQuery(q).match(self.item)) + + def test_bitrate_range_positive(self): + q = dbcore.query.NumericQuery(u'bitrate', u'100000..200000') + self.assertTrue(q.match(self.item)) + self.assertFalse(dbcore.query.NotQuery(q).match(self.item)) + + def test_bitrate_range_negative(self): + q = dbcore.query.NumericQuery(u'bitrate', u'200000..300000') + self.assertFalse(q.match(self.item)) + self.assertTrue(dbcore.query.NotQuery(q).match(self.item)) + + def test_open_range(self): + q = dbcore.query.NumericQuery(u'bitrate', u'100000..') + dbcore.query.NotQuery(q) + + +class NotQueryTest(DummyDataTestCase): + """Test `query.NotQuery` against the dummy data: + - `test_type_xxx`: tests for the negation of a particular XxxQuery class. + - `test_get_yyy`: tests on query strings (similar to `GetTest`) + """ + def assertNegationProperties(self, q): # noqa + """Given a Query `q`, assert that: + - q OR not(q) == all items + - q AND not(q) == 0 + - not(not(q)) == q + """ + not_q = dbcore.query.NotQuery(q) + # assert using OrQuery, AndQuery + q_or = dbcore.query.OrQuery([q, not_q]) + q_and = dbcore.query.AndQuery([q, not_q]) + self.assert_items_matched_all(self.lib.items(q_or)) + self.assert_items_matched(self.lib.items(q_and), []) + + # assert manually checking the item titles + all_titles = set([i.title for i in self.lib.items()]) + q_results = set([i.title for i in self.lib.items(q)]) + not_q_results = set([i.title for i in self.lib.items(not_q)]) + self.assertEqual(q_results.union(not_q_results), all_titles) + self.assertEqual(q_results.intersection(not_q_results), set()) + + # round trip + not_not_q = dbcore.query.NotQuery(not_q) + self.assertEqual(set([i.title for i in self.lib.items(q)]), + set([i.title for i in self.lib.items(not_not_q)])) + + def test_type_and(self): + # not(a and b) <-> not(a) or not(b) + q = dbcore.query.AndQuery([ + dbcore.query.BooleanQuery(u'comp', True), + dbcore.query.NumericQuery(u'year', u'2002')], + ) + not_results = self.lib.items(dbcore.query.NotQuery(q)) + self.assert_items_matched(not_results, [u'foo bar', u'beets 4 eva']) + self.assertNegationProperties(q) + + def test_type_anyfield(self): + q = dbcore.query.AnyFieldQuery(u'foo', [u'title', u'artist', u'album'], + dbcore.query.SubstringQuery) + not_results = self.lib.items(dbcore.query.NotQuery(q)) + self.assert_items_matched(not_results, [u'baz qux']) + self.assertNegationProperties(q) + + def test_type_boolean(self): + q = dbcore.query.BooleanQuery(u'comp', True) + not_results = self.lib.items(dbcore.query.NotQuery(q)) + self.assert_items_matched(not_results, [u'beets 4 eva']) + self.assertNegationProperties(q) + + def test_type_date(self): + q = dbcore.query.DateQuery(u'added', u'2000-01-01') + not_results = self.lib.items(dbcore.query.NotQuery(q)) + # query date is in the past, thus the 'not' results should contain all + # items + self.assert_items_matched(not_results, [u'foo bar', u'baz qux', + u'beets 4 eva']) + self.assertNegationProperties(q) + + def test_type_false(self): + q = dbcore.query.FalseQuery() + not_results = self.lib.items(dbcore.query.NotQuery(q)) + self.assert_items_matched_all(not_results) + self.assertNegationProperties(q) + + def test_type_match(self): + q = dbcore.query.MatchQuery(u'year', u'2003') + not_results = self.lib.items(dbcore.query.NotQuery(q)) + self.assert_items_matched(not_results, [u'foo bar', u'baz qux']) + self.assertNegationProperties(q) + + def test_type_none(self): + q = dbcore.query.NoneQuery(u'rg_track_gain') + not_results = self.lib.items(dbcore.query.NotQuery(q)) + self.assert_items_matched(not_results, []) + self.assertNegationProperties(q) + + def test_type_numeric(self): + q = dbcore.query.NumericQuery(u'year', u'2001..2002') + not_results = self.lib.items(dbcore.query.NotQuery(q)) + self.assert_items_matched(not_results, [u'beets 4 eva']) + self.assertNegationProperties(q) + + def test_type_or(self): + # not(a or b) <-> not(a) and not(b) + q = dbcore.query.OrQuery([dbcore.query.BooleanQuery(u'comp', True), + dbcore.query.NumericQuery(u'year', u'2002')]) + not_results = self.lib.items(dbcore.query.NotQuery(q)) + self.assert_items_matched(not_results, [u'beets 4 eva']) + self.assertNegationProperties(q) + + def test_type_regexp(self): + q = dbcore.query.RegexpQuery(u'artist', u'^t') + not_results = self.lib.items(dbcore.query.NotQuery(q)) + self.assert_items_matched(not_results, [u'foo bar']) + self.assertNegationProperties(q) + + def test_type_substring(self): + q = dbcore.query.SubstringQuery(u'album', u'ba') + not_results = self.lib.items(dbcore.query.NotQuery(q)) + self.assert_items_matched(not_results, [u'beets 4 eva']) + self.assertNegationProperties(q) + + def test_type_true(self): + q = dbcore.query.TrueQuery() + not_results = self.lib.items(dbcore.query.NotQuery(q)) + self.assert_items_matched(not_results, []) + self.assertNegationProperties(q) + + def test_get_prefixes_keyed(self): + """Test both negation prefixes on a keyed query.""" + q0 = u'-title:qux' + q1 = u'^title:qux' + results0 = self.lib.items(q0) + results1 = self.lib.items(q1) + self.assert_items_matched(results0, [u'foo bar', u'beets 4 eva']) + self.assert_items_matched(results1, [u'foo bar', u'beets 4 eva']) + + def test_get_prefixes_unkeyed(self): + """Test both negation prefixes on an unkeyed query.""" + q0 = u'-qux' + q1 = u'^qux' + results0 = self.lib.items(q0) + results1 = self.lib.items(q1) + self.assert_items_matched(results0, [u'foo bar', u'beets 4 eva']) + self.assert_items_matched(results1, [u'foo bar', u'beets 4 eva']) + + def test_get_one_keyed_regexp(self): + q = u'-artist::t.+r' + results = self.lib.items(q) + self.assert_items_matched(results, [u'foo bar', u'baz qux']) + + def test_get_one_unkeyed_regexp(self): + q = u'-:x$' + results = self.lib.items(q) + self.assert_items_matched(results, [u'foo bar', u'beets 4 eva']) + + def test_get_multiple_terms(self): + q = u'baz -bar' + results = self.lib.items(q) + self.assert_items_matched(results, [u'baz qux']) + + def test_get_mixed_terms(self): + q = u'baz -title:bar' + results = self.lib.items(q) + self.assert_items_matched(results, [u'baz qux']) + + def test_fast_vs_slow(self): + """Test that the results are the same regardless of the `fast` flag + for negated `FieldQuery`s. + + TODO: investigate NoneQuery(fast=False), as it is raising + AttributeError: type object 'NoneQuery' has no attribute 'field' + at NoneQuery.match() (due to being @classmethod, and no self?) + """ + classes = [(dbcore.query.DateQuery, [u'added', u'2001-01-01']), + (dbcore.query.MatchQuery, [u'artist', u'one']), + # (dbcore.query.NoneQuery, ['rg_track_gain']), + (dbcore.query.NumericQuery, [u'year', u'2002']), + (dbcore.query.StringFieldQuery, [u'year', u'2001']), + (dbcore.query.RegexpQuery, [u'album', u'^.a']), + (dbcore.query.SubstringQuery, [u'title', u'x'])] + + for klass, args in classes: + q_fast = dbcore.query.NotQuery(klass(*(args + [True]))) + q_slow = dbcore.query.NotQuery(klass(*(args + [False]))) + + try: + self.assertEqual([i.title for i in self.lib.items(q_fast)], + [i.title for i in self.lib.items(q_slow)]) + except NotImplementedError: + # ignore classes that do not provide `fast` implementation + pass + + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_replaygain.py b/test/test_replaygain.py index 3eb93520f..6ddee54da 100644 --- a/test/test_replaygain.py +++ b/test/test_replaygain.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes +# Copyright 2016, Thomas Scholtes # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -13,13 +14,17 @@ # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function + +import unittest +import six -from test._common import unittest from test.helper import TestHelper, has_program +from beets import config from beets.mediafile import MediaFile +from beetsplug.replaygain import (FatalGstreamerPluginReplayGainError, + GStreamerBackend) try: import gi @@ -43,24 +48,24 @@ class ReplayGainCliTestBase(TestHelper): def setUp(self): self.setup_beets() + self.config['replaygain']['backend'] = self.backend try: self.load_plugins('replaygain') - except: + except Exception: import sys # store exception info so an error in teardown does not swallow it exc_info = sys.exc_info() try: self.teardown_beets() self.unload_plugins() - except: + except Exception: # if load_plugins() failed then setup is incomplete and # teardown operations may fail. In particular # {Item,Album} # may not have the _original_types attribute in unload_plugins pass - raise exc_info[1], None, exc_info[2] + six.reraise(exc_info[1], None, exc_info[2]) - self.config['replaygain']['backend'] = self.backend album = self.add_album_fixture(2) for item in album.items(): self._reset_replaygain(item) @@ -86,6 +91,13 @@ class ReplayGainCliTestBase(TestHelper): self.assertIsNone(mediafile.rg_track_gain) self.run_command('replaygain') + + # Skip the test if rg_track_peak and rg_track gain is None, assuming + # that it could only happen if the decoder plugins are missing. + if all(i.rg_track_peak is None and i.rg_track_gain is None + for i in self.lib.items()): + self.skipTest(u'decoder plugins could not be loaded.') + for item in self.lib.items(): self.assertIsNotNone(item.rg_track_peak) self.assertIsNotNone(item.rg_track_gain) @@ -96,11 +108,11 @@ class ReplayGainCliTestBase(TestHelper): mediafile.rg_track_gain, item.rg_track_gain, places=2) def test_cli_skips_calculated_tracks(self): - self.run_command('replaygain') + self.run_command(u'replaygain') item = self.lib.items()[0] peak = item.rg_track_peak item.rg_track_gain = 0.0 - self.run_command('replaygain') + self.run_command(u'replaygain') self.assertEqual(item.rg_track_gain, 0.0) self.assertEqual(item.rg_track_peak, peak) @@ -110,7 +122,7 @@ class ReplayGainCliTestBase(TestHelper): self.assertIsNone(mediafile.rg_album_peak) self.assertIsNone(mediafile.rg_album_gain) - self.run_command('replaygain', '-a') + self.run_command(u'replaygain', u'-a') peaks = [] gains = [] @@ -127,17 +139,29 @@ class ReplayGainCliTestBase(TestHelper): self.assertNotEqual(max(peaks), 0.0) -@unittest.skipIf(not GST_AVAILABLE, 'gstreamer cannot be found') +@unittest.skipIf(not GST_AVAILABLE, u'gstreamer cannot be found') class ReplayGainGstCliTest(ReplayGainCliTestBase, unittest.TestCase): backend = u'gstreamer' + def setUp(self): + try: + # Check if required plugins can be loaded by instantiating a + # GStreamerBackend (via its .__init__). + config['replaygain']['targetlevel'] = 89 + GStreamerBackend(config['replaygain'], None) + except FatalGstreamerPluginReplayGainError as e: + # Skip the test if plugins could not be loaded. + self.skipTest(str(e)) -@unittest.skipIf(not GAIN_PROG_AVAILABLE, 'no *gain command found') + super(ReplayGainGstCliTest, self).setUp() + + +@unittest.skipIf(not GAIN_PROG_AVAILABLE, u'no *gain command found') class ReplayGainCmdCliTest(ReplayGainCliTestBase, unittest.TestCase): backend = u'command' -@unittest.skipIf(not LOUDNESS_PROG_AVAILABLE, 'bs1770gain cannot be found') +@unittest.skipIf(not LOUDNESS_PROG_AVAILABLE, u'bs1770gain cannot be found') class ReplayGainLdnsCliTest(ReplayGainCliTestBase, unittest.TestCase): backend = u'bs1770gain' @@ -145,5 +169,5 @@ class ReplayGainLdnsCliTest(ReplayGainCliTestBase, unittest.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_smartplaylist.py b/test/test_smartplaylist.py index ddfa8a156..af60501a4 100644 --- a/test/test_smartplaylist.py +++ b/test/test_smartplaylist.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Bruno Cauet. +# Copyright 2016, Bruno Cauet. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,12 +13,12 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function from os import path, remove from tempfile import mkdtemp from shutil import rmtree +import unittest from mock import Mock, MagicMock @@ -25,11 +26,10 @@ from beetsplug.smartplaylist import SmartPlaylistPlugin from beets.library import Item, Album, parse_query_string from beets.dbcore import OrQuery from beets.dbcore.query import NullSort, MultipleSort, FixedFieldSort -from beets.util import syspath +from beets.util import syspath, bytestring_path, py3_path, CHAR_REPLACE from beets.ui import UserError from beets import config -from test._common import unittest from test.helper import TestHelper @@ -45,36 +45,42 @@ class SmartPlaylistTest(unittest.TestCase): self.assertEqual(spl._unmatched_playlists, set()) config['smartplaylist']['playlists'].set([ - {'name': 'foo', - 'query': 'FOO foo'}, - {'name': 'bar', - 'album_query': ['BAR bar1', 'BAR bar2']}, - {'name': 'baz', - 'query': 'BAZ baz', - 'album_query': 'BAZ baz'} + {'name': u'foo', + 'query': u'FOO foo'}, + {'name': u'bar', + 'album_query': [u'BAR bar1', u'BAR bar2']}, + {'name': u'baz', + 'query': u'BAZ baz', + 'album_query': u'BAZ baz'} ]) spl.build_queries() self.assertEqual(spl._matched_playlists, set()) - foo_foo = parse_query_string('FOO foo', Item) - baz_baz = parse_query_string('BAZ baz', Item) - baz_baz2 = parse_query_string('BAZ baz', Album) - bar_bar = OrQuery((parse_query_string('BAR bar1', Album)[0], - parse_query_string('BAR bar2', Album)[0])) + foo_foo = parse_query_string(u'FOO foo', Item) + baz_baz = parse_query_string(u'BAZ baz', Item) + baz_baz2 = parse_query_string(u'BAZ baz', Album) + bar_bar = OrQuery((parse_query_string(u'BAR bar1', Album)[0], + parse_query_string(u'BAR bar2', Album)[0])) self.assertEqual(spl._unmatched_playlists, set([ - ('foo', foo_foo, (None, None)), - ('baz', baz_baz, baz_baz2), - ('bar', (None, None), (bar_bar, None)), + (u'foo', foo_foo, (None, None)), + (u'baz', baz_baz, baz_baz2), + (u'bar', (None, None), (bar_bar, None)), ])) def test_build_queries_with_sorts(self): spl = SmartPlaylistPlugin() config['smartplaylist']['playlists'].set([ - {'name': 'no_sort', 'query': 'foo'}, - {'name': 'one_sort', 'query': 'foo year+'}, - {'name': 'only_empty_sorts', 'query': ['foo', 'bar']}, - {'name': 'one_non_empty_sort', 'query': ['foo year+', 'bar']}, - {'name': 'multiple_sorts', 'query': ['foo year+', 'bar genre-']}, - {'name': 'mixed', 'query': ['foo year+', 'bar', 'baz genre+ id-']} + {'name': u'no_sort', + 'query': u'foo'}, + {'name': u'one_sort', + 'query': u'foo year+'}, + {'name': u'only_empty_sorts', + 'query': [u'foo', u'bar']}, + {'name': u'one_non_empty_sort', + 'query': [u'foo year+', u'bar']}, + {'name': u'multiple_sorts', + 'query': [u'foo year+', u'bar genre-']}, + {'name': u'mixed', + 'query': [u'foo year+', u'bar', u'baz genre+ id-']} ]) spl.build_queries() @@ -82,15 +88,15 @@ class SmartPlaylistTest(unittest.TestCase): for name, (_, sort), _ in spl._unmatched_playlists) asseq = self.assertEqual # less cluttered code - S = FixedFieldSort # short cut since we're only dealing with this + sort = FixedFieldSort # short cut since we're only dealing with this asseq(sorts["no_sort"], NullSort()) - asseq(sorts["one_sort"], S('year')) + asseq(sorts["one_sort"], sort(u'year')) asseq(sorts["only_empty_sorts"], None) - asseq(sorts["one_non_empty_sort"], S('year')) + asseq(sorts["one_non_empty_sort"], sort(u'year')) asseq(sorts["multiple_sorts"], - MultipleSort([S('year'), S('genre', False)])) + MultipleSort([sort('year'), sort(u'genre', False)])) asseq(sorts["mixed"], - MultipleSort([S('year'), S('genre'), S('id', False)])) + MultipleSort([sort('year'), sort(u'genre'), sort(u'id', False)])) def test_matches(self): spl = SmartPlaylistPlugin() @@ -118,44 +124,48 @@ class SmartPlaylistTest(unittest.TestCase): spl = SmartPlaylistPlugin() nones = None, None - pl1 = '1', ('q1', None), nones - pl2 = '2', ('q2', None), nones - pl3 = '3', ('q3', None), nones + pl1 = '1', (u'q1', None), nones + pl2 = '2', (u'q2', None), nones + pl3 = '3', (u'q3', None), nones spl._unmatched_playlists = set([pl1, pl2, pl3]) spl._matched_playlists = set() spl.matches = Mock(return_value=False) - spl.db_change(None, "nothing") + spl.db_change(None, u"nothing") self.assertEqual(spl._unmatched_playlists, set([pl1, pl2, pl3])) self.assertEqual(spl._matched_playlists, set()) - spl.matches.side_effect = lambda _, q, __: q == 'q3' - spl.db_change(None, "matches 3") + spl.matches.side_effect = lambda _, q, __: q == u'q3' + spl.db_change(None, u"matches 3") self.assertEqual(spl._unmatched_playlists, set([pl1, pl2])) self.assertEqual(spl._matched_playlists, set([pl3])) - spl.matches.side_effect = lambda _, q, __: q == 'q1' - spl.db_change(None, "matches 3") + spl.matches.side_effect = lambda _, q, __: q == u'q1' + spl.db_change(None, u"matches 3") self.assertEqual(spl._matched_playlists, set([pl1, pl3])) self.assertEqual(spl._unmatched_playlists, set([pl2])) def test_playlist_update(self): spl = SmartPlaylistPlugin() - i = Mock(path='/tagada.mp3') - i.evaluate_template.side_effect = lambda x, _: x - q = Mock() - a_q = Mock() + i = Mock(path=b'/tagada.mp3') + i.evaluate_template.side_effect = \ + lambda pl, _: pl.replace(b'$title', b'ta:ga:da').decode() + lib = Mock() + lib.replacements = CHAR_REPLACE lib.items.return_value = [i] lib.albums.return_value = [] - pl = 'my_playlist.m3u', (q, None), (a_q, None) + + q = Mock() + a_q = Mock() + pl = b'$title-my<playlist>.m3u', (q, None), (a_q, None) spl._matched_playlists = [pl] - dir = mkdtemp() + dir = bytestring_path(mkdtemp()) config['smartplaylist']['relative_to'] = False - config['smartplaylist']['playlist_dir'] = dir + config['smartplaylist']['playlist_dir'] = py3_path(dir) try: spl.update_playlists(lib) except Exception: @@ -165,13 +175,13 @@ class SmartPlaylistTest(unittest.TestCase): lib.items.assert_called_once_with(q, None) lib.albums.assert_called_once_with(a_q, None) - m3u_filepath = path.join(dir, pl[0]) + m3u_filepath = path.join(dir, b'ta_ga_da-my_playlist_.m3u') self.assertTrue(path.exists(m3u_filepath)) - with open(syspath(m3u_filepath), 'r') as f: + with open(syspath(m3u_filepath), 'rb') as f: content = f.read() rmtree(dir) - self.assertEqual(content, "/tagada.mp3\n") + self.assertEqual(content, b'/tagada.mp3\n') class SmartPlaylistCLITest(unittest.TestCase, TestHelper): @@ -183,9 +193,9 @@ class SmartPlaylistCLITest(unittest.TestCase, TestHelper): {'name': 'my_playlist.m3u', 'query': self.item.title}, {'name': 'all.m3u', - 'query': ''} + 'query': u''} ]) - config['smartplaylist']['playlist_dir'].set(self.temp_dir) + config['smartplaylist']['playlist_dir'].set(py3_path(self.temp_dir)) self.load_plugins('smartplaylist') def tearDown(self): @@ -194,23 +204,23 @@ class SmartPlaylistCLITest(unittest.TestCase, TestHelper): def test_splupdate(self): with self.assertRaises(UserError): - self.run_with_output('splupdate', 'tagada') + self.run_with_output(u'splupdate', u'tagada') - self.run_with_output('splupdate', 'my_playlist') - m3u_path = path.join(self.temp_dir, 'my_playlist.m3u') + self.run_with_output(u'splupdate', u'my_playlist') + m3u_path = path.join(self.temp_dir, b'my_playlist.m3u') self.assertTrue(path.exists(m3u_path)) - with open(m3u_path, 'r') as f: + with open(m3u_path, 'rb') as f: self.assertEqual(f.read(), self.item.path + b"\n") remove(m3u_path) - self.run_with_output('splupdate', 'my_playlist.m3u') - with open(m3u_path, 'r') as f: + self.run_with_output(u'splupdate', u'my_playlist.m3u') + with open(m3u_path, 'rb') as f: self.assertEqual(f.read(), self.item.path + b"\n") remove(m3u_path) - self.run_with_output('splupdate') - for name in ('my_playlist.m3u', 'all.m3u'): - with open(path.join(self.temp_dir, name), 'r') as f: + self.run_with_output(u'splupdate') + for name in (b'my_playlist.m3u', b'all.m3u'): + with open(path.join(self.temp_dir, name), 'rb') as f: self.assertEqual(f.read(), self.item.path + b"\n") @@ -218,5 +228,5 @@ def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_sort.py b/test/test_sort.py index e763b6167..d611ff2d6 100644 --- a/test/test_sort.py +++ b/test/test_sort.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,11 +15,10 @@ """Various tests for querying the library database. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function +import unittest from test import _common -from test._common import unittest import beets.library from beets import dbcore from beets import config @@ -32,71 +32,71 @@ class DummyDataTestCase(_common.TestCase): self.lib = beets.library.Library(':memory:') albums = [_common.album() for _ in range(3)] - albums[0].album = "Album A" - albums[0].genre = "Rock" + albums[0].album = u"Album A" + albums[0].genre = u"Rock" albums[0].year = 2001 - albums[0].flex1 = "Flex1-1" - albums[0].flex2 = "Flex2-A" - albums[0].albumartist = "Foo" + albums[0].flex1 = u"Flex1-1" + albums[0].flex2 = u"Flex2-A" + albums[0].albumartist = u"Foo" albums[0].albumartist_sort = None - albums[1].album = "Album B" - albums[1].genre = "Rock" + albums[1].album = u"Album B" + albums[1].genre = u"Rock" albums[1].year = 2001 - albums[1].flex1 = "Flex1-2" - albums[1].flex2 = "Flex2-A" - albums[1].albumartist = "Bar" + albums[1].flex1 = u"Flex1-2" + albums[1].flex2 = u"Flex2-A" + albums[1].albumartist = u"Bar" albums[1].albumartist_sort = None - albums[2].album = "Album C" - albums[2].genre = "Jazz" + albums[2].album = u"Album C" + albums[2].genre = u"Jazz" albums[2].year = 2005 - albums[2].flex1 = "Flex1-1" - albums[2].flex2 = "Flex2-B" - albums[2].albumartist = "Baz" + albums[2].flex1 = u"Flex1-1" + albums[2].flex2 = u"Flex2-B" + albums[2].albumartist = u"Baz" albums[2].albumartist_sort = None for album in albums: self.lib.add(album) items = [_common.item() for _ in range(4)] - items[0].title = 'Foo bar' - items[0].artist = 'One' - items[0].album = 'Baz' + items[0].title = u'Foo bar' + items[0].artist = u'One' + items[0].album = u'Baz' items[0].year = 2001 items[0].comp = True - items[0].flex1 = "Flex1-0" - items[0].flex2 = "Flex2-A" + items[0].flex1 = u"Flex1-0" + items[0].flex2 = u"Flex2-A" items[0].album_id = albums[0].id items[0].artist_sort = None items[0].path = "/path0.mp3" items[0].track = 1 - items[1].title = 'Baz qux' - items[1].artist = 'Two' - items[1].album = 'Baz' + items[1].title = u'Baz qux' + items[1].artist = u'Two' + items[1].album = u'Baz' items[1].year = 2002 items[1].comp = True - items[1].flex1 = "Flex1-1" - items[1].flex2 = "Flex2-A" + items[1].flex1 = u"Flex1-1" + items[1].flex2 = u"Flex2-A" items[1].album_id = albums[0].id items[1].artist_sort = None items[1].path = "/patH1.mp3" items[1].track = 2 - items[2].title = 'Beets 4 eva' - items[2].artist = 'Three' - items[2].album = 'Foo' + items[2].title = u'Beets 4 eva' + items[2].artist = u'Three' + items[2].album = u'Foo' items[2].year = 2003 items[2].comp = False - items[2].flex1 = "Flex1-2" - items[2].flex2 = "Flex1-B" + items[2].flex1 = u"Flex1-2" + items[2].flex2 = u"Flex1-B" items[2].album_id = albums[1].id items[2].artist_sort = None items[2].path = "/paTH2.mp3" items[2].track = 3 - items[3].title = 'Beets 4 eva' - items[3].artist = 'Three' - items[3].album = 'Foo2' + items[3].title = u'Beets 4 eva' + items[3].artist = u'Three' + items[3].album = u'Foo2' items[3].year = 2004 items[3].comp = False - items[3].flex1 = "Flex1-2" - items[3].flex2 = "Flex1-C" + items[3].flex1 = u"Flex1-2" + items[3].flex2 = u"Flex1-C" items[3].album_id = albums[2].id items[3].artist_sort = None items[3].path = "/PATH3.mp3" @@ -107,100 +107,100 @@ class DummyDataTestCase(_common.TestCase): class SortFixedFieldTest(DummyDataTestCase): def test_sort_asc(self): - q = '' - sort = dbcore.query.FixedFieldSort("year", True) + q = u'' + sort = dbcore.query.FixedFieldSort(u"year", True) results = self.lib.items(q, sort) self.assertLessEqual(results[0]['year'], results[1]['year']) self.assertEqual(results[0]['year'], 2001) # same thing with query string - q = 'year+' + q = u'year+' results2 = self.lib.items(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_desc(self): - q = '' - sort = dbcore.query.FixedFieldSort("year", False) + q = u'' + sort = dbcore.query.FixedFieldSort(u"year", False) results = self.lib.items(q, sort) self.assertGreaterEqual(results[0]['year'], results[1]['year']) self.assertEqual(results[0]['year'], 2004) # same thing with query string - q = 'year-' + q = u'year-' results2 = self.lib.items(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_two_field_asc(self): - q = '' - s1 = dbcore.query.FixedFieldSort("album", True) - s2 = dbcore.query.FixedFieldSort("year", True) + q = u'' + s1 = dbcore.query.FixedFieldSort(u"album", True) + s2 = dbcore.query.FixedFieldSort(u"year", True) sort = dbcore.query.MultipleSort() sort.add_sort(s1) sort.add_sort(s2) results = self.lib.items(q, sort) self.assertLessEqual(results[0]['album'], results[1]['album']) self.assertLessEqual(results[1]['album'], results[2]['album']) - self.assertEqual(results[0]['album'], 'Baz') - self.assertEqual(results[1]['album'], 'Baz') + self.assertEqual(results[0]['album'], u'Baz') + self.assertEqual(results[1]['album'], u'Baz') self.assertLessEqual(results[0]['year'], results[1]['year']) # same thing with query string - q = 'album+ year+' + q = u'album+ year+' results2 = self.lib.items(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_path_field(self): - q = '' + q = u'' sort = dbcore.query.FixedFieldSort('path', True) results = self.lib.items(q, sort) - self.assertEqual(results[0]['path'], '/path0.mp3') - self.assertEqual(results[1]['path'], '/patH1.mp3') - self.assertEqual(results[2]['path'], '/paTH2.mp3') - self.assertEqual(results[3]['path'], '/PATH3.mp3') + self.assertEqual(results[0]['path'], b'/path0.mp3') + self.assertEqual(results[1]['path'], b'/patH1.mp3') + self.assertEqual(results[2]['path'], b'/paTH2.mp3') + self.assertEqual(results[3]['path'], b'/PATH3.mp3') class SortFlexFieldTest(DummyDataTestCase): def test_sort_asc(self): - q = '' - sort = dbcore.query.SlowFieldSort("flex1", True) + q = u'' + sort = dbcore.query.SlowFieldSort(u"flex1", True) results = self.lib.items(q, sort) self.assertLessEqual(results[0]['flex1'], results[1]['flex1']) - self.assertEqual(results[0]['flex1'], 'Flex1-0') + self.assertEqual(results[0]['flex1'], u'Flex1-0') # same thing with query string - q = 'flex1+' + q = u'flex1+' results2 = self.lib.items(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_desc(self): - q = '' - sort = dbcore.query.SlowFieldSort("flex1", False) + q = u'' + sort = dbcore.query.SlowFieldSort(u"flex1", False) results = self.lib.items(q, sort) self.assertGreaterEqual(results[0]['flex1'], results[1]['flex1']) self.assertGreaterEqual(results[1]['flex1'], results[2]['flex1']) self.assertGreaterEqual(results[2]['flex1'], results[3]['flex1']) - self.assertEqual(results[0]['flex1'], 'Flex1-2') + self.assertEqual(results[0]['flex1'], u'Flex1-2') # same thing with query string - q = 'flex1-' + q = u'flex1-' results2 = self.lib.items(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_two_field(self): - q = '' - s1 = dbcore.query.SlowFieldSort("flex2", False) - s2 = dbcore.query.SlowFieldSort("flex1", True) + q = u'' + s1 = dbcore.query.SlowFieldSort(u"flex2", False) + s2 = dbcore.query.SlowFieldSort(u"flex1", True) sort = dbcore.query.MultipleSort() sort.add_sort(s1) sort.add_sort(s2) results = self.lib.items(q, sort) self.assertGreaterEqual(results[0]['flex2'], results[1]['flex2']) self.assertGreaterEqual(results[1]['flex2'], results[2]['flex2']) - self.assertEqual(results[0]['flex2'], 'Flex2-A') - self.assertEqual(results[1]['flex2'], 'Flex2-A') + self.assertEqual(results[0]['flex2'], u'Flex2-A') + self.assertEqual(results[1]['flex2'], u'Flex2-A') self.assertLessEqual(results[0]['flex1'], results[1]['flex1']) # same thing with query string - q = 'flex2- flex1+' + q = u'flex2- flex1+' results2 = self.lib.items(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) @@ -208,44 +208,44 @@ class SortFlexFieldTest(DummyDataTestCase): class SortAlbumFixedFieldTest(DummyDataTestCase): def test_sort_asc(self): - q = '' - sort = dbcore.query.FixedFieldSort("year", True) + q = u'' + sort = dbcore.query.FixedFieldSort(u"year", True) results = self.lib.albums(q, sort) self.assertLessEqual(results[0]['year'], results[1]['year']) self.assertEqual(results[0]['year'], 2001) # same thing with query string - q = 'year+' + q = u'year+' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_desc(self): - q = '' - sort = dbcore.query.FixedFieldSort("year", False) + q = u'' + sort = dbcore.query.FixedFieldSort(u"year", False) results = self.lib.albums(q, sort) self.assertGreaterEqual(results[0]['year'], results[1]['year']) self.assertEqual(results[0]['year'], 2005) # same thing with query string - q = 'year-' + q = u'year-' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_two_field_asc(self): - q = '' - s1 = dbcore.query.FixedFieldSort("genre", True) - s2 = dbcore.query.FixedFieldSort("album", True) + q = u'' + s1 = dbcore.query.FixedFieldSort(u"genre", True) + s2 = dbcore.query.FixedFieldSort(u"album", True) sort = dbcore.query.MultipleSort() sort.add_sort(s1) sort.add_sort(s2) results = self.lib.albums(q, sort) self.assertLessEqual(results[0]['genre'], results[1]['genre']) self.assertLessEqual(results[1]['genre'], results[2]['genre']) - self.assertEqual(results[1]['genre'], 'Rock') - self.assertEqual(results[2]['genre'], 'Rock') + self.assertEqual(results[1]['genre'], u'Rock') + self.assertEqual(results[2]['genre'], u'Rock') self.assertLessEqual(results[1]['album'], results[2]['album']) # same thing with query string - q = 'genre+ album+' + q = u'genre+ album+' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) @@ -253,44 +253,44 @@ class SortAlbumFixedFieldTest(DummyDataTestCase): class SortAlbumFlexFieldTest(DummyDataTestCase): def test_sort_asc(self): - q = '' - sort = dbcore.query.SlowFieldSort("flex1", True) + q = u'' + sort = dbcore.query.SlowFieldSort(u"flex1", True) results = self.lib.albums(q, sort) self.assertLessEqual(results[0]['flex1'], results[1]['flex1']) self.assertLessEqual(results[1]['flex1'], results[2]['flex1']) # same thing with query string - q = 'flex1+' + q = u'flex1+' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_desc(self): - q = '' - sort = dbcore.query.SlowFieldSort("flex1", False) + q = u'' + sort = dbcore.query.SlowFieldSort(u"flex1", False) results = self.lib.albums(q, sort) self.assertGreaterEqual(results[0]['flex1'], results[1]['flex1']) self.assertGreaterEqual(results[1]['flex1'], results[2]['flex1']) # same thing with query string - q = 'flex1-' + q = u'flex1-' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_two_field_asc(self): - q = '' - s1 = dbcore.query.SlowFieldSort("flex2", True) - s2 = dbcore.query.SlowFieldSort("flex1", True) + q = u'' + s1 = dbcore.query.SlowFieldSort(u"flex2", True) + s2 = dbcore.query.SlowFieldSort(u"flex1", True) sort = dbcore.query.MultipleSort() sort.add_sort(s1) sort.add_sort(s2) results = self.lib.albums(q, sort) self.assertLessEqual(results[0]['flex2'], results[1]['flex2']) self.assertLessEqual(results[1]['flex2'], results[2]['flex2']) - self.assertEqual(results[0]['flex2'], 'Flex2-A') - self.assertEqual(results[1]['flex2'], 'Flex2-A') + self.assertEqual(results[0]['flex2'], u'Flex2-A') + self.assertEqual(results[1]['flex2'], u'Flex2-A') self.assertLessEqual(results[0]['flex1'], results[1]['flex1']) # same thing with query string - q = 'flex2+ flex1+' + q = u'flex2+ flex1+' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) @@ -298,25 +298,25 @@ class SortAlbumFlexFieldTest(DummyDataTestCase): class SortAlbumComputedFieldTest(DummyDataTestCase): def test_sort_asc(self): - q = '' - sort = dbcore.query.SlowFieldSort("path", True) + q = u'' + sort = dbcore.query.SlowFieldSort(u"path", True) results = self.lib.albums(q, sort) self.assertLessEqual(results[0]['path'], results[1]['path']) self.assertLessEqual(results[1]['path'], results[2]['path']) # same thing with query string - q = 'path+' + q = u'path+' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_desc(self): - q = '' - sort = dbcore.query.SlowFieldSort("path", False) + q = u'' + sort = dbcore.query.SlowFieldSort(u"path", False) results = self.lib.albums(q, sort) self.assertGreaterEqual(results[0]['path'], results[1]['path']) self.assertGreaterEqual(results[1]['path'], results[2]['path']) # same thing with query string - q = 'path-' + q = u'path-' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) @@ -324,24 +324,24 @@ class SortAlbumComputedFieldTest(DummyDataTestCase): class SortCombinedFieldTest(DummyDataTestCase): def test_computed_first(self): - q = '' - s1 = dbcore.query.SlowFieldSort("path", True) - s2 = dbcore.query.FixedFieldSort("year", True) + q = u'' + s1 = dbcore.query.SlowFieldSort(u"path", True) + s2 = dbcore.query.FixedFieldSort(u"year", True) sort = dbcore.query.MultipleSort() sort.add_sort(s1) sort.add_sort(s2) results = self.lib.albums(q, sort) self.assertLessEqual(results[0]['path'], results[1]['path']) self.assertLessEqual(results[1]['path'], results[2]['path']) - q = 'path+ year+' + q = u'path+ year+' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_computed_second(self): - q = '' - s1 = dbcore.query.FixedFieldSort("year", True) - s2 = dbcore.query.SlowFieldSort("path", True) + q = u'' + s1 = dbcore.query.FixedFieldSort(u"year", True) + s2 = dbcore.query.SlowFieldSort(u"path", True) sort = dbcore.query.MultipleSort() sort.add_sort(s1) sort.add_sort(s2) @@ -349,7 +349,7 @@ class SortCombinedFieldTest(DummyDataTestCase): self.assertLessEqual(results[0]['year'], results[1]['year']) self.assertLessEqual(results[1]['year'], results[2]['year']) self.assertLessEqual(results[0]['path'], results[1]['path']) - q = 'year+ path+' + q = u'year+ path+' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) @@ -384,23 +384,23 @@ class CaseSensitivityTest(DummyDataTestCase, _common.TestCase): super(CaseSensitivityTest, self).setUp() album = _common.album() - album.album = "album" - album.genre = "alternative" - album.year = "2001" - album.flex1 = "flex1" - album.flex2 = "flex2-A" - album.albumartist = "bar" + album.album = u"album" + album.genre = u"alternative" + album.year = u"2001" + album.flex1 = u"flex1" + album.flex2 = u"flex2-A" + album.albumartist = u"bar" album.albumartist_sort = None self.lib.add(album) item = _common.item() - item.title = 'another' - item.artist = 'lowercase' - item.album = 'album' + item.title = u'another' + item.artist = u'lowercase' + item.album = u'album' item.year = 2001 item.comp = True - item.flex1 = "flex1" - item.flex2 = "flex2-A" + item.flex1 = u"flex1" + item.flex2 = u"flex2-A" item.album_id = album.id item.artist_sort = None item.track = 10 @@ -416,49 +416,49 @@ class CaseSensitivityTest(DummyDataTestCase, _common.TestCase): def test_smart_artist_case_insensitive(self): config['sort_case_insensitive'] = True - q = 'artist+' + q = u'artist+' results = list(self.lib.items(q)) - self.assertEqual(results[0].artist, 'lowercase') - self.assertEqual(results[1].artist, 'One') + self.assertEqual(results[0].artist, u'lowercase') + self.assertEqual(results[1].artist, u'One') def test_smart_artist_case_sensitive(self): config['sort_case_insensitive'] = False - q = 'artist+' + q = u'artist+' results = list(self.lib.items(q)) - self.assertEqual(results[0].artist, 'One') - self.assertEqual(results[-1].artist, 'lowercase') + self.assertEqual(results[0].artist, u'One') + self.assertEqual(results[-1].artist, u'lowercase') def test_fixed_field_case_insensitive(self): config['sort_case_insensitive'] = True - q = 'album+' + q = u'album+' results = list(self.lib.albums(q)) - self.assertEqual(results[0].album, 'album') - self.assertEqual(results[1].album, 'Album A') + self.assertEqual(results[0].album, u'album') + self.assertEqual(results[1].album, u'Album A') def test_fixed_field_case_sensitive(self): config['sort_case_insensitive'] = False - q = 'album+' + q = u'album+' results = list(self.lib.albums(q)) - self.assertEqual(results[0].album, 'Album A') - self.assertEqual(results[-1].album, 'album') + self.assertEqual(results[0].album, u'Album A') + self.assertEqual(results[-1].album, u'album') def test_flex_field_case_insensitive(self): config['sort_case_insensitive'] = True - q = 'flex1+' + q = u'flex1+' results = list(self.lib.items(q)) - self.assertEqual(results[0].flex1, 'flex1') - self.assertEqual(results[1].flex1, 'Flex1-0') + self.assertEqual(results[0].flex1, u'flex1') + self.assertEqual(results[1].flex1, u'Flex1-0') def test_flex_field_case_sensitive(self): config['sort_case_insensitive'] = False - q = 'flex1+' + q = u'flex1+' results = list(self.lib.items(q)) - self.assertEqual(results[0].flex1, 'Flex1-0') - self.assertEqual(results[-1].flex1, 'flex1') + self.assertEqual(results[0].flex1, u'Flex1-0') + self.assertEqual(results[-1].flex1, u'flex1') def test_case_sensitive_only_affects_text(self): config['sort_case_insensitive'] = True - q = 'track+' + q = u'track+' results = list(self.lib.items(q)) # If the numerical values were sorted as strings, # then ['1', '10', '2'] would be valid. @@ -468,9 +468,73 @@ class CaseSensitivityTest(DummyDataTestCase, _common.TestCase): self.assertEqual(results[-1].track, 10) +class NonExistingFieldTest(DummyDataTestCase): + """Test sorting by non-existing fields""" + + def test_non_existing_fields_not_fail(self): + qs = [u'foo+', u'foo-', u'--', u'-+', u'+-', + u'++', u'-foo-', u'-foo+', u'---'] + + q0 = u'foo+' + results0 = list(self.lib.items(q0)) + for q1 in qs: + results1 = list(self.lib.items(q1)) + for r1, r2 in zip(results0, results1): + self.assertEqual(r1.id, r2.id) + + def test_combined_non_existing_field_asc(self): + all_results = list(self.lib.items(u'id+')) + q = u'foo+ id+' + results = list(self.lib.items(q)) + self.assertEqual(len(all_results), len(results)) + for r1, r2 in zip(all_results, results): + self.assertEqual(r1.id, r2.id) + + def test_combined_non_existing_field_desc(self): + all_results = list(self.lib.items(u'id+')) + q = u'foo- id+' + results = list(self.lib.items(q)) + self.assertEqual(len(all_results), len(results)) + for r1, r2 in zip(all_results, results): + self.assertEqual(r1.id, r2.id) + + def test_field_present_in_some_items(self): + """Test ordering by a field not present on all items.""" + # append 'foo' to two to items (1,2) + items = self.lib.items(u'id+') + ids = [i.id for i in items] + items[1].foo = u'bar1' + items[2].foo = u'bar2' + items[1].store() + items[2].store() + + results_asc = list(self.lib.items(u'foo+ id+')) + self.assertEqual([i.id for i in results_asc], + # items without field first + [ids[0], ids[3], ids[1], ids[2]]) + results_desc = list(self.lib.items(u'foo- id+')) + self.assertEqual([i.id for i in results_desc], + # items without field last + [ids[2], ids[1], ids[0], ids[3]]) + + def test_negation_interaction(self): + """Test the handling of negation and sorting together. + + If a string ends with a sorting suffix, it takes precedence over the + NotQuery parsing. + """ + query, sort = beets.library.parse_query_string(u'-bar+', + beets.library.Item) + self.assertEqual(len(query.subqueries), 1) + self.assertTrue(isinstance(query.subqueries[0], + dbcore.query.TrueQuery)) + self.assertTrue(isinstance(sort, dbcore.query.SlowFieldSort)) + self.assertEqual(sort.field, u'-bar') + + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_spotify.py b/test/test_spotify.py index 61da6a378..17f3ef42f 100644 --- a/test/test_spotify.py +++ b/test/test_spotify.py @@ -1,16 +1,19 @@ +# -*- coding: utf-8 -*- + """Tests for the 'spotify' plugin""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function + +import os +import responses +import unittest from test import _common -import responses -from test._common import unittest from beets import config from beets.library import Item from beetsplug import spotify from test.helper import TestHelper -import urlparse +from six.moves.urllib.parse import parse_qs, urlparse class ArgumentsMock(object): @@ -22,7 +25,7 @@ class ArgumentsMock(object): def _params(url): """Get the query parameters from a URL.""" - return urlparse.parse_qs(urlparse.urlparse(url).query) + return parse_qs(urlparse(url).query) class SpotifyPluginTest(_common.TestCase, TestHelper): @@ -44,168 +47,69 @@ class SpotifyPluginTest(_common.TestCase, TestHelper): self.assertEqual(True, self.spotify.parse_opts(opts)) def test_empty_query(self): - self.assertEqual(None, self.spotify.query_spotify(self.lib, "1=2")) + self.assertEqual(None, self.spotify.query_spotify(self.lib, u"1=2")) @responses.activate def test_missing_request(self): - response_body = bytes( - '{' - '"tracks" : {' - '"href" : "https://api.spotify.com/v1/search?query=duifhjslkef' - '+album%3Alkajsdflakjsd+artist%3A&offset=0&limit=20&type=track",' - '"items" : [ ],' - '"limit" : 20,' - '"next" : null,' - '"offset" : 0,' - '"previous" : null,' - '"total" : 0' - '}' - '}' - ) + json_file = os.path.join(_common.RSRC, b'spotify', + b'missing_request.json') + with open(json_file, 'rb') as f: + response_body = f.read() + responses.add(responses.GET, 'https://api.spotify.com/v1/search', body=response_body, status=200, content_type='application/json') item = Item( - mb_trackid='01234', - album='lkajsdflakjsd', - albumartist='ujydfsuihse', - title='duifhjslkef', + mb_trackid=u'01234', + album=u'lkajsdflakjsd', + albumartist=u'ujydfsuihse', + title=u'duifhjslkef', length=10 ) item.add(self.lib) - self.assertEqual([], self.spotify.query_spotify(self.lib, "")) + self.assertEqual([], self.spotify.query_spotify(self.lib, u"")) params = _params(responses.calls[0].request.url) self.assertEqual( params['q'], - ['duifhjslkef album:lkajsdflakjsd artist:ujydfsuihse'], + [u'duifhjslkef album:lkajsdflakjsd artist:ujydfsuihse'], ) - self.assertEqual(params['type'], ['track']) + self.assertEqual(params['type'], [u'track']) @responses.activate def test_track_request(self): - response_body = bytes( - '{' - '"tracks" : {' - '"href" : "https://api.spotify.com/v1/search?query=Happy+album%3A' - 'Despicable+Me+2+artist%3APharrell+Williams&offset=0&limit=20' - '&type=track",' - '"items" : [ {' - '"album" : {' - '"album_type" : "compilation",' - '"available_markets" : [ "AD", "AR", "AT", "AU", "BE", "BG",' - '"BO", "BR", "CA", "CH", "CL", "CO",' - '"CR", "CY", "CZ", "DE", "DK", "DO",' - '"EC", "EE", "ES", "FI", "FR", "GB",' - '"GR", "GT", "HK", "HN", "HU", "IE",' - '"IS", "IT", "LI", "LT", "LU", "LV",' - '"MC", "MT", "MX", "MY", "NI", "NL",' - '"NO", "NZ", "PA", "PE", "PH", "PL",' - '"PT", "PY", "RO", "SE", "SG", "SI",' - '"SK", "SV", "TR", "TW", "US", "UY" ],' - '"external_urls" : {' - '"spotify" : "https://open.spotify.com/album/' - '5l3zEmMrOhOzG8d8s83GOL"' - '},' - '"href" : "https://api.spotify.com/v1/albums/' - '5l3zEmMrOhOzG8d8s83GOL",' - '"id" : "5l3zEmMrOhOzG8d8s83GOL",' - '"images" : [ {' - '"height" : 640,' - '"url" : "https://i.scdn.co/image/cb7905340c132365bb' - 'aee3f17498f062858382e8",' - '"width" : 640' - '}, {' - '"height" : 300,' - '"url" : "https://i.scdn.co/image/af369120f0b20099' - 'd6784ab31c88256113f10ffb",' - '"width" : 300' - '}, {' - '"height" : 64,' - '"url" : "https://i.scdn.co/image/' - '9dad385ddf2e7db0bef20cec1fcbdb08689d9ae8",' - '"width" : 64' - '} ],' - '"name" : "Despicable Me 2 (Original Motion Picture Soundtrack)",' - '"type" : "album",' - '"uri" : "spotify:album:5l3zEmMrOhOzG8d8s83GOL"' - '},' - '"artists" : [ {' - '"external_urls" : {' - '"spotify" : "https://open.spotify.com/artist/' - '2RdwBSPQiwcmiDo9kixcl8"' - '},' - '"href" : "https://api.spotify.com/v1/artists/' - '2RdwBSPQiwcmiDo9kixcl8",' - '"id" : "2RdwBSPQiwcmiDo9kixcl8",' - '"name" : "Pharrell Williams",' - '"type" : "artist",' - '"uri" : "spotify:artist:2RdwBSPQiwcmiDo9kixcl8"' - '} ],' - '"available_markets" : [ "AD", "AR", "AT", "AU", "BE", "BG", "BO",' - '"BR", "CA", "CH", "CL", "CO", "CR", "CY",' - '"CZ", "DE", "DK", "DO", "EC", "EE", "ES",' - '"FI", "FR", "GB", "GR", "GT", "HK", "HN",' - '"HU", "IE", "IS", "IT", "LI", "LT", "LU",' - '"LV", "MC", "MT", "MX", "MY", "NI", "NL",' - '"NO", "NZ", "PA", "PE", "PH", "PL", "PT",' - '"PY", "RO", "SE", "SG", "SI", "SK", "SV",' - '"TR", "TW", "US", "UY" ],' - '"disc_number" : 1,' - '"duration_ms" : 233305,' - '"explicit" : false,' - '"external_ids" : {' - '"isrc" : "USQ4E1300686"' - '},' - '"external_urls" : {' - '"spotify" : "https://open.spotify.com/track/' - '6NPVjNh8Jhru9xOmyQigds"' - '},' - '"href" : "https://api.spotify.com/v1/tracks/' - '6NPVjNh8Jhru9xOmyQigds",' - '"id" : "6NPVjNh8Jhru9xOmyQigds",' - '"name" : "Happy",' - '"popularity" : 89,' - '"preview_url" : "https://p.scdn.co/mp3-preview/' - '6b00000be293e6b25f61c33e206a0c522b5cbc87",' - '"track_number" : 4,' - '"type" : "track",' - '"uri" : "spotify:track:6NPVjNh8Jhru9xOmyQigds"' - '} ],' - '"limit" : 20,' - '"next" : null,' - '"offset" : 0,' - '"previous" : null,' - '"total" : 1' - '}' - '}' - ) + + json_file = os.path.join(_common.RSRC, b'spotify', + b'track_request.json') + with open(json_file, 'rb') as f: + response_body = f.read() + responses.add(responses.GET, 'https://api.spotify.com/v1/search', body=response_body, status=200, content_type='application/json') item = Item( - mb_trackid='01234', - album='Despicable Me 2', - albumartist='Pharrell Williams', - title='Happy', + mb_trackid=u'01234', + album=u'Despicable Me 2', + albumartist=u'Pharrell Williams', + title=u'Happy', length=10 ) item.add(self.lib) - results = self.spotify.query_spotify(self.lib, "Happy") + results = self.spotify.query_spotify(self.lib, u"Happy") self.assertEqual(1, len(results)) - self.assertEqual("6NPVjNh8Jhru9xOmyQigds", results[0]['id']) + self.assertEqual(u"6NPVjNh8Jhru9xOmyQigds", results[0]['id']) self.spotify.output_results(results) params = _params(responses.calls[0].request.url) self.assertEqual( params['q'], - ['Happy album:Despicable Me 2 artist:Pharrell Williams'], + [u'Happy album:Despicable Me 2 artist:Pharrell Williams'], ) - self.assertEqual(params['type'], ['track']) + self.assertEqual(params['type'], [u'track']) def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_template.py b/test/test_template.py index 1a0daa42e..288bc2314 100644 --- a/test/test_template.py +++ b/test/test_template.py @@ -1,6 +1,6 @@ -# -*- coding: utf8 -*- +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,12 +15,10 @@ """Tests for template engine. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function -import warnings - -from test._common import unittest +import unittest +import six from beets.util import functemplate @@ -31,7 +29,7 @@ def _normexpr(expr): """ textbuf = [] for part in expr.parts: - if isinstance(part, basestring): + if isinstance(part, six.string_types): textbuf.append(part) else: if textbuf: @@ -213,12 +211,26 @@ class ParseTest(unittest.TestCase): self._assert_call(arg_parts[0], u"bar", 1) self.assertEqual(list(_normexpr(arg_parts[0].args[0])), [u'baz']) - def test_fail_on_utf8(self): - parts = u'é'.encode('utf8') - warnings.simplefilter("ignore") - with self.assertRaises(UnicodeDecodeError): - functemplate._parse(parts) - warnings.simplefilter("default") + def test_sep_before_call_two_args(self): + parts = list(_normparse(u'hello, %foo{bar,baz}')) + self.assertEqual(len(parts), 2) + self.assertEqual(parts[0], u'hello, ') + self._assert_call(parts[1], u"foo", 2) + self.assertEqual(list(_normexpr(parts[1].args[0])), [u'bar']) + self.assertEqual(list(_normexpr(parts[1].args[1])), [u'baz']) + + def test_sep_with_symbols(self): + parts = list(_normparse(u'hello,$foo,$bar')) + self.assertEqual(len(parts), 4) + self.assertEqual(parts[0], u'hello,') + self._assert_symbol(parts[1], u"foo") + self.assertEqual(parts[2], u',') + self._assert_symbol(parts[3], u"bar") + + def test_newline_at_end(self): + parts = list(_normparse(u'foo\n')) + self.assertEqual(len(parts), 1) + self.assertEqual(parts[0], u'foo\n') class EvalTest(unittest.TestCase): @@ -228,7 +240,7 @@ class EvalTest(unittest.TestCase): u'baz': u'BaR', } functions = { - u'lower': unicode.lower, + u'lower': six.text_type.lower, u'len': len, } return functemplate.Template(template).substitute(values, functions) @@ -259,7 +271,7 @@ class EvalTest(unittest.TestCase): def test_function_call_exception(self): res = self._eval(u"%lower{a,b,c,d,e}") - self.assertTrue(isinstance(res, basestring)) + self.assertTrue(isinstance(res, six.string_types)) def test_function_returning_integer(self): self.assertEqual(self._eval(u"%len{foo}"), u"3") @@ -277,5 +289,5 @@ class EvalTest(unittest.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_the.py b/test/test_the.py index e04db1aec..72e9bf161 100644 --- a/test/test_the.py +++ b/test/test_the.py @@ -1,9 +1,10 @@ +# -*- coding: utf-8 -*- + """Tests for the 'the' plugin""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function -from test._common import unittest +import unittest from test import _common from beets import config from beetsplug.the import ThePlugin, PATTERN_A, PATTERN_THE, FORMAT @@ -12,55 +13,56 @@ from beetsplug.the import ThePlugin, PATTERN_A, PATTERN_THE, FORMAT class ThePluginTest(_common.TestCase): def test_unthe_with_default_patterns(self): - self.assertEqual(ThePlugin().unthe('', PATTERN_THE), '') - self.assertEqual(ThePlugin().unthe('The Something', PATTERN_THE), - 'Something, The') - self.assertEqual(ThePlugin().unthe('The The', PATTERN_THE), - 'The, The') - self.assertEqual(ThePlugin().unthe('The The', PATTERN_THE), - 'The, The') - self.assertEqual(ThePlugin().unthe('The The X', PATTERN_THE), - 'The X, The') - self.assertEqual(ThePlugin().unthe('the The', PATTERN_THE), - 'The, the') - self.assertEqual(ThePlugin().unthe('Protected The', PATTERN_THE), - 'Protected The') - self.assertEqual(ThePlugin().unthe('A Boy', PATTERN_A), - 'Boy, A') - self.assertEqual(ThePlugin().unthe('a girl', PATTERN_A), - 'girl, a') - self.assertEqual(ThePlugin().unthe('An Apple', PATTERN_A), - 'Apple, An') - self.assertEqual(ThePlugin().unthe('An A Thing', PATTERN_A), - 'A Thing, An') - self.assertEqual(ThePlugin().unthe('the An Arse', PATTERN_A), - 'the An Arse') + self.assertEqual(ThePlugin().unthe(u'', PATTERN_THE), '') + self.assertEqual(ThePlugin().unthe(u'The Something', PATTERN_THE), + u'Something, The') + self.assertEqual(ThePlugin().unthe(u'The The', PATTERN_THE), + u'The, The') + self.assertEqual(ThePlugin().unthe(u'The The', PATTERN_THE), + u'The, The') + self.assertEqual(ThePlugin().unthe(u'The The X', PATTERN_THE), + u'The X, The') + self.assertEqual(ThePlugin().unthe(u'the The', PATTERN_THE), + u'The, the') + self.assertEqual(ThePlugin().unthe(u'Protected The', PATTERN_THE), + u'Protected The') + self.assertEqual(ThePlugin().unthe(u'A Boy', PATTERN_A), + u'Boy, A') + self.assertEqual(ThePlugin().unthe(u'a girl', PATTERN_A), + u'girl, a') + self.assertEqual(ThePlugin().unthe(u'An Apple', PATTERN_A), + u'Apple, An') + self.assertEqual(ThePlugin().unthe(u'An A Thing', PATTERN_A), + u'A Thing, An') + self.assertEqual(ThePlugin().unthe(u'the An Arse', PATTERN_A), + u'the An Arse') def test_unthe_with_strip(self): config['the']['strip'] = True - self.assertEqual(ThePlugin().unthe('The Something', PATTERN_THE), - 'Something') - self.assertEqual(ThePlugin().unthe('An A', PATTERN_A), 'A') + self.assertEqual(ThePlugin().unthe(u'The Something', PATTERN_THE), + u'Something') + self.assertEqual(ThePlugin().unthe(u'An A', PATTERN_A), u'A') def test_template_function_with_defaults(self): ThePlugin().patterns = [PATTERN_THE, PATTERN_A] - self.assertEqual(ThePlugin().the_template_func('The The'), 'The, The') - self.assertEqual(ThePlugin().the_template_func('An A'), 'A, An') + self.assertEqual(ThePlugin().the_template_func(u'The The'), + u'The, The') + self.assertEqual(ThePlugin().the_template_func(u'An A'), u'A, An') def test_custom_pattern(self): config['the']['patterns'] = [u'^test\s'] config['the']['format'] = FORMAT - self.assertEqual(ThePlugin().the_template_func('test passed'), - 'passed, test') + self.assertEqual(ThePlugin().the_template_func(u'test passed'), + u'passed, test') def test_custom_format(self): config['the']['patterns'] = [PATTERN_THE, PATTERN_A] config['the']['format'] = u'{1} ({0})' - self.assertEqual(ThePlugin().the_template_func('The A'), 'The (A)') + self.assertEqual(ThePlugin().the_template_func(u'The A'), u'The (A)') def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_thumbnails.py b/test/test_thumbnails.py index 0b4eddd05..dc03f06f7 100644 --- a/test/test_thumbnails.py +++ b/test/test_thumbnails.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Bruno Cauet +# Copyright 2016, Bruno Cauet # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,17 +13,17 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import os.path from mock import Mock, patch, call from tempfile import mkdtemp from shutil import rmtree +import unittest -from test._common import unittest from test.helper import TestHelper +from beets.util import bytestring_path from beetsplug.thumbnails import (ThumbnailsPlugin, NORMAL_DIR, LARGE_DIR, write_metadata_im, write_metadata_pil, PathlibURI, GioURI) @@ -37,13 +38,13 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): @patch('beetsplug.thumbnails.util') def test_write_metadata_im(self, mock_util): - metadata = {"a": "A", "b": "B"} + metadata = {"a": u"A", "b": u"B"} write_metadata_im("foo", metadata) try: - command = "convert foo -set a A -set b B foo".split(' ') + command = u"convert foo -set a A -set b B foo".split(' ') mock_util.command_output.assert_called_once_with(command) except AssertionError: - command = "convert foo -set b B -set a A foo".split(' ') + command = u"convert foo -set b B -set a A foo".split(' ') mock_util.command_output.assert_called_once_with(command) @patch('beetsplug.thumbnails.ThumbnailsPlugin._check_local_ok') @@ -58,16 +59,16 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): plugin.add_tags(album, b"/path/to/thumbnail") - metadata = {"Thumb::URI": b"COVER_URI", - "Thumb::MTime": "12345"} + metadata = {"Thumb::URI": "COVER_URI", + "Thumb::MTime": u"12345"} plugin.write_metadata.assert_called_once_with(b"/path/to/thumbnail", metadata) mock_stat.assert_called_once_with(album.artpath) @patch('beetsplug.thumbnails.os') @patch('beetsplug.thumbnails.ArtResizer') - @patch('beetsplug.thumbnails.has_IM') - @patch('beetsplug.thumbnails.has_PIL') + @patch('beetsplug.thumbnails.get_im_version') + @patch('beetsplug.thumbnails.get_pil_version') @patch('beetsplug.thumbnails.GioURI') def test_check_local_ok(self, mock_giouri, mock_pil, mock_im, mock_artresizer, mock_os): @@ -84,7 +85,7 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): return False if path == LARGE_DIR: return True - raise ValueError("unexpected path {0!r}".format(path)) + raise ValueError(u"unexpected path {0!r}".format(path)) mock_os.path.exists = exists plugin = ThumbnailsPlugin() mock_os.makedirs.assert_called_once_with(NORMAL_DIR) @@ -114,7 +115,8 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): self.assertEqual(ThumbnailsPlugin().get_uri, giouri_inst.uri) giouri_inst.available = False - self.assertEqual(ThumbnailsPlugin().get_uri.im_class, PathlibURI) + self.assertEqual(ThumbnailsPlugin().get_uri.__self__.__class__, + PathlibURI) @patch('beetsplug.thumbnails.ThumbnailsPlugin._check_local_ok') @patch('beetsplug.thumbnails.ArtResizer') @@ -133,7 +135,7 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): album = Mock(artpath=path_to_art) mock_util.syspath.side_effect = lambda x: x - plugin.thumbnail_file_name = Mock(return_value="md5") + plugin.thumbnail_file_name = Mock(return_value=b'md5') mock_os.path.exists.return_value = False def os_stat(target): @@ -142,7 +144,7 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): elif target == path_to_art: return Mock(st_mtime=2) else: - raise ValueError("invalid target {0}".format(target)) + raise ValueError(u"invalid target {0}".format(target)) mock_os.stat.side_effect = os_stat plugin.make_cover_thumbnail(album, 12345, thumbnail_dir) @@ -168,7 +170,7 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): elif target == path_to_art: return Mock(st_mtime=2) else: - raise ValueError("invalid target {0}".format(target)) + raise ValueError(u"invalid target {0}".format(target)) mock_os.stat.side_effect = os_stat plugin.make_cover_thumbnail(album, 12345, thumbnail_dir) @@ -182,7 +184,7 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): @patch('beetsplug.thumbnails.ThumbnailsPlugin._check_local_ok') def test_make_dolphin_cover_thumbnail(self, _): plugin = ThumbnailsPlugin() - tmp = mkdtemp() + tmp = bytestring_path(mkdtemp()) album = Mock(path=tmp, artpath=os.path.join(tmp, b"cover.jpg")) plugin.make_dolphin_cover_thumbnail(album) @@ -265,30 +267,25 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): @patch('beetsplug.thumbnails.BaseDirectory') def test_thumbnail_file_name(self, mock_basedir): plug = ThumbnailsPlugin() - plug.get_uri = Mock(return_value="file:///my/uri") - self.assertEqual(plug.thumbnail_file_name("idontcare"), + plug.get_uri = Mock(return_value=u"file:///my/uri") + self.assertEqual(plug.thumbnail_file_name(b'idontcare'), b"9488f5797fbe12ffb316d607dfd93d04.png") def test_uri(self): gio = GioURI() - plib = PathlibURI() if not gio.available: - self.skipTest("GIO library not found") + self.skipTest(u"GIO library not found") - self.assertEqual(gio.uri("/foo"), b"file:///") # silent fail - self.assertEqual(gio.uri(b"/foo"), b"file:///foo") - self.assertEqual(gio.uri(b"/foo!"), b"file:///foo!") - self.assertEqual(plib.uri(b"/foo!"), b"file:///foo%21") + self.assertEqual(gio.uri(u"/foo"), u"file:///") # silent fail + self.assertEqual(gio.uri(b"/foo"), u"file:///foo") + self.assertEqual(gio.uri(b"/foo!"), u"file:///foo!") self.assertEqual( gio.uri(b'/music/\xec\x8b\xb8\xec\x9d\xb4'), - b'file:///music/%EC%8B%B8%EC%9D%B4') - self.assertEqual( - plib.uri(b'/music/\xec\x8b\xb8\xec\x9d\xb4'), - b'file:///music/%EC%8B%B8%EC%9D%B4') + u'file:///music/%EC%8B%B8%EC%9D%B4') def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_types_plugin.py b/test/test_types_plugin.py index 7e0e6e082..541bd30df 100644 --- a/test/test_types_plugin.py +++ b/test/test_types_plugin.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -12,13 +13,12 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import time from datetime import datetime +import unittest -from test._common import unittest from test.helper import TestHelper from beets.util.confit import ConfigValueError @@ -36,69 +36,77 @@ class TypesPluginTest(unittest.TestCase, TestHelper): def test_integer_modify_and_query(self): self.config['types'] = {'myint': 'int'} - item = self.add_item(artist='aaa') + item = self.add_item(artist=u'aaa') # Do not match unset values - out = self.list('myint:1..3') - self.assertEqual('', out) + out = self.list(u'myint:1..3') + self.assertEqual(u'', out) - self.modify('myint=2') + self.modify(u'myint=2') item.load() self.assertEqual(item['myint'], 2) # Match in range - out = self.list('myint:1..3') - self.assertIn(b'aaa', out) + out = self.list(u'myint:1..3') + self.assertIn('aaa', out) def test_album_integer_modify_and_query(self): - self.config['types'] = {'myint': 'int'} - album = self.add_album(albumartist='aaa') + self.config['types'] = {'myint': u'int'} + album = self.add_album(albumartist=u'aaa') # Do not match unset values - out = self.list_album('myint:1..3') - self.assertEqual('', out) + out = self.list_album(u'myint:1..3') + self.assertEqual(u'', out) - self.modify('-a', 'myint=2') + self.modify(u'-a', u'myint=2') album.load() self.assertEqual(album['myint'], 2) # Match in range - out = self.list_album('myint:1..3') - self.assertIn(b'aaa', out) + out = self.list_album(u'myint:1..3') + self.assertIn('aaa', out) def test_float_modify_and_query(self): - self.config['types'] = {'myfloat': 'float'} - item = self.add_item(artist='aaa') + self.config['types'] = {'myfloat': u'float'} + item = self.add_item(artist=u'aaa') - self.modify('myfloat=-9.1') + # Do not match unset values + out = self.list(u'myfloat:10..0') + self.assertEqual(u'', out) + + self.modify(u'myfloat=-9.1') item.load() self.assertEqual(item['myfloat'], -9.1) # Match in range - out = self.list('myfloat:-10..0') - self.assertIn(b'aaa', out) + out = self.list(u'myfloat:-10..0') + self.assertIn('aaa', out) def test_bool_modify_and_query(self): - self.config['types'] = {'mybool': 'bool'} - true = self.add_item(artist='true') - false = self.add_item(artist='false') - self.add_item(artist='unset') + self.config['types'] = {'mybool': u'bool'} + true = self.add_item(artist=u'true') + false = self.add_item(artist=u'false') + self.add_item(artist=u'unset') + + # Do not match unset values + out = self.list(u'mybool:true, mybool:false') + self.assertEqual(u'', out) # Set true - self.modify('mybool=1', 'artist:true') + self.modify(u'mybool=1', u'artist:true') true.load() self.assertEqual(true['mybool'], True) # Set false - self.modify('mybool=false', 'artist:false') + self.modify(u'mybool=false', u'artist:false') false.load() self.assertEqual(false['mybool'], False) # Query bools - out = self.list('mybool:true', '$artist $mybool') - self.assertEqual('true True', out) + out = self.list(u'mybool:true', u'$artist $mybool') + self.assertEqual(u'true True', out) - out = self.list('mybool:false', '$artist $mybool') + out = self.list(u'mybool:false', u'$artist $mybool') # Dealing with unset fields? # self.assertEqual('false False', out) @@ -106,23 +114,27 @@ class TypesPluginTest(unittest.TestCase, TestHelper): # self.assertIn('unset $mybool', out) def test_date_modify_and_query(self): - self.config['types'] = {'mydate': 'date'} + self.config['types'] = {'mydate': u'date'} # FIXME parsing should also work with default time format self.config['time_format'] = '%Y-%m-%d' - old = self.add_item(artist='prince') - new = self.add_item(artist='britney') + old = self.add_item(artist=u'prince') + new = self.add_item(artist=u'britney') - self.modify('mydate=1999-01-01', 'artist:prince') + # Do not match unset values + out = self.list(u'mydate:..2000') + self.assertEqual(u'', out) + + self.modify(u'mydate=1999-01-01', u'artist:prince') old.load() - self.assertEqual(old['mydate'], mktime(1999, 01, 01)) + self.assertEqual(old['mydate'], mktime(1999, 1, 1)) - self.modify('mydate=1999-12-30', 'artist:britney') + self.modify(u'mydate=1999-12-30', u'artist:britney') new.load() self.assertEqual(new['mydate'], mktime(1999, 12, 30)) # Match in range - out = self.list('mydate:..1999-07', '$artist $mydate') - self.assertEqual('prince 1999-01-01', out) + out = self.list(u'mydate:..1999-07', u'$artist $mydate') + self.assertEqual(u'prince 1999-01-01', out) # FIXME some sort of timezone issue here # out = self.list('mydate:1999-12-30', '$artist $mydate') @@ -131,17 +143,17 @@ class TypesPluginTest(unittest.TestCase, TestHelper): def test_unknown_type_error(self): self.config['types'] = {'flex': 'unkown type'} with self.assertRaises(ConfigValueError): - self.run_command('ls') + self.run_command(u'ls') def modify(self, *args): - return self.run_with_output('modify', '--yes', '--nowrite', - '--nomove', *args) + return self.run_with_output(u'modify', u'--yes', u'--nowrite', + u'--nomove', *args) - def list(self, query, fmt='$artist - $album - $title'): - return self.run_with_output('ls', '-f', fmt, query).strip() + def list(self, query, fmt=u'$artist - $album - $title'): + return self.run_with_output(u'ls', u'-f', fmt, query).strip() - def list_album(self, query, fmt='$albumartist - $album - $title'): - return self.run_with_output('ls', '-a', '-f', fmt, query).strip() + def list_album(self, query, fmt=u'$albumartist - $album - $title'): + return self.run_with_output(u'ls', u'-a', u'-f', fmt, query).strip() def mktime(*args): @@ -151,5 +163,5 @@ def mktime(*args): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_ui.py b/test/test_ui.py index c1c853e03..77804d3d2 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,8 +15,7 @@ """Tests for the command-line interface. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import os import shutil @@ -23,10 +23,11 @@ import re import subprocess import platform from copy import deepcopy +import six +import unittest -from mock import patch +from mock import patch, Mock from test import _common -from test._common import unittest from test.helper import capture_stdout, has_program, TestHelper, control_stdin from beets import library @@ -38,6 +39,8 @@ from beets.mediafile import MediaFile from beets import config from beets import plugins from beets.util.confit import ConfigError +from beets import util +from beets.util import syspath, MoveOperation class ListTest(unittest.TestCase): @@ -48,12 +51,13 @@ class ListTest(unittest.TestCase): self.lib.add(self.item) self.lib.add_album([self.item]) - def _run_list(self, query='', album=False, path=False, fmt=''): - commands.list_items(self.lib, query, album, fmt) + def _run_list(self, query=u'', album=False, path=False, fmt=u''): + with capture_stdout() as stdout: + commands.list_items(self.lib, query, album, fmt) + return stdout def test_list_outputs_item(self): - with capture_stdout() as stdout: - self._run_list() + stdout = self._run_list() self.assertIn(u'the title', stdout.getvalue()) def test_list_unicode_query(self): @@ -61,57 +65,49 @@ class ListTest(unittest.TestCase): self.item.store() self.lib._connection().commit() - with capture_stdout() as stdout: - self._run_list([u'na\xefve']) + stdout = self._run_list([u'na\xefve']) out = stdout.getvalue() - self.assertTrue(u'na\xefve' in out.decode(stdout.encoding)) + if six.PY2: + out = out.decode(stdout.encoding) + self.assertTrue(u'na\xefve' in out) def test_list_item_path(self): - with capture_stdout() as stdout: - self._run_list(fmt='$path') + stdout = self._run_list(fmt=u'$path') self.assertEqual(stdout.getvalue().strip(), u'xxx/yyy') def test_list_album_outputs_something(self): - with capture_stdout() as stdout: - self._run_list(album=True) + stdout = self._run_list(album=True) self.assertGreater(len(stdout.getvalue()), 0) def test_list_album_path(self): - with capture_stdout() as stdout: - self._run_list(album=True, fmt='$path') + stdout = self._run_list(album=True, fmt=u'$path') self.assertEqual(stdout.getvalue().strip(), u'xxx') def test_list_album_omits_title(self): - with capture_stdout() as stdout: - self._run_list(album=True) + stdout = self._run_list(album=True) self.assertNotIn(u'the title', stdout.getvalue()) def test_list_uses_track_artist(self): - with capture_stdout() as stdout: - self._run_list() + stdout = self._run_list() self.assertIn(u'the artist', stdout.getvalue()) self.assertNotIn(u'the album artist', stdout.getvalue()) def test_list_album_uses_album_artist(self): - with capture_stdout() as stdout: - self._run_list(album=True) + stdout = self._run_list(album=True) self.assertNotIn(u'the artist', stdout.getvalue()) self.assertIn(u'the album artist', stdout.getvalue()) def test_list_item_format_artist(self): - with capture_stdout() as stdout: - self._run_list(fmt='$artist') + stdout = self._run_list(fmt=u'$artist') self.assertIn(u'the artist', stdout.getvalue()) def test_list_item_format_multiple(self): - with capture_stdout() as stdout: - self._run_list(fmt='$artist - $album - $year') + stdout = self._run_list(fmt=u'$artist - $album - $year') self.assertEqual(u'the artist - the album - 0001', stdout.getvalue().strip()) def test_list_album_format(self): - with capture_stdout() as stdout: - self._run_list(album=True, fmt='$genre') + stdout = self._run_list(album=True, fmt=u'$genre') self.assertIn(u'the genre', stdout.getvalue()) self.assertNotIn(u'the album', stdout.getvalue()) @@ -122,25 +118,38 @@ class RemoveTest(_common.TestCase): self.io.install() - self.libdir = os.path.join(self.temp_dir, 'testlibdir') + self.libdir = os.path.join(self.temp_dir, b'testlibdir') os.mkdir(self.libdir) # Copy a file into the library. self.lib = library.Library(':memory:', self.libdir) - self.i = library.Item.from_path(os.path.join(_common.RSRC, 'full.mp3')) + item_path = os.path.join(_common.RSRC, b'full.mp3') + self.i = library.Item.from_path(item_path) self.lib.add(self.i) - self.i.move(True) + self.i.move(operation=MoveOperation.COPY) def test_remove_items_no_delete(self): self.io.addinput('y') - commands.remove_items(self.lib, '', False, False) + commands.remove_items(self.lib, u'', False, False, False) items = self.lib.items() self.assertEqual(len(list(items)), 0) self.assertTrue(os.path.exists(self.i.path)) def test_remove_items_with_delete(self): self.io.addinput('y') - commands.remove_items(self.lib, '', False, True) + commands.remove_items(self.lib, u'', False, True, False) + items = self.lib.items() + self.assertEqual(len(list(items)), 0) + self.assertFalse(os.path.exists(self.i.path)) + + def test_remove_items_with_force_no_delete(self): + commands.remove_items(self.lib, u'', False, False, True) + items = self.lib.items() + self.assertEqual(len(list(items)), 0) + self.assertTrue(os.path.exists(self.i.path)) + + def test_remove_items_with_force_delete(self): + commands.remove_items(self.lib, u'', False, True, True) items = self.lib.items() self.assertEqual(len(list(items)), 0) self.assertFalse(os.path.exists(self.i.path)) @@ -156,44 +165,68 @@ class ModifyTest(unittest.TestCase, TestHelper): def tearDown(self): self.teardown_beets() + def modify_inp(self, inp, *args): + with control_stdin(inp): + self.run_command('modify', *args) + def modify(self, *args): - with control_stdin('y'): - ui._raw_main(['modify'] + list(args), self.lib) + self.modify_inp('y', *args) # Item tests def test_modify_item(self): - self.modify("title=newTitle") + self.modify(u"title=newTitle") item = self.lib.items().get() - self.assertEqual(item.title, 'newTitle') + self.assertEqual(item.title, u'newTitle') + + def test_modify_item_abort(self): + item = self.lib.items().get() + title = item.title + self.modify_inp('n', u"title=newTitle") + item = self.lib.items().get() + self.assertEqual(item.title, title) + + def test_modify_item_no_change(self): + title = u"Tracktitle" + item = self.add_item_fixture(title=title) + self.modify_inp('y', u"title", u"title={0}".format(title)) + item = self.lib.items(title).get() + self.assertEqual(item.title, title) def test_modify_write_tags(self): - self.modify("title=newTitle") + self.modify(u"title=newTitle") item = self.lib.items().get() item.read() - self.assertEqual(item.title, 'newTitle') + self.assertEqual(item.title, u'newTitle') def test_modify_dont_write_tags(self): - self.modify("--nowrite", "title=newTitle") + self.modify(u"--nowrite", u"title=newTitle") item = self.lib.items().get() item.read() self.assertNotEqual(item.title, 'newTitle') def test_move(self): - self.modify("title=newTitle") + self.modify(u"title=newTitle") item = self.lib.items().get() self.assertIn(b'newTitle', item.path) def test_not_move(self): - self.modify("--nomove", "title=newTitle") + self.modify(u"--nomove", u"title=newTitle") item = self.lib.items().get() self.assertNotIn(b'newTitle', item.path) + def test_no_write_no_move(self): + self.modify(u"--nomove", u"--nowrite", u"title=newTitle") + item = self.lib.items().get() + item.read() + self.assertNotIn(b'newTitle', item.path) + self.assertNotEqual(item.title, u'newTitle') + def test_update_mtime(self): item = self.item old_mtime = item.mtime - self.modify("title=newTitle") + self.modify(u"title=newTitle") item.load() self.assertNotEqual(old_mtime, item.mtime) self.assertEqual(item.current_mtime(), item.mtime) @@ -201,37 +234,53 @@ class ModifyTest(unittest.TestCase, TestHelper): def test_reset_mtime_with_no_write(self): item = self.item - self.modify("--nowrite", "title=newTitle") + self.modify(u"--nowrite", u"title=newTitle") item.load() self.assertEqual(0, item.mtime) + def test_selective_modify(self): + title = u"Tracktitle" + album = u"album" + original_artist = u"composer" + new_artist = u"coverArtist" + for i in range(0, 10): + self.add_item_fixture(title=u"{0}{1}".format(title, i), + artist=original_artist, + album=album) + self.modify_inp('s\ny\ny\ny\nn\nn\ny\ny\ny\ny\nn', + title, u"artist={0}".format(new_artist)) + original_items = self.lib.items(u"artist:{0}".format(original_artist)) + new_items = self.lib.items(u"artist:{0}".format(new_artist)) + self.assertEqual(len(list(original_items)), 3) + self.assertEqual(len(list(new_items)), 7) + # Album Tests def test_modify_album(self): - self.modify("--album", "album=newAlbum") + self.modify(u"--album", u"album=newAlbum") album = self.lib.albums().get() - self.assertEqual(album.album, 'newAlbum') + self.assertEqual(album.album, u'newAlbum') def test_modify_album_write_tags(self): - self.modify("--album", "album=newAlbum") + self.modify(u"--album", u"album=newAlbum") item = self.lib.items().get() item.read() - self.assertEqual(item.album, 'newAlbum') + self.assertEqual(item.album, u'newAlbum') def test_modify_album_dont_write_tags(self): - self.modify("--album", "--nowrite", "album=newAlbum") + self.modify(u"--album", u"--nowrite", u"album=newAlbum") item = self.lib.items().get() item.read() - self.assertEqual(item.album, 'the album') + self.assertEqual(item.album, u'the album') def test_album_move(self): - self.modify("--album", "album=newAlbum") + self.modify(u"--album", u"album=newAlbum") item = self.lib.items().get() item.read() self.assertIn(b'newAlbum', item.path) def test_album_not_move(self): - self.modify("--nomove", "--album", "album=newAlbum") + self.modify(u"--nomove", u"--album", u"album=newAlbum") item = self.lib.items().get() item.read() self.assertNotIn(b'newAlbum', item.path) @@ -239,62 +288,62 @@ class ModifyTest(unittest.TestCase, TestHelper): # Misc def test_write_initial_key_tag(self): - self.modify("initial_key=C#m") + self.modify(u"initial_key=C#m") item = self.lib.items().get() - mediafile = MediaFile(item.path) - self.assertEqual(mediafile.initial_key, 'C#m') + mediafile = MediaFile(syspath(item.path)) + self.assertEqual(mediafile.initial_key, u'C#m') def test_set_flexattr(self): - self.modify("flexattr=testAttr") + self.modify(u"flexattr=testAttr") item = self.lib.items().get() - self.assertEqual(item.flexattr, 'testAttr') + self.assertEqual(item.flexattr, u'testAttr') def test_remove_flexattr(self): item = self.lib.items().get() - item.flexattr = 'testAttr' + item.flexattr = u'testAttr' item.store() - self.modify("flexattr!") + self.modify(u"flexattr!") item = self.lib.items().get() - self.assertNotIn("flexattr", item) + self.assertNotIn(u"flexattr", item) - @unittest.skip('not yet implemented') + @unittest.skip(u'not yet implemented') def test_delete_initial_key_tag(self): item = self.lib.items().get() - item.initial_key = 'C#m' + item.initial_key = u'C#m' item.write() item.store() - mediafile = MediaFile(item.path) - self.assertEqual(mediafile.initial_key, 'C#m') + mediafile = MediaFile(syspath(item.path)) + self.assertEqual(mediafile.initial_key, u'C#m') - self.modify("initial_key!") - mediafile = MediaFile(item.path) + self.modify(u"initial_key!") + mediafile = MediaFile(syspath(item.path)) self.assertIsNone(mediafile.initial_key) def test_arg_parsing_colon_query(self): - (query, mods, dels) = commands.modify_parse_args(["title:oldTitle", - "title=newTitle"]) - self.assertEqual(query, ["title:oldTitle"]) - self.assertEqual(mods, {"title": "newTitle"}) + (query, mods, dels) = commands.modify_parse_args([u"title:oldTitle", + u"title=newTitle"]) + self.assertEqual(query, [u"title:oldTitle"]) + self.assertEqual(mods, {"title": u"newTitle"}) def test_arg_parsing_delete(self): - (query, mods, dels) = commands.modify_parse_args(["title:oldTitle", - "title!"]) - self.assertEqual(query, ["title:oldTitle"]) + (query, mods, dels) = commands.modify_parse_args([u"title:oldTitle", + u"title!"]) + self.assertEqual(query, [u"title:oldTitle"]) self.assertEqual(dels, ["title"]) def test_arg_parsing_query_with_exclaimation(self): - (query, mods, dels) = commands.modify_parse_args(["title:oldTitle!", - "title=newTitle!"]) - self.assertEqual(query, ["title:oldTitle!"]) - self.assertEqual(mods, {"title": "newTitle!"}) + (query, mods, dels) = commands.modify_parse_args([u"title:oldTitle!", + u"title=newTitle!"]) + self.assertEqual(query, [u"title:oldTitle!"]) + self.assertEqual(mods, {"title": u"newTitle!"}) def test_arg_parsing_equals_in_value(self): - (query, mods, dels) = commands.modify_parse_args(["title:foo=bar", - "title=newTitle"]) - self.assertEqual(query, ["title:foo=bar"]) - self.assertEqual(mods, {"title": "newTitle"}) + (query, mods, dels) = commands.modify_parse_args([u"title:foo=bar", + u"title=newTitle"]) + self.assertEqual(query, [u"title:foo=bar"]) + self.assertEqual(mods, {"title": u"newTitle"}) class WriteTest(unittest.TestCase, TestHelper): @@ -306,11 +355,11 @@ class WriteTest(unittest.TestCase, TestHelper): self.teardown_beets() def write_cmd(self, *args): - ui._raw_main(['write'] + list(args), self.lib) + return self.run_with_output('write', *args) def test_update_mtime(self): item = self.add_item_fixture() - item['title'] = 'a new title' + item['title'] = u'a new title' item.store() item = self.lib.items().get() @@ -332,24 +381,22 @@ class WriteTest(unittest.TestCase, TestHelper): item.bitrate = 123 item.store() - with capture_stdout() as stdout: - self.write_cmd() + output = self.write_cmd() - self.assertEqual(stdout.getvalue(), '') + self.assertEqual(output, '') def test_write_metadata_field(self): item = self.add_item_fixture() item.read() old_title = item.title - item.title = 'new title' + item.title = u'new title' item.store() - with capture_stdout() as stdout: - self.write_cmd() + output = self.write_cmd() - self.assertTrue('{0} -> new title'.format(old_title) - in stdout.getvalue()) + self.assertTrue(u'{0} -> new title'.format(old_title) + in output) class MoveTest(_common.TestCase): @@ -358,11 +405,11 @@ class MoveTest(_common.TestCase): self.io.install() - self.libdir = os.path.join(self.temp_dir, 'testlibdir') + self.libdir = os.path.join(self.temp_dir, b'testlibdir') os.mkdir(self.libdir) - self.itempath = os.path.join(self.libdir, 'srcfile') - shutil.copy(os.path.join(_common.RSRC, 'full.mp3'), self.itempath) + self.itempath = os.path.join(self.libdir, b'srcfile') + shutil.copy(os.path.join(_common.RSRC, b'full.mp3'), self.itempath) # Add a file to the library but don't copy it in yet. self.lib = library.Library(':memory:', self.libdir) @@ -371,63 +418,82 @@ class MoveTest(_common.TestCase): self.album = self.lib.add_album([self.i]) # Alternate destination directory. - self.otherdir = os.path.join(self.temp_dir, 'testotherdir') + self.otherdir = os.path.join(self.temp_dir, b'testotherdir') def _move(self, query=(), dest=None, copy=False, album=False, - pretend=False): - commands.move_items(self.lib, dest, query, copy, album, pretend) + pretend=False, export=False): + commands.move_items(self.lib, dest, query, copy, album, pretend, + export=export) def test_move_item(self): self._move() self.i.load() - self.assertTrue('testlibdir' in self.i.path) + self.assertTrue(b'testlibdir' in self.i.path) self.assertExists(self.i.path) self.assertNotExists(self.itempath) def test_copy_item(self): self._move(copy=True) self.i.load() - self.assertTrue('testlibdir' in self.i.path) + self.assertTrue(b'testlibdir' in self.i.path) self.assertExists(self.i.path) self.assertExists(self.itempath) def test_move_album(self): self._move(album=True) self.i.load() - self.assertTrue('testlibdir' in self.i.path) + self.assertTrue(b'testlibdir' in self.i.path) self.assertExists(self.i.path) self.assertNotExists(self.itempath) def test_copy_album(self): self._move(copy=True, album=True) self.i.load() - self.assertTrue('testlibdir' in self.i.path) + self.assertTrue(b'testlibdir' in self.i.path) self.assertExists(self.i.path) self.assertExists(self.itempath) def test_move_item_custom_dir(self): self._move(dest=self.otherdir) self.i.load() - self.assertTrue('testotherdir' in self.i.path) + self.assertTrue(b'testotherdir' in self.i.path) self.assertExists(self.i.path) self.assertNotExists(self.itempath) def test_move_album_custom_dir(self): self._move(dest=self.otherdir, album=True) self.i.load() - self.assertTrue('testotherdir' in self.i.path) + self.assertTrue(b'testotherdir' in self.i.path) self.assertExists(self.i.path) self.assertNotExists(self.itempath) def test_pretend_move_item(self): self._move(dest=self.otherdir, pretend=True) self.i.load() - self.assertIn('srcfile', self.i.path) + self.assertIn(b'srcfile', self.i.path) def test_pretend_move_album(self): self._move(album=True, pretend=True) self.i.load() - self.assertIn('srcfile', self.i.path) + self.assertIn(b'srcfile', self.i.path) + + def test_export_item_custom_dir(self): + self._move(dest=self.otherdir, export=True) + self.i.load() + self.assertEqual(self.i.path, self.itempath) + self.assertExists(self.otherdir) + + def test_export_album_custom_dir(self): + self._move(dest=self.otherdir, album=True, export=True) + self.i.load() + self.assertEqual(self.i.path, self.itempath) + self.assertExists(self.otherdir) + + def test_pretend_export_item(self): + self._move(dest=self.otherdir, pretend=True, export=True) + self.i.load() + self.assertIn(b'srcfile', self.i.path) + self.assertNotExists(self.otherdir) class UpdateTest(_common.TestCase): @@ -436,28 +502,31 @@ class UpdateTest(_common.TestCase): self.io.install() - self.libdir = os.path.join(self.temp_dir, 'testlibdir') + self.libdir = os.path.join(self.temp_dir, b'testlibdir') # Copy a file into the library. self.lib = library.Library(':memory:', self.libdir) - self.i = library.Item.from_path(os.path.join(_common.RSRC, 'full.mp3')) + item_path = os.path.join(_common.RSRC, b'full.mp3') + self.i = library.Item.from_path(item_path) self.lib.add(self.i) - self.i.move(True) + self.i.move(operation=MoveOperation.COPY) self.album = self.lib.add_album([self.i]) # Album art. - artfile = os.path.join(self.temp_dir, 'testart.jpg') + artfile = os.path.join(self.temp_dir, b'testart.jpg') _common.touch(artfile) self.album.set_art(artfile) self.album.store() os.remove(artfile) - def _update(self, query=(), album=False, move=False, reset_mtime=True): + def _update(self, query=(), album=False, move=False, reset_mtime=True, + fields=None): self.io.addinput('y') if reset_mtime: self.i.mtime = 0 self.i.store() - commands.update_items(self.lib, query, album, move, False) + commands.update_items(self.lib, query, album, move, False, + fields=fields) def test_delete_removes_item(self): self.assertTrue(list(self.lib.items())) @@ -479,49 +548,89 @@ class UpdateTest(_common.TestCase): self.assertNotExists(artpath) def test_modified_metadata_detected(self): - mf = MediaFile(self.i.path) - mf.title = 'differentTitle' + mf = MediaFile(syspath(self.i.path)) + mf.title = u'differentTitle' mf.save() self._update() item = self.lib.items().get() - self.assertEqual(item.title, 'differentTitle') + self.assertEqual(item.title, u'differentTitle') def test_modified_metadata_moved(self): - mf = MediaFile(self.i.path) - mf.title = 'differentTitle' + mf = MediaFile(syspath(self.i.path)) + mf.title = u'differentTitle' mf.save() self._update(move=True) item = self.lib.items().get() - self.assertTrue('differentTitle' in item.path) + self.assertTrue(b'differentTitle' in item.path) def test_modified_metadata_not_moved(self): - mf = MediaFile(self.i.path) - mf.title = 'differentTitle' + mf = MediaFile(syspath(self.i.path)) + mf.title = u'differentTitle' mf.save() self._update(move=False) item = self.lib.items().get() - self.assertTrue('differentTitle' not in item.path) + self.assertTrue(b'differentTitle' not in item.path) + + def test_selective_modified_metadata_moved(self): + mf = MediaFile(syspath(self.i.path)) + mf.title = u'differentTitle' + mf.genre = u'differentGenre' + mf.save() + self._update(move=True, fields=['title']) + item = self.lib.items().get() + self.assertTrue(b'differentTitle' in item.path) + self.assertNotEqual(item.genre, u'differentGenre') + + def test_selective_modified_metadata_not_moved(self): + mf = MediaFile(syspath(self.i.path)) + mf.title = u'differentTitle' + mf.genre = u'differentGenre' + mf.save() + self._update(move=False, fields=['title']) + item = self.lib.items().get() + self.assertTrue(b'differentTitle' not in item.path) + self.assertNotEqual(item.genre, u'differentGenre') def test_modified_album_metadata_moved(self): - mf = MediaFile(self.i.path) - mf.album = 'differentAlbum' + mf = MediaFile(syspath(self.i.path)) + mf.album = u'differentAlbum' mf.save() self._update(move=True) item = self.lib.items().get() - self.assertTrue('differentAlbum' in item.path) + self.assertTrue(b'differentAlbum' in item.path) def test_modified_album_metadata_art_moved(self): artpath = self.album.artpath - mf = MediaFile(self.i.path) - mf.album = 'differentAlbum' + mf = MediaFile(syspath(self.i.path)) + mf.album = u'differentAlbum' mf.save() self._update(move=True) album = self.lib.albums()[0] self.assertNotEqual(artpath, album.artpath) + def test_selective_modified_album_metadata_moved(self): + mf = MediaFile(syspath(self.i.path)) + mf.album = u'differentAlbum' + mf.genre = u'differentGenre' + mf.save() + self._update(move=True, fields=['album']) + item = self.lib.items().get() + self.assertTrue(b'differentAlbum' in item.path) + self.assertNotEqual(item.genre, u'differentGenre') + + def test_selective_modified_album_metadata_not_moved(self): + mf = MediaFile(syspath(self.i.path)) + mf.album = u'differentAlbum' + mf.genre = u'differentGenre' + mf.save() + self._update(move=True, fields=['genre']) + item = self.lib.items().get() + self.assertTrue(b'differentAlbum' not in item.path) + self.assertEqual(item.genre, u'differentGenre') + def test_mtime_match_skips_update(self): - mf = MediaFile(self.i.path) - mf.title = 'differentTitle' + mf = MediaFile(syspath(self.i.path)) + mf.title = u'differentTitle' mf.save() # Make in-memory mtime match on-disk mtime. @@ -530,7 +639,7 @@ class UpdateTest(_common.TestCase): self._update(reset_mtime=False) item = self.lib.items().get() - self.assertEqual(item.title, 'full') + self.assertEqual(item.title, u'full') class PrintTest(_common.TestCase): @@ -546,7 +655,7 @@ class PrintTest(_common.TestCase): try: ui.print_(u'something') except TypeError: - self.fail('TypeError during print') + self.fail(u'TypeError during print') finally: if lang: os.environ['LANG'] = lang @@ -560,7 +669,7 @@ class PrintTest(_common.TestCase): try: ui.print_(u'something') except ValueError: - self.fail('ValueError during print') + self.fail(u'ValueError during print') finally: if old_lang: os.environ['LANG'] = old_lang @@ -580,20 +689,8 @@ class ImportTest(_common.TestCase): None) -class InputTest(_common.TestCase): - def setUp(self): - super(InputTest, self).setUp() - self.io.install() - - def test_manual_search_gets_unicode(self): - self.io.addinput(b'\xc3\x82me') - self.io.addinput(b'\xc3\x82me') - artist, album = commands.manual_search(False) - self.assertEqual(artist, u'\xc2me') - self.assertEqual(album, u'\xc2me') - - -class ConfigTest(unittest.TestCase, TestHelper): +@_common.slow_test() +class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): def setUp(self): self.setup_beets() @@ -601,7 +698,12 @@ class ConfigTest(unittest.TestCase, TestHelper): # directory there. Some tests will set `BEETSDIR` themselves. del os.environ['BEETSDIR'] self._old_home = os.environ.get('HOME') - os.environ['HOME'] = self.temp_dir + os.environ['HOME'] = util.py3_path(self.temp_dir) + + # Also set APPDATA, the Windows equivalent of setting $HOME. + self._old_appdata = os.environ.get('APPDATA') + os.environ['APPDATA'] = \ + util.py3_path(os.path.join(self.temp_dir, b'AppData', b'Roaming')) self._orig_cwd = os.getcwd() self.test_cmd = self._make_test_cmd() @@ -610,18 +712,18 @@ class ConfigTest(unittest.TestCase, TestHelper): # Default user configuration if platform.system() == 'Windows': self.user_config_dir = os.path.join( - self.temp_dir, 'AppData', 'Roaming', 'beets' + self.temp_dir, b'AppData', b'Roaming', b'beets' ) else: self.user_config_dir = os.path.join( - self.temp_dir, '.config', 'beets' + self.temp_dir, b'.config', b'beets' ) os.makedirs(self.user_config_dir) self.user_config_path = os.path.join(self.user_config_dir, - 'config.yaml') + b'config.yaml') # Custom BEETSDIR - self.beetsdir = os.path.join(self.temp_dir, 'beetsdir') + self.beetsdir = os.path.join(self.temp_dir, b'beetsdir') os.makedirs(self.beetsdir) self._reset_config() @@ -629,11 +731,16 @@ class ConfigTest(unittest.TestCase, TestHelper): def tearDown(self): commands.default_commands.pop() os.chdir(self._orig_cwd) - os.environ['HOME'] = self._old_home + if self._old_home is not None: + os.environ['HOME'] = self._old_home + if self._old_appdata is None: + del os.environ['APPDATA'] + else: + os.environ['APPDATA'] = self._old_appdata self.teardown_beets() def _make_test_cmd(self): - test_cmd = ui.Subcommand('test', help='test') + test_cmd = ui.Subcommand('test', help=u'test') def run(lib, options, args): test_cmd.lib = lib @@ -655,7 +762,7 @@ class ConfigTest(unittest.TestCase, TestHelper): with self.write_config_file() as config: config.write('paths: {x: y}') - ui._raw_main(['test']) + self.run_command('test', lib=None) key, template = self.test_cmd.lib.path_formats[0] self.assertEqual(key, 'x') self.assertEqual(template.original, 'y') @@ -666,8 +773,7 @@ class ConfigTest(unittest.TestCase, TestHelper): self._reset_config() with self.write_config_file() as config: config.write('paths: {x: y}') - - ui._raw_main(['test']) + self.run_command('test', lib=None) key, template = self.test_cmd.lib.path_formats[0] self.assertEqual(key, 'x') self.assertEqual(template.original, 'y') @@ -679,70 +785,66 @@ class ConfigTest(unittest.TestCase, TestHelper): config.write('library: /xxx/yyy/not/a/real/path') with self.assertRaises(ui.UserError): - ui._raw_main(['test']) + self.run_command('test', lib=None) def test_user_config_file(self): with self.write_config_file() as file: file.write('anoption: value') - ui._raw_main(['test']) + self.run_command('test', lib=None) self.assertEqual(config['anoption'].get(), 'value') def test_replacements_parsed(self): with self.write_config_file() as config: config.write("replace: {'[xy]': z}") - ui._raw_main(['test']) + self.run_command('test', lib=None) replacements = self.test_cmd.lib.replacements - self.assertEqual(replacements, [(re.compile(r'[xy]'), b'z')]) + self.assertEqual(replacements, [(re.compile(u'[xy]'), 'z')]) def test_multiple_replacements_parsed(self): with self.write_config_file() as config: config.write("replace: {'[xy]': z, foo: bar}") - - ui._raw_main(['test']) + self.run_command('test', lib=None) replacements = self.test_cmd.lib.replacements self.assertEqual(replacements, [ - (re.compile(r'[xy]'), 'z'), - (re.compile(r'foo'), 'bar'), + (re.compile(u'[xy]'), u'z'), + (re.compile(u'foo'), u'bar'), ]) def test_cli_config_option(self): - config_path = os.path.join(self.temp_dir, 'config.yaml') + config_path = os.path.join(self.temp_dir, b'config.yaml') with open(config_path, 'w') as file: file.write('anoption: value') - - ui._raw_main(['--config', config_path, 'test']) + self.run_command('--config', config_path, 'test', lib=None) self.assertEqual(config['anoption'].get(), 'value') def test_cli_config_file_overwrites_user_defaults(self): with open(self.user_config_path, 'w') as file: file.write('anoption: value') - cli_config_path = os.path.join(self.temp_dir, 'config.yaml') + cli_config_path = os.path.join(self.temp_dir, b'config.yaml') with open(cli_config_path, 'w') as file: file.write('anoption: cli overwrite') - - ui._raw_main(['--config', cli_config_path, 'test']) + self.run_command('--config', cli_config_path, 'test', lib=None) self.assertEqual(config['anoption'].get(), 'cli overwrite') def test_cli_config_file_overwrites_beetsdir_defaults(self): - os.environ['BEETSDIR'] = self.beetsdir - env_config_path = os.path.join(self.beetsdir, 'config.yaml') + os.environ['BEETSDIR'] = util.py3_path(self.beetsdir) + env_config_path = os.path.join(self.beetsdir, b'config.yaml') with open(env_config_path, 'w') as file: file.write('anoption: value') - cli_config_path = os.path.join(self.temp_dir, 'config.yaml') + cli_config_path = os.path.join(self.temp_dir, b'config.yaml') with open(cli_config_path, 'w') as file: file.write('anoption: cli overwrite') - - ui._raw_main(['--config', cli_config_path, 'test']) + self.run_command('--config', cli_config_path, 'test', lib=None) self.assertEqual(config['anoption'].get(), 'cli overwrite') # @unittest.skip('Difficult to implement with optparse') # def test_multiple_cli_config_files(self): -# cli_config_path_1 = os.path.join(self.temp_dir, 'config.yaml') -# cli_config_path_2 = os.path.join(self.temp_dir, 'config_2.yaml') +# cli_config_path_1 = os.path.join(self.temp_dir, b'config.yaml') +# cli_config_path_2 = os.path.join(self.temp_dir, b'config_2.yaml') # # with open(cli_config_path_1, 'w') as file: # file.write('first: value') @@ -750,16 +852,16 @@ class ConfigTest(unittest.TestCase, TestHelper): # with open(cli_config_path_2, 'w') as file: # file.write('second: value') # -# ui._raw_main(['--config', cli_config_path_1, -# '--config', cli_config_path_2, 'test']) +# self.run_command('--config', cli_config_path_1, +# '--config', cli_config_path_2, 'test', lib=None) # self.assertEqual(config['first'].get(), 'value') # self.assertEqual(config['second'].get(), 'value') # # @unittest.skip('Difficult to implement with optparse') # def test_multiple_cli_config_overwrite(self): -# cli_config_path = os.path.join(self.temp_dir, 'config.yaml') +# cli_config_path = os.path.join(self.temp_dir, b'config.yaml') # cli_overwrite_config_path = os.path.join(self.temp_dir, -# 'overwrite_config.yaml') +# b'overwrite_config.yaml') # # with open(cli_config_path, 'w') as file: # file.write('anoption: value') @@ -767,57 +869,63 @@ class ConfigTest(unittest.TestCase, TestHelper): # with open(cli_overwrite_config_path, 'w') as file: # file.write('anoption: overwrite') # -# ui._raw_main(['--config', cli_config_path, -# '--config', cli_overwrite_config_path, 'test']) +# self.run_command('--config', cli_config_path, +# '--config', cli_overwrite_config_path, 'test') # self.assertEqual(config['anoption'].get(), 'cli overwrite') def test_cli_config_paths_resolve_relative_to_user_dir(self): - cli_config_path = os.path.join(self.temp_dir, 'config.yaml') + cli_config_path = os.path.join(self.temp_dir, b'config.yaml') with open(cli_config_path, 'w') as file: file.write('library: beets.db\n') file.write('statefile: state') - ui._raw_main(['--config', cli_config_path, 'test']) - self.assertEqual(config['library'].as_filename(), - os.path.join(self.user_config_dir, 'beets.db')) - self.assertEqual(config['statefile'].as_filename(), - os.path.join(self.user_config_dir, 'state')) + self.run_command('--config', cli_config_path, 'test', lib=None) + self.assert_equal_path( + util.bytestring_path(config['library'].as_filename()), + os.path.join(self.user_config_dir, b'beets.db') + ) + self.assert_equal_path( + util.bytestring_path(config['statefile'].as_filename()), + os.path.join(self.user_config_dir, b'state') + ) def test_cli_config_paths_resolve_relative_to_beetsdir(self): - os.environ['BEETSDIR'] = self.beetsdir + os.environ['BEETSDIR'] = util.py3_path(self.beetsdir) - cli_config_path = os.path.join(self.temp_dir, 'config.yaml') + cli_config_path = os.path.join(self.temp_dir, b'config.yaml') with open(cli_config_path, 'w') as file: file.write('library: beets.db\n') file.write('statefile: state') - ui._raw_main(['--config', cli_config_path, 'test']) - self.assertEqual(config['library'].as_filename(), - os.path.join(self.beetsdir, 'beets.db')) - self.assertEqual(config['statefile'].as_filename(), - os.path.join(self.beetsdir, 'state')) + self.run_command('--config', cli_config_path, 'test', lib=None) + self.assert_equal_path( + util.bytestring_path(config['library'].as_filename()), + os.path.join(self.beetsdir, b'beets.db') + ) + self.assert_equal_path( + util.bytestring_path(config['statefile'].as_filename()), + os.path.join(self.beetsdir, b'state') + ) def test_command_line_option_relative_to_working_dir(self): os.chdir(self.temp_dir) - ui._raw_main(['--library', 'foo.db', 'test']) - self.assertEqual(config['library'].as_filename(), - os.path.join(os.getcwd(), 'foo.db')) + self.run_command('--library', 'foo.db', 'test', lib=None) + self.assert_equal_path(config['library'].as_filename(), + os.path.join(os.getcwd(), 'foo.db')) def test_cli_config_file_loads_plugin_commands(self): - plugin_path = os.path.join(_common.RSRC, 'beetsplug') - - cli_config_path = os.path.join(self.temp_dir, 'config.yaml') + cli_config_path = os.path.join(self.temp_dir, b'config.yaml') with open(cli_config_path, 'w') as file: - file.write('pluginpath: %s\n' % plugin_path) + file.write('pluginpath: %s\n' % _common.PLUGINPATH) file.write('plugins: test') - ui._raw_main(['--config', cli_config_path, 'plugin']) + self.run_command('--config', cli_config_path, 'plugin', lib=None) self.assertTrue(plugins.find_plugins()[0].is_test_plugin) def test_beetsdir_config(self): - os.environ['BEETSDIR'] = self.beetsdir + os.environ['BEETSDIR'] = util.py3_path(self.beetsdir) - env_config_path = os.path.join(self.beetsdir, 'config.yaml') + env_config_path = os.path.join(self.beetsdir, b'config.yaml') with open(env_config_path, 'w') as file: file.write('anoption: overwrite') @@ -825,13 +933,13 @@ class ConfigTest(unittest.TestCase, TestHelper): self.assertEqual(config['anoption'].get(), 'overwrite') def test_beetsdir_points_to_file_error(self): - beetsdir = os.path.join(self.temp_dir, 'beetsfile') + beetsdir = os.path.join(self.temp_dir, b'beetsfile') open(beetsdir, 'a').close() - os.environ['BEETSDIR'] = beetsdir - self.assertRaises(ConfigError, ui._raw_main, ['test']) + os.environ['BEETSDIR'] = util.py3_path(beetsdir) + self.assertRaises(ConfigError, self.run_command, 'test') def test_beetsdir_config_does_not_load_default_user_config(self): - os.environ['BEETSDIR'] = self.beetsdir + os.environ['BEETSDIR'] = util.py3_path(self.beetsdir) with open(self.user_config_path, 'w') as file: file.write('anoption: value') @@ -840,27 +948,35 @@ class ConfigTest(unittest.TestCase, TestHelper): self.assertFalse(config['anoption'].exists()) def test_default_config_paths_resolve_relative_to_beetsdir(self): - os.environ['BEETSDIR'] = self.beetsdir + os.environ['BEETSDIR'] = util.py3_path(self.beetsdir) config.read() - self.assertEqual(config['library'].as_filename(), - os.path.join(self.beetsdir, 'library.db')) - self.assertEqual(config['statefile'].as_filename(), - os.path.join(self.beetsdir, 'state.pickle')) + self.assert_equal_path( + util.bytestring_path(config['library'].as_filename()), + os.path.join(self.beetsdir, b'library.db') + ) + self.assert_equal_path( + util.bytestring_path(config['statefile'].as_filename()), + os.path.join(self.beetsdir, b'state.pickle') + ) def test_beetsdir_config_paths_resolve_relative_to_beetsdir(self): - os.environ['BEETSDIR'] = self.beetsdir + os.environ['BEETSDIR'] = util.py3_path(self.beetsdir) - env_config_path = os.path.join(self.beetsdir, 'config.yaml') + env_config_path = os.path.join(self.beetsdir, b'config.yaml') with open(env_config_path, 'w') as file: file.write('library: beets.db\n') file.write('statefile: state') config.read() - self.assertEqual(config['library'].as_filename(), - os.path.join(self.beetsdir, 'beets.db')) - self.assertEqual(config['statefile'].as_filename(), - os.path.join(self.beetsdir, 'state')) + self.assert_equal_path( + util.bytestring_path(config['library'].as_filename()), + os.path.join(self.beetsdir, b'beets.db') + ) + self.assert_equal_path( + util.bytestring_path(config['statefile'].as_filename()), + os.path.join(self.beetsdir, b'state') + ) class ShowModelChangeTest(_common.TestCase): @@ -885,34 +1001,34 @@ class ShowModelChangeTest(_common.TestCase): self.b.title = 'x' change, out = self._show() self.assertTrue(change) - self.assertTrue('title' in out) + self.assertTrue(u'title' in out) def test_int_fixed_field_change(self): self.b.track = 9 change, out = self._show() self.assertTrue(change) - self.assertTrue('track' in out) + self.assertTrue(u'track' in out) def test_floats_close_to_identical(self): self.a.length = 1.00001 self.b.length = 1.00005 change, out = self._show() self.assertFalse(change) - self.assertEqual(out, '') + self.assertEqual(out, u'') def test_floats_different(self): self.a.length = 1.00001 self.b.length = 2.00001 change, out = self._show() self.assertTrue(change) - self.assertTrue('length' in out) + self.assertTrue(u'length' in out) def test_both_values_shown(self): - self.a.title = 'foo' - self.b.title = 'bar' + self.a.title = u'foo' + self.b.title = u'bar' change, out = self._show() - self.assertTrue('foo' in out) - self.assertTrue('bar' in out) + self.assertTrue(u'foo' in out) + self.assertTrue(u'bar' in out) class ShowChangeTest(_common.TestCase): @@ -922,7 +1038,7 @@ class ShowChangeTest(_common.TestCase): self.items = [_common.item()] self.items[0].track = 1 - self.items[0].path = '/path/to/file.mp3' + self.items[0].path = b'/path/to/file.mp3' self.info = autotag.AlbumInfo( u'the album', u'album id', u'the artist', u'artist id', [ autotag.TrackInfo(u'the title', u'track id', index=1) @@ -945,7 +1061,7 @@ class ShowChangeTest(_common.TestCase): autotag.AlbumMatch(album_dist, info, mapping, set(), set()), ) # FIXME decoding shouldn't be done here - return self.io.getoutput().lower().decode('utf8') + return util.text_string(self.io.getoutput().lower()) def test_null_change(self): msg = self._show_change() @@ -970,21 +1086,22 @@ class ShowChangeTest(_common.TestCase): def test_album_data_change_with_unicode(self): msg = self._show_change(cur_artist=u'caf\xe9', cur_album=u'another album') - self.assertTrue('correcting tags from:' in msg) + self.assertTrue(u'correcting tags from:' in msg) def test_item_data_change_title_missing(self): self.items[0].title = u'' msg = re.sub(r' +', ' ', self._show_change()) - self.assertTrue('file.mp3 -> the title' in msg) + self.assertTrue(u'file.mp3 -> the title' in msg) def test_item_data_change_title_missing_with_unicode_filename(self): self.items[0].title = u'' - self.items[0].path = u'/path/to/caf\xe9.mp3'.encode('utf8') + self.items[0].path = u'/path/to/caf\xe9.mp3'.encode('utf-8') msg = re.sub(r' +', ' ', self._show_change()) self.assertTrue(u'caf\xe9.mp3 -> the title' in msg or u'caf.mp3 ->' in msg) +@patch('beets.library.Item.try_filesize', Mock(return_value=987)) class SummarizeItemsTest(_common.TestCase): def setUp(self): super(SummarizeItemsTest, self).setUp() @@ -993,33 +1110,31 @@ class SummarizeItemsTest(_common.TestCase): item.length = 10 * 60 + 54 item.format = "F" self.item = item - fsize_mock = patch('beets.library.Item.try_filesize').start() - fsize_mock.return_value = 987 def test_summarize_item(self): summary = commands.summarize_items([], True) - self.assertEqual(summary, "") + self.assertEqual(summary, u"") summary = commands.summarize_items([self.item], True) - self.assertEqual(summary, "F, 4kbps, 10:54, 987.0 B") + self.assertEqual(summary, u"F, 4kbps, 10:54, 987.0 B") def test_summarize_items(self): summary = commands.summarize_items([], False) - self.assertEqual(summary, "0 items") + self.assertEqual(summary, u"0 items") summary = commands.summarize_items([self.item], False) - self.assertEqual(summary, "1 items, F, 4kbps, 10:54, 987.0 B") + self.assertEqual(summary, u"1 items, F, 4kbps, 10:54, 987.0 B") i2 = deepcopy(self.item) summary = commands.summarize_items([self.item, i2], False) - self.assertEqual(summary, "2 items, F, 4kbps, 21:48, 1.9 KiB") + self.assertEqual(summary, u"2 items, F, 4kbps, 21:48, 1.9 KiB") i2.format = "G" summary = commands.summarize_items([self.item, i2], False) - self.assertEqual(summary, "2 items, F 1, G 1, 4kbps, 21:48, 1.9 KiB") + self.assertEqual(summary, u"2 items, F 1, G 1, 4kbps, 21:48, 1.9 KiB") summary = commands.summarize_items([self.item, i2, i2], False) - self.assertEqual(summary, "3 items, G 2, F 1, 4kbps, 32:42, 2.9 KiB") + self.assertEqual(summary, u"3 items, G 2, F 1, 4kbps, 32:42, 2.9 KiB") class PathFormatTest(_common.TestCase): @@ -1029,58 +1144,67 @@ class PathFormatTest(_common.TestCase): config['paths'] = {u'foo': u'bar'} pf = ui.get_path_formats() key, tmpl = pf[0] - self.assertEqual(key, 'foo') - self.assertEqual(tmpl.original, 'bar') + self.assertEqual(key, u'foo') + self.assertEqual(tmpl.original, u'bar') self.assertEqual(pf[1:], default_formats) -class PluginTest(_common.TestCase): +@_common.slow_test() +class PluginTest(_common.TestCase, TestHelper): def test_plugin_command_from_pluginpath(self): - config['pluginpath'] = [os.path.join(_common.RSRC, 'beetsplug')] + config['pluginpath'] = [_common.PLUGINPATH] config['plugins'] = ['test'] - ui._raw_main(['test']) + self.run_command('test', lib=None) -class CompletionTest(_common.TestCase): +@_common.slow_test() +class CompletionTest(_common.TestCase, TestHelper): def test_completion(self): # Load plugin commands - config['pluginpath'] = [os.path.join(_common.RSRC, 'beetsplug')] + config['pluginpath'] = [_common.PLUGINPATH] config['plugins'] = ['test'] - test_script = os.path.join( - os.path.dirname(__file__), 'test_completion.sh' - ) - bash_completion = os.path.abspath(os.environ.get( - 'BASH_COMPLETION_SCRIPT', '/etc/bash_completion')) + # Do not load any other bash completion scripts on the system. + env = dict(os.environ) + env['BASH_COMPLETION_DIR'] = os.devnull + env['BASH_COMPLETION_COMPAT_DIR'] = os.devnull - # Tests run in bash + # Open a `bash` process to run the tests in. We'll pipe in bash + # commands via stdin. cmd = os.environ.get('BEETS_TEST_SHELL', '/bin/bash --norc').split() if not has_program(cmd[0]): - self.skipTest('bash not available') + self.skipTest(u'bash not available') tester = subprocess.Popen(cmd, stdin=subprocess.PIPE, - stdout=subprocess.PIPE) + stdout=subprocess.PIPE, env=env) - # Load bash_completion + # Load bash_completion library. + for path in commands.BASH_COMPLETION_PATHS: + if os.path.exists(util.syspath(path)): + bash_completion = path + break + else: + self.skipTest(u'bash-completion script not found') try: - with open(bash_completion, 'r') as bash_completion: - tester.stdin.writelines(bash_completion) + with open(util.syspath(bash_completion), 'rb') as f: + tester.stdin.writelines(f) except IOError: - self.skipTest('bash-completion script not found') + self.skipTest(u'could not read bash-completion script') - # Load complection script + # Load completion script. self.io.install() - ui._raw_main(['completion']) - completion_script = self.io.getoutput() + self.run_command('completion', lib=None) + completion_script = self.io.getoutput().encode('utf-8') self.io.restore() - tester.stdin.writelines(completion_script) + tester.stdin.writelines(completion_script.splitlines(True)) - # Load testsuite - with open(test_script, 'r') as test_script: - tester.stdin.writelines(test_script) - (out, err) = tester.communicate() - if tester.returncode != 0 or out != "completion tests passed\n": - print(out) - self.fail('test/test_completion.sh did not execute properly') + # Load test suite. + test_script_name = os.path.join(_common.RSRC, b'test_completion.sh') + with open(test_script_name, 'rb') as test_script_file: + tester.stdin.writelines(test_script_file) + out, err = tester.communicate() + if tester.returncode != 0 or out != b'completion tests passed\n': + print(out.decode('utf-8')) + self.fail(u'test/test_completion.sh did not execute properly') class CommonOptionsParserCliTest(unittest.TestCase, TestHelper): @@ -1091,7 +1215,7 @@ class CommonOptionsParserCliTest(unittest.TestCase, TestHelper): self.setup_beets() self.lib = library.Library(':memory:') self.item = _common.item() - self.item.path = 'xxx/yyy' + self.item.path = b'xxx/yyy' self.lib.add(self.item) self.lib.add_album([self.item]) @@ -1099,34 +1223,67 @@ class CommonOptionsParserCliTest(unittest.TestCase, TestHelper): self.teardown_beets() def test_base(self): - l = self.run_with_output('ls') - self.assertEqual(l, 'the artist - the album - the title\n') + l = self.run_with_output(u'ls') + self.assertEqual(l, u'the artist - the album - the title\n') - l = self.run_with_output('ls', '-a') - self.assertEqual(l, 'the album artist - the album\n') + l = self.run_with_output(u'ls', u'-a') + self.assertEqual(l, u'the album artist - the album\n') def test_path_option(self): - l = self.run_with_output('ls', '-p') - self.assertEqual(l, 'xxx/yyy\n') + l = self.run_with_output(u'ls', u'-p') + self.assertEqual(l, u'xxx/yyy\n') - l = self.run_with_output('ls', '-a', '-p') - self.assertEqual(l, 'xxx\n') + l = self.run_with_output(u'ls', u'-a', u'-p') + self.assertEqual(l, u'xxx\n') def test_format_option(self): - l = self.run_with_output('ls', '-f', '$artist') - self.assertEqual(l, 'the artist\n') + l = self.run_with_output(u'ls', u'-f', u'$artist') + self.assertEqual(l, u'the artist\n') - l = self.run_with_output('ls', '-a', '-f', '$albumartist') - self.assertEqual(l, 'the album artist\n') + l = self.run_with_output(u'ls', u'-a', u'-f', u'$albumartist') + self.assertEqual(l, u'the album artist\n') + + def test_format_option_unicode(self): + l = self.run_with_output(b'ls', b'-f', + u'caf\xe9'.encode(util.arg_encoding())) + self.assertEqual(l, u'caf\xe9\n') def test_root_format_option(self): - l = self.run_with_output('--format-item', '$artist', - '--format-album', 'foo', 'ls') - self.assertEqual(l, 'the artist\n') + l = self.run_with_output(u'--format-item', u'$artist', + u'--format-album', u'foo', u'ls') + self.assertEqual(l, u'the artist\n') - l = self.run_with_output('--format-item', 'foo', - '--format-album', '$albumartist', 'ls', '-a') - self.assertEqual(l, 'the album artist\n') + l = self.run_with_output(u'--format-item', u'foo', + u'--format-album', u'$albumartist', + u'ls', u'-a') + self.assertEqual(l, u'the album artist\n') + + def test_help(self): + l = self.run_with_output(u'help') + self.assertIn(u'Usage:', l) + + l = self.run_with_output(u'help', u'list') + self.assertIn(u'Usage:', l) + + with self.assertRaises(ui.UserError): + self.run_command(u'help', u'this.is.not.a.real.command') + + def test_stats(self): + l = self.run_with_output(u'stats') + self.assertIn(u'Approximate total size:', l) + + # # Need to have more realistic library setup for this to work + # l = self.run_with_output('stats', '-e') + # self.assertIn('Total size:', l) + + def test_version(self): + l = self.run_with_output(u'version') + self.assertIn(u'Python version', l) + self.assertIn(u'no plugins loaded', l) + + # # Need to have plugin loaded + # l = self.run_with_output('version') + # self.assertIn('plugins: ', l) class CommonOptionsParserTest(unittest.TestCase, TestHelper): @@ -1143,8 +1300,9 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper): self.assertTrue(bool(parser._album_flags)) self.assertEqual(parser.parse_args([]), ({'album': None}, [])) - self.assertEqual(parser.parse_args(['-a']), ({'album': True}, [])) - self.assertEqual(parser.parse_args(['--album']), ({'album': True}, [])) + self.assertEqual(parser.parse_args([u'-a']), ({'album': True}, [])) + self.assertEqual(parser.parse_args([u'--album']), + ({'album': True}, [])) def test_path_option(self): parser = ui.CommonOptionsParser() @@ -1153,15 +1311,15 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper): config['format_item'].set('$foo') self.assertEqual(parser.parse_args([]), ({'path': None}, [])) - self.assertEqual(config['format_item'].get(unicode), u'$foo') + self.assertEqual(config['format_item'].as_str(), u'$foo') - self.assertEqual(parser.parse_args(['-p']), - ({'path': True, 'format': '$path'}, [])) + self.assertEqual(parser.parse_args([u'-p']), + ({'path': True, 'format': u'$path'}, [])) self.assertEqual(parser.parse_args(['--path']), - ({'path': True, 'format': '$path'}, [])) + ({'path': True, 'format': u'$path'}, [])) - self.assertEqual(config['format_item'].get(unicode), '$path') - self.assertEqual(config['format_album'].get(unicode), '$path') + self.assertEqual(config['format_item'].as_str(), u'$path') + self.assertEqual(config['format_album'].as_str(), u'$path') def test_format_option(self): parser = ui.CommonOptionsParser() @@ -1170,15 +1328,15 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper): config['format_item'].set('$foo') self.assertEqual(parser.parse_args([]), ({'format': None}, [])) - self.assertEqual(config['format_item'].get(unicode), u'$foo') + self.assertEqual(config['format_item'].as_str(), u'$foo') - self.assertEqual(parser.parse_args(['-f', '$bar']), - ({'format': '$bar'}, [])) - self.assertEqual(parser.parse_args(['--format', '$baz']), - ({'format': '$baz'}, [])) + self.assertEqual(parser.parse_args([u'-f', u'$bar']), + ({'format': u'$bar'}, [])) + self.assertEqual(parser.parse_args([u'--format', u'$baz']), + ({'format': u'$baz'}, [])) - self.assertEqual(config['format_item'].get(unicode), '$baz') - self.assertEqual(config['format_album'].get(unicode), '$baz') + self.assertEqual(config['format_item'].as_str(), u'$baz') + self.assertEqual(config['format_album'].as_str(), u'$baz') def test_format_option_with_target(self): with self.assertRaises(KeyError): @@ -1190,11 +1348,11 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper): config['format_item'].set('$item') config['format_album'].set('$album') - self.assertEqual(parser.parse_args(['-f', '$bar']), - ({'format': '$bar'}, [])) + self.assertEqual(parser.parse_args([u'-f', u'$bar']), + ({'format': u'$bar'}, [])) - self.assertEqual(config['format_item'].get(unicode), '$bar') - self.assertEqual(config['format_album'].get(unicode), '$album') + self.assertEqual(config['format_item'].as_str(), u'$bar') + self.assertEqual(config['format_album'].as_str(), u'$album') def test_format_option_with_album(self): parser = ui.CommonOptionsParser() @@ -1204,16 +1362,16 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper): config['format_item'].set('$item') config['format_album'].set('$album') - parser.parse_args(['-f', '$bar']) - self.assertEqual(config['format_item'].get(unicode), '$bar') - self.assertEqual(config['format_album'].get(unicode), '$album') + parser.parse_args([u'-f', u'$bar']) + self.assertEqual(config['format_item'].as_str(), u'$bar') + self.assertEqual(config['format_album'].as_str(), u'$album') - parser.parse_args(['-a', '-f', '$foo']) - self.assertEqual(config['format_item'].get(unicode), '$bar') - self.assertEqual(config['format_album'].get(unicode), '$foo') + parser.parse_args([u'-a', u'-f', u'$foo']) + self.assertEqual(config['format_item'].as_str(), u'$bar') + self.assertEqual(config['format_album'].as_str(), u'$foo') - parser.parse_args(['-f', '$foo2', '-a']) - self.assertEqual(config['format_album'].get(unicode), '$foo2') + parser.parse_args([u'-f', u'$foo2', u'-a']) + self.assertEqual(config['format_album'].as_str(), u'$foo2') def test_add_all_common_options(self): parser = ui.CommonOptionsParser() @@ -1222,8 +1380,32 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper): ({'album': None, 'path': None, 'format': None}, [])) +class EncodingTest(_common.TestCase): + """Tests for the `terminal_encoding` config option and our + `_in_encoding` and `_out_encoding` utility functions. + """ + + def out_encoding_overridden(self): + config['terminal_encoding'] = 'fake_encoding' + self.assertEqual(ui._out_encoding(), 'fake_encoding') + + def in_encoding_overridden(self): + config['terminal_encoding'] = 'fake_encoding' + self.assertEqual(ui._in_encoding(), 'fake_encoding') + + def out_encoding_default_utf8(self): + with patch('sys.stdout') as stdout: + stdout.encoding = None + self.assertEqual(ui._out_encoding(), 'utf-8') + + def in_encoding_default_utf8(self): + with patch('sys.stdin') as stdin: + stdin.encoding = None + self.assertEqual(ui._in_encoding(), 'utf-8') + + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_ui_commands.py b/test/test_ui_commands.py index dd8eb47a3..764d1b009 100644 --- a/test/test_ui_commands.py +++ b/test/test_ui_commands.py @@ -1,6 +1,6 @@ -# -*- coding: utf8 -*- +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,11 +15,14 @@ """Test module for file ui/commands.py """ + +from __future__ import division, absolute_import, print_function + import os import shutil +import unittest from test import _common -from test._common import unittest from beets import library from beets import ui @@ -30,16 +33,16 @@ class QueryTest(_common.TestCase): def setUp(self): super(QueryTest, self).setUp() - self.libdir = os.path.join(self.temp_dir, 'testlibdir') + self.libdir = os.path.join(self.temp_dir, b'testlibdir') os.mkdir(self.libdir) # Add a file to the library but don't copy it in yet. self.lib = library.Library(':memory:', self.libdir) # Alternate destination directory. - self.otherdir = os.path.join(self.temp_dir, 'testotherdir') + self.otherdir = os.path.join(self.temp_dir, b'testotherdir') - def add_item(self, filename='srcfile', templatefile='full.mp3'): + def add_item(self, filename=b'srcfile', templatefile=b'full.mp3'): itempath = os.path.join(self.libdir, filename) shutil.copy(os.path.join(_common.RSRC, templatefile), itempath) item = library.Item.from_path(itempath) @@ -116,5 +119,5 @@ class FieldsTest(_common.LibTestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_ui_importer.py b/test/test_ui_importer.py index 2c571925f..48a66dc5f 100644 --- a/test/test_ui_importer.py +++ b/test/test_ui_importer.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -18,14 +19,15 @@ test_importer module. But here the test importer inherits from ``TerminalImportSession``. So we test this class, too. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function +import unittest -from test._common import unittest, DummyIO +from test._common import DummyIO from test import test_importer from beets.ui.commands import TerminalImportSession from beets import importer from beets import config +import six class TestTerminalImportSession(TerminalImportSession): @@ -58,21 +60,21 @@ class TestTerminalImportSession(TerminalImportSession): choice = self.default_choice if choice == importer.action.APPLY: - self.io.addinput('A') + self.io.addinput(u'A') elif choice == importer.action.ASIS: - self.io.addinput('U') + self.io.addinput(u'U') elif choice == importer.action.ALBUMS: - self.io.addinput('G') + self.io.addinput(u'G') elif choice == importer.action.TRACKS: - self.io.addinput('T') + self.io.addinput(u'T') elif choice == importer.action.SKIP: - self.io.addinput('S') + self.io.addinput(u'S') elif isinstance(choice, int): - self.io.addinput('M') - self.io.addinput(unicode(choice)) + self.io.addinput(u'M') + self.io.addinput(six.text_type(choice)) self._add_choice_input() else: - raise Exception('Unknown choice %s' % choice) + raise Exception(u'Unknown choice %s' % choice) class TerminalImportSessionSetup(object): @@ -148,5 +150,5 @@ class GlobalGroupAlbumsImportTest(TerminalImportSessionSetup, def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_ui_init.py b/test/test_ui_init.py index f31deefe7..3a146b0c0 100644 --- a/test/test_ui_init.py +++ b/test/test_ui_init.py @@ -1,6 +1,6 @@ -# -*- coding: utf8 -*- +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -15,12 +15,65 @@ """Test module for file ui/__init__.py """ + +from __future__ import division, absolute_import, print_function + +import unittest from test import _common -from test._common import unittest from beets import ui +class InputMethodsTest(_common.TestCase): + def setUp(self): + super(InputMethodsTest, self).setUp() + self.io.install() + + def _print_helper(self, s): + print(s) + + def _print_helper2(self, s, prefix): + print(prefix, s) + + def test_input_select_objects(self): + full_items = ['1', '2', '3', '4', '5'] + + # Test no + self.io.addinput('n') + items = ui.input_select_objects( + "Prompt", full_items, self._print_helper) + self.assertEqual(items, []) + + # Test yes + self.io.addinput('y') + items = ui.input_select_objects( + "Prompt", full_items, self._print_helper) + self.assertEqual(items, full_items) + + # Test selective 1 + self.io.addinput('s') + self.io.addinput('n') + self.io.addinput('y') + self.io.addinput('n') + self.io.addinput('y') + self.io.addinput('n') + items = ui.input_select_objects( + "Prompt", full_items, self._print_helper) + self.assertEqual(items, ['2', '4']) + + # Test selective 2 + self.io.addinput('s') + self.io.addinput('y') + self.io.addinput('y') + self.io.addinput('n') + self.io.addinput('y') + self.io.addinput('n') + items = ui.input_select_objects( + "Prompt", full_items, + lambda s: self._print_helper2(s, "Prefix")) + self.assertEqual(items, ['1', '2', '4']) + + class InitTest(_common.LibTestCase): def setUp(self): super(InitTest, self).setUp() @@ -63,5 +116,5 @@ class InitTest(_common.LibTestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_util.py b/test/test_util.py index 324a4d589..0d0bbd7b0 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -13,19 +14,19 @@ # included in all copies or substantial portions of the Software. """Tests for base utils from the beets.util package. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import sys import re import os import subprocess +import unittest from mock import patch, Mock -from test._common import unittest from test import _common from beets import util +import six class UtilTest(unittest.TestCase): @@ -42,39 +43,39 @@ class UtilTest(unittest.TestCase): @patch('os.execlp') @patch('beets.util.open_anything') def test_interactive_open(self, mock_open, mock_execlp): - mock_open.return_value = 'tagada' - util.interactive_open(['foo']) - mock_execlp.assert_called_once_with('tagada', 'tagada', 'foo') + mock_open.return_value = u'tagada' + util.interactive_open(['foo'], util.open_anything()) + mock_execlp.assert_called_once_with(u'tagada', u'tagada', u'foo') mock_execlp.reset_mock() - util.interactive_open(['foo'], 'bar') - mock_execlp.assert_called_once_with('bar', 'bar', 'foo') + util.interactive_open(['foo'], u'bar') + mock_execlp.assert_called_once_with(u'bar', u'bar', u'foo') def test_sanitize_unix_replaces_leading_dot(self): with _common.platform_posix(): p = util.sanitize_path(u'one/.two/three') - self.assertFalse('.' in p) + self.assertFalse(u'.' in p) def test_sanitize_windows_replaces_trailing_dot(self): with _common.platform_windows(): p = util.sanitize_path(u'one/two./three') - self.assertFalse('.' in p) + self.assertFalse(u'.' in p) def test_sanitize_windows_replaces_illegal_chars(self): with _common.platform_windows(): p = util.sanitize_path(u':*?"<>|') - self.assertFalse(':' in p) - self.assertFalse('*' in p) - self.assertFalse('?' in p) - self.assertFalse('"' in p) - self.assertFalse('<' in p) - self.assertFalse('>' in p) - self.assertFalse('|' in p) + self.assertFalse(u':' in p) + self.assertFalse(u'*' in p) + self.assertFalse(u'?' in p) + self.assertFalse(u'"' in p) + self.assertFalse(u'<' in p) + self.assertFalse(u'>' in p) + self.assertFalse(u'|' in p) def test_sanitize_windows_replaces_trailing_space(self): with _common.platform_windows(): p = util.sanitize_path(u'one/two /three') - self.assertFalse(' ' in p) + self.assertFalse(u' ' in p) def test_sanitize_path_works_on_empty_string(self): with _common.platform_posix(): @@ -95,7 +96,7 @@ class UtilTest(unittest.TestCase): ]) self.assertEqual(p, u'bar/bar') - @unittest.skip('unimplemented: #359') + @unittest.skip(u'unimplemented: #359') def test_sanitize_empty_component(self): with _common.platform_posix(): p = util.sanitize_path(u'foo//bar', [ @@ -103,26 +104,35 @@ class UtilTest(unittest.TestCase): ]) self.assertEqual(p, u'foo/_/bar') + @unittest.skipIf(six.PY2, 'surrogateescape error handler not available' + 'on Python 2') + def test_convert_command_args_keeps_undecodeable_bytes(self): + arg = b'\x82' # non-ascii bytes + cmd_args = util.convert_command_args([arg]) + + self.assertEqual(cmd_args[0], + arg.decode(util.arg_encoding(), 'surrogateescape')) + @patch('beets.util.subprocess.Popen') def test_command_output(self, mock_popen): def popen_fail(*args, **kwargs): m = Mock(returncode=1) - m.communicate.return_value = None, None + m.communicate.return_value = u'foo', u'bar' return m mock_popen.side_effect = popen_fail with self.assertRaises(subprocess.CalledProcessError) as exc_context: - util.command_output([b"taga", b"\xc3\xa9"]) + util.command_output(['taga', '\xc3\xa9']) self.assertEqual(exc_context.exception.returncode, 1) - self.assertEqual(exc_context.exception.cmd, b"taga \xc3\xa9") + self.assertEqual(exc_context.exception.cmd, 'taga \xc3\xa9') class PathConversionTest(_common.TestCase): def test_syspath_windows_format(self): with _common.platform_windows(): - path = os.path.join('a', 'b', 'c') + path = os.path.join(u'a', u'b', u'c') outpath = util.syspath(path) - self.assertTrue(isinstance(outpath, unicode)) + self.assertTrue(isinstance(outpath, six.text_type)) self.assertTrue(outpath.startswith(u'\\\\?\\')) def test_syspath_windows_format_unc_path(self): @@ -131,12 +141,12 @@ class PathConversionTest(_common.TestCase): path = '\\\\server\\share\\file.mp3' with _common.platform_windows(): outpath = util.syspath(path) - self.assertTrue(isinstance(outpath, unicode)) + self.assertTrue(isinstance(outpath, six.text_type)) self.assertEqual(outpath, u'\\\\?\\UNC\\server\\share\\file.mp3') def test_syspath_posix_unchanged(self): with _common.platform_posix(): - path = os.path.join('a', 'b', 'c') + path = os.path.join(u'a', u'b', u'c') outpath = util.syspath(path) self.assertEqual(path, outpath) @@ -152,12 +162,12 @@ class PathConversionTest(_common.TestCase): def test_bytestring_path_windows_encodes_utf8(self): path = u'caf\xe9' outpath = self._windows_bytestring_path(path) - self.assertEqual(path, outpath.decode('utf8')) + self.assertEqual(path, outpath.decode('utf-8')) def test_bytesting_path_windows_removes_magic_prefix(self): path = u'\\\\?\\C:\\caf\xe9' outpath = self._windows_bytestring_path(path) - self.assertEqual(outpath, u'C:\\caf\xe9'.encode('utf8')) + self.assertEqual(outpath, u'C:\\caf\xe9'.encode('utf-8')) class PathTruncationTest(_common.TestCase): @@ -180,5 +190,5 @@ class PathTruncationTest(_common.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_vfs.py b/test/test_vfs.py index 0d6b280e5..b94acfd09 100644 --- a/test/test_vfs.py +++ b/test/test_vfs.py @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -13,11 +14,10 @@ # included in all copies or substantial portions of the Software. """Tests for the virtual filesystem builder..""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function +import unittest from test import _common -from test._common import unittest from beets import library from beets import vfs @@ -26,8 +26,8 @@ class VFSTest(_common.TestCase): def setUp(self): super(VFSTest, self).setUp() self.lib = library.Library(':memory:', path_formats=[ - ('default', 'albums/$album/$title'), - ('singleton:true', 'tracks/$artist/$title'), + (u'default', u'albums/$album/$title'), + (u'singleton:true', u'tracks/$artist/$title'), ]) self.lib.add(_common.item()) self.lib.add_album([_common.item()]) @@ -45,5 +45,5 @@ class VFSTest(_common.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_web.py b/test/test_web.py index 9a8cb55e8..e7d1f334f 100644 --- a/test/test_web.py +++ b/test/test_web.py @@ -1,14 +1,16 @@ +# -*- coding: utf-8 -*- + """Tests for the 'web' plugin""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function -from test._common import unittest -from test import _common import json -import beetsplug +import unittest +import os.path +from six import assertCountEqual + +from test import _common from beets.library import Item, Album -beetsplug.__path__ = ['./beetsplug', '../beetsplug'] # noqa from beetsplug import web @@ -20,92 +22,127 @@ class WebPluginTest(_common.LibTestCase): # Add fixtures for track in self.lib.items(): track.remove() - self.lib.add(Item(title='title', path='', id=1)) - self.lib.add(Item(title='another title', path='', id=2)) - self.lib.add(Album(album='album', id=3)) - self.lib.add(Album(album='another album', id=4)) + self.lib.add(Item(title=u'title', path='/path_1', id=1)) + self.lib.add(Item(title=u'another title', path='/path_2', id=2)) + self.lib.add(Album(album=u'album', id=3)) + self.lib.add(Album(album=u'another album', id=4)) web.app.config['TESTING'] = True web.app.config['lib'] = self.lib + web.app.config['INCLUDE_PATHS'] = False self.client = web.app.test_client() + def test_config_include_paths_true(self): + web.app.config['INCLUDE_PATHS'] = True + response = self.client.get('/item/1') + res_json = json.loads(response.data.decode('utf-8')) + + self.assertEqual(response.status_code, 200) + self.assertEqual(res_json['path'], u'/path_1') + + def test_config_include_paths_false(self): + web.app.config['INCLUDE_PATHS'] = False + response = self.client.get('/item/1') + res_json = json.loads(response.data.decode('utf-8')) + + self.assertEqual(response.status_code, 200) + self.assertNotIn('path', res_json) + def test_get_all_items(self): response = self.client.get('/item/') - response.json = json.loads(response.data) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEqual(len(response.json['items']), 2) + self.assertEqual(len(res_json['items']), 2) def test_get_single_item_by_id(self): response = self.client.get('/item/1') - response.json = json.loads(response.data) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json['id'], 1) - self.assertEqual(response.json['title'], 'title') + self.assertEqual(res_json['id'], 1) + self.assertEqual(res_json['title'], u'title') def test_get_multiple_items_by_id(self): response = self.client.get('/item/1,2') - response.json = json.loads(response.data) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEqual(len(response.json['items']), 2) - response_titles = [item['title'] for item in response.json['items']] - self.assertItemsEqual(response_titles, ['title', 'another title']) + self.assertEqual(len(res_json['items']), 2) + response_titles = [item['title'] for item in res_json['items']] + assertCountEqual(self, response_titles, [u'title', u'another title']) def test_get_single_item_not_found(self): response = self.client.get('/item/3') self.assertEqual(response.status_code, 404) - def test_get_item_empty_query(self): - response = self.client.get('/item/query/') - response.json = json.loads(response.data) + def test_get_single_item_by_path(self): + data_path = os.path.join(_common.RSRC, b'full.mp3') + self.lib.add(Item.from_path(data_path)) + response = self.client.get('/item/path/' + data_path.decode('utf-8')) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEqual(len(response.json['items']), 2) + self.assertEqual(res_json['title'], u'full') + + def test_get_single_item_by_path_not_found_if_not_in_library(self): + data_path = os.path.join(_common.RSRC, b'full.mp3') + # data_path points to a valid file, but we have not added the file + # to the library. + response = self.client.get('/item/path/' + data_path.decode('utf-8')) + + self.assertEqual(response.status_code, 404) + + def test_get_item_empty_query(self): + response = self.client.get('/item/query/') + res_json = json.loads(response.data.decode('utf-8')) + + self.assertEqual(response.status_code, 200) + self.assertEqual(len(res_json['items']), 2) def test_get_simple_item_query(self): response = self.client.get('/item/query/another') - response.json = json.loads(response.data) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEqual(len(response.json['results']), 1) - self.assertEqual(response.json['results'][0]['title'], 'another title') + self.assertEqual(len(res_json['results']), 1) + self.assertEqual(res_json['results'][0]['title'], + u'another title') def test_get_all_albums(self): response = self.client.get('/album/') - response.json = json.loads(response.data) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - response_albums = [album['album'] for album in response.json['albums']] - self.assertItemsEqual(response_albums, ['album', 'another album']) + response_albums = [album['album'] for album in res_json['albums']] + assertCountEqual(self, response_albums, [u'album', u'another album']) def test_get_single_album_by_id(self): response = self.client.get('/album/2') - response.json = json.loads(response.data) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json['id'], 2) - self.assertEqual(response.json['album'], 'another album') + self.assertEqual(res_json['id'], 2) + self.assertEqual(res_json['album'], u'another album') def test_get_multiple_albums_by_id(self): response = self.client.get('/album/1,2') - response.json = json.loads(response.data) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - response_albums = [album['album'] for album in response.json['albums']] - self.assertItemsEqual(response_albums, ['album', 'another album']) + response_albums = [album['album'] for album in res_json['albums']] + assertCountEqual(self, response_albums, [u'album', u'another album']) def test_get_album_empty_query(self): response = self.client.get('/album/query/') - response.json = json.loads(response.data) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEqual(len(response.json['albums']), 2) + self.assertEqual(len(res_json['albums']), 2) def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_zero.py b/test/test_zero.py index a23b47d1c..025eaa540 100644 --- a/test/test_zero.py +++ b/test/test_zero.py @@ -1,127 +1,319 @@ +# -*- coding: utf-8 -*- + """Tests for the 'zero' plugin""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function -from test._common import unittest -from test.helper import TestHelper +import unittest +from test.helper import TestHelper, control_stdin from beets.library import Item -from beets import config from beetsplug.zero import ZeroPlugin from beets.mediafile import MediaFile +from beets.util import syspath class ZeroPluginTest(unittest.TestCase, TestHelper): def setUp(self): self.setup_beets() + self.config['zero'] = { + 'fields': [], + 'keep_fields': [], + 'update_database': False, + } def tearDown(self): + ZeroPlugin.listeners = None self.teardown_beets() self.unload_plugins() def test_no_patterns(self): - tags = { - 'comments': 'test comment', - 'day': 13, - 'month': 3, - 'year': 2012, - } - z = ZeroPlugin() - z.debug = False - z.fields = ['comments', 'month', 'day'] - z.patterns = {'comments': ['.'], - 'month': ['.'], - 'day': ['.']} - z.write_event(None, None, tags) - self.assertEqual(tags['comments'], None) - self.assertEqual(tags['day'], None) - self.assertEqual(tags['month'], None) - self.assertEqual(tags['year'], 2012) + self.config['zero']['fields'] = ['comments', 'month'] - def test_patterns(self): - z = ZeroPlugin() - z.debug = False - z.fields = ['comments', 'year'] - z.patterns = {'comments': 'eac lame'.split(), - 'year': '2098 2099'.split()} - - tags = { - 'comments': 'from lame collection, ripped by eac', - 'year': 2012, - } - z.write_event(None, None, tags) - self.assertEqual(tags['comments'], None) - self.assertEqual(tags['year'], 2012) - - def test_delete_replaygain_tag(self): - path = self.create_mediafile_fixture() - item = Item.from_path(path) - item.rg_track_peak = 0.0 + item = self.add_item_fixture( + comments=u'test comment', + title=u'Title', + month=1, + year=2000, + ) item.write() - mediafile = MediaFile(item.path) - self.assertIsNotNone(mediafile.rg_track_peak) - self.assertIsNotNone(mediafile.rg_track_gain) - - config['zero'] = { - 'fields': ['rg_track_peak', 'rg_track_gain'], - } self.load_plugins('zero') - item.write() - mediafile = MediaFile(item.path) - self.assertIsNone(mediafile.rg_track_peak) - self.assertIsNone(mediafile.rg_track_gain) + + mf = MediaFile(syspath(item.path)) + self.assertIsNone(mf.comments) + self.assertIsNone(mf.month) + self.assertEqual(mf.title, u'Title') + self.assertEqual(mf.year, 2000) + + def test_pattern_match(self): + self.config['zero']['fields'] = ['comments'] + self.config['zero']['comments'] = [u'encoded by'] + + item = self.add_item_fixture(comments=u'encoded by encoder') + item.write() + + self.load_plugins('zero') + item.write() + + mf = MediaFile(syspath(item.path)) + self.assertIsNone(mf.comments) + + def test_pattern_nomatch(self): + self.config['zero']['fields'] = ['comments'] + self.config['zero']['comments'] = [u'encoded by'] + + item = self.add_item_fixture(comments=u'recorded at place') + item.write() + + self.load_plugins('zero') + item.write() + + mf = MediaFile(syspath(item.path)) + self.assertEqual(mf.comments, u'recorded at place') def test_do_not_change_database(self): + self.config['zero']['fields'] = ['year'] + item = self.add_item_fixture(year=2000) item.write() - mediafile = MediaFile(item.path) - self.assertEqual(2000, mediafile.year) - config['zero'] = {'fields': ['year']} self.load_plugins('zero') - item.write() - mediafile = MediaFile(item.path) + self.assertEqual(item['year'], 2000) - self.assertIsNone(mediafile.year) def test_change_database(self): + self.config['zero']['fields'] = ['year'] + self.config['zero']['update_database'] = True + item = self.add_item_fixture(year=2000) item.write() - mediafile = MediaFile(item.path) - self.assertEqual(2000, mediafile.year) - config['zero'] = { - 'fields': ['year'], - 'update_database': True, - } self.load_plugins('zero') - item.write() - mediafile = MediaFile(item.path) + self.assertEqual(item['year'], 0) - self.assertIsNone(mediafile.year) def test_album_art(self): + self.config['zero']['fields'] = ['images'] + path = self.create_mediafile_fixture(images=['jpg']) item = Item.from_path(path) - mediafile = MediaFile(item.path) - self.assertNotEqual(0, len(mediafile.images)) - - config['zero'] = {'fields': ['images']} self.load_plugins('zero') + item.write() + + mf = MediaFile(syspath(path)) + self.assertEqual(0, len(mf.images)) + + def test_auto_false(self): + self.config['zero']['fields'] = ['year'] + self.config['zero']['update_database'] = True + self.config['zero']['auto'] = False + + item = self.add_item_fixture(year=2000) + item.write() + + self.load_plugins('zero') + item.write() + + self.assertEqual(item['year'], 2000) + + def test_subcommand_update_database_true(self): + item = self.add_item_fixture( + year=2016, + day=13, + month=3, + comments=u'test comment' + ) + item.write() + item_id = item.id + self.config['zero']['fields'] = ['comments'] + self.config['zero']['update_database'] = True + self.config['zero']['auto'] = False + + self.load_plugins('zero') + with control_stdin('y'): + self.run_command('zero') + + mf = MediaFile(syspath(item.path)) + item = self.lib.get_item(item_id) + + self.assertEqual(item['year'], 2016) + self.assertEqual(mf.year, 2016) + self.assertEqual(mf.comments, None) + self.assertEqual(item['comments'], u'') + + def test_subcommand_update_database_false(self): + item = self.add_item_fixture( + year=2016, + day=13, + month=3, + comments=u'test comment' + ) + item.write() + item_id = item.id + + self.config['zero']['fields'] = ['comments'] + self.config['zero']['update_database'] = False + self.config['zero']['auto'] = False + + self.load_plugins('zero') + with control_stdin('y'): + self.run_command('zero') + + mf = MediaFile(syspath(item.path)) + item = self.lib.get_item(item_id) + + self.assertEqual(item['year'], 2016) + self.assertEqual(mf.year, 2016) + self.assertEqual(item['comments'], u'test comment') + self.assertEqual(mf.comments, None) + + def test_subcommand_query_include(self): + item = self.add_item_fixture( + year=2016, + day=13, + month=3, + comments=u'test comment' + ) item.write() - mediafile = MediaFile(item.path) - self.assertEqual(0, len(mediafile.images)) + + self.config['zero']['fields'] = ['comments'] + self.config['zero']['update_database'] = False + self.config['zero']['auto'] = False + + self.load_plugins('zero') + self.run_command('zero', 'year: 2016') + + mf = MediaFile(syspath(item.path)) + + self.assertEqual(mf.year, 2016) + self.assertEqual(mf.comments, None) + + def test_subcommand_query_exclude(self): + item = self.add_item_fixture( + year=2016, + day=13, + month=3, + comments=u'test comment' + ) + + item.write() + + self.config['zero']['fields'] = ['comments'] + self.config['zero']['update_database'] = False + self.config['zero']['auto'] = False + + self.load_plugins('zero') + self.run_command('zero', 'year: 0000') + + mf = MediaFile(syspath(item.path)) + + self.assertEqual(mf.year, 2016) + self.assertEqual(mf.comments, u'test comment') + + def test_no_fields(self): + item = self.add_item_fixture(year=2016) + item.write() + mediafile = MediaFile(syspath(item.path)) + self.assertEqual(mediafile.year, 2016) + + item_id = item.id + + self.load_plugins('zero') + with control_stdin('y'): + self.run_command('zero') + + item = self.lib.get_item(item_id) + + self.assertEqual(item['year'], 2016) + self.assertEqual(mediafile.year, 2016) + + def test_whitelist_and_blacklist(self): + item = self.add_item_fixture(year=2016) + item.write() + mf = MediaFile(syspath(item.path)) + self.assertEqual(mf.year, 2016) + + item_id = item.id + self.config['zero']['fields'] = [u'year'] + self.config['zero']['keep_fields'] = [u'comments'] + + self.load_plugins('zero') + with control_stdin('y'): + self.run_command('zero') + + item = self.lib.get_item(item_id) + + self.assertEqual(item['year'], 2016) + self.assertEqual(mf.year, 2016) + + def test_keep_fields(self): + item = self.add_item_fixture(year=2016, comments=u'test comment') + self.config['zero']['keep_fields'] = [u'year'] + self.config['zero']['fields'] = None + self.config['zero']['update_database'] = True + + tags = { + 'comments': u'test comment', + 'year': 2016, + } + self.load_plugins('zero') + + z = ZeroPlugin() + z.write_event(item, item.path, tags) + self.assertEqual(tags['comments'], None) + self.assertEqual(tags['year'], 2016) + + def test_keep_fields_removes_preserved_tags(self): + self.config['zero']['keep_fields'] = [u'year'] + self.config['zero']['fields'] = None + self.config['zero']['update_database'] = True + + z = ZeroPlugin() + + self.assertNotIn('id', z.fields_to_progs) + + def test_fields_removes_preserved_tags(self): + self.config['zero']['fields'] = [u'year id'] + self.config['zero']['update_database'] = True + + z = ZeroPlugin() + + self.assertNotIn('id', z.fields_to_progs) + + def test_empty_query_n_response_no_changes(self): + item = self.add_item_fixture( + year=2016, + day=13, + month=3, + comments=u'test comment' + ) + item.write() + item_id = item.id + self.config['zero']['fields'] = ['comments'] + self.config['zero']['update_database'] = True + self.config['zero']['auto'] = False + + self.load_plugins('zero') + with control_stdin('n'): + self.run_command('zero') + + mf = MediaFile(syspath(item.path)) + item = self.lib.get_item(item_id) + + self.assertEqual(item['year'], 2016) + self.assertEqual(mf.year, 2016) + self.assertEqual(mf.comments, u'test comment') + self.assertEqual(item['comments'], u'test comment') def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/testall.py b/test/testall.py index 320e2c677..88eb70117 100755 --- a/test/testall.py +++ b/test/testall.py @@ -1,7 +1,8 @@ #!/usr/bin/env python +# -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -14,26 +15,17 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import os import re import sys - -from test._common import unittest +import unittest pkgpath = os.path.dirname(__file__) or '.' sys.path.append(pkgpath) os.chdir(pkgpath) -# Make sure we use local version of beetsplug and not system namespaced version -# for tests -try: - del sys.modules["beetsplug"] -except KeyError: - pass - def suite(): s = unittest.TestSuite() @@ -46,5 +38,6 @@ def suite(): s.addTest(__import__(modname).suite()) return s -if __name__ == b'__main__': + +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/tox.ini b/tox.ini index af245bf8f..8c3731f5d 100644 --- a/tox.ini +++ b/tox.ini @@ -4,46 +4,54 @@ # and then run "tox" from this directory. [tox] -envlist = py27, pypy, docs, flake8 +envlist = py27-test, py36-test, py27-flake8, docs -[testenv] +# The exhaustive list of environments is: +# envlist = py{27,34,35}-{test,cov}, py{27,34,35}-flake8, docs + +[_test] deps = beautifulsoup4 flask mock nose - pyechonest + nose-show-skipped pylast rarfile responses>=0.3.0 - pathlib pyxdg jellyfish python-mpd2 -commands = - nosetests {posargs} - -[testenv:py27cov] -basepython = python2.7 -deps = - {[testenv]deps} coverage -commands = - nosetests --with-coverage {posargs} + discogs-client -[testenv:py27setup] -basepython = python2.7 -commands = - python ./setup.py test {posargs} - -[testenv:docs] -changedir = docs -deps = - sphinx -commands = - sphinx-build -W -q -b html . {envtmpdir}/html - -[testenv:flake8] +[_flake8] deps = flake8 -commands = flake8 beets beetsplug beet test setup.py docs + flake8-coding + flake8-future-import + flake8-blind-except + pep8-naming +files = beets beetsplug beet test setup.py docs + +[testenv] +passenv = + NOSE_SHOW_SKIPPED # Undocumented feature of nose-show-skipped. +deps = + {test,cov}: {[_test]deps} + py27: pathlib + py{27,34,35,36}-flake8: {[_flake8]deps} +commands = + py27-cov: python -m nose --with-coverage {posargs} + py27-test: python -m nose {posargs} + py{34,35}-cov: python -bb -m nose --with-coverage {posargs} + py{34,35,36}-test: python -bb -m nose {posargs} + py27-flake8: flake8 --min-version 2.7 {posargs} {[_flake8]files} + py34-flake8: flake8 --min-version 3.4 {posargs} {[_flake8]files} + py35-flake8: flake8 --min-version 3.5 {posargs} {[_flake8]files} + py36-flake8: flake8 --min-version 3.6 {posargs} {[_flake8]files} + +[testenv:docs] +basepython = python2.7 +deps = sphinx +commands = sphinx-build -W -q -b html docs {envtmpdir}/html {posargs}