# Source: https://gitee.com/yangro/ql/blob/main/utils/getCookie.py
# Raw: https://gitee.com/yangro/ql/raw/main/utils/getCookie.py
# Repo: yangro/ql
# Path: utils/getCookie.py
# UploadedAt: 2023-10-25T14:45:53+08:00
# SHA256: 153cd6f59fa7cbea00fe2909c7ff135afaa9c1938dcc12bc95dcf081812a7666
# Category: APP版/抓包
# Evidence: cookie/token/authorization/header

'''
获取青龙面板环境变量
'''
import os
import requests


class GetQlEnvs:
    def __init__(self):
        try:
            port = os.environ["QL_PORT"]
            client_id = os.environ["QL_CLIENT_ID"]
            client_secret = os.environ["QL_CLIENT_SECRET"]
            if (port != '' and client_id != '' and client_secret != ''):
                self.qlUrl = "127.0.0.1:" + port
                self.client_id = client_id
                self.client_secret = client_secret
                self.flag = True
                self.getQlToken()
            else:
                print("配置不能为空")
                self.flag = False
        except Exception as e:
            print("config.sh 配置文件缺少配置!")
            self.flag = False

    # 获取青龙token
    def getQlToken(self):
        try:
            res = requests.get("http://"+self.qlUrl+"/open/auth/token?client_id="+self.client_id+"&client_secret="+self.client_secret).json()
            self.qlToken = res['data']['token']
        except Exception:
            print("配置文件有误")
        

    # 获取指定环境变量
    def getCookies(self, key):
        cookies = []
        if (self.flag == False):
            return cookies
        headers = {
            'Authorization': "Bearer " + self.qlToken
        }
        json = requests.get(
            "http://"+self.qlUrl+"/open/envs?searchValue=&t=1673152342396", headers=headers).json()

        if (json['code'] == 200):
            for data in json['data']:
                if (data['status'] == 0 and data['name'] == key):
                    cookies.append(
                        {'cookie': data['value'], 'name': data['remarks']})

        return cookies
