| 1 | import re |
|---|
| 2 | import logging |
|---|
| 3 | import yaml |
|---|
| 4 | from flexget.plugin import * |
|---|
| 5 | |
|---|
| 6 | log = logging.getLogger('regexp') |
|---|
| 7 | |
|---|
| 8 | class ResolveRegexp: |
|---|
| 9 | """ |
|---|
| 10 | Generic regexp resolver. |
|---|
| 11 | |
|---|
| 12 | Example: |
|---|
| 13 | |
|---|
| 14 | regexp_resolve: |
|---|
| 15 | demonoid: |
|---|
| 16 | match: http://www.demonoid.com/files/details/ |
|---|
| 17 | replace: http://www.demonoid.com/files/download/HTTP/ |
|---|
| 18 | """ |
|---|
| 19 | |
|---|
| 20 | # built-in resolves |
|---|
| 21 | |
|---|
| 22 | resolves = yaml.safe_load(""" |
|---|
| 23 | tvsubtitles: |
|---|
| 24 | match: http://www.tvsubtitles.net/subtitle- |
|---|
| 25 | replace: http://www.tvsubtitles.net/download- |
|---|
| 26 | """ |
|---|
| 27 | ) |
|---|
| 28 | |
|---|
| 29 | def validator(self): |
|---|
| 30 | from flexget import validator |
|---|
| 31 | root = validator.factory('dict') |
|---|
| 32 | config = root.accept_any_key('dict') |
|---|
| 33 | config.accept('regexp', key='match', required=True) |
|---|
| 34 | config.accept('regexp', key='replace', required=True) |
|---|
| 35 | return root |
|---|
| 36 | |
|---|
| 37 | def process_start(self, feed): |
|---|
| 38 | for name, config in feed.config.get('regexp_resolve', {}).iteritems(): |
|---|
| 39 | match = re.compile(config['match']) |
|---|
| 40 | replace = config['replace'] |
|---|
| 41 | self.resolves[name] = {'match': match, 'replace': replace } |
|---|
| 42 | log.debug('Added regexp resolve %s' % name) |
|---|
| 43 | |
|---|
| 44 | def resolvable(self, feed, entry): |
|---|
| 45 | for name, config in self.resolves.iteritems(): |
|---|
| 46 | if config['match'].match(entry['url']): |
|---|
| 47 | return True |
|---|
| 48 | return False |
|---|
| 49 | |
|---|
| 50 | def resolve(self, feed, entry): |
|---|
| 51 | for name, config in self.resolves.iteritems(): |
|---|
| 52 | if config['match'].match(entry['url']): |
|---|
| 53 | log.debug('Regexp resolving %s with %s' % (entry['url'], name)) |
|---|
| 54 | entry['url'] = config['match'].sub(config['replace'], entry['url']) |
|---|
| 55 | if config['match'].match(entry['url']): |
|---|
| 56 | from module_resolver import ResolverException |
|---|
| 57 | raise ResolverException('Regexp %s replace result should NOT continue to match!' % name) |
|---|
| 58 | return |
|---|
| 59 | |
|---|
| 60 | register_plugin(ResolveRegexp, 'regexp_resolve', groups=['resolver']) |
|---|