mirror of
https://github.com/beetbox/beets.git
synced 2026-12-01 13:16:08 -06:00
Merge branch 'master' of https://github.com/sampsyo/beets
This commit is contained in:
@@ -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)
|
||||
```
|
||||
+81
-29
@@ -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
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
^dist/
|
||||
^beets\.egg-info/
|
||||
^build/
|
||||
^MANIFEST$
|
||||
^docs/_build/
|
||||
^\.tox/
|
||||
^\.idea/
|
||||
@@ -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
|
||||
+49
-14
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 *
|
||||
|
||||
+34
-16
@@ -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/
|
||||
|
||||
+17
-8
@@ -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%"
|
||||
|
||||
@@ -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__':
|
||||
|
||||
+20
-15
@@ -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 <adrian@radbox.org>'
|
||||
__version__ = u'1.4.7'
|
||||
__author__ = u'Adrian Sampson <adrian@radbox.org>'
|
||||
|
||||
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__)
|
||||
|
||||
@@ -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:])
|
||||
+38
-13
@@ -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))
|
||||
|
||||
+41
-12
@@ -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
|
||||
|
||||
+71
-38
@@ -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
|
||||
|
||||
+88
-59
@@ -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)
|
||||
|
||||
+114
-22
@@ -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'])
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Regular → Executable
+128
-48
@@ -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
|
||||
|
||||
+202
-59
@@ -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<sign>[+|-]?)(?P<quantity>[0-9]+)' + \
|
||||
'(?P<timespan>[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):
|
||||
|
||||
+86
-39
@@ -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'(?<!\\):' # Unescaped :
|
||||
@@ -36,80 +39,124 @@ PARSE_QUERY_PART_REGEX = re.compile(
|
||||
|
||||
def parse_query_part(part, query_classes={}, prefixes={},
|
||||
default_class=query.SubstringQuery):
|
||||
"""Take a query in the form of a key/value pair separated by a
|
||||
colon and return a tuple of `(key, value, cls)`. `key` may be None,
|
||||
indicating that any field may be matched. `cls` is a subclass of
|
||||
`FieldQuery`.
|
||||
"""Parse a single *query part*, which is a chunk of a complete query
|
||||
string representing a single criterion.
|
||||
|
||||
The optional `query_classes` parameter maps field names to default
|
||||
query types; `default_class` is the fallback. `prefixes` is a map
|
||||
from query prefix markers and query types. Prefix-indicated queries
|
||||
take precedence over type-based queries.
|
||||
A query part is a string consisting of:
|
||||
- A *pattern*: the value to look for.
|
||||
- Optionally, a *field name* preceding the pattern, separated by a
|
||||
colon. So in `foo:bar`, `foo` is the field name and `bar` is the
|
||||
pattern.
|
||||
- Optionally, a *query prefix* just before the pattern (and after the
|
||||
optional colon) indicating the type of query that should be used. For
|
||||
example, in `~foo`, `~` might be a prefix. (The set of prefixes to
|
||||
look for is given in the `prefixes` parameter.)
|
||||
- Optionally, a negation indicator, `-` or `^`, at the very beginning.
|
||||
|
||||
To determine the query class, two factors are used: prefixes and
|
||||
field types. For example, the colon prefix denotes a regular
|
||||
expression query and a type map might provide a special kind of
|
||||
query for numeric values. If neither a prefix nor a specific query
|
||||
class is available, `default_class` is used.
|
||||
Both prefixes and the separating `:` character may be escaped with a
|
||||
backslash to avoid their normal meaning.
|
||||
|
||||
For instance,
|
||||
'stapler' -> (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):
|
||||
|
||||
+15
-11
@@ -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)
|
||||
|
||||
+285
-101
@@ -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
|
||||
|
||||
|
||||
+335
-169
@@ -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 = \
|
||||
|
||||
+9
-8
@@ -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:
|
||||
|
||||
+323
-213
File diff suppressed because it is too large
Load Diff
Executable → Regular
+113
-38
@@ -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
|
||||
|
||||
+259
-159
@@ -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)
|
||||
|
||||
+570
-396
File diff suppressed because it is too large
Load Diff
@@ -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
|
||||
|
||||
+328
-79
@@ -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)
|
||||
|
||||
+54
-45
@@ -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:
|
||||
|
||||
+9
-21
@@ -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)
|
||||
|
||||
|
||||
|
||||
+173
-88
@@ -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))
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
+99
-49
@@ -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'<generated>', b'exec')
|
||||
prog = compile(mod, '<generated>', '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)
|
||||
|
||||
@@ -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']
|
||||
+41
-30
@@ -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)
|
||||
|
||||
+3
-3
@@ -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
|
||||
|
||||
@@ -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__)
|
||||
|
||||
@@ -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)
|
||||
@@ -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
|
||||
+53
-21
@@ -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]
|
||||
|
||||
@@ -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"<BeatportRelease: {0} - {1} ({2})>".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"<BeatportTrack: {0} - {1} ({2})>"
|
||||
.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
|
||||
+3
-2
@@ -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')
|
||||
|
||||
+66
-64
@@ -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)
|
||||
|
||||
+66
-36
@@ -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))
|
||||
|
||||
+11
-8
@@ -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']:
|
||||
|
||||
+25
-20
@@ -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<bef>\D*)(?P<fromyear>\d+)(?P<sep>\D*)"
|
||||
"(?P<toyear>\d*)(?P<after>\D*)")
|
||||
regex = re.compile(r"(?P<bef>\D*)(?P<fromyear>\d+)(?P<sep>\D*)"
|
||||
r"(?P<toyear>\d*)(?P<after>\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
|
||||
|
||||
+11
-12
@@ -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',
|
||||
|
||||
+150
-76
@@ -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.
|
||||
|
||||
+5
-2
@@ -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)
|
||||
|
||||
+232
-62
@@ -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.
|
||||
|
||||
+86
-79
@@ -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:
|
||||
|
||||
@@ -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]
|
||||
@@ -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)
|
||||
+90
-34
@@ -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()
|
||||
|
||||
@@ -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.')
|
||||
@@ -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)
|
||||
+526
-219
@@ -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: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
|
||||
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: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
|
||||
PREFIX dbpprop: <http://dbpedia.org/property/>
|
||||
PREFIX owl: <http://dbpedia.org/ontology/>
|
||||
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
|
||||
@@ -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)
|
||||
|
||||
+10
-4
@@ -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
|
||||
|
||||
@@ -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")
|
||||
|
||||
+16
-24
@@ -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<artist>.+)-(?P<title>.+)-(?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'])
|
||||
|
||||
|
||||
+15
-17
@@ -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)
|
||||
|
||||
+7
-7
@@ -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}
|
||||
|
||||
@@ -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'])
|
||||
@@ -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)
|
||||
+3
-3
@@ -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)."""
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
+18
-38
@@ -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())
|
||||
|
||||
+74
-26
@@ -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):
|
||||
|
||||
+7
-6
@@ -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
|
||||
|
||||
|
||||
+8
-2
@@ -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)
|
||||
|
||||
+10
-12
@@ -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
|
||||
|
||||
@@ -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')
|
||||
@@ -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).
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
+114
-55
@@ -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
|
||||
|
||||
+495
-143
@@ -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
|
||||
|
||||
+95
-39
@@ -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.')
|
||||
|
||||
@@ -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())
|
||||
+21
-16
@@ -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
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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())
|
||||
|
||||
+112
-30
@@ -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
|
||||
|
||||
+50
-54
@@ -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()
|
||||
|
||||
+20
-19
@@ -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.')
|
||||
|
||||
+76
-54
@@ -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)
|
||||
|
||||
+115
-51
@@ -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)
|
||||
|
||||
@@ -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.')
|
||||
|
||||
+111
-41
@@ -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):
|
||||
|
||||
+238
-119
@@ -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]
|
||||
|
||||
@@ -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:
|
||||
|
||||
+68
-63
@@ -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)
|
||||
|
||||
+74
-51
@@ -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))
|
||||
|
||||
@@ -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')
|
||||
+20
-20
@@ -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')
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user