#!/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 = [
        'yiyufun.com',
        'wlwysig.com',
    ]

    # 以下这个字典,是为了接口查询不了的时候,来调用
    domain_expire_dict = {
        "yiyufun.com": "2025-04-16 00:00:01",
        "wlwysig.com": "2026-04-17 00:00:01",
    }

    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(int(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()

