# Faraday Penetration Test IDE
# Copyright (C) 2016  Infobyte LLC (http://www.infobytesec.com/)
# See the file 'doc/LICENSE' for the license information
import flask
import requests
import logging

from flask import Blueprint, abort, make_response, jsonify
from faraday.server.utils.web import gzipped

exploits_api = Blueprint('exploits_api', __name__)

logger = logging.getLogger(__name__)


@gzipped
@exploits_api.route('/v3/vulners/exploits/<cveid>', methods=['GET'])
def get_exploits(cveid):
    """
    ---
    get:
      tags: ["Vulnerability"]
      description: Use Vulns API to get all exploits available for a specific CVE-ID
      responses:
        200:
          description: Ok
    """

    logger.debug(
        f"Request parameters: {flask.request.args!r}")

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json"}

    response = requests.get(
        "https://vulners.com/api/v3/search/id/?references=True&id=" + cveid,
        headers=headers,
        timeout=3
    )

    try:

        json_response = {
            "metasploit": [],
            "exploitdb": [],
            "cveid": cveid
        }

        if response.status_code == 200:

            obj_response = response.json()

            if obj_response["data"]["references"] is not {}:

                metasploit_modules = obj_response["data"]["references"][cveid].get("metasploit", [])
                exploitdb_modules = obj_response["data"]["references"][cveid].get("exploitdb", [])

                for module in metasploit_modules:
                    obj_module = {}
                    obj_module.update({"title": module["title"]})
                    obj_module.update({"id": module["id"]})
                    obj_module.update({"href": module["href"]})
                    json_response["metasploit"].append(obj_module)

                for module in exploitdb_modules:
                    obj_module = {}
                    obj_module.update({"title": module["title"]})
                    obj_module.update({"id": module["id"]})
                    obj_module.update({"href": module["href"]})
                    json_response["exploitdb"].append(obj_module)

    except KeyError as ex:
        abort(make_response(jsonify(message=f'Could not find {str(ex)}'), 400))

    return flask.jsonify(json_response)
