File: zero.py

package info (click to toggle)
beets 1.3.8%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 3,636 kB
  • ctags: 3,973
  • sloc: python: 23,849; makefile: 137; sh: 96
file content (95 lines) | stat: -rw-r--r-- 3,216 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# This file is part of beets.
# Copyright 2013, 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
# "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.

""" Clears tag fields in media files."""

import re
import logging
from beets.plugins import BeetsPlugin
from beets.library import Item
from beets.importer import action
from beets.util import confit

__author__ = 'baobab@heresiarch.info'
__version__ = '0.10'

log = logging.getLogger('beets')


class ZeroPlugin(BeetsPlugin):

    _instance = None

    def __init__(self):
        super(ZeroPlugin, self).__init__()

        # Listeners.
        self.register_listener('write', self.write_event)
        self.register_listener('import_task_choice',
                               self.import_task_choice_event)

        self.config.add({
            'fields': [],
        })

        self.patterns = {}
        self.warned = False

        for field in self.config['fields'].as_str_seq():
            if field in ('id', 'path', 'album_id'):
                log.warn(u'[zero] field \'{0}\' ignored, zeroing '
                         u'it would be dangerous'.format(field))
                continue
            if field not in Item._fields.keys():
                log.error(u'[zero] invalid field: {0}'.format(field))
                continue

            try:
                self.patterns[field] = self.config[field].as_str_seq()
            except confit.NotFoundError:
                # Matches everything
                self.patterns[field] = [u'']

    def import_task_choice_event(self, session, task):
        """Listen for import_task_choice event."""
        if task.choice_flag == action.ASIS and not self.warned:
            log.warn(u'[zero] cannot zero in \"as-is\" mode')
            self.warned = True
        # TODO request write in as-is mode

    @classmethod
    def match_patterns(cls, field, patterns):
        """Check if field (as string) is matching any of the patterns in
        the list.
        """
        for p in patterns:
            if re.search(p, unicode(field), flags=re.IGNORECASE):
                return True
        return False

    def write_event(self, item, path, tags):
        """Listen for write event."""
        if not self.patterns:
            log.warn(u'[zero] no fields, nothing to do')
            return

        for field, patterns in self.patterns.items():
            if field not in tags:
                log.error(u'[zero] no such field: {0}'.format(field))
                continue

            value = tags[field]
            if self.match_patterns(value, patterns):
                log.debug(u'[zero] {0}: {1} -> None'.format(field, value))
                tags[field] = None