flexget.plugins.modify_torrent
Covered: 77 lines
Missed: 1 lines
Skipped 34 lines
Percent: 98 %
  1
import logging
  2
from flexget.plugin import register_plugin, priority, PluginError
  4
from flexget.utils.bittorrent import Torrent, is_torrent_file, TORRENT_RE 
  5
import os
  7
log = logging.getLogger('modif_torrent')
 10
class TorrentFilename(object):
 11
    """
 12
        Makes sure that entries containing torrent-file have .torrent
 13
        extension. This is enabled always by default (builtins).
 14
    """
 15
    TORRENT_PRIO = 255
 17
    @priority(TORRENT_PRIO)
 18
    def on_feed_modify(self, feed):
 19
        for entry in feed.entries:
 21
            if not 'file' in entry:
 22
                log.debugall('%s doesn\'t have a file associated' % entry['title'])
 23
                continue
 24
            if not os.path.exists(entry['file']):
 25
                raise PluginError('File %s does not exists' % entry['file'])
 26
            if os.path.getsize(entry['file']) == 0:
 27
                raise PluginError('File %s is 0 bytes in size' % entry['file'])
 29
            if not is_torrent_file(entry['file']):
 30
                continue
 31
            log.debug('%s seems to be a torrent' % entry['title'])
 34
            try:
 35
                f = open(entry['file'], 'rb')
 38
                data = f.read()
 39
                f.close()
 41
                if 'content-length' in entry:
 42
                    if len(data) != entry['content-length']:
 43
                        feed.fail(entry, 'Torrent file length doesn\'t match to the one reported by the server')
 44
                        self.purge(entry)
 45
                        continue
 48
                try:
 49
                    torrent = Torrent(data)
 50
                except SyntaxError, e:
 51
                    feed.fail(entry, '%s - Torrent could not be parsed' % e.message)
 52
                    self.purge(entry)
 53
                    continue
 55
                entry['torrent'] = torrent
 56
                entry['torrent_info_hash'] = torrent.get_info_hash()
 59
                if entry.get('filename'):
 60
                    if not entry['filename'].lower().endswith('.torrent'):
 62
                        entry['filename'] = entry['filename'] + '.torrent'
 63
                else:
 65
                    entry['filename'] = self.make_filename(torrent, entry)
 66
            except Exception, e:
 67
                log.exception(e)
 69
    @priority(TORRENT_PRIO)
 70
    def on_feed_output(self, feed):
 71
        for entry in feed.entries:
 72
            if 'torrent' in entry:
 73
                if entry['torrent'].modified:
 75
                    log.debug('Writing modified torrent file for %s' % entry['title'])
 76
                    f = open(entry['file'], 'wb+')
 77
                    f.write(entry['torrent'].encode())
 78
                    f.close()
 80
    def make_filename(self, torrent, entry):
 81
        """Build a filename for this torrent"""
 83
        title = entry['title']
 84
        files = torrent.get_filelist()
 85
        if len(files) == 1:
 87
            fn = files[0]['name']
 88
            if len(fn) > len(title):
 89
                title = fn[:fn.rfind('.')]
 92
        title = title.replace('/', '_')
 93
        title = title.replace(' ', '_')
 94
        title = title.replace('\u200b', '')
 99
        fn = '%s.torrent' % title
100
        log.debug('make_filename made %s' % fn)
101
        return fn
103
    def purge(self, entry):
104
        import os
105
        if os.path.exists(entry['file']):
106
            log.debug('removing temp file %s from %s' % (entry['file'], entry['title']))
107
            os.remove(entry['file'])
108
        del(entry['file'])
111
register_plugin(TorrentFilename, 'torrent', builtin=True)