#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time    : 2017/8/23 14:50
# @Author  : WYM

import whois
import time
import os
import json
import requests


# 时间格式转换成timestamp
def time_to_timestamp(datestring):
    """
    datestring: 2018-01-01 00:00:00
    """
    # 转换为数组
    timeArray = time.strptime(datestring, '%Y-%m-%d %H:%M:%S')
    # 转换为时间戳
    timestamp = int(time.mktime(timeArray))

    return timestamp


# 获取过期时间
def get_expire_time(domainname):
    try:
        print('whois get')
        expiration_date = whois.whois(domainname)['expiration_date']
        if isinstance(expiration_date, list):
            expire_date = time_to_timestamp(str(expiration_date[0]))
        else:
            expire_date = time_to_timestamp(str(expiration_date))
    except:
        try:
            print('api get')
            url = 'http://api.91cha.com/whois?key=%s&host=%s' % (secret_key, domainname)
            #url = 'http://api.jisuapi.com/whois/query?appkey=%s&domain=%s' % (secret_key, domainname)
            headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'}
            request = requests.get(url, headers=headers)
            result = request.json()
            if isinstance(result, dict) and result.has_key('state') == 1:
                expire_date = time_to_timestamp(str(result['data']['expiretime']) + ' 00:00:00')
            else:
                expire_date = time.time()
        except:
            expire_date = time_to_timestamp(domain_expire_dict[domainname])

    return int(expire_date)


# 计算域名过期时间和现在的时间还有多少天
def calc_expire_date(domainname):
    diff = get_expire_time(domainname) - int(time.time())
    return int(diff) / 60 / 60 / 24


if __name__ == '__main__':
    # API的key
    secret_key = '3279756f38b44e3cb6d280dec0affa48'
    #secret_key = '35cb860a607f4c8c'

    # 需要监控的域名
    monotor_domain = [
        'yundyx.com',
        'jingyoufun.com',
        'hugenstar.org',
        'ihugenstar.com',
        'hugenstar.com',
        'hugenstar.net',
        'hugenstar.cn',
        'sg2d.cn',
        'sg2d.net',
        'sg2d.com',
        'sg2d.org',
        'vxinyou.org',
        'vxinyou.net',
        'vxinyou.com',
        'timebox.cn',
        'bnngame.org',
        'bnngame.com',
        'vxytech.com',
        'thdim.com',
        'sxscience.com',
        'flashpe.com',
        'cotaut.com',
        'shkuoyou.com',
        'vzidou.com'
    ]

    # 以下这个字典,是为了接口查询不了的时候,来调用
    domain_expire_dict = {
        "vzidou.com": "2022-8-29 14:06:38",
        "vxytech.com": "2019-11-20 4:06:09",
        "thdim.com": "2019-11-20 4:06:07",
        "sxscience.com": "2019-11-20 4:06:04",
        "flashpe.com": "2019-11-20 4:06:02",
        "cotaut.com": "2019-11-20 4:05:59",
        "bnngame.com": "2020-10-9 10:55:44",
        "bnngame.org": "2020-10-9 10:55:36",
        "yundyx.com": "2022-4-6 12:09:01",
        "shkuoyou.com": "2021-10-14 18:10:31",
        "ihugenstar.com": "2022-2-24 19:00:07",
        "vxinyou.net": "2020-4-17 16:16:06",
        "vxinyou.org": "2020-4-17 0:00:00",
        "vxinyou.com": "2024-3-18 0:50:27",
        "hugenstar.org": "2021-12-21 17:42:29",
        "hugenstar.com": "2020-12-21 16:46:57",
        "hugenstar.net": "2020-12-21 16:46:34",
        "hugenstar.cn": "2020-12-21 0:00:00",
        "sg2d.net": "2019-11-12 14:46:43",
        "sg2d.com": "2019-11-12 14:46:38",
        "sg2d.org": "2019-11-12 0:00:00",
        "sg2d.cn": "2019-11-12 0:00:00",
        "timebox.cn": "2020-3-12 0:00:00"
    }

    data_file = os.path.join(os.path.split(os.path.realpath(__file__))[0], 'monitor.txt')

    # 最外层字典
    data = {}
    list_data = []
    for domain in monotor_domain:
        print(domain)
        sub_dict = {}
        sub_dict['{#DOMAINNAME}'] = domain
        sub_dict['{#EXPIREDATE}'] = str(calc_expire_date(domain))
        list_data.append(sub_dict)
        # time.sleep(10)

    data['data'] = list_data

    # 先把字典dump成string,再写入到文件里面去
    with open(data_file, 'w') as f:
        f.write(json.dumps(data))
        f.flush()
        f.close()

