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

# https://www.jianshu.com/p/57475845f3ad

from html.parser import HTMLParser
from fastapi import Request
import json
from exceptions import XssException

class StripTagsHTMLParser(HTMLParser):
    data = ""
    def handle_data(self, data):
        self.data += data
    
    def getData(self):
        return self.data

async def remove_xss_json(request: Request) -> dict:
    data = await request.body()
    if len(data) == 0:
        return {}
    
    body = data.decode(encoding='utf-8')

    try:
        parser = StripTagsHTMLParser()
        parser.feed(body)
        data = parser.getData()
        data = json.loads(data)
        return data
    except:
        raise XssException()

def remove_xss(val: str) -> str:
    try:
        if val is None:
            return ""
        else:
            parser = StripTagsHTMLParser()
            parser.feed(val)
            return parser.getData()
    except:
        raise XssException(val)