#coding: utf-8
# +-------------------------------------------------------------------
# | 宝塔Windows面板
# +-------------------------------------------------------------------
# | Copyright (c) 2015-2020 宝塔软件(http://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 win2ban_push:

    name = 'win2ban' 
    __pids = { 4624:"服务器登录成功",4625:"服务器登录失败",4720:"创建用户",4722:"启用用户",4738:"更改用户",4724:"重置密码",4732:"添加用户组",4733:"删除用户组",4726:"删除用户",4731:"创建用户组",4735:"启用用户组",4725:"禁用用户",4740:"锁定用户",4739:"更改用户锁定策略" }
    __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-07-14'
        data['author'] = '宝塔'
        data['help'] = 'http://www.bt.cn'
        return data

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

        data = []                  
        for skey in self.__pids:
            item = {}
       
            item['project'] = str(skey)
            item['title'] = '{}告警'.format(self.__pids[skey])
            item['type'] = 'win2ban'
            item['keys'] = []            
            
            if skey == 4625:                
                item['count'] = 5
                item['cycle'] = 60

            item['push'] = ['dingding','weixin']           
            item['interval'] = 600
            item['helps'] = ['注意：此功能需购买企业版后使用']
            data.append(item)
                
        return data


    #-----------------------------------------------------------end 添加推送 ------------------------------------------------------


    """
    @格式化数据  
    @total 统计数据
    @return  {"title":"宝塔面板","msg":"测试推送","to_email":"","sms_type":"","sms_argv":""}
    """
    def get_push_data(self,conf,total):
        if conf['module'] in ['sms']: 
            return public.returnMsg(False,"暂不支持模板，跳过.")            
        
        index = 0
        if 'index' in conf: index = conf['index']            

        start_time = int(time.time()) - conf['cycle']

        sql = db.Sql().dbfile('win2ban')
        count = sql.table('logs').where("pid=? and addtime>=? and id>?",(conf['project'],start_time,index,)).count()

        if count >= conf['count']:          
            return self.__get_result(conf,count)
        return public.returnMsg(False,"未达到阈值，跳过.")


    def get_total(self):        
        return True;

    def _set_push_config(self,module,data):
        pass

    """
    @格式化返回
    """
    def __get_result(self,data,count):
        sql = db.Sql().dbfile('win2ban') 
        find = sql.table('logs').where("pid=?",(data['project'],)).order("id desc").find()

        result = {
            'status':True,
            'msg':'触发拦截',
            'index':find['id'],
            'data':{
                  'title':data['title'],
                  'to_email':'',
                  'sms_type':'',
                  'sms_argv':{},
                  'title':data['title'],
                  'msg':'您的项目[{}] {}秒内触发了{}次拦截'.format(data['project'],data['cycle'],count)
            }
        }              
       
        for m_module in data['module'].split(','): 
            if m_module in ['dingding','weixin']: 
                result[m_module] = self.__push.format_msg_data()

                m_list = ['>触发周期：{} 秒 '.format(data['cycle'])]     
                if data['project'] in ['4624']: m_list = ['>登录地址：{}'.format(find['ip'])]

                m_list.append(">触发次数：<font color=#ff0000>" + str(count)+" 次</font>\n\n")
                m_list.append(">操作类型：" + self.__pids[int(data['project'])])
                try:
                    msg = public.get_push_info('堡塔防爆破告警提醒',m_list)['msg']
                except:
                    m_list.append(">服务器 ："+ public.GetLocalIp())
                    m_list.append(">最新时间：" + public.format_date(times=find['addtime']))
                    m_list.insert(0,"#### 堡塔防爆破告警提醒")

                    msg = "\n\n".join(m_list);
                
                result[m_module]['msg'] = msg


        return result