# -*- coding: utf-8 -*-
#
# Test links:
#   http://filecrypt.cc/Container/64E039F859.html
import binascii
import re
import urlparse
from Crypto.Cipher import AES
from module.plugins.internal.Crypter import Crypter, create_getInfo
from module.plugins.captcha.ReCaptcha import ReCaptcha
from module.plugins.captcha.SolveMedia import SolveMedia
class FilecryptCc(Crypter):
    __name__    = "FilecryptCc"
    __type__    = "crypter"
    __version__ = "0.21"
    __status__  = "testing"
    __pattern__ = r'https?://(?:www\.)?filecrypt\.cc/Container/\w+'
    __config__  = [("activated", "bool", "Activated", True)]
    __description__ = """Filecrypt.cc decrypter plugin"""
    __license__     = "GPLv3"
    __authors__     = [("zapp-brannigan", "fuerst.reinje@web.de"),
                       ("GammaC0de"     , None                  )]
    # URL_REPLACEMENTS  = [(r'.html$', ""), (r'$', ".html")]  #@TODO: Extend SimpleCrypter
    DLC_LINK_PATTERN = r'onclick="DownloadDLC\(\'(.+)\'\);">'
    WEBLINK_PATTERN  = r"openLink.?'([\w\-]*)',"
    CAPTCHA_PATTERN          = r'class="safety">Sicherheitsabfrage<'
    INTERNAL_CAPTCHA_PATTERN = r'
'
    def setup(self):
        self.links = []
    def decrypt(self, pyfile):
        self.html = self.load(pyfile.url)
        if "content notfound" in self.html:  #@NOTE: "content notfound" is NOT a typo
            self.offline()
        self.handle_password_protection()
        self.handle_captcha()
        self.handle_mirror_pages()
        for handle in (self.handle_CNL, self.handle_weblinks, self.handle_dlc_container):
            handle()
            if self.links:
                self.packages = [(pyfile.package().name, self.links, pyfile.package().name)]
                return
    def handle_mirror_pages(self):
        if "mirror=" not in self.site_with_links:
            return
        mirror = re.findall(self.MIRROR_PAGE_PATTERN, self.site_with_links)
        self.log_info(_("Found %d mirrors") % len(mirror))
        for i in mirror[1:]:
            self.site_with_links = self.site_with_links + self.load(i)
    def handle_password_protection(self):
        if '', res)
                if link2:
                    res2  = self.load(link2.group(1), just_header=True)
                    self.links.append(res2['location'])
        except Exception, e:
            self.log_debug("Error decrypting weblinks: %s" % e)
    def handle_CNL(self):
        try:
            vjk = re.findall('', self.site_with_links)
            vcrypted = re.findall('', self.site_with_links)
            for i in xrange(len(vcrypted)):
                self.links.extend(self._get_links(vcrypted[i], vjk[i]))
        except Exception, e:
            self.log_debug("Error decrypting CNL: %s" % e)
    def _get_links(self, crypted, jk):
        #: Get key
        key = binascii.unhexlify(str(jk))
        #: Decrypt
        Key  = key
        IV   = key
        obj  = AES.new(Key, AES.MODE_CBC, IV)
        text = obj.decrypt(crypted.decode('base64'))
        #: Extract links
        text  = text.replace("\x00", "").replace("\r", "")
        links = filter(bool, text.split('\n'))
        return links
getInfo = create_getInfo(FilecryptCc)