from burp import IProxyListener

from pentestmapper.APIMapper import LogEntry

# Class to handle auto log requests from proxy
class Autologclas(IProxyListener):
    def __init__(self,handlingoutput):
        self._handlingoutput = handlingoutput
        #self._handlingoutput.callbacks.registerHttpListener(self)


    def processProxyMessage(self,messageIsRequest, message):

        if self._handlingoutput.Autologcheck == True:
            if not messageIsRequest:
                if self._handlingoutput.callbacks.isInScope(self._handlingoutput.helpers.analyzeRequest(message.getMessageInfo()).getUrl()):

                    req = self._handlingoutput.helpers.analyzeRequest(message.getMessageInfo())
                    self.url = self._handlingoutput.helpers.analyzeRequest(message.getMessageInfo()).getUrl()
                    response = message.getMessageInfo().getResponse()
                    responseInfo = self._handlingoutput.helpers.analyzeResponse(response)

                    # Find out if image
                    self.responsetype = responseInfo.getInferredMimeType()
                    self.responsetype2 = responseInfo.getStatedMimeType()
                    self.exludelist = self._handlingoutput.Excludefiletextfield.getText().split(",")
                    
                    if (self.responsetype.upper() not in self.exludelist) and (self.responsetype2.upper() not in self.exludelist):
                    #if self.responsetype.upper() not in self.exludelist:
                        
                        self.method = req.getMethod()
                        self.requestinst = self._handlingoutput.helpers.bytesToString(message.getMessageInfo().getRequest())
                        getody = req.getBodyOffset()
                        self.body = self.requestinst[getody:len(self.requestinst)]
                        self.responseinst = self._handlingoutput.helpers.bytesToString(message.getMessageInfo().getResponse())   
                        rowss = self._handlingoutput.logTable.getRowCount()
                        self.sr2 = str((rowss + 1))
                        
                        self._handlingoutput._lock.acquire()
                        row = len(self._handlingoutput._log)
                        self._handlingoutput._log.append(LogEntry(self.sr2, self.url, self.method, self.body, self.requestinst, '', '', self.responseinst,''))
                        self._handlingoutput.fireTableRowsInserted(row, row)
                        self._handlingoutput._lock.release()
            
        else:
            self._handlingoutput.callbacks.removeProxyListener(self)
