Assistant: 
User: User: 能否帮我优化下UI，要时间一点
```plaintext
from flask import Flask, jsonify, request, render_template_string
import requests
import uuid
import json
import time
import hashlib
import urllib.parse
import re
from datetime import datetime

app = Flask(__name__)

def sytTokens(payload, deviceId):
    t = int(time.time() * 1000)
    datamd5 = generate_md5(payload + '&080R3MAC57J2{A19!$3:WO{I<1N$31BI')
    deviceidmd5 = generate_md5(
        deviceId + f'{t}' + '9.65.302NBF+BE4{@P:@X${Q9BAE>{PAK!D:N*^CNsc' + datamd5 + '705088894ad6ef475bdf4875c9d533b8&2NBF+BE4{@P:@X${Q9BAE>{PAK!D:N*^')
    sytToken = generate_md5(deviceidmd5 + '&0HQ%H91K&AA{DH$*XV>XR)VKL:QFE{&%')
    return sytToken, t

def generate_md5(input_string):
    md5_hash = hashlib.md5()
    md5_hash.update(input_string.encode('utf-8'))
    md5_digest = md5_hash.hexdigest()
    return md5_digest

def session_ids(url):
    try:
        response = requests.get(url, allow_redirects=False)
        session_id_pattern = r'sessionId=([^;]+);'
        login_mobile_pattern = r'_login_mobile_=([^;]+);'
        session_id = re.search(session_id_pattern, str(response.headers)).group(1)
        login_mobile = re.search(login_mobile_pattern, str(response.headers)).group(1)
        if session_id and login_mobile and '用户手机号校验未通过' not in response.text:
            return session_id, login_mobile
        else:
            print('用户信息无效，请检查')
            return None, None
    except Exception as e:
        return None, None

@app.route('/')
def index():
    html_content = """
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>呆呆的扫码获取</title>
        <style>
            body {
                display: flex;
                flex-direction: row;
                align-items: flex-start;
                justify-content: center;
                height: 100vh;
                font-family: Arial, sans-serif;
            }
            .main-container {
                display: flex;
                flex-direction: column;
                align-items: center;
                margin-right: 20px;
            }
            h1 {
                text-align: center;
            }
            .button-container {
                display: flex;
                justify-content: center;
                margin: 10px;
            }
            button {
                margin: 10px;
                padding: 10px 20px;
                font-size: 16px;
            }
            #qrCodeContainer, #loginUrlContainer {
                margin-top: 20px;
                text-align: center;
            }
            input {
                width: 300px;
                padding: 10px;
                margin-top: 10px;
                font-size: 16px;
                text-align: center;
            }
            #recordList {
                list-style-type: none;
                padding: 0;
            }
            #recordList li {
                cursor: pointer;
                margin: 5px 0;
                padding: 5px;
                background-color: #f0f0f0;
                border-radius: 5px;
            }
        </style>
    </head>
    <body>
        <div class="main-container">
            <h1>扫码获取</h1>
            <div class="button-container">
                <button id="getQrBtn">Get Sfsy QR Code</button>
                <button id="getPupuQrBtn">Get Pupu QR Code</button>
            </div>
            <div id="qrCodeContainer"></div>
            <div id="loginUrlContainer">
                <input type="text" id="loginUrl" readonly placeholder="Refresh Token">
            </div>
            <button id="encodeUrlBtn">适配新建变量或&分割格式的URL</button>
            <button id="normalUrlBtn">适配leaf脚本变量格式的URL</button>
        </div>
        <ul id="recordList"></ul>

        <script>
            let originalUrl = '';
            let encodedUrl = '';
            let recordCount = 0;
            const recordList = document.getElementById('recordList');

            document.getElementById('getQrBtn').addEventListener('click', function() {
                fetch('/get_qr', { method: 'POST' })
                    .then(response => response.json())
                    .then(data => {
                        document.getElementById('qrCodeContainer').innerHTML = `<img src="${data.img_url}" alt="QR Code">`;
                        localStorage.setItem('qrcode', data.uuid);
                        checkQrStatus(data.uuid); 
                    });
            });

            document.getElementById('getPupuQrBtn').addEventListener('click', function() {
                fetch('/get_pupu_qr', { method: 'POST' })
                    .then(response => response.json())
                    .then(data => {
                        document.getElementById('qrCodeContainer').innerHTML = `<img src="${data.img_url}" alt="Pupu QR Code">`;
                        localStorage.setItem('pupu_qrcode', data.uuid);
                        checkPupuQrStatus(data.uuid); 
                    });
            });

            document.getElementById('encodeUrlBtn').addEventListener('click', function() {
                const loginUrl = document.getElementById('loginUrl').value;
                if (loginUrl && loginUrl === originalUrl) {
                    encodedUrl = encodeURIComponent(loginUrl);
                    document.getElementById('loginUrl').value = encodedUrl;
                    console.log('Encoded URL:', encodedUrl);
                } else if (!loginUrl) {
                    console.error('No URL to encode');
                }
            });

            document.getElementById('normalUrlBtn').addEventListener('click', function() {
                if (originalUrl) {
                    document.getElementById('loginUrl').value = originalUrl;
                    console.log('Normal URL:', originalUrl);
                } else {
                    console.error('No original URL available');
                }
            });

            function checkQrStatus(qrcode) {
                const interval = setInterval(() => {
                    fetch('/check_qr', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ qrcode })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.code) {
                            clearInterval(interval);
                            fetch('/get_login_data', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({ code: data.code })
                            })
                            .then(response => response.json())
                            .then(loginData => {
                                if (loginData.url) {
                                    document.getElementById('loginUrl').value = loginData.url;
                                    originalUrl = loginData.url;
                                    addRecord(loginData.url);
                                    console.log('URL:', loginData.url);
                                } else {
                                    console.error('Error:', loginData.error);
                                }
                            });
                        }
                    });
                }, 1000);
            }

            function checkPupuQrStatus(qrcode) {
                const interval = setInterval(() => {
                    fetch('/check_pupu_qr', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ qrcode })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.code) {
                            clearInterval(interval);
                            fetch('/get_pupu_login_data', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({ code: data.code })
                            })
                            .then(response => response.json())
                            .then(loginData => {
                                if (loginData.refresh_token) {
                                    document.getElementById('loginUrl').value = loginData.refresh_token;
                                    addRecord(loginData.refresh_token);
                                    console.log('Refresh Token:', loginData.refresh_token);
                                } else {
                                    console.error('Error:', loginData.error);
                                }
                            });
                        }
                    });
                }, 1000);
            }

            function addRecord(url) {
                recordCount++;
                const listItem = document.createElement('li');
                listItem.textContent = `获取记录 ${recordCount}`;
                listItem.addEventListener('click', () => {
                    document.getElementById('loginUrl').value = url;
                });
                recordList.appendChild(listItem);
            }
        </script>
    </body>
    </html>
    """
    return render_template_string(html_content)

@app.route('/get_qr', methods=['POST'])
def get_qr():
    url_getQr = 'http://8.140.63.151:9024/api/getQr'
    response = requests.post(url_getQr, json={'project': 'sf'})
    QRcode = response.json()['uuid']
    QRcodeImg = response.json()['img_url']
    return jsonify({'uuid': QRcode, 'img_url': QRcodeImg})

@app.route('/check_qr', methods=['POST'])
def check_qr():
    QRcode = request.json.get('qrcode')
    url_checkQr = 'http://8.140.63.151:9024/api/checkQr'
    retry = 60
    while retry > 0:
        time.sleep(1)
        data = {'project': 'sf', 'qrcode': QRcode}
        response = requests.post(url_checkQr, json=data)
        state_code = response.json()['state_code']
        if state_code == 405:
            code = response.json()['code']
            return jsonify({'code': code})
        retry -= 1
    return jsonify({'error': 'timeout'}), 408

@app.route('/get_login_data', methods=['POST'])
def get_login_data():
    try:
        code = request.json.get('code')
        deviceId = str(uuid.uuid4())
        url = "https://ccsp-egmas.sf-express.com/cx-app-member/member/app/weixin/getAccessTokenByCode"
        payload = json.dumps({"code": code})
        sytToken, t = sytTokens(payload, deviceId)
        headers = {
            'User-Agent': "okhttp/4.9.1",
            'Connection': "Keep-Alive",
            'Accept-Encoding': "gzip",
            'Content-Type': "application/json",
            'jsbundle': "705088894ad6ef475bdf4875c9d533b8",
            'clientVersion': "9.65.30",
            'languageCode': "sc",
            'systemVersion': "13",
            'deviceId': deviceId,
            'regionCode': "CN",
            'carrier': "unknown",
            'screenSize': "1080x2400",
            'sytToken': sytToken,
            'timeInterval': f"{t}",
            'model': "MEIZU 20",
            'mediaCode': "AndroidML"
        }
        response = requests.post(url, data=payload, headers=headers)
        response_data = response.json()

        if not response_data.get('success'):
            error_message = response_data.get('errorMessage', 'Unknown error')
            return jsonify({'error': error_message}), 500

        if not response_data.get('obj') or not response_data['obj'].get('memInfos'):
            return jsonify({'error': 'Invalid response structure'}), 500

        url = "https://ccsp-egmas.sf-express.com/cx-app-member/member/app/user/universalSign"
        account = response_data['obj']['memInfos'][0]['userId']
        memNo = response_data['obj']['memInfos'][0]['memNo']
        mobile = response_data['obj']['memInfos'][0]['mobile']

        payload = json.dumps({
            "mobile": mobile,
            "userId": account,
            "memNo": memNo,
            "name": "mcs-mimp-web.sf-express.com",
            "extra": "",
            "needReqTime": "1"
        })
        sytToken, t = sytTokens(payload, deviceId)
        headers['sytToken'] = sytToken
        headers['timeInterval'] = str(t)
        response = requests.post(url, data=payload, headers=headers)
        sign = response.json()['obj']['sign']
        encoded_string = urllib.parse.quote(sign)
        Token = f'https://mcs-mimp-web.sf-express.com/mcs-mimp/share/app/shareRedirect?sign={encoded_string}&source=SFAPP&bizCode=619'
        account = mobile
        mobile = mobile[:3] + '*' * 4 + mobile[7:]

        return jsonify({'url': Token, 'account': account, 'mobile': mobile})
    except Exception as e:
        return jsonify({'error': '登录出错！'}), 500

@app.route('/get_pupu_qr', methods=['POST'])
def get_pupu_qr():
    url_getQr = 'http://8.140.63.151:9024/api/getQr'
    response = requests.post(url_getQr, json={'project': 'ppcs'})
    QRcode = response.json()['uuid']
    QRcodeImg = response.json()['img_url']
    return jsonify({'uuid': QRcode, 'img_url': QRcodeImg})

@app.route('/check_pupu_qr', methods=['POST'])
def check_pupu_qr():
    QRcode = request.json.get('qrcode')
    url_checkQr = 'http://8.140.63.151:9024/api/checkQr'
    retry = 60
    while retry > 0:
        time.sleep(1)
        data = {'project': 'ppcs', 'qrcode': QRcode}
        response = requests.post(url_checkQr, json=data)
        state_code = response.json()['state_code']
        if state_code == 405:
            code = response.json()['code']
            return jsonify({'code': code})
        retry -= 1
    return jsonify({'error': 'timeout'}), 408

@app.route('/get_pupu_login_data', methods=['POST'])
def get_pupu_login_data():
    try:
        code = request.json.get('code')
        url = "https://cauth.pupuapi.com/clientauth/user/society/wechat/login"
        params = {'user_society_type': "11"}
        payload = json.dumps({
            "code": code,
            "user_device": {
                "app_version": 400804,
                "device_model": "MEIZU 20",
                "device_os": 10,
                "device_token": "",
                "mac_address": ""
            }
        })
        headers = {
            'User-Agent': "Pupumall/4.8.4;Android/13;",
            'Connection': "Keep-Alive",
            'Accept-Encoding': "gzip",
            'pp-version': "2023022500",
            'pp-os': "10",
            'pp_store_city_zip': "440100",
            'pp-elder-mode': "false",
            'Content-Type': "application/json; charset=UTF-8"
        }
        response = requests.post(url, params=params, data=payload, headers=headers)
        refresh_token = response.json()['data']['refresh_token']
        return jsonify({'refresh_token': refresh_token})
    except Exception as e:
        return jsonify({'error': '登录出错'}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=1845)
```
Assistant: One message exceeds the 1000chars per message limit. Join our discord for more: [https://discord.com/invite/q55gsH8z5F](https://discord.com/invite/q55gsH8z5F)One message exceeds the 1000chars per message limit. Join our discord for more: [https://discord.com/invite/q55gsH8z5F](https://discord.com/invite/q55gsH8z5F)One message exceeds the 1000chars per message limit. Join our discord for more: [https://discord.com/invite/q55gsH8z5F](https://discord.com/invite/q55gsH8z5F)One message exceeds the 1000chars per message limit. Join our discord for more: [https://discord.com/invite/q55gsH8z5F](https://discord.com/invite/q55gsH8z5F)
User: from flask import Flask, jsonify, request, render_template_string
import requests
import uuid
import json
import time
import hashlib
import urllib.parse
import re
from datetime import datetime

app = Flask(__name__)

def sytTokens(payload, deviceId):
    t = int(time.time() * 1000)
    datamd5 = generate_md5(payload + '&080R3MAC57J2{A19!$3:WO{I<1N$31BI')
    deviceidmd5 = generate_md5(
        deviceId + f'{t}' + '9.65.302NBF+BE4{@P:@X${Q9BAE>{PAK!D:N*^CNsc' + datamd5 + '705088894ad6ef475bdf4875c9d533b8&2NBF+BE4{@P:@X${Q9BAE>{PAK!D:N*^')
    sytToken = generate_md5(deviceidmd5 + '&0HQ%H91K&AA{DH$*XV>XR)VKL:QFE{&%')
    return sytToken, t

def generate_md5(input_string):
    md5_hash = hashlib.md5()
    md5_hash.update(input_string.encode('utf-8'))
    md5_digest = md5_hash.hexdigest()
    return md5_digest

def session_ids(url):
    try:
        response = requests.get(url, allow_redirects=False)
        session_id_pattern = r'sessionId=([^;]+);'
        login_mobile_pattern = r'_login_mobile_=([^;]+);'
        session_id = re.search(session_id_pattern, str(response.headers)).group(1)
        login_mobile = re.search(login_mobile_pattern, str(response.headers)).group(1)
        if session_id and login_mobile and '用户手机号校验未通过' not in response.text:
            return session_id, login_mobile
        else:
            print('用户信息无效，请检查')
            return None, None
    except Exception as e:
        return None, None

@app.route('/')
def index():
    html_content = """
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>呆呆的扫码获取</title>
        <style>
            body {
                display: flex;
                flex-direction: row;
                align-items: flex-start;
                justify-content: center;
                height: 100vh;
                font-family: Arial, sans-serif;
            }
            .main-container {
                display: flex;
                flex-direction: column;
                align-items: center;
                margin-right: 20px;
            }
            h1 {
                text-align: center;
            }
            .button-container {
                display: flex;
                justify-content: center;
                margin: 10px;
            }
            button {
                margin: 10px;
                padding: 10px 20px;
                font-size: 16px;
            }
            #qrCodeContainer, #loginUrlContainer {
                margin-top: 20px;
                text-align: center;
            }
            input {
                width: 300px;
                padding: 10px;
                margin-top: 10px;
                font-size: 16px;
                text-align: center;
            }
            #recordList {
                list-style-type: none;
                padding: 0;
            }
            #recordList li {
                cursor: pointer;
                margin: 5px 0;
                padding: 5px;
                background-color: #f0f0f0;
                border-radius: 5px;
            }
        </style>
    </head>
    <body>
        <div class="main-container">
            <h1>扫码获取</h1>
            <div class="button-container">
                <button id="getQrBtn">Get Sfsy QR Code</button>
                <button id="getPupuQrBtn">Get Pupu QR Code</button>
            </div>
            <div id="qrCodeContainer"></div>
            <div id="loginUrlContainer">
                <input type="text" id="loginUrl" readonly placeholder="Refresh Token">
            </div>
            <button id="encodeUrlBtn">适配新建变量或&分割格式的URL</button>
            <button id="normalUrlBtn">适配leaf脚本变量格式的URL</button>
        </div>
        <ul id="recordList"></ul>

        <script>
            let originalUrl = '';
            let encodedUrl = '';
            let recordCount = 0;
            const recordList = document.getElementById('recordList');

            document.getElementById('getQrBtn').addEventListener('click', function() {
                fetch('/get_qr', { method: 'POST' })
                    .then(response => response.json())
                    .then(data => {
                        document.getElementById('qrCodeContainer').innerHTML = `<img src="${data.img_url}" alt="QR Code">`;
                        localStorage.setItem('qrcode', data.uuid);
                        checkQrStatus(data.uuid); 
                    });
            });

            document.getElementById('getPupuQrBtn').addEventListener('click', function() {
                fetch('/get_pupu_qr', { method: 'POST' })
                    .then(response => response.json())
                    .then(data => {
                        document.getElementById('qrCodeContainer').innerHTML = `<img src="${data.img_url}" alt="Pupu QR Code">`;
                        localStorage.setItem('pupu_qrcode', data.uuid);
                        checkPupuQrStatus(data.uuid); 
                    });
            });

            document.getElementById('encodeUrlBtn').addEventListener('click', function() {
                const loginUrl = document.getElementById('loginUrl').value;
                if (loginUrl && loginUrl === originalUrl) {
                    encodedUrl = encodeURIComponent(loginUrl);
                    document.getElementById('loginUrl').value = encodedUrl;
                    console.log('Encoded URL:', encodedUrl);
                } else if (!loginUrl) {
                    console.error('No URL to encode');
                }
            });

            document.getElementById('normalUrlBtn').addEventListener('click', function() {
                if (originalUrl) {
                    document.getElementById('loginUrl').value = originalUrl;
                    console.log('Normal URL:', originalUrl);
                } else {
                    console.error('No original URL available');
                }
            });

            function checkQrStatus(qrcode) {
                const interval = setInterval(() => {
                    fetch('/check_qr', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ qrcode })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.code) {
                            clearInterval(interval);
                            fetch('/get_login_data', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({ code: data.code })
                            })
                            .then(response => response.json())
                            .then(loginData => {
                                if (loginData.url) {
                                    document.getElementById('loginUrl').value = loginData.url;
                                    originalUrl = loginData.url;
                                    addRecord(loginData.url);
                                    console.log('URL:', loginData.url);
                                } else {
                                    console.error('Error:', loginData.error);
                                }
                            });
                        }
                    });
                }, 1000);
            }

            function checkPupuQrStatus(qrcode) {
                const interval = setInterval(() => {
                    fetch('/check_pupu_qr', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ qrcode })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.code) {
                            clearInterval(interval);
                            fetch('/get_pupu_login_data', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({ code: data.code })
                            })
                            .then(response => response.json())
                            .then(loginData => {
                                if (loginData.refresh_token) {
                                    document.getElementById('loginUrl').value = loginData.refresh_token;
                                    addRecord(loginData.refresh_token);
                                    console.log('Refresh Token:', loginData.refresh_token);
                                } else {
                                    console.error('Error:', loginData.error);
                                }
                            });
                        }
                    });
                }, 1000);
            }

            function addRecord(url) {
                recordCount++;
                const listItem = document.createElement('li');
                listItem.textContent = `获取记录 ${recordCount}`;
                listItem.addEventListener('click', () => {
                    document.getElementById('loginUrl').value = url;
                });
                recordList.appendChild(listItem);
            }
        </script>
    </body>
    </html>
    """
    return render_template_string(html_content)

@app.route('/get_qr', methods=['POST'])
def get_qr():
    url_getQr = 'http://8.140.63.151:9024/api/getQr'
    response = requests.post(url_getQr, json={'project': 'sf'})
    QRcode = response.json()['uuid']
    QRcodeImg = response.json()['img_url']
    return jsonify({'uuid': QRcode, 'img_url': QRcodeImg})

@app.route('/check_qr', methods=['POST'])
def check_qr():
    QRcode = request.json.get('qrcode')
    url_checkQr = 'http://8.140.63.151:9024/api/checkQr'
    retry = 60
    while retry > 0:
        time.sleep(1)
        data = {'project': 'sf', 'qrcode': QRcode}
        response = requests.post(url_checkQr, json=data)
        state_code = response.json()['state_code']
        if state_code == 405:
            code = response.json()['code']
            return jsonify({'code': code})
        retry -= 1
    return jsonify({'error': 'timeout'}), 408

@app.route('/get_login_data', methods=['POST'])
def get_login_data():
    try:
        code = request.json.get('code')
        deviceId = str(uuid.uuid4())
        url = "https://ccsp-egmas.sf-express.com/cx-app-member/member/app/weixin/getAccessTokenByCode"
        payload = json.dumps({"code": code})
        sytToken, t = sytTokens(payload, deviceId)
        headers = {
            'User-Agent': "okhttp/4.9.1",
            'Connection': "Keep-Alive",
            'Accept-Encoding': "gzip",
            'Content-Type': "application/json",
            'jsbundle': "705088894ad6ef475bdf4875c9d533b8",
            'clientVersion': "9.65.30",
            'languageCode': "sc",
            'systemVersion': "13",
            'deviceId': deviceId,
            'regionCode': "CN",
            'carrier': "unknown",
            'screenSize': "1080x2400",
            'sytToken': sytToken,
            'timeInterval': f"{t}",
            'model': "MEIZU 20",
            'mediaCode': "AndroidML"
        }
        response = requests.post(url, data=payload, headers=headers)
        response_data = response.json()

        if not response_data.get('success'):
            error_message = response_data.get('errorMessage', 'Unknown error')
            return jsonify({'error': error_message}), 500

        if not response_data.get('obj') or not response_data['obj'].get('memInfos'):
            return jsonify({'error': 'Invalid response structure'}), 500

        url = "https://ccsp-egmas.sf-express.com/cx-app-member/member/app/user/universalSign"
        account = response_data['obj']['memInfos'][0]['userId']
        memNo = response_data['obj']['memInfos'][0]['memNo']
        mobile = response_data['obj']['memInfos'][0]['mobile']

        payload = json.dumps({
            "mobile": mobile,
            "userId": account,
            "memNo": memNo,
            "name": "mcs-mimp-web.sf-express.com",
            "extra": "",
            "needReqTime": "1"
        })
        sytToken, t = sytTokens(payload, deviceId)
        headers['sytToken'] = sytToken
        headers['timeInterval'] = str(t)
        response = requests.post(url, data=payload, headers=headers)
        sign = response.json()['obj']['sign']
        encoded_string = urllib.parse.quote(sign)
        Token = f'https://mcs-mimp-web.sf-express.com/mcs-mimp/share/app/shareRedirect?sign={encoded_string}&source=SFAPP&bizCode=619'
        account = mobile
        mobile = mobile[:3] + '*' * 4 + mobile[7:]

        return jsonify({'url': Token, 'account': account, 'mobile': mobile})
    except Exception as e:
        return jsonify({'error': '登录出错！'}), 500

@app.route('/get_pupu_qr', methods=['POST'])
def get_pupu_qr():
    url_getQr = 'http://8.140.63.151:9024/api/getQr'
    response = requests.post(url_getQr, json={'project': 'ppcs'})
    QRcode = response.json()['uuid']
    QRcodeImg = response.json()['img_url']
    return jsonify({'uuid': QRcode, 'img_url': QRcodeImg})

@app.route('/check_pupu_qr', methods=['POST'])
def check_pupu_qr():
    QRcode = request.json.get('qrcode')
    url_checkQr = 'http://8.140.63.151:9024/api/checkQr'
    retry = 60
    while retry > 0:
        time.sleep(1)
        data = {'project': 'ppcs', 'qrcode': QRcode}
        response = requests.post(url_checkQr, json=data)
        state_code = response.json()['state_code']
        if state_code == 405:
            code = response.json()['code']
            return jsonify({'code': code})
        retry -= 1
    return jsonify({'error': 'timeout'}), 408

@app.route('/get_pupu_login_data', methods=['POST'])
def get_pupu_login_data():
    try:
        code = request.json.get('code')
        url = "https://cauth.pupuapi.com/clientauth/user/society/wechat/login"
        params = {'user_society_type': "11"}
        payload = json.dumps({
            "code": code,
            "user_device": {
                "app_version": 400804,
                "device_model": "MEIZU 20",
                "device_os": 10,
                "device_token": "",
                "mac_address": ""
            }
        })
        headers = {
            'User-Agent': "Pupumall/4.8.4;Android/13;",
            'Connection': "Keep-Alive",
            'Accept-Encoding': "gzip",
            'pp-version': "2023022500",
            'pp-os': "10",
            'pp_store_city_zip': "440100",
            'pp-elder-mode': "false",
            'Content-Type': "application/json; charset=UTF-8"
        }
        response = requests.post(url, params=params, data=payload, headers=headers)
        refresh_token = response.json()['data']['refresh_token']
        return jsonify({'refresh_token': refresh_token})
    except Exception as e:
        return jsonify({'error': '登录出错'}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=1845)
```plaintext
from flask import Flask, jsonify, request, render_template_string
import requests
import uuid
import json
import time
import hashlib
import urllib.parse
import re
from datetime import datetime

app = Flask(__name__)

def sytTokens(payload, deviceId):
    t = int(time.time() * 1000)
    datamd5 = generate_md5(payload + '&080R3MAC57J2{A19!$3:WO{I<1N$31BI')
    deviceidmd5 = generate_md5(
        deviceId + f'{t}' + '9.65.302NBF+BE4{@P:@X${Q9BAE>{PAK!D:N*^CNsc' + datamd5 + '705088894ad6ef475bdf4875c9d533b8&2NBF+BE4{@P:@X${Q9BAE>{PAK!D:N*^')
    sytToken = generate_md5(deviceidmd5 + '&0HQ%H91K&AA{DH$*XV>XR)VKL:QFE{&%')
    return sytToken, t

def generate_md5(input_string):
    md5_hash = hashlib.md5()
    md5_hash.update(input_string.encode('utf-8'))
    md5_digest = md5_hash.hexdigest()
    return md5_digest

def session_ids(url):
    try:
        response = requests.get(url, allow_redirects=False)
        session_id_pattern = r'sessionId=([^;]+);'
        login_mobile_pattern = r'_login_mobile_=([^;]+);'
        session_id = re.search(session_id_pattern, str(response.headers)).group(1)
        login_mobile = re.search(login_mobile_pattern, str(response.headers)).group(1)
        if session_id and login_mobile and '用户手机号校验未通过' not in response.text:
            return session_id, login_mobile
        else:
            print('用户信息无效，请检查')
            return None, None
    except Exception as e:
        return None, None

@app.route('/')
def index():
    html_content = """
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>呆呆的扫码获取</title>
        <style>
            body {
                display: flex;
                flex-direction: row;
                align-items: flex-start;
                justify-content: center;
                height: 100vh;
                font-family: Arial, sans-serif;
            }
            .main-container {
                display: flex;
                flex-direction: column;
                align-items: center;
                margin-right: 20px;
            }
            h1 {
                text-align: center;
            }
            .button-container {
                display: flex;
                justify-content: center;
                margin: 10px;
            }
            button {
                margin: 10px;
                padding: 10px 20px;
                font-size: 16px;
            }
            #qrCodeContainer, #loginUrlContainer {
                margin-top: 20px;
                text-align: center;
            }
            input {
                width: 300px;
                padding: 10px;
                margin-top: 10px;
                font-size: 16px;
                text-align: center;
            }
            #recordList {
                list-style-type: none;
                padding: 0;
            }
            #recordList li {
                cursor: pointer;
                margin: 5px 0;
                padding: 5px;
                background-color: #f0f0f0;
                border-radius: 5px;
            }
        </style>
    </head>
    <body>
        <div class="main-container">
            <h1>扫码获取</h1>
            <div class="button-container">
                <button id="getQrBtn">Get Sfsy QR Code</button>
                <button id="getPupuQrBtn">Get Pupu QR Code</button>
            </div>
            <div id="qrCodeContainer"></div>
            <div id="loginUrlContainer">
                <input type="text" id="loginUrl" readonly placeholder="Refresh Token">
            </div>
            <button id="encodeUrlBtn">适配新建变量或&分割格式的URL</button>
            <button id="normalUrlBtn">适配leaf脚本变量格式的URL</button>
        </div>
        <ul id="recordList"></ul>

        <script>
            let originalUrl = '';
            let encodedUrl = '';
            let recordCount = 0;
            const recordList = document.getElementById('recordList');

            document.getElementById('getQrBtn').addEventListener('click', function() {
                fetch('/get_qr', { method: 'POST' })
                    .then(response => response.json())
                    .then(data => {
                        document.getElementById('qrCodeContainer').innerHTML = `<img src="${data.img_url}" alt="QR Code">`;
                        localStorage.setItem('qrcode', data.uuid);
                        checkQrStatus(data.uuid); 
                    });
            });

            document.getElementById('getPupuQrBtn').addEventListener('click', function() {
                fetch('/get_pupu_qr', { method: 'POST' })
                    .then(response => response.json())
                    .then(data => {
                        document.getElementById('qrCodeContainer').innerHTML = `<img src="${data.img_url}" alt="Pupu QR Code">`;
                        localStorage.setItem('pupu_qrcode', data.uuid);
                        checkPupuQrStatus(data.uuid); 
                    });
            });

            document.getElementById('encodeUrlBtn').addEventListener('click', function() {
                const loginUrl = document.getElementById('loginUrl').value;
                if (loginUrl && loginUrl === originalUrl) {
                    encodedUrl = encodeURIComponent(loginUrl);
                    document.getElementById('loginUrl').value = encodedUrl;
                    console.log('Encoded URL:', encodedUrl);
                } else if (!loginUrl) {
                    console.error('No URL to encode');
                }
            });

            document.getElementById('normalUrlBtn').addEventListener('click', function() {
                if (originalUrl) {
                    document.getElementById('loginUrl').value = originalUrl;
                    console.log('Normal URL:', originalUrl);
                } else {
                    console.error('No original URL available');
                }
            });

            function checkQrStatus(qrcode) {
                const interval = setInterval(() => {
                    fetch('/check_qr', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ qrcode })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.code) {
                            clearInterval(interval);
                            fetch('/get_login_data', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({ code: data.code })
                            })
                            .then(response => response.json())
                            .then(loginData => {
                                if (loginData.url) {
                                    document.getElementById('loginUrl').value = loginData.url;
                                    originalUrl = loginData.url;
                                    addRecord(loginData.url);
                                    console.log('URL:', loginData.url);
                                } else {
                                    console.error('Error:', loginData.error);
                                }
                            });
                        }
                    });
                }, 1000);
            }

            function checkPupuQrStatus(qrcode) {
                const interval = setInterval(() => {
                    fetch('/check_pupu_qr', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ qrcode })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.code) {
                            clearInterval(interval);
                            fetch('/get_pupu_login_data', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({ code: data.code })
                            })
                            .then(response => response.json())
                            .then(loginData => {
                                if (loginData.refresh_token) {
                                    document.getElementById('loginUrl').value = loginData.refresh_token;
                                    addRecord(loginData.refresh_token);
                                    console.log('Refresh Token:', loginData.refresh_token);
                                } else {
                                    console.error('Error:', loginData.error);
                                }
                            });
                        }
                    });
                }, 1000);
            }

            function addRecord(url) {
                recordCount++;
                const listItem = document.createElement('li');
                listItem.textContent = `获取记录 ${recordCount}`;
                listItem.addEventListener('click', () => {
                    document.getElementById('loginUrl').value = url;
                });
                recordList.appendChild(listItem);
            }
        </script>
    </body>
    </html>
    """
    return render_template_string(html_content)

@app.route('/get_qr', methods=['POST'])
def get_qr():
    url_getQr = 'http://8.140.63.151:9024/api/getQr'
    response = requests.post(url_getQr, json={'project': 'sf'})
    QRcode = response.json()['uuid']
    QRcodeImg = response.json()['img_url']
    return jsonify({'uuid': QRcode, 'img_url': QRcodeImg})

@app.route('/check_qr', methods=['POST'])
def check_qr():
    QRcode = request.json.get('qrcode')
    url_checkQr = 'http://8.140.63.151:9024/api/checkQr'
    retry = 60
    while retry > 0:
        time.sleep(1)
        data = {'project': 'sf', 'qrcode': QRcode}
        response = requests.post(url_checkQr, json=data)
        state_code = response.json()['state_code']
        if state_code == 405:
            code = response.json()['code']
            return jsonify({'code': code})
        retry -= 1
    return jsonify({'error': 'timeout'}), 408

@app.route('/get_login_data', methods=['POST'])
def get_login_data():
    try:
        code = request.json.get('code')
        deviceId = str(uuid.uuid4())
        url = "https://ccsp-egmas.sf-express.com/cx-app-member/member/app/weixin/getAccessTokenByCode"
        payload = json.dumps({"code": code})
        sytToken, t = sytTokens(payload, deviceId)
        headers = {
            'User-Agent': "okhttp/4.9.1",
            'Connection': "Keep-Alive",
            'Accept-Encoding': "gzip",
            'Content-Type': "application/json",
            'jsbundle': "705088894ad6ef475bdf4875c9d533b8",
            'clientVersion': "9.65.30",
            'languageCode': "sc",
            'systemVersion': "13",
            'deviceId': deviceId,
            'regionCode': "CN",
            'carrier': "unknown",
            'screenSize': "1080x2400",
            'sytToken': sytToken,
            'timeInterval': f"{t}",
            'model': "MEIZU 20",
            'mediaCode': "AndroidML"
        }
        response = requests.post(url, data=payload, headers=headers)
        response_data = response.json()

        if not response_data.get('success'):
            error_message = response_data.get('errorMessage', 'Unknown error')
            return jsonify({'error': error_message}), 500

        if not response_data.get('obj') or not response_data['obj'].get('memInfos'):
            return jsonify({'error': 'Invalid response structure'}), 500

        url = "https://ccsp-egmas.sf-express.com/cx-app-member/member/app/user/universalSign"
        account = response_data['obj']['memInfos'][0]['userId']
        memNo = response_data['obj']['memInfos'][0]['memNo']
        mobile = response_data['obj']['memInfos'][0]['mobile']

        payload = json.dumps({
            "mobile": mobile,
            "userId": account,
            "memNo": memNo,
            "name": "mcs-mimp-web.sf-express.com",
            "extra": "",
            "needReqTime": "1"
        })
        sytToken, t = sytTokens(payload, deviceId)
        headers['sytToken'] = sytToken
        headers['timeInterval'] = str(t)
        response = requests.post(url, data=payload, headers=headers)
        sign = response.json()['obj']['sign']
        encoded_string = urllib.parse.quote(sign)
        Token = f'https://mcs-mimp-web.sf-express.com/mcs-mimp/share/app/shareRedirect?sign={encoded_string}&source=SFAPP&bizCode=619'
        account = mobile
        mobile = mobile[:3] + '*' * 4 + mobile[7:]

        return jsonify({'url': Token, 'account': account, 'mobile': mobile})
    except Exception as e:
        return jsonify({'error': '登录出错！'}), 500

@app.route('/get_pupu_qr', methods=['POST'])
def get_pupu_qr():
    url_getQr = 'http://8.140.63.151:9024/api/getQr'
    response = requests.post(url_getQr, json={'project': 'ppcs'})
    QRcode = response.json()['uuid']
    QRcodeImg = response.json()['img_url']
    return jsonify({'uuid': QRcode, 'img_url': QRcodeImg})

@app.route('/check_pupu_qr', methods=['POST'])
def check_pupu_qr():
    QRcode = request.json.get('qrcode')
    url_checkQr = 'http://8.140.63.151:9024/api/checkQr'
    retry = 60
    while retry > 0:
        time.sleep(1)
        data = {'project': 'ppcs', 'qrcode': QRcode}
        response = requests.post(url_checkQr, json=data)
        state_code = response.json()['state_code']
        if state_code == 405:
            code = response.json()['code']
            return jsonify({'code': code})
        retry -= 1
    return jsonify({'error': 'timeout'}), 408

@app.route('/get_pupu_login_data', methods=['POST'])
def get_pupu_login_data():
    try:
        code = request.json.get('code')
        url = "https://cauth.pupuapi.com/clientauth/user/society/wechat/login"
        params = {'user_society_type': "11"}
        payload = json.dumps({
            "code": code,
            "user_device": {
                "app_version": 400804,
                "device_model": "MEIZU 20",
                "device_os": 10,
                "device_token": "",
                "mac_address": ""
            }
        })
        headers = {
            'User-Agent': "Pupumall/4.8.4;Android/13;",
            'Connection': "Keep-Alive",
            'Accept-Encoding': "gzip",
            'pp-version': "2023022500",
            'pp-os': "10",
            'pp_store_city_zip': "440100",
            'pp-elder-mode': "false",
            'Content-Type': "application/json; charset=UTF-8"
        }
        response = requests.post(url, params=params, data=payload, headers=headers)
        refresh_token = response.json()['data']['refresh_token']
        return jsonify({'refresh_token': refresh_token})
    except Exception as e:
        return jsonify({'error': '登录出错'}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=1845)
```
Assistant:
Assistant: