import re
import json
import requests
import subprocess


# Ding !!!!!
def send_message(title, text):
# 请求的URL，WebHook地址
        webhook = 'https://oapi.dingtalk.com/robot/send?access_token=4b8e7de0defb55fdf001b6c928b258512f9af6ebbb565713e834c97d7f81f730'
        #构建请求头部
        header = {
                'Content-Type': 'application/json',
                'Charset': 'UTF-8'
        }
        message = {
                'msgtype': 'markdown',
                'markdown': {
                        'title': title,
                        'text': text
                }
        }

        message = json.dumps(message)

        info = requests.post(url=webhook,data=message,headers=header)



def readList(file_path):
    with open(file_path, 'r') as file:
        bj_list = json.load(file)
        return bj_list


def writeList(file_path, bj_list):
    with open(file_path, 'w') as file:
        json.dump(bj_list, file, indent=4)


def matchUrl(url):
    pattern = r'GROUP-ID="720.*\n.*\n(https?://[^\s]+)'
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
        "Origin": "https://www.pandalive.co.kr",
    }
    response = requests.get(url=url, headers=headers)
    if response.status_code == 200:
        content = response.text
        match = re.search(pattern, content)
        if match:
            url = match.group(1)
            return url
    else:
        return ''


def autoRecNormal(name, url):
    subprocess.getstatusoutput(f'bash /home/uftp/nrkawai.sh {name} {url}')



def main():
    bj_list = readList('/home/uftp/lazy_list.json')
    playlist = {}
    for name, value in bj_list.items():
        if value['address']:
            url = matchUrl(value['address'])
            playlist[name] = url
            autoRecNormal(name, url)
        else:
            text = f'# {name}'
            send_message('Start Error', text)
    writeList('/home/uftp/bj_playlist.json', playlist)
    subprocess.getstatusoutput('rm /home/uftp/lazy_list.json')
    subprocess.getstatusoutput('echo "bash ~/rekill.sh" | at -M now + 100minutes')
    # subprocess.getstatusoutput('echo "python3 ~/tokill.py" | at -M now + 100minutes') # 只通知，避免同时kill掉粉丝房的录制

if __name__ == '__main__':
    main()
