import logging
from flexget.plugin import register_plugin

log = logging.getLogger('find')


class InputFind:
    """
        Uses local path content as an input, recurses through directories and creates entries for files that match mask.

        You can specify either the mask key, in shell file matching format, (see python fnmatch module,) or regexp key.

        Example:

        find:
          path: /storage/movies/
          mask: *.avi

        find:
          path:
            - /storage/movies/
            - /storage/tv/
          regexp: .*\.(avi|mkv)$
    """

    def validator(self):
        from flexget import validator
        root = validator.factory('dict')
        root.accept('path', key='path', required=True)
        root.accept('list', key='path').accept('path')
        root.accept('text', key='mask')
        root.accept('regexp', key='regexp')
        root.accept('boolean', key='recursive')
        return root

    def get_config(self, feed):
        from fnmatch import translate
        config = feed.config.get('find', None)
        # If only a single path is passed turn it into a 1 element list
        if isinstance(config['path'], basestring):
            config['path'] = [config['path']]
        config.setdefault('recursive', False)
        # If mask was specified, turn it in to a regexp
        if config.get('mask'):
            config['regexp'] = translate(config['mask'])
        # If no mask or regexp specified, accept all files
        if not config.get('regexp'):
            config['regexp'] = '.'
        return config

    def on_feed_input(self, feed):
        from flexget.feed import Entry
        import os
        import re
        config = self.get_config(feed)
        match = re.compile(config['regexp'], re.IGNORECASE).match
        for path in config['path']:
            for item in os.walk(unicode(path)):
                for name in item[2]:
                    #If mask fails continue
                    if match(name) is None:
                        continue
                    e = Entry()
                    e['title'] = name
                    filepath = os.path.join(item[0], name)
                    e['location'] = filepath
                    # Windows paths need an extra / prepended to them for url
                    if not filepath.startswith('/'):
                        filepath = '/' + filepath
                    e['url'] = 'file://%s' % (filepath)
                    feed.entries.append(e)
                # If we are not searching recursively, break after first (base) directory
                if not config['recursive']:
                    break

register_plugin(InputFind, 'find')

Add the find input plugin, which will produce entries from a local directory that match a mask.
Add the find input plugin, which will produce entries from a local directory that match a mask.

git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@1616 3942dd89-8c5d-46d7-aeed-044bccf3e60c
