from intelligence.base import *
import requests
import json


URL = "http://api.malshare.com"

class Malshare(OnlineChecker):

    name = "Malshare"
    options = {
        "key": ("", "Malshare API key"),
    }

    def get_details(self, sha256,):
        key = self.options.get("key")
        if not key:
            raise KeyError("No API key")
        session = self.preconfigured_session()  # automatically set options such as timeout or ssl_verify
        session.headers.update({'accept': 'application/json'})
        response = session.get(URL + "/api.php", params = {
                "action": "details",
                "api_key": key,
                "hash": sha256
        })
        if not response.ok:
            if response.status_code == 404:
                return None
            else:
                raise response.raise_for_status()
        data = response.json()
        if not "MD5" in data:
            return None
        return data
    
    def check(self, analysis):
        details = self.get_details(analysis.entropy.sha256)
        if details is None:
            return None
        # we don't know if samples are malicious or not :(
        detections = { 
            details["MD5"]: OnlineDetection(name=f"Seen as {' + '.join(details.get('FILENAMES', []))}")
        }
        return OnlineResult(detections=detections, 
            url="https://malshare.com/sample.php?action=detail&hash={}".format(analysis.entropy.sha256)
        )

    def download(self, query):
        details = self.get_details(query)
        if details is None:
            return None
        key = self.options.get("key")
        response = requests.get(URL + "/api.php",  params = {
                "action": "getfile",
                "api_key": key,
                "hash": query
        })
        if not response.ok:
            raise response.raise_for_status()
        return OnlineFile(
            url="https://malshare.com/sample.php?action=detail&hash={}".format(query),
            content=response.content
        )
