#coding: utf-8
# +-------------------------------------------------------------------
# | 宝塔Windows面板
# +-------------------------------------------------------------------
# | Copyright (c) 2015-2020 宝塔软件(https://www.bt.cn) All rights reserved.
# +-------------------------------------------------------------------
# | Author: 沐落 <cjx@bt.cn>
# +-------------------------------------------------------------------
import sys,os,time,json,re
panelPath = os.getenv('BT_PANEL')
os.chdir(panelPath);
sys.path.append("class/")
import public,db,time,html,panelPush

try:
    from BTPanel import cache
except :
    from cachelib import SimpleCache
    cache = SimpleCache()

class panel_push:

    __push = None
    def __init__(self):
        self.__push = panelPush.panelPush()

    #-----------------------------------------------------------start 添加推送 ------------------------------------------------------
    def get_version_info(self,get):
        """
        获取版本信息
        """
        data = {}
        data['ps'] = ''
        data['version'] = '1.0'
        data['date'] = '2020-08-10'
        data['author'] = '宝塔'
        data['help'] = 'http://www.bt.cn/bbs'
        return data

    """
    @获取推送模块配置
    """
    def get_module_config(self,get):

        data = []

        item = self.__push.format_push_data(push = ['dingding','weixin','wx_account'],project = 'ssl',type = 'ssl')
        item['cycle'] = 30
        item['title'] = 'SSL到期提醒'        
        item['helps'] = ['SSL到期提醒一天只发送一次','证书夹内【剩余天数不足30天】的所有证书.']
        data.append(item)
   
        item = self.__push.format_push_data(push = ['dingding','weixin'],project = 'endtime',type = 'endtime')
        item['cycle'] = 5
        item['title'] = '专业版/企业版到期提醒'   
        item['helps'] = ['每个账号每天只允许提醒一次.','到期提醒不扣除短信条数且一天只允许推送一次']
        data.append(item)

        services = [ 'IIS','nginx','apache',"FTP服务端","SQL Server",'mysql','php-fpm','memcached','redis','MongoDB','other']
        for x in services:
            item = {}                       
            item['project'] = x
            item['title'] = '{}服务停止通知'.format(x)       
            if x == 'other':
                item['title'] = '自定义服务停止通知'
            else:
                ser_name = self.__get_service_name(x)
                if public.get_server_status(ser_name) == -1: continue   

            item['type'] = 'services'
            item['keys'] = []
            item['interval'] = 300
            for x in ['stop']:
               item['keys'].append({'key':x,'val':'停止'})
        
            item['push'] = ['dingding','weixin','sms','wx_account']   
            item['helps'] = ['部分服务停止可能会造成业务中断.','短信推送需提前购买，如需购买请联系[<a href="http://q.url.cn/CDfQPS?_type=wpa&amp;qidian=true" target="_blank" class="btlink">宝塔客服</a>]']
            data.append(item)
        return data


    def get_push_cycle(self,data):
        """
        @获取执行周期
        """
        result = {}
        for skey in data:
            result[skey] = data[skey]

            m_cycle =[]                
            m_type = data[skey]['type']       
            if m_type in ['endtime','ssl']:
                m_cycle.append('剩余{}天时，每天1次'.format(data[skey]['cycle'])) 
            elif m_type in ['services']:
                m_cycle.append('服务停止时，每{}秒1次'.format(data[skey]['interval']))                 
            if len(m_cycle) > 0: 
                result[skey]['m_cycle'] = ''.join(m_cycle)
        return result

    #-----------------------------------------------------------end 添加推送 ------------------------------------------------------
    """
    @获取服务真实名称
    """
    def __get_service_name(self,name):
        slist = {"IIS":'W3SVC',"FTP服务端":'FileZilla Server',"SQL Server":"MSSQLSERVER"}
        if name in slist: name = slist[name]

        return name
    """
    @获取推送栏目
    """
    def get_total(self):        
        return True;

    def get_push_data(self,data,total):   
        if data['type'] == 'services':
            ser_name =  data['project']        
            ser_name = self.__get_service_name(ser_name)

            status = public.get_server_status(ser_name)
            if status > 0:  
                return public.returnMsg(False,"状态正常，跳过.")
            else:
                if status == 0:
                    return self.__get_service_result(data)
                return public.returnMsg(False,"服务未安装，跳过.")        

        elif data['type'] in ['ssl']:
            
            if time.time() < data['index'] + 86400:
                return public.returnMsg(False,"一天推送一次，跳过.")          
                
            import panelSSL
            ssl = panelSSL.panelSSL()
            clist = []
            for x in ssl.GetCertList(None):
                endtime = ssl.get_unixtime(x['notAfter'],'%Y-%m-%d')
                day = int((endtime - time.time()) / 86400)
                if day > data['cycle']: continue                    
                clist.append(x)

            return self.__get_ssl_result(data,clist)

        elif data['type'] in ['endtime']:
            if time.time() < data['index'] + 86400:
                return public.returnMsg(False,"一天推送一次，跳过.")    

            import panelPlugin
            get = public.dict_obj()
            get.force = 1
            softs = panelPlugin.panelPlugin().get_cloud_list(get)
            if softs['pro'] == 0: return public.returnMsg(False,"永久专业版，跳过.")    
       
            if softs['ltd'] == -2 and softs['pro'] == -2:
                pass
            else:
                pro_data = {}
                if softs['ltd'] > 0:
                    pro_data['endtime'] = softs['ltd']
                    pro_data['name'] = "Windows企业版"
                    pro_data['affect'] = '全部企业版插件'
                elif softs['pro'] > 0:
                    pro_data['endtime'] = softs['pro']
                    pro_data['name'] = "Windows专业版"
                    pro_data['affect'] = '全部专业版插件'

                pro_data['day'] = int((pro_data['endtime'] - time.time()) / 86400)
                
                if pro_data['day'] <= data['cycle']:
                    return self.__get_ltd_result(data,pro_data)

        return public.returnMsg(False,"未达到阈值，跳过.")

    """
    @企业版到期提醒
    """
    def __get_ltd_result(self,data,pro_data):
        result = {'index':time.time()}

        for m_module in data['module'].split(','):
            result[m_module] = self.__push.format_msg_data()
            if m_module in ['sms']:
                pass
            else:            
                result[m_module]['msg'] = "".join((
                    "#### 宝塔面板业务到期提醒\n\n",
                    ">服务器 ："+ public.GetLocalIp() +"\n\n ",
                    ">剩余天数：<font color=#ff0000>"+ str(pro_data['day'] + 1) +" 天</font>\n\n",
                    ">到期产品："+ pro_data['name'] +"\n\n",
                    ">到期时间："+ public.format_date(times =pro_data['endtime']) +"\n\n",
                    ">影响业务："+ pro_data['affect'] +"\n\n",
                    ">通知时间：" + public.format_date() + "\n\n"))    
        return result

    """
    @ssl到期返回
    """
    def __get_ssl_result(self,data,clist):
        if len(clist) == 0: 
            return public.returnMsg(False,"未找到到期证书，跳过.")            

        result = {'index':time.time() }
        for m_module in data['module'].split(','):

            if m_module in ['sms']:
                pass
            else:           
                result[m_module] = self.__push.format_msg_data()
                
                p_msg = ""
                for x in clist: p_msg+= "  到期：{}  域名：{}\n\n".format(x['notAfter'],x['subject'])

                result[m_module]['msg'] ="".join((
                    "#### 宝塔面板SSL到期提醒\n\n",
                    ">服务器 ："+ public.GetLocalIp() +"\n\n ",
                    ">检测时间：" + public.format_date() +"\n\n",
                    ">即将到期：<font color=#ff0000>"+ str(len(clist)) +" 张</font>\n\n",
                    p_msg))
        return result

    """
    @服务停止返回
    """
    def __get_service_result(self,data):  
        
        s_idx = int(time.time())
        if s_idx < data['index'] + data['interval']: 
            return public.returnMsg(False,"未达到间隔时间，跳过.")        
            
        result = {'index':s_idx}
        
        for m_module in data['module'].split(','):    
            result[m_module] = self.__push.format_msg_data()
            if m_module in ['mail']:
                pass            
            elif m_module in ['sms']:     
                result[m_module]['sm_type'] = 'servcies'
                result[m_module]['sm_args'] = { 'name':'{}'.format(public.get_push_title()), 'product':data["project"],'product1':data["project"]}
            else:  
                m_list = [">服务类型：" + data["project"] ,'>服务状态：<font color=#ff0000>已停止</font>']
                try:
                   msg = public.get_push_info("堡塔服务停止告警",m_list)['msg'] 
                except :
                    m_list.insert(0,'#### 堡塔服务停止告警')
                    msg = '\n\n'.join(m_list)
                
                result[m_module]['msg'] = msg
        return result



