#!/usr/bin/python
# -*- coding: utf-8 -*-

from model.result import Result
from bots.bot_base import Base
import re
import sys


class ExploitDB(Base):

    def __init__(self):
        Base.__init__(self)

    def bot_search(self):
        self.results = []

        for i in range(5):
            url = "https://www.exploit-db.com/search/"
            parameters = {"order_by": "date",
                          "order": "desc",
                          "pg": "{0}".format(i),
                          "action": "search",
                          "text": "{0}".format(self.filter_description)
                          }
            try:
                pagehtml = self.object_download.get_download_page(
                    url, parameters)
                if (pagehtml):
                    self.extract_data(pagehtml)
            except Exception, ex:
                pass
        return self.results

    def extract_data(self, html):
        html = re.sub(r"\n", " ", html)
        html = re.sub(r"\"", "'", html)
        r = re.compile(r"<tr.*?<td class='date'>(?P<Date>\d{4}-\d{2}-\d{2}).*?"
                       "<td class='dlink'>.*?<a href='(?P<Download>[^']*?)'.*?"
                       "description.*?<a[^>]*?>(?P<Description>[^<]*?)<.*?author.*?"
                       "title='(?P<Author>[^']*?')")
        for match in r.finditer(html):
            if match:
                self.results.append(match.groupdict())