﻿from __future__ import unicode_literals, division, absolute_import
import logging
import re

from flexget import plugin
from flexget.event import event
from flexget.plugins.plugin_urlrewriting import UrlRewritingError
from flexget.utils.requests import Session

log = logging.getLogger('animeindex')

requests = Session()
requests.headers.update({'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'})

#http://tracker.anime-index.org/index.php?page=torrent-details&id=b8327fdf9003e87446c8b3601951a9a65526abb2
#http://tracker.anime-index.org/download.php?id=b8327fdf9003e87446c8b3601951a9a65526abb2&f=[DeadFish]%20Yowamushi%20Pedal:%20Grande%20Road%20-%2002%20[720p][AAC].mp4.torrent

class UrlRewriteAnimeIndex(object):
    """AnimeIndex urlrewriter."""

    def url_rewritable(self, task, entry):
        return entry['url'].startswith('http://tracker.anime-index.org/index.php?page=torrent-details&id=')

    def url_rewrite(self, task, entry):
	entry['url'] = self.parse_download_page(entry['url'])
	
    def parse_download_page(self, url):
	page = requests.get(url)
	torrent_first_part = url.replace('index.php?page=torrent-details&', 'download.php?')
	torrent_id = torrent_first_part.replace('http://tracker.anime-index.org/download.php?', '')
	regexp_torrent = "\?" + torrent_id + "(.+)\""
	torrent_id_prog = re.compile(regexp_torrent)
	test = torrent_id_prog.findall(page.text)
	murl = torrent_first_part + test[0]
	murl = murl.replace('&amp;','&')
	log.info("Regexp murl: %s" % murl)
	return murl

@event('plugin.register')
def register_plugin():
    plugin.register(UrlRewriteAnimeIndex, 'animeindex', groups=['urlrewriter'], api_ver=2)
@@ -83,18 +83,22 @@
 %0Aimport 
-re
+urllib
 %0A%0Afrom f
@@ -154,266 +154,45 @@
 ent%0A
-from flexget.plugins.plugin_urlrewriting import UrlRewritingError%0Afrom flexget.utils.requests import Session%0A%0Alog = logging.getLogger('animeindex')%0A%0Arequests = Session()%0Arequests.headers.update(%7B'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'%7D
+%0Alog = logging.getLogger('animeindex'
 )%0A%0A#
@@ -755,549 +755,155 @@
 %5D = 
-self.parse_download_page(entry%5B'url'%5D)%0A%09%0A    def parse_download_page(self, url):%0A%09page = requests.get(url)%0A%09torrent_first_part = url.replace('index.php?page=torrent-details&', 'download.php?')%0A%09torrent_id = torrent_first_part.replace('http://tracker.anime-index.org/download.php?', '')%0A%09regexp_torrent = %22%5C?%22 + torrent_id + %22(.+)%5C%22%22%0A%09torrent_id_prog = re.compile(regexp_torrent)%0A%09test = torrent_id_prog.findall(page.text)%0A%09murl = torrent_first_part + test%5B0%5D%0A%09murl = murl.replace('&amp;','&')%0A%09log.info(%22Regexp murl: %25s%22 %25 murl)%0A%09return murl
+entry%5B'url'%5D.replace('index.php?page=torrent-details&', 'download.php?')%0A%09entry%5B'url'%5D += '&f=%25s.torrent' %25 (urllib.quote(entry%5B'title'%5D, safe=''))
 %0A%0A@e

Simplify a lot the urlrewrite for anime-index