Completed
Push — dev-4.1 ( c55916...bc345b )
by Felipe A.
01:10
created

PlayableDirectory.iter_files()   A

Complexity

Conditions 4

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 4
dl 0
loc 5
rs 9.2
c 1
b 0
f 1
1
2
import sys
3
import codecs
4
import os.path
5
6
from flask._compat import with_metaclass
7
from werkzeug.utils import cached_property
8
from browsepy.compat import walk, range, str_base, PY_LEGACY
9
from browsepy.file import File, Directory, underscore_replace, check_under_base
10
11
12
if PY_LEGACY:
13
    import ConfigParser as configparser
14
else:
15
    import configparser
16
17
18
mimetypes = {
19
    'mp3': 'audio/mpeg',
20
    'ogg': 'audio/ogg',
21
    'wav': 'audio/wav',
22
    'm3u': 'audio/x-mpegurl',
23
    'm3u8': 'audio/x-mpegurl',
24
    'pls': 'audio/x-scpls',
25
}
26
27
28
class PlayableFile(File):
29
    media_map = {
30
        'audio/mpeg': 'mp3',
31
        'audio/ogg': 'ogg',
32
        'audio/wav': 'wav',
33
    }
34
    mimetypes = tuple(media_map)
35
36
    def __init__(self, duration=None, title=None, **kwargs):
37
        self.duration = duration
38
        self.title = title
39
        super(PlayableFile, self).__init__(**kwargs)
40
41
    @property
42
    def title(self):
43
        return self._title or self.name
44
45
    @title.setter
46
    def title(self, title):
47
        self._title = title
48
49
    @property
50
    def media_format(self):
51
        return self.media_map[self.type]
52
53
54
class MetaPlayListFile(type):
55
    def __init__(cls, name, bases, nmspc):
56
        '''
57
        Abstract-class mimetype-based implementation registration on nearest
58
        abstract parent.
59
        '''
60
        type.__init__(cls, name, bases, nmspc)
61
        if cls.abstract_class is None:
62
            cls.specific_classes = {}
63
            cls.abstract_class = cls
64
        elif isinstance(cls.mimetype, str_base):
65
            cls.abstract_class.specific_classes[cls.mimetype] = cls
66
67
68
class PlayListFile(with_metaclass(MetaPlayListFile, File)):
69
    abstract_class = None
70
    playable_class = PlayableFile
71
    mimetypes = ('audio/x-mpegurl', 'audio/x-scpls')
72
73
    def __new__(cls, *args, **kwargs):
74
        '''
75
        Polimorfic mimetype-based constructor
76
        '''
77
        self = super(PlayListFile, cls).__new__(cls)
78
        if cls is cls.abstract_class:
79
            self.__init__(*args, **kwargs)
80
            if self.mimetype in cls.abstract_class.specific_classes:
81
                return cls.specific_classes[self.mimetype](*args, **kwargs)
82
        return self
83
84
    def iter_files(self):
85
        return
86
        yield
87
88
    def normalize_playable_path(self, path):
89
        if not os.path.isabs(path):
90
            path = os.path.normpath(os.path.join(self.parent.path, path))
91
        if check_under_base(path, self.app.config['directory_base']):
92
            return path
93
        return None
94
95
96
class PLSFile(PlayListFile):
97
    ini_parser_cls = (
98
        configparser.SafeConfigParser
99
        if hasattr(configparser, 'SafeConfigParser') else
100
        configparser.ConfigParser
101
        )
102
    maxsize = getattr(sys, 'maxsize', None) or getattr(sys, 'maxint', None)
103
    mimetype = 'audio/x-scpls'
104
105
    @cached_property
106
    def _parser(self):
107
        parser = self.ini_parser()
108
        parser.read(self.path)
109
        return parser
110
111
    def iter_files(self):
112
        maxsize = self._parser.getint('playlist', 'NumberOfEntries', None)
113
        for i in range(self.maxsize if maxsize is None else maxsize):
114
            pf = self.playable_class(
115
                path=self.normalize_playable_path(
116
                    self._parser.get('playlist', 'File%d' % i, None)
117
                    ),
118
                duration=self._parser.getint('playlist', 'Length%d' % i, None),
119
                title=self._parser.get('playlist', 'Title%d' % i, None),
120
                )
121
            if pf.path:
122
                yield pf
123
            elif maxsize is None:
124
                break
125
126
127
class M3UFile(PlayListFile):
128
    mimetype = 'audio/x-mpegurl'
129
130
    def _extract_line(self, line, file=None):
131
        if line.startswith('#EXTINF:'):
132
            duration, title = line.split(',', 1)
133
            file.duration = None if duration == '-1' else int(duration)
134
            file.title = title
135
            return False
136
        file.path = self.normalize_playable_path(line)
137
        return file.path is not None
138
139
    def iter_files(self):
140
        prefix = '#EXTM3U\n'
141
        encoding = 'utf-8' if self.path.endswith('.m3u8') else 'ascii'
142
        with codecs.open(
143
          self.path, 'r',
144
          encoding=encoding,
145
          errors=underscore_replace
146
          ) as f:
147
            if f.read(len(prefix)) == prefix:
148
                pf = PlayableFile()
149
                for line in f:
150
                    line = line.rstrip('\n', 1)
151
                    if line and self._extract_line(line, pf):
152
                        yield pf
153
                        pf = PlayableFile()
154
155
156
class PlayableDirectory(Directory):
157
    detection_deep = 5
158
159
    def iter_files(self):
160
        for root, directories, files in walk(file.path, followlinks=True):
161
            for filename in files:
162
                if filename.rsplit('.', 1)[-1] in mimetypes:
163
                    yield os.path.join(root, filename)
164
165
    @classmethod
166
    def detect(self, file):
167
        max_level = file.path.rstrip('/').count('/') + self.detection_deep
168
        for root, directories, files in walk(file.path, followlinks=True):
169
            if any(fn.rsplit('.', 1)[-1] in mimetypes for fn in files):
170
                return True
171
            if root.rstrip('/').count('/') >= max_level:
172
                del directories[:]
173