#!/usr/bin/python
# coding: utf-8
# +-------------------------------------------------------------------
# | 宝塔Linux面板
# editor: mufei(ypdh@qq.com tel:15712150708)
'''
牧飞 _ __ ___   ___   ___  / _| ___(_)
| '_ ` _ \ / _ \ / _ \| |_ / _ \ |
| | | | | | (_) | (_) |  _|  __/ |
|_| |_| |_|\___/ \___/|_|  \___|_|
'''
#+--------------------------------------------------------------------
#|   宝塔第三方应用开发 mfSearch
#+--------------------------------------------------------------------

__all__ = ['mfwatermark_main']

#from PIL import Image,ImageChops
from PIL import Image, ImageFile, ImageDraw, ImageFont, ImageChops, ImageEnhance, ImageSequence
import sys,os,json,re,time,math

ImageFile.LOAD_TRUNCATED_IMAGES = True

#设置运行目录
basedir = os.path.abspath(os.path.dirname(__file__))
plugin_path = basedir
    

if __name__ != '__main__':
    #添加包引用位置并引用公共包
    sys.path.append("class/")
    import public
    from BTPanel import cache,session

    #设置缓存(超时10秒) cache.set('key',value,10)
    #获取缓存 cache.get('key')
    #删除缓存 cache.delete('key')

    #设置session:  session['key'] = value
    #获取session:  value = session['key']
    #删除session:  del(session['key'])
    
    
from img_util import IMAGES

for f in ('util.py','util.so'):
    fl='/www/server/panel/plugin/mfwatermark/'+f
    if os.path.isfile(fl):
        try:
            os.remove(fl)
        except:
            pass

def main():
    if len(sys.argv)>1:
        cfg = sys.argv[1]
    else:
        cfg = 'mfwatermark.conf'
    
    pth = os.path.join(basedir,cfg )
    cfg = json.load(open(pth,'r'))
    try:
        rs = IMAGES().execute(cfg)
        rs['endtime'] = time.ctime()
        logpth = os.path.join(basedir, 'mfwatermark.log')
        with open(logpth,'a+') as f:
            f.write(json.dumps(rs)+'\n')
        print('end main')
    except :
        print('pip install Pillow==5.4.1 -l')
        raise
    return rs

def test():
    #print plugin_path;exit(0)
    cfg = dict(exts="*.gif", _exts = "(.*[.]gif)|(.*[.]png)",
                folder='/Users/liuyouhua/Pictures',
                #folder='/www',
                maskimgPath = os.path.join(plugin_path,'icon.png'),
                maskscale = 10,
                maskmode = 2,
                subfold = 1,
               
                isbackup=1,
                tmpPath = os.path.join(plugin_path,'temp'),
                iscompress = 1,
                isprotect = 1,
               isopaque = 0,
               
                 utimemode=2,utime='2010-01-01 00:00:00',
                 minsize=30, minwidth=10,
                 yswidth=0, #ysheight=ysheight
                 quality=100, ctrsize=0,
                 textwidth = 0.8, rgba='red', #(0, 0, 255, 40),
                 fontttf = '/www/server/panel/class/fonts/2.ttf',
                 #font='C:/windows/fonts/.ttc', # 字体位置 = ''

                 masktext = 'aaa111',
                 outpath = '/temp/1',
                 result = {"maskcount":0, 'compresscount':0}
                 )
    #cfgsimsun['']
    IMAGES().execute(cfg);print(cfg['result'])

if __name__ == "__main__":
    print(main(), "__main__")

    
 
class mfwatermark_main:
    __plugin_path = plugin_path
    __config = None
    __pro_shell = "ps -ef |grep mfwatermark_main.py |grep -v grep | awk '{print $2}'"

    def get_pro(self):
        L = public.ExecShell(self.__pro_shell)
        L = L[0].strip(),L[1]
        return L

    def stop_pro(self, args):
        pro = self.get_pro()
        if pro[0]:
            L = public.ExecShell("kill -9 %s"%(pro[0]))
            print(L)
        
        return {'msg':"程序已经关闭", "status":1}
    
    



    #构造方法
    def  __init__(self):
        pass

    def clear(self, args):
        for f in os.listdir(basedir):
            fpath = os.path.join(basedir,f)
            if not os.path.isfile(fpath): continue
            if not f.endswith('.conf'): continue
            try:
                os.remove(fpath)
            except:
                pass
        d = {'msg':"清理完成", 'status':1}
        return d
    
    def index(self, args):
        pth = os.path.join(basedir, 'mfwatermark.conf')
        if os.path.isfile(pth):
            d=json.load(open(pth))
        else :
            d = {}
        d['shell'] = self.get_pro()
        return d    
            
    def get_logs(self, args):
        path = os.path.join(basedir, 'mfwatermark.sqlite3')
        import sqlite3
        conn = sqlite3.connect(path)
        c = conn.cursor()

        cursor = c.execute("SELECT ctime,folder, flags,maskcount,compresscount,second  from image_logs order by ctime desc limit 100 ")
        L = cursor.fetchall()
        conn.close()
        rs = []
        for e in L:
            e = list(e)
            e.append(time.ctime(e[0]))
            rs.append(e)
        
        
        return {'data':rs}
    
    def view_do(self, args):
        key = args.key.strip()
        
        path = os.path.join(basedir, 'mfwatermark.sqlite3')
        import sqlite3
        conn = sqlite3.connect(path)
        c = conn.cursor()
        try:
            cursor = c.execute("SELECT records  from image_logs where ctime=? ", [key])
            rs = cursor.fetchone()
        except:
            rs = ['{}']
        conn.close()
        rs = json.loads(rs[0])
        #rs = json.dumps(rs[0], indent=4)
        return {'data':rs}
    
  
    def upload_image(self, args):
        from flask import request
        #from werkzeug.utils import secure_filename
        file = request.files['maskfile']
        fname = str(int(time.time())) + '.' + file.filename.rsplit('.', 1)[1]
        path = os.path.join(plugin_path,'temp')
        if not os.path.isdir(path):
            os.mkdir(path)
        path = os.path.join(path, fname)
        file.save(path)
        return {'fname':fname}
        

    def get_result(self, args):
        if 'exts' not in args or not args.exts: return {"error":"文件类型有误"}
        if 'folder' not in args or not args.folder or args.folder=='/': return {"error":"搜索目录有误"}
        maskmode = int(args.maskmode)
        
        exts = args.exts
        _exts = ''
        if isinstance(exts, str):
            _exts = exts.replace('.','[.]').replace('*','.*').replace(';','|').strip('|')
            _exts = '('+_exts+')'+'$'

        utimemode = int(args.utimemode) if 'utimemode' in args else 0
        utime = args.utime if 'utime' in args else ''
        minsize = int(args.minsize) if 'minsize' in args else 0
        minwidth = int(args.minwidth) if 'minwidth' in args else 0
        isbackup = int(args.isbackup) if 'isbackup' in args else 0
        subfold = int(args.subfold) if 'subfold' in args else 0
        outpath = args.outpath if 'outpath' in args else ''
        if outpath and not os.path.isdir(outpath):
            try:
                os.makedirs(outpath)
            except:
                return {"error":"输出目录创建不成功，请检查是否有误或者权限"}
        
        yswidth = int(args.yswidth) if 'yswidth' in args else 0
        ysheight = int(args.ysheight) if 'ysheight' in args else 0
        quality = int(args.quality) if 'quality' in args else 0
        ctrsize = int(args.ctrsize) if 'ctrsize' in args else 0

        isprotect = int(args.isprotect) if 'isprotect' in args else 0
        isaprotect = int(args.isaprotect) if 'isaprotect' in args else 0
        iscompress = int(args.iscompress) if 'iscompress' in args else 0
        isopaque = int(args.isopaque) if 'isopaque' in args else 0

        masktext = args.masktext if 'masktext' in args else ''
        rgba = args.rgba if 'rgba' in args else '#00000080'
        fontttf = args.fontttf if 'fontttf' in args else './fonts/simfang.ttf'
        if maskmode==2:
            if not os.path.isfile(fontttf):
                fontttf = os.path.join(plugin_path, fontttf)
                if not os.path.isfile(fontttf): return {"error":"字体文件ttf不存在"}
            if not masktext.strip():
                return {"error":"水印文件不存在"}
        
        fontsize = int(args.fontsize) if 'fontsize' in args else 36
        
        maskimg = args.maskimg if 'maskimg' in args else ''
        markpos = args.markpos if 'markpos' in args else ''
        marginx = int(args.marginx) if 'marginx' in args else 0
        marginy = int(args.marginy) if 'marginy' in args else 0
        maskscale = int(args.maskscale) if 'maskscale' in args else 0
        maskopacity = int(args.maskopacity) if 'maskopacity' in args else 0
        imgpath = args.imgpath if 'imgpath' in args else ''
        maskimgPath = ''
        optimize = int(args.optimize if 'optimize' in args else '0')
        jumperr = int(args.jumperr if 'jumperr' in args else '0')


        isgifsicle = int(args.isgifsicle if 'isgifsicle' in args else '0')
        gif_qty = args.gif_qty if 'gif_qty' in args else 'O3'
        gif_loss = int(args.gif_loss)
        gif_color = int(args.gif_color)
        
        
        if imgpath:
            maskimgPath = os.path.join(plugin_path,'temp',imgpath)
            if not os.path.isfile(maskimgPath):
                return {"error":"水印图片不存在"}
        if maskmode==3 and not imgpath:
            return {"error":"水印图片不存在"}
        
        d = dict(
                isgifsicle = isgifsicle, gif_qty=gif_qty, gif_loss=gif_loss, gif_color=gif_color, 
                
                jumperr = jumperr, 
                maskmode = int(args.maskmode),
                subfold=subfold, outpath=outpath,
                
                exts=args.exts, _exts=_exts, folder=args.folder, isbackup=isbackup,
                utimemode=utimemode,utime=utime,
                minsize=minsize, minwidth=minwidth,
                yswidth=yswidth, ysheight=ysheight,
                quality=quality, ctrsize=ctrsize,
                isopaque = isopaque,
                optimize = optimize,

                isprotect =isprotect, isaprotect=isaprotect, iscompress=iscompress,
                masktext=masktext,rgba=rgba,
                fontttf =fontttf, fontsize=fontsize,

                markpos=markpos,marginx=marginx, marginy=marginy,
                maskscale = maskscale, maskopacity=maskopacity,
                maskimgPath = maskimgPath,
                result = {"maskcount":0, 'compresscount':0,
                          'ctime':time.time(),
                          'files':[]
                          },
                
                )

        if 'saveconf' in args and args.saveconf:
            pth = os.path.join(basedir, 'mfwatermark.conf')
            json.dump(d, open(pth,'w'))

            _pth = '%s.conf'%(int(time.time()))
            pth = os.path.join(basedir, _pth)
            json.dump(d, open(pth,'w'))
            
            d = {'msg':"定时任务配置已保存", 'status':1, 'pth':_pth}
        elif 'clear' in args and args.clear:
            return self.clear(args)
        
        else:
            o = IMAGES()
            d=o.execute(d)
            d['result']['etime'] = time.time()
            o.save_db (d)

            d['result'].pop('files',None)
            
        return d
        
        
    
    
        
    

