import requests
import json
import time
import subprocess

url = 'https://api.flextv.co.kr/api/channels/live-list-main?includeAdult=false&liveOption=viewer'

# 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 f:
        lines = [line.strip() for line in f]
    return lines


def writeList(file_path, bj_list):
    with open(file_path, 'w') as f:
        for bj in bj_list:
            f.write(bj + '\n')


def getFanList(url):
    new_list = []
    response = requests.get(url=url)
    if response.status_code == 200:
        content = response.json()
        for bj in content['data']:
            if bj['barrier']['minRatingLevel'] != 0:
                new_list.append(bj['owner']['loginId'])
        return new_list
    else:
        return []

def main():
    date = time.strftime('%H:%M', time.localtime())
    file_path = '/home/uftp/flfanlist.txt'
    fan_list = readList(file_path)
    new_list = getFanList(url)
    for bj in new_list:
        if bj not in fan_list:
            text = f'# {date}\n #Flex_new\n- {bj}'
            send_message('Bookmark-new', text)
    writeList(file_path, new_list)
    #----------------添加到crontab里--------------------
    job = subprocess.getoutput('crontab -l | grep getwinktv')
    if 'getxfan' not in job:
        subprocess.getstatusoutput('( crontab -l | grep -v getxfan) | crontab - && (crontab -l | cat; echo "*/4 * * * * python3 /home/uftp/getxfan.py >/dev/null 2>&1") | crontab -')


if __name__ == '__main__':
    main()
