<!DOCTYPE html>
<html>

<head>
    <title>Fenjing</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <style>
        body {
            background-color: #f2f2f2;
            color: #444;
            font-family: 'Helvetica Neue', sans-serif;
            font-size: 16px;
            line-height: 1.5;
            padding: 2em;
        }

        header {
            background-color: #8B0000;
            color: #fff;
            padding: 20px;
            text-align: center;
        }

        nav ul {
            list-style: none;
            margin: 0;
            padding: 0;
        }

        nav li {
            display: inline-block;
            margin: 0 10px;
        }

        nav li a {
            color: #fff;
            text-decoration: none;
            font-size: 18px;
        }

        nav li a:hover {
            color: #FFFACD;
        }

        main {
            display: flex;
            flex-direction: row;
            margin-top: 2em;
        }

        textarea,
        input {
            font-family: 'Helvetica Neue', sans-serif;
            font-size: 16px;
            line-height: 1.5;
        }

        .left-part {
            padding-right: 2%;

            display: flex;
            flex-direction: column;
            width: 70%
        }

        .left-part textarea,
        .left-part input {
            font-family: monospace;
        }

        #taskFlashMessage {
            flex: 1;
            resize: none;
        }

        #taskMessage {
            flex: 5;
            resize: none;

        }

        #createInteractiveTaskForm {
            width: 100%;
            display: flex;

        }

        #createInteractiveTaskForm input[type='text'] {
            display: inline-block;
            flex: 1;
            /* width: 70%; */
        }

        #createInteractiveTaskForm input[type='submit'] {
            display: inline-block;
            /* margin-left: 20px; */
        }



        #createInteractiveTaskForm input {
            font-size: 16px;
            letter-spacing: 1px;
            /* margin: 6px 10px; */
        }

        .right-part {
            flex-grow: 3;
            background-color: #fff;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 2%;
            box-sizing: border-box;
            line-height: 1.5em;
        }

        .right-part input[type="text"] {
            width: 100%;
        }

        .right-part label {
            display: block;
        }

        .right-part input[type=checkbox] {
            display: inline-block;
            /* margin-right: 0.5em; */
        }

        .submit-button {
            border: none;
            padding: 0.5em 1em;
            background-color: #2ecc71;
            color: #fff;
            font-size: 1.2em;
            cursor: pointer;
            font-weight: bold;
        }
    </style>
</head>

<body>
    <!-- <header>
        <h1>Header Here</h1>
    </header> -->
    <header>
        <nav>
            <ul>
                <li><a href="#">首 页</a></li>
                <!-- <li><a href="#">关于我们</a></li> -->
            </ul>
        </nav>
    </header>
    <main>
        <div class="left-part">
            <textarea name="taskMessage" id="taskMessage" cols="100" rows="20" readonly></textarea>
            <textarea name="taskFlashMessage" id="taskFlashMessage" cols="100" rows="3" readonly></textarea>

            <form id="createInteractiveTaskForm">
                <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>
        </div>
        <div class="right-part">
            <form id="createCrackTask">
                <label for="url">URL:</label>
                <input type="text" id="url" name="url" placeholder="http://127.0.0.1:1234" />
                <br /><br />

                <label for="method">请求方式:</label>
                <select id="method" name="method">
                    <option value="POST">POST</option>
                    <option value="GET">GET</option>
                </select>
                <br /><br />

                <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 />

                <input type="hidden" name="type" value="crack" />
                <input type="submit" value="开始分析">
            </form>
        </div>
    </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>