from intelligence.base import *
import requests
import json


URL = "https://www.joesandbox.com/api"



class JoeSandbox(OnlineChecker):

    name = "JoeSandbox"
    options = {
        "key": ("", "JoeSandbox API key"),
    }
    
    def check(self, analysis):
        detections = { }
        key = self.options.get("key")
        if not key:
            raise KeyError("No API key")
        url = "https://www.joesandbox.com/search?q={}".format(analysis.entropy.sha256)
        session = self.preconfigured_session()  # automatically set options such as timeout or ssl_verify

        # search
        response = session.post(URL + "/v2/analysis/search", data={'apikey': key, 'q': analysis.entropy.sha256})
        if response.ok:
            data = response.json().get("data")
            if not data:
                return None
            for webid in data:
                webid = webid.get("webid")
                if webid is None:
                    continue
                response = session.post(URL + "/v2/analysis/info", data={'apikey': key, 'webid': webid})
                response.raise_for_status()
                data = response.json().get("data", {})
                #print(json.dumps(data, indent=4))
                url = "https://www.joesandbox.com/analysis/{}/0/html".format(data.get("analysisid", ""))
                det = OnlineDetection()
                det.level = DetectionLevel.from_text(data.get("detection", ""))
                det.name = data.get("threatname", "")
                analysis_name = "{}:{}".format(data.get("filename", ""), data.get("analysisid", ""))
                detections[analysis_name] = det

        elif response.status_code == 404:
            return None
        else:
            response.raise_for_status()
            return None
        return OnlineResult(detections=detections, 
            url=url
        )

