import logging
import re
import os
import sys

from flexget import plugin
from flexget import validator

log = logging.getLogger('rtorrent_magnet')
pat = re.compile('xt=urn:btih:([^&/]+)')


class PluginRtorrentMagnet(object):
    """
    Process Magnet URI's into rtorrent compatible torrent files

    Magnet URI's will look somethign like this:

    magnet:?xt=urn:btih:190F1ABAED7AE7252735A811149753AA83E34309&dn=URL+Escaped+Torrent+Name

    rTorrent would expect to see something like meta-URL_Escaped_Torrent_Name.torrent

    The torrent file must also contain the text:

    d10:magnet-uri88:xt=urn:btih:190F1ABAED7AE7252735A811149753AA83E34309&dn=URL+Escaped+Torrent+Namee

    This plugin will check if a download URL is a magnet link, and then create the appropriate torrent file.

    Example:
      rtorrent_magnet: ~/torrents/
    """

    def write_torrent_file(self, task, entry):
        path = os.path.join(
            entry['path'],
            'meta-%s.torrent' % entry['title'].encode(sys.getfilesystemencoding(), 'replace')
        )
        path = os.path.expanduser(path)
        log.info('Writing rTorrent Magnet File: %s', path)

        if task.manager.options.test:
            log.info('Would write: d10:magnet-uri%d:%se' % (entry['url'].__len__(), entry['url']))
        else:
            with open(path, 'w') as f:
                f.write('d10:magnet-uri%d:%se' % (entry['url'].__len__(), entry['url']))
            f.closed

        entry['output'] = path

    def validator(self):
        root = validator.factory()
        root.accept('path', allow_replacement=True)
        return root

    @plugin.priority(0)
    def on_task_output(self, task, config):

        for entry in task.accepted:
            if 'output' in entry:
                log.debug('Ignoring, %s already has an output file: %s' % (entry['title'], entry['output']))
                continue

            urls = entry.get('urls', [entry['url']])

            for url in urls:
                if url.startswith('magnet:'):
                    log.debug('Magnet URI detected for url %s (%s)' % (url, entry['title']))

                    m = pat.search(url)
                    if m:
                        entry['url'] = url
                        entry['path'] = entry.get('path', config)
                        entry['hash'] = m.groups()[0]

                        log.debug('Magnet Hash Detected: %s' % entry['hash'])

                        self.write_torrent_file(task, entry)

                        break
                    else:
                        log.warning('Unrecognized Magnet URI Format: %s', url)

plugin.register_plugin(PluginRtorrentMagnet, 'rtorrent_magnet', api_ver=2)

@@ -1,12 +1,79 @@
+from __future__ import unicode_literals, division, absolute_import%0A
 import loggi
@@ -98,19 +98,8 @@
 t os
-%0Aimport sys
 %0A%0Afr
@@ -126,38 +126,8 @@
 ugin
-%0Afrom flexget import validator
 %0A%0Alo
@@ -353,18 +353,18 @@
  somethi
-g
 n
+g
  like th
@@ -870,16 +870,67 @@
    %22%22%22%0A%0A
+    schema = %7B'type': 'string', 'format': 'path'%7D%0A%0A
     def 
@@ -965,16 +965,22 @@
 k, entry
+, path
 ):%0A     
@@ -1006,233 +1006,84 @@
 oin(
-%0A            entry%5B'path'%5D,%0A            'meta-%25s.torrent' %25 entry%5B'title'%5D.encode(sys.getfilesystemencoding(), 'replace')%0A        )%0A        path = os.path.expanduser(path)%0A        log.info('Writing rTorrent Magnet File: %25s', 
+path, 'meta-%25s.torrent' %25 entry%5B'title'%5D)%0A        path = os.path.expanduser(
 path
@@ -1162,85 +1162,96 @@
 te: 
-d10:magnet-uri%25d:
 %25s
-e
 ' %25 
-(entry%5B'url'%5D.__len__(), entry%5B'url'%5D))%0A        else:
+path)%0A        else:%0A            log.info('Writing rTorrent Magnet File: %25s', path)
 %0A   
@@ -1331,24 +1331,28 @@
 ri%25d:%25se' %25 
+(len
 (entry%5B'url'
@@ -1356,17 +1356,8 @@
 rl'%5D
-.__len__(
 ), e
@@ -1374,30 +1374,8 @@
 %5D))%0A
-            f.closed%0A%0A
     
@@ -1410,136 +1410,85 @@
     
-def validator(self):%0A        root = validator.factory()%0A        root.accept('path', allow_replacement=True)%0A        return root%0A
+# Run after download plugin to only pick up entries it did not already handle
 %0A   
@@ -1774,14 +1774,18 @@
     
-urls =
+for url in
  ent
@@ -1818,37 +1818,8 @@
 '%5D%5D)
-%0A%0A            for url in urls
 :%0A  
@@ -1955,17 +1955,16 @@
 tle'%5D))%0A
-%0A
         
@@ -1979,11 +1979,10 @@
     
-m =
+if
  pat
@@ -1997,33 +1997,8 @@
 url)
-%0A                    if m
 :%0A  
@@ -2023,288 +2023,71 @@
     
-entry%5B'url'%5D = url%0A                        entry%5B'path'%5D = entry.get('path', config)%0A                        entry%5B'hash'%5D = m.groups()%5B0%5D%0A%0A                        log.debug('Magnet Hash Detected: %25s' %25 entry%5B'hash'%5D)%0A%0A                        self.write_torrent_file(task, entry)%0A
+self.write_torrent_file(task, entry, entry.get('path', config))
 %0A   

Clean up rtorrent_magnet plugin. refs #1994