<!DOCTYPE html>
<html>

<head>
    <title>Fenjing</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f1f1f1;
            margin: 0;
            padding: 0;
        }

        header {
            background-color: #fff;
            color: #1F2421;
            padding: 20px;
            text-align: left;
        }

        header h1 {
            margin: 0;
        }

        main {
            margin: 20px;
            display: flex;
        }

        form,
        div.panel {
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
            margin: 10px;
            display: flex;
            flex-direction: column;
        }

        form#createCrackTask {
            width: 30%;
            justify-content: flex-end;
        }

        form#createInteractiveTaskForm {
            width: 70%;
            justify-content: flex-end;

        }

        label {
            display: block;
            margin-bottom: 10px;
        }

        input[type="text"],
        input[type="password"],
        select {
            padding: 10px;
            border: 1px solid #D8E2DC;
            border-radius: 5px;
            margin-bottom: 20px;
            /* margin-top: 5px; */
        }

        input[type="submit"] {
            background-color: #F69479;
            color: #fff;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        input#cmd {
            margin-top: 5px;

        }

        /* 
input[type="submit"]:hover {
  background-color: #555;
} */
    </style>
</head>

<body>
    <header>
        <h1>首页</h1>
    </header>


    <main>
        <form id="createCrackTask">
            <label for="url">URL:</label>
            <input type="text" id="url" name="url" placeholder="http://127.0.0.1:1234" />
            <label for="method">请求方式:</label>
            <select id="method" name="method">
                <option value="POST">POST</option>
                <option value="GET">GET</option>
            </select>
            <label for="inputs">表单的所有输入:</label>
            <input type="text" id="inputs" name="inputs" placeholder="id,name" />
            <br /><br />

            <label for="action">提交 URL:</label>
            <input type="text" id="action" name="action" placeholder="可不填，默认和URL相同" />
            <br /><br />

            <label for="action">最小请求间隔:</label>
            <input type="text" id="interval" name="interval" value="0.1" />
            <br /><br />

            <label for="detect_mode">分析模式:</label>
            <select id="detect_mode" name="detect_mode">
                <option value="accurate">精确</option>
                <option value="fast">快速</option>
            </select>

            <label for="environment">模板渲染环境:</label>
            <select id="environment" name="environment">
                <option value="jinja">jinja内部</option>
                <option value="flask">flask内部(如render_template_string函数)</option>
            </select>

            <label for="replaced_keyword_strategy">关键字被替换时:</label>
            <select id="replaced_keyword_strategy" name="replaced_keyword_strategy">
                <option value="avoid">避免使用会被替换的关键字</option>
                <option value="ignore">忽略所有会被替换的关键字</option>
                <option value="doubletapping">对这些关键字进行双写</option>
            </select>

            <input type="hidden" name="type" value="crack" />
            <input type="submit" value="开始分析">

        </form>

        <form id="createInteractiveTaskForm">
            <textarea name="taskMessage" id="taskMessage" cols="100" rows="40" readonly></textarea>
            <textarea name="taskFlashMessage" id="taskFlashMessage" cols="100" rows="3" readonly></textarea>
            <input type="text" id="cmd" name="cmd" placeholder="uname -a" />
            <input type="hidden" name="type" value="interactive" />
            <input type="hidden" name="last_task_id" value="" />
            <input type="submit" value="执行Shell指令">
        </form>


    </main>
    <script>

        const taskFlashMessage = document.getElementById("taskFlashMessage")
        const taskMessage = document.getElementById("taskMessage")

        function Task(form, checkFormData, afterFetch) {
            let taskObj = {
                form: form,
                running: false,
            }
            function onSubmit(event) {
                event.preventDefault();
                if (taskObj.running) {
                    console.log("task " + uri + " is running");
                    return
                }
                // 从表单中获取数据
                const formData = new FormData(form);
                if (!checkFormData(formData)) {
                    return
                }
                // 使用fetch向服务器发送POST请求
                taskObj.running = true;
                fetch("/createTask", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    },
                    body: new URLSearchParams(formData).toString()
                })
                    .then(response => response.json())
                    .then(afterFetch)
                    .catch(error => { console.error(error); });
                taskObj.running = false;
            }
            form.addEventListener("submit", onSubmit);
            return taskObj
        }

        function watchTask(taskid, callback = undefined) {
            function fillData(data) {
                taskFlashMessage.textContent = data["flash_messages"][data["flash_messages"].length - 1]
                taskMessage.textContent = data["messages"].join("\n")
                taskMessage.scrollTop = taskMessage.scrollHeight - taskMessage.clientHeight;
            }
            function handleData(data) {
                console.log(data)
                fillData(data)
                if (data.done) {
                    console.log(`Done! clear id: ${timerId}`)
                    clearInterval(timerId)
                    if (callback) {
                        callback(data)
                    }
                }
            }
            function update() {
                fetch("/watchTask", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    },
                    body: new URLSearchParams({ taskid: taskid }).toString()
                })
                    .then(response => response.json())
                    .then(handleData)
            }
            let timerId = setInterval(update, 200)
        }
        function afterCrackTaskDone(data) {
            const input = createInteractiveTaskForm.querySelector('input[name="last_task_id"]');
            input.value = data.taskid;
        }
        function isValidUrl(string) {
            const pattern = /^(?:\w+:)?\/\/([^\s\.]+\.\S{2}|localhost[\:?\d]*)\S*$/;
            return pattern.test(string);
        }
        const crackTask = Task(
            document.querySelector("#createCrackTask"),
            formData => {
                console.log(formData);
                console.log(formData.get("inputs"));
                return isValidUrl(formData.get("url")) && formData.get("inputs") != "" && Number(formData.get("interval")) >= 0
            },
            data => {
                console.log(data);
                watchTask(data.taskid, afterCrackTaskDone);
            }
        )
        const interactiveTask = Task(
            document.querySelector("#createInteractiveTaskForm"),
            formData => formData.get("cmd") != "",
            data => {
                console.log(data);
                if (data.taskid) {
                    watchTask(data.taskid)
                } else {
                    taskFlashMessage.textContent = "找不到之前的分析记录，也许你需要先分析一下？"
                }
            }
        )

    </script>
</body>

</html>