import json
import requests
import random
import urllib.request
import re


def headers_str_to_dict(headers):
    headers_dict = {}
    for line in headers.split('\n'):
        if ':' in line:
            key, value = re.split(':|=', line.strip(), maxsplit=1)
            headers_dict[key.strip()] = value.strip()
    return headers_dict


def get_request(url, headers):
    # 假设 IP 池已经包含了多个代理 IP 地址
    proxy_list = ['http://127.0.0.1:8888']
    # 随机选择一个代理 IP 地址进行请求
    proxies = {"http": random.choice(proxy_list)}
    proxies = urllib.request.getproxies()
    if proxies == {'http': 'http://127.0.0.1:8888', 'https': 'https://127.0.0.1:8888'}:
        proxies = {
            'http': 'http://127.0.0.1:8888',
            'https': 'http://127.0.0.1:8888'  # https -> http
        }
    res = requests.get(url, headers=headers, proxies=proxies, verify=False, timeout=1)
    content_type = res.headers['Content-Type']
    if 'image' in content_type:
        # 返回图片内容
        return res.content
    else:
        # 返回文本内容
        return res.text


def post_request(url, headers, data):
    # 假设 IP 池已经包含了多个代理 IP 地址
    proxy_list = ['http://127.0.0.1:8888']
    # 随机选择一个代理 IP 地址进行请求
    proxies = {"http": random.choice(proxy_list)}
    proxies = urllib.request.getproxies()
    if proxies == {'http': 'http://127.0.0.1:8888', 'https': 'https://127.0.0.1:8888'}:
        proxies = {
            'http': 'http://127.0.0.1:8888',
            'https': 'http://127.0.0.1:8888'  # https -> http
        }

    res = requests.post(url, headers=headers, data=data, proxies=proxies, verify=False, timeout=1)
    content_type = res.headers['Content-Type']
    if 'image' in content_type:
        # 返回图片内容
        return res.content
    else:
        # 返回文本内容
        return res.text


_method = '{{{method}}}'

_headers_str = '''
{{{headers_str}}}
'''
_headers_dict = headers_str_to_dict(_headers_str)

_post_data_string = ''

# 自动生成的代码，设置的新值会当作变量传入url
_url = '{{{url}}}'

if _method == 'POST':
    _post_data_string = '''{{{post_data_string}}}'''
    if _post_data_string.startswith('{') or _post_data_string.startswith('['):
        data = json.loads(_post_data_string)
        _post_data_string = json.dumps(data)
    response = post_request(_url, _headers_dict, _post_data_string)
else:
    response = get_request(_url, _headers_dict)

print(response)

import uuid
import os
import sqlite3

_guid = str(uuid.uuid4())


# 2：连接基础数据库【CXT.RPA.db】
def Guid2DB(guid, url, headers, postData, body):
    print(os.getenv("PROGRAMDATA") + r"\CXT.RPA\CXT.RPA.db")
    conn = sqlite3.connect(os.getenv("PROGRAMDATA") + r"\CXT.RPA\CXT.RPA.db", timeout=10)
    cursor = conn.cursor()
    # 3：根据参数GUID查询【ListenUrlRunLog】表中的【请求地址】，【数据请求头】，【请求返回数据】
    insert_tb_cmd = f"insert into ListenUrlRunLog(guid,url,headers,postData,body) values('{guid}','{url}','{headers}','{postData}','{body}')"
    print(insert_tb_cmd)
    # results = cursor.execute(insert_tb_cmd)

    # cursor.execute("insert into ListenUrlRunLog(guid) values (?)", (guid))
    results = cursor.execute("insert into ListenUrlRunLog(guid,url,headers,postData,body) values(?, ?, ?, ?, ?);",
                             (guid, url, headers, postData, body))
    conn.commit()
    # r = cursor.execute(f"SELECT url,headers,postData,body FROM ListenUrlRunLog where guid='{guid}'").fetchall()
    r = cursor.execute(f"SELECT * FROM ListenUrlRunLog where guid='{guid}'").fetchall()
    conn.close()
    url2 = (r[0][0])

    cmd = r'"{{{Guid2DB.exe}}}" ' + guid
    res = os.popen(cmd)
    output_str = res.read()
    print(output_str)


Guid2DB(_guid, _url, _headers_str, _post_data_string, response)
