# Path: src/utils/tool.py
# class DO(dict):
#     def __getattr__(self, name):
# def ip_check(ip):
# def email_check(email):
# def ParseMySQL(mysql, callback="dict"):
# def UploadImage2Upyun(FilePath, FileData, kwargs=PLUGINS['UpYunStorage']):
# def UploadRealFile2Upyun(file, imgurl, kwargs=PLUGINS['UpYunStorage']):
# def BaiduActivePush(pushUrl, original=True, callUrl=PLUGINS['BaiduActivePush']['callUrl']):
# def ChoiceColor():
# def TagRandomColor():
# def getIpArea(ip):
# def getIpArea2(ip):
# def get_current_timestamp():
# def timestamp_after_timestamp(timestamp=None, seconds=0, minutes=0, hours=0, days=0):
# def timestamp_to_timestring(timestamp, format='%Y-%m-%d %H:%M:%S'):
# def url_check(addr):
# def sql_safestring_check(string):
# def formatSize(bytes):
# def make_zipfile(zip_filename, zip_path, exclude=[]):
# def str_count(str):
#         M = kb / 1024
#             G = M / 1024
# 
# Path: src/utils/send_email_msg.py
# class SendMail(object):
#     """发送邮件类"""
# 
#     def __init__(self):
#         self.useraddr = EMAIL["useraddr"]
#         self.password = EMAIL["userpass"]
#         self.smtp_server = EMAIL["smtpServer"]
#         self.smtp_port = EMAIL["smtpPort"]
#         self.smtp_ssl = True if EMAIL["smtpSSL"] in ("true", "True", True) else False
#         self.from_addr = self._format_addr("SaintIC EauDouce <{}>".format(self.useraddr))
# 
#     def _format_addr(self, s):
#         name, addr = parseaddr(s)
#         return formataddr((Header(name, 'utf-8').encode(), addr))
# 
#     def SendMessage(self, to_addr, subject, message, formatType="plain"):
#         """
#         发送文本/HTML消息
#         @param to_addr(str, unicode, list, tuple) 收件人地址，多个收件人请使用列表或元组
#         @param subject(str, unicode) 主题
#         @param message(str, unicode) 邮件正文
#         @param formatType(str, unicode)  邮件格式类型 plain或html
#         """
#         res = dict(success=False)
#         if subject and message and isinstance(subject, (str, unicode)) and isinstance(message, (str, unicode)) and isinstance(to_addr, (str, unicode, list, tuple)):
#             if isinstance(to_addr, (str, unicode)):
#                 to_addrs = (to_addr,)
#             else:
#                 to_addrs = to_addr
#             msg = MIMEText(message, formatType, 'utf-8')
#             msg['From'] = self.from_addr
#             msg['To'] = to_addr
#             msg['Subject'] = Header(subject, 'utf-8').encode()
#             try:
#                 if self.smtp_ssl is True:
#                     server = smtplib.SMTP_SSL(self.smtp_server, port=self.smtp_port)
#                 else:
#                     server = smtplib.SMTP(self.smtp_server, port=self.smtp_port)
#                 # server.set_debuglevel(1)
#                 server.login(self.useraddr, self.password)
#                 server.sendmail(self.useraddr, to_addrs, msg.as_string())
#                 server.quit()
#             except smtplib.SMTPException, e:
#                 logger.sys.error(e, exc_info=True)
#                 res.update(msg="Mail delivery failed, please try again later")
#             else:
#                 res.update(success=True)
#         else:
#             res.update(msg="Bad mailbox format")
#         logger.sys.debug(res)
#         return res


import os, sys, time, shutil, requests
from .tool import logger, getIpArea, get_current_timestamp, get_today, make_zipfile, formatSize, email_check
from .send_email_msg import SendMail
from libs.base import ServiceBase
from user_agents import parse as user_agents_parse
from multiprocessing.dummy import Pool as ThreadPool
    Queue function.

    :copyright: (c) 2017 by Mr.tao.
    :license: Apache2.0, see LICENSE for more details.
"""
reload(sys)
sys.setdefaultencoding('utf-8')

_sb = ServiceBase()

def Click2MySQL(data):
    if isinstance(data, dict):
        if "/rqdashboard" in data.get("url") or "/static/" in data.get("url"):
            return
        if data.get("agent"):
            # 解析User-Agent
            uap = user_agents_parse(data.get("agent"))
            browserDevice, browserOs, browserFamily = str(uap).split(' / ')
            if uap.is_mobile:
                browserType = "mobile"
            elif uap.is_pc:
                browserType = "pc"
            elif uap.is_tablet:
                browserType = "tablet"
            elif uap.is_bot:
                browserType = "bot"
            else:
                browserType = "unknown"
            sql = "insert into blog_clicklog set url=%s, ip=%s, agent=%s, method=%s, status_code=%s, referer=%s, isp=%s, browserType=%s, browserDevice=%s, browserOs=%s, browserFamily=%s, clickTime=%s"
            try:

# Path: src/utils/tool.py
# class DO(dict):
#     def __getattr__(self, name):
# def ip_check(ip):
# def email_check(email):
# def ParseMySQL(mysql, callback="dict"):
# def UploadImage2Upyun(FilePath, FileData, kwargs=PLUGINS['UpYunStorage']):
# def UploadRealFile2Upyun(file, imgurl, kwargs=PLUGINS['UpYunStorage']):
# def BaiduActivePush(pushUrl, original=True, callUrl=PLUGINS['BaiduActivePush']['callUrl']):
# def ChoiceColor():
# def TagRandomColor():
# def getIpArea(ip):
# def getIpArea2(ip):
# def get_current_timestamp():
# def timestamp_after_timestamp(timestamp=None, seconds=0, minutes=0, hours=0, days=0):
# def timestamp_to_timestring(timestamp, format='%Y-%m-%d %H:%M:%S'):
# def url_check(addr):
# def sql_safestring_check(string):
# def formatSize(bytes):
# def make_zipfile(zip_filename, zip_path, exclude=[]):
# def str_count(str):
#         M = kb / 1024
#             G = M / 1024
# 
# Path: src/utils/send_email_msg.py
# class SendMail(object):
#     """发送邮件类"""
# 
#     def __init__(self):
#         self.useraddr = EMAIL["useraddr"]
#         self.password = EMAIL["userpass"]
#         self.smtp_server = EMAIL["smtpServer"]
#         self.smtp_port = EMAIL["smtpPort"]
#         self.smtp_ssl = True if EMAIL["smtpSSL"] in ("true", "True", True) else False
#         self.from_addr = self._format_addr("SaintIC EauDouce <{}>".format(self.useraddr))
# 
#     def _format_addr(self, s):
#         name, addr = parseaddr(s)
#         return formataddr((Header(name, 'utf-8').encode(), addr))
# 
#     def SendMessage(self, to_addr, subject, message, formatType="plain"):
#         """
#         发送文本/HTML消息
#         @param to_addr(str, unicode, list, tuple) 收件人地址，多个收件人请使用列表或元组
#         @param subject(str, unicode) 主题
#         @param message(str, unicode) 邮件正文
#         @param formatType(str, unicode)  邮件格式类型 plain或html
#         """
#         res = dict(success=False)
#         if subject and message and isinstance(subject, (str, unicode)) and isinstance(message, (str, unicode)) and isinstance(to_addr, (str, unicode, list, tuple)):
#             if isinstance(to_addr, (str, unicode)):
#                 to_addrs = (to_addr,)
#             else:
#                 to_addrs = to_addr
#             msg = MIMEText(message, formatType, 'utf-8')
#             msg['From'] = self.from_addr
#             msg['To'] = to_addr
#             msg['Subject'] = Header(subject, 'utf-8').encode()
#             try:
#                 if self.smtp_ssl is True:
#                     server = smtplib.SMTP_SSL(self.smtp_server, port=self.smtp_port)
#                 else:
#                     server = smtplib.SMTP(self.smtp_server, port=self.smtp_port)
#                 # server.set_debuglevel(1)
#                 server.login(self.useraddr, self.password)
#                 server.sendmail(self.useraddr, to_addrs, msg.as_string())
#                 server.quit()
#             except smtplib.SMTPException, e:
#                 logger.sys.error(e, exc_info=True)
#                 res.update(msg="Mail delivery failed, please try again later")
#             else:
#                 res.update(success=True)
#         else:
#             res.update(msg="Bad mailbox format")
#         logger.sys.debug(res)
#         return res


# Path: src/utils/qf.py
import os, sys, time, shutil, requests
from .tool import logger, getIpArea, get_current_timestamp, get_today, make_zipfile, formatSize, email_check
from .send_email_msg import SendMail
from libs.base import ServiceBase
from user_agents import parse as user_agents_parse
from multiprocessing.dummy import Pool as ThreadPool

    Queue function.

    :copyright: (c) 2017 by Mr.tao.
    :license: Apache2.0, see LICENSE for more details.
"""
reload(sys)
sys.setdefaultencoding('utf-8')

_sb = ServiceBase()

def Click2MySQL(data):
    if isinstance(data, dict):
        if "/rqdashboard" in data.get("url") or "/static/" in data.get("url"):
            return
        if data.get("agent"):
            # 解析User-Agent
            uap = user_agents_parse(data.get("agent"))
            browserDevice, browserOs, browserFamily = str(uap).split(' / ')
            if uap.is_mobile:
                browserType = "mobile"
            elif uap.is_pc:
                browserType = "pc"
            elif uap.is_tablet:
                browserType = "tablet"
            elif uap.is_bot:
                browserType = "bot"
            else:
                browserType = "unknown"
            sql = "insert into blog_clicklog set url=%s, ip=%s, agent=%s, method=%s, status_code=%s, referer=%s, isp=%s, browserType=%s, browserDevice=%s, browserOs=%s, browserFamily=%s, clickTime=%s"
            try:

                mid = _sb.mysql_write.insert(sql, data.get("url"), data.get("ip"), data.get("agent"), data.get("method"), data.get("status_code"), data.get("referer"), getIpArea(data.get("ip")), browserType, browserDevice, browserOs, browserFamily, get_current_timestamp())