'''
Created on Jun 09, 2014

@author: G
'''
from impacket.smbconnection import *
from impacket import smb, version, smb3, nt_errors
from impacket.dcerpc.v5 import samr, transport, srvs
from impacket.dcerpc.v5.dtypes import NULL
from impacket.smbconnection import *
#import ho.pisa as pisa
import collections
import email,email.encoders,email.mime.text,email.mime.base,email.mime.application
import sys
import threading
import datetime
import sqlite3
import subprocess
import psutil
#from smb.SMBHandler import SMBHandler
#from smb.SMBConnection import SMBConnection
import os
from smb import smb_structs
#from smb.SMBConnection import SMBConnection
import socket
import distutils.core
import time
import Queue
import smtplib
dep_up = Queue.Queue(1)
back_up = Queue.Queue(1)
from PyQt4 import QtGui, QtCore
from PyQt4.QtWebKit import QWebView
_fromUtf8 = QtCore.QString.fromUtf8
from g import Ui_TabWidget
threadLock = threading.Lock()
c_d = os.getcwd()
#smb_structs.SUPPORT_SMB2 = True
#from smb.SMBConnection import SMBConnection
#smb_structs.SUPPORT_SMB2 = True
global u_time
class mail2:
    def __init__(self, message,triger=''):
        self.message = message
        self.triger = triger
        self.mail_me()
    def mail_me(self):
        try:
            print "MAIL :" 
            con = sqlite3.connect(c_d+'\\mail.db')
            cursor = con.cursor()
            cursor.execute('select from_mail,to_mail,password,cc,subject,smtp_server,active,mail_on,ttls from smb')
            mail_1 = cursor.fetchone()
            con.close()
            self.from_addr = mail_1[0]
            self.login = self.from_addr
            all_mail2 = mail_1[1].split(",")
            self.to_addr_list = all_mail2
            self.password = mail_1[2]
            self.cc_addr_list = mail_1[3]
            self.subject = mail_1[4]
            self.smtpserver = mail_1[5]
            mail_on = mail_1[7]
            print "MAIL ON",mail_on
            if mail_1[6].find("Yes") != -1 and mail_on.find(self.triger) != -1:
                time = datetime.datetime.now().strftime("%d-%m-%Y  %H:%M:%S")
                l_time = unicode(time)
                if self.triger.find("BACKUP") !=-1:
                    self.triger = " Patch Backup Report "
                else:
                    self.triger = "Patch deployment Report"
                print self.message
                f2=self.message
                html =str("""<!doctype html><html><head>
                <table>
                        <tr><td><img src="logo.jpg" alt="some_text"></td><td><h1><font color="blue">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{report}</font></h1></td><td><p align="right"><h5>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{report2}</p></h5></td></table>
                        <br><br><br>
                        <table style="border:2px solid #0000FF; margin:0 auto; " cellpadding="20px" width="75%">
       
                        {code}
      
                        </table><br><br><br><br><br><br><table width="100%"><tr><td><div dir="ltr">Internal Purpose</div></td><td><div dir="rtl">Signature  </div></td></tr></table></html>""").format(code=str(f2),report=str(self.triger),report2=str(l_time))
                try:
                    a = file(c_d+"\\pdf\\mail2.html","wb")
                    print ">>>>>>>>>>>>>>>>>>>>"
                    print html
                    print "<<<<<<<<<<<<<<<<<<<<"
                    a.write(html)
                    #pisa.CreatePDF(html,a)
                    a.close()
                    print c_d+"\\pd\\wkhtmltopdf.exe "+c_d+"\\pdf\\mail2.html "+c_d+"\\pdf\\mail2.pdf"
                    subprocess.call(c_d+"\\pd\\wkhtmltopdf.exe "+c_d+"\\pdf\\mail2.html "+c_d+"\\pdf\\mail2.pdf")
#                     print html
#                     web = QWebView()
#                     web.setHtml(html)
#                     printer = QtGui.QPrinter()
#                     #printer.setPageSize(QtGui.QPrinter.A4)
#                     printer.setOutputFormat(QtGui.QPrinter.PdfFormat)
#                     printer.setOutputFileName(c_d+"\\mail.pdf")
#                     web.print_(printer)
                except Exception as e:
                    print "PDF CONVERT ERROR : ",e
                html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" '
                html +='"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">'
                html +='<body style="font-size:12px;font-family:Verdana"><p>...</p>'
                html += "</body></html>"
                emailMsg = email.MIMEMultipart.MIMEMultipart('alternative')
                emailMsg['Subject'] = self.subject
                emailMsg['From'] = self.from_addr
                emailMsg['To'] = ', '.join(self.to_addr_list)
                emailMsg['Cc'] = ", ".join(self.cc_addr_list)
                emailMsg.attach(email.mime.text.MIMEText(html,'html'))
                try:
                    filename=c_d+'\\pdf\\mail2.pdf'
                    fp=open(filename,'rb')
                    ffp = fp.read()
                    fp.close
                except Exception as e:
                    print "PDF OPEN ERROR MAIL.PDF",e
                att = email.mime.application.MIMEApplication(ffp,_subtype="pdf")
                att.add_header('Content-Disposition','attachment;filename=patch.pdf')
                emailMsg.attach(att)
                server = smtplib.SMTP(self.smtpserver)
                if mail_1[8].find("YES") != -1:
                    server.starttls()
                server.ehlo()
                print self.to_addr_list
                if str(self.password) > 0:
                    try:
                        server.login(self.login,self.password)
                    except Exception as e:
                        print e
                
                problems = server.sendmail(self.from_addr, self.to_addr_list, emailMsg.as_string())
                
                print "MAIL>",problems
                server.quit()
        except Exception as e:
            print "ERROR ON MAIL SEND:",e
        finally:
            print "Mail Finished..."
            return None

class resolve_name(QtCore.QThread):
    def __init__(self,textEdit_4,remote_ip):
        self.remote_ip = remote_ip
        self.textEdit_4 = textEdit_4
        for r_ip in remote_ip:
            try:
                b_name = socket.gethostbyaddr(unicode(r_ip))
                self.textEdit_4.setText(unicode(r_ip)+':'+unicode(b_name[0]))
            except Exception as e:
                pass;

class find_name:
    def __init__(self,iip):
        self.iip = iip
        try_host=0
        sys_name=""
        while try_host<2:
            try:
                try_host+=1
                print try_host
                sys_name=socket.gethostbyaddr(unicode(self.iip))
                if len(sys_name)>1:
                    print sys_name
                    self.sys_nn = sys_name[0]
                    break;
            except Exception as nm_fail:
                print "[Name Resolve fail:]"
                self.sys_nn = "no"
    def fet_name(self):
        return self.sys_nn

class run2:
    def __init__(self,chk_ip):
        self.chk_ip=chk_ip
        pass;
    def ping_chk(self):
        c_ip = self.chk_ip
        return c_ip
class com_file(QtCore.QThread):
    def __init__(self,r_ip,r_user,r_pass,r_file,l_file,listWidget_2,label_6,pushButton_9,checkBox_8):
        self.r_ip = r_ip
        self.r_user = r_user
        self.checkBox_8 = checkBox_8
        self.r_pass = r_pass
        self.r_file = r_file
        self.l_file = l_file
        self.pushButton_9 = pushButton_9
        self.listWidget_2=listWidget_2
        self.label_6 = label_6
        self.cmpp()
    def cmpp(self):
        try:
            print "COMPARING......"
            show_det = self.checkBox_8.isChecked()
            re_ip = self.r_ip.split("\n")
            #smb_structs.SUPPORT_SMB2 = True
            good_ip=[]
            failed_ip=[]
            total_size = 0
            total_file = 0
            missed = 0
            missed2=0
            for rr_ip in re_ip:
                error="no"
                missed_itm = 0
                missed = 0
                missed2=0
                all_local=[]
                remote_file=[]
                local_file=[]
                remote_file2=[]
                try:
                    print "CONNECTING..."
                    conn=SMBConnection(unicode(rr_ip), unicode(rr_ip), sess_port=445)
                    domain = ''
                    if unicode(self.r_user).find('/') > 0:
                        domain, self.r_user = unicode(self.r_user).split('/')
                    cnn = conn.login(unicode(self.r_user), unicode(self.r_pass), domain)
                    print "Login >",cnn
                    if cnn ==False:
                        missed=1
                        missed2 = 1
                        self.listWidget_2.addItem("[FAILED] "+unicode(rr_ip)+" AUTHENDICATION")
                        failed_ip.append(unicode(rr_ip))
                        continue;
                except Exception as e:
                    self.listWidget_2.addItem("[FAILED] "+unicode(rr_ip)+" CONNECTION FAILED")
                    failed_ip.append(unicode(rr_ip))
                    missed=1
                    missed2 = 1
                    print "Code Wrong 2",e
                    continue;
                for ll_file in self.l_file:
                    folder = "no"
                    missed_itm = 0
                    missed2=0
                    error="no"
                    file_ok="no"
                    folder_ok="no"
                    local_file=[]
                    remote_file=[]
                    remote_file2=[]
                    ll_file = unicode(ll_file)
                    if os.path.isfile(ll_file) == True:
                        folder = "no"
                        re_file = self.r_file.split("\\")
                        root = re_file[0]
                        all_f = unicode(self.r_file)
                        #half_path = all_f.replace(root,'')
                        dev3=''
                        dev1 = all_f.split("\\")
                        dev1.pop(0)
                        for dev2 in dev1:
                            dev3=dev3+"\\"+dev2
                        half_path = dev3
                        b = unicode(ll_file).split("\\")
                        b.reverse()
                        file_name = b[0]
                        l_siz = os.stat(unicode(ll_file)).st_size
                        try:
                            print "ROOT",root,"HALF PATH",unicode(half_path)
                            r_list = conn.listPath(root,unicode(half_path+"\\*"))
                            for all_list in r_list:
                                print file_name,">>>",all_list.get_longname()
                                print all_list.get_filesize(),">>>",l_siz
                                if file_name == all_list.get_longname() and all_list.get_filesize() == l_siz:
                                    total_file = total_file + 1
                                    file_ok="yes"
                                    all_local.append(unicode(l_siz)) #STORE SIZE OF THE FILE
                                    self.listWidget_2.addItem("[OK] "+unicode(rr_ip)+":"+unicode(file_name)+" : "+unicode(l_siz)+" bytes")
                            if file_ok == "no":
                                missed = 1
                                missed2 = 1
                                self.listWidget_2.addItem("[MISSED] "+unicode(rr_ip)+":"+unicode(file_name)+" : "+unicode(l_siz)+" bytes")
                        except Exception as e:
                            missed = 1
                            missed2 = 1
                            print e
                            self.listWidget_2.addItem("[MISSED] "+unicode(rr_ip)+" :"+unicode(half_path)+" NOT FOUND")
                    if os.path.isdir(ll_file) == True:
                        folder = "yes"
                        min_path = "\\"
                        all_22 = unicode(self.r_file)
                        re_file2 = all_22.split("\\")
                        root2 = re_file2[0]
                        re_file2.pop(0)
                        for trt in re_file2:
                            if trt != '':
                                min_path = min_path+"\\"+trt 
                        aa = ll_file.split("\\")
                        aa.reverse()
                        end_folder = aa[0]
                        for dirName, subdirList, fileList in os.walk(ll_file):
                            root_only = dirName.replace(ll_file,'')
                            for ff in fileList:
                                siz = os.stat(unicode(dirName+"\\"+ff)).st_size
                                f1 = end_folder+root_only+"\\"+ff
                                total_file = total_file + 1
                                local_file.append(f1+":"+unicode(siz))
                            for ff2 in subdirList:
                                total_file = total_file + 1
                                f2 = end_folder+root_only+"\\"+ff2
                                remote_file2.append(f2)
                                local_file.append(f2+":0")
                        remote_file2.append(end_folder+"\\")
                        
                        for rm_path in remote_file2:
                            try:
                                r_lst = conn.listPath(root2,min_path+"\\"+unicode(rm_path+"\\*"))
                            except Exception as e:
                                missed = 1
                                missed2 = 1
                                error = "yes"
                                self.listWidget_2.addItem("[MISSED] "+unicode(rr_ip)+" : "+unicode(rm_path)+" PATH NOT FOUND")
                                break;
                            for r_f in r_lst:
                                if r_f.get_longname() == '.' or r_f.get_longname() == '..':
                                    pass;
                                else:
                                    val = unicode(rm_path)+"\\"+unicode(r_f.get_longname())
                                    val = unicode(val)
                                    val = val.replace("\\\\", "\\")
                                    remote_file.append(val+":"+unicode(r_f.get_filesize()))
                    if error !="yes":
                        missed_itm = 0
                        for ll in local_file:
                            print "LOCAL FILE >>",ll
                            a = ll in remote_file
                            if a==True:
                                try:
                                    siz = ll.split(":")
                                    all_local.append(unicode(siz[1]))
                                except:
                                    print "File Size Find Error",e
                            else:
                                print ">>REMOTE FILES",a
                                missed_itm = missed_itm +1
                                missed = 1
                                missed2 = 1
                                if show_det == True:
                                    self.listWidget_2.addItem("[MISSED] "+unicode(ll)+" : "+unicode(rr_ip))

                    if missed2==1 and folder == "yes":
                            self.listWidget_2.addItem("[MISSED] "+unicode(end_folder)+" : "+unicode(rr_ip))
                    if missed2==0 and folder=="yes":
                        self.listWidget_2.addItem("[OK] "+unicode(rr_ip)+" : "+unicode(end_folder))
                #ALL LOCAL REMOTE FILE DETAILE COLLECTED FOR SINGLE IP
                try:
                    print "Logged off",re_ip
                    lf = conn.logoff()
                    print "LOG OFF>",lf
                except Exception as e:
                    print "LOGOFF ERROR ",e
                if missed==0:
                    total_size = 0
                    for size_l in all_local:
                        try:
                            total_size = total_size + int(size_l)
                        except Exception as e:
                            print "Total Size Calc Error",e
                    
                    good_ip.append(unicode(rr_ip))
                else:
                    failed_ip.append(unicode(rr_ip))           
                
                

            
            #ALL IP ARE DONE 
            try:
                all_time = self.label_6.text()
                all_time = unicode(all_time)
                g_ip=''
                f_ip=''
                print "GOOD IP",good_ip
                for g in good_ip:
                    g_ip = unicode(g_ip)+","+unicode(g)
                for f in failed_ip:
                    f_ip = unicode(f_ip) +" , "+ unicode(f)
                if int(total_size) > 1073741825:
                    total_size = total_size / float(1073741824)
                    total_size = ("%.2f" % round(total_size,2))
                    total_size = unicode(total_size)+" GB"
                    print "TOTAL SIZE >>"+total_size
                    print "TOTAL FILE >>"+unicode(total_file)
                elif int(total_size) > 1048575:
                    total_size = total_size / float(1048576)
                    total_size = ("%.2f" % round(total_size,2))
                    total_size = unicode(total_size)+" MB"
                    print "TOTAL SIZE >>"+total_size
                    print "TOTAL FILE >>"+unicode(total_file)
                elif int(total_size) > 1023:
                    total_size = total_size / float(1024)
                    total_size = ("%.2f" % round(total_size,2))
                    total_size = unicode(total_size)+" KB"
                    print "TOTAL SIZE >>"+total_size
                    print "TOTAL FILE >>"+unicode(total_file)
                else:
                    total_size = unicode(total_size)+" Bytes"
                stat_all = "Total item "+unicode(total_file)+" Total Size "+unicode(total_size)
                print stat_all
                con4 = sqlite3.connect(c_d+'\\log.db')
                cursor4 = con4.cursor()
                file_all = ''
                for ff in remote_file:
                    fff = ff.split(":")
                    for sss in fff:
                        file_all = file_all+"  "+fff[0]
                cursor4.execute('update user_log set fail='+'\''+f_ip[1:]+'\''+',status='+'\''+file_all+"<br>"+stat_all+'\''+',success='+'\''+unicode(g_ip)+'\''+' where l_time LIKE '+'\'%'+unicode(all_time)+'%\'')
                con4.commit()
                con4.close()
                con5 = sqlite3.connect(c_d+'\\log.db')
                cursor5 = con5.cursor()
                cursor5.execute("select name,l_file,r_file,local_ip,application from user_log where l_time LIKE \"%"+unicode(all_time)+"%\"")
                mm_mm = cursor5.fetchone()
                m_name = mm_mm[0]
                m_l_file = mm_mm[1]
                m_r_file = mm_mm[2]
                m_local_ip = mm_mm[3]
                application_1 = mm_mm[4]
                f2=''
                #all_mail =OrderedDict([ {'USERNAME':unicode(self.b_usr),'Time':unicode(time3),'REMOTE IP':unicode(self.b_rip),'SOURCE FILE':unicode(self.b_src),'DESTINATION FILE':unicode(self.b_des),'LOCAL IP':unicode(l_ip),'BACKUP FILES':unicode(val)}])
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">UserName</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(m_name))
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Date</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(all_time))
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Source ip</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(m_local_ip))
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Source Path</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(m_l_file)[1:])
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Destination ip</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(g_ip)[1:])
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Destination Path</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(m_r_file))
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Failed ip</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=f_ip[1:])
                f2= f2 + f1
                #r_list
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Item information</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(stat_all))
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Item information</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(stat_all))
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Application</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(application_1))
                f2= f2 + f1
                #d = OrderedDict([('first', 1), ('second', 2),('third', 3)])
                #all_mail = {'UserName':unicode(m_name),'Date':unicode(all_time),'Source ip':unicode(m_local_ip),'Source Path':unicode(m_l_file),'Destination ip':unicode(g_ip),'Destination Path':unicode(m_r_file),'Item information':unicode(stat_all),'Deployed ip':unicode(g_ip),'Failed ip':unicode(f_ip),'APPLICATION':unicode(application_1)}
                #sorted(all_mail.items())
                
                processThread = threading.Thread(target=mail2, args=(f2,"DEPLOY",))
                processThread.start()
            except Exception as e:
                print e
        except Exception as e:
            print "ERROR UNKNOWN",e
            self.listWidget_2.addItem("ERROR UNKNOWN TRY AGAIN")
        finally:
            self.pushButton_9.setText("COMPARE FILES")
        
class file_backup(QtCore.QThread):
    def __init__(self,b_rip,b_usr,b_pass,b_src,b_des,label_22,pushButton_4,listWidget_3,label_48,label_49,pushButton_21,listWidget_6,label_66,all_items):
        self.b_rip = b_rip
        self.b_usr = b_usr
        self.b_pass = b_pass
        self.b_src = b_src
        self.b_des = b_des
        self.label_22 = label_22
        self.label_48 = label_48
        self.label_49 = label_49
        self.pushButton_21 = pushButton_21
        self.listWidget_3 = listWidget_3
        self.pushButton_4 = pushButton_4
        self.listWidget_6 = listWidget_6
        self.label_66 = label_66
        self.all_items = all_items
        QtCore.QThread.__init__(self)
        #self.pushButton_21.clicked.connect(self.cancel2)
        self.run()
    def run(self):
        try:
            error_1 = 0
            self.listWidget_3.clear()
            faild=0
            self.listWidget_6.clear()
            self.label_49.clear()
            print "BACKUP..."
            rip = unicode(self.b_rip)
            usr = unicode(self.b_usr)
            passwd = unicode(self.b_pass)
            src2 = unicode(self.b_src) 
            des = unicode(self.b_des)
            my_command2 = "net use \\\\"+rip+''' "'''+passwd+'''" '''+"/user:"+usr
            #print "CONNECT>",my_command2
            try:
                print "DELETING OLD SESSIONS"
                sub_process3 = subprocess.Popen("net use * /d /y", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            except Exception as e:
                print "DELETING NET USE >",e
            
            sub_process2 = subprocess.Popen(my_command2, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            good2,bad2 = sub_process2.communicate()
            
            if bad2 == None:
                pass;
            else:
                print "AUTH ERROR>",bad2
                if bad2.find("Logon failure")!= -1:
                    self.label_22.setText("AUTHENDICATION FAILED")
                    return None
                self.label_22.setText(bad2)
            if good2.find("successfully")!=-1:
                print "Connected>",rip
            else:
                print "Connection Failed>",rip
                self.listWidget_3.addItem(rip+":CONNECTION FAILED")
                self.label_22.setText(good2)
                print "Reasion>",good2
                return None;
            end_f = ''
            print "src>>>",self.all_items
            for src in self.all_items:
                print "src>>>",src
                if src[-1:]=="\\":
                    end_f = src.split("\\")
                    end_f.reverse()
                    end_f = "\\"+end_f[1]
                    b_command = "xcopy /V /E /H /y /I /C /Z "+'''"\\\\'''+rip+"\\"+src[:-1]+'''" "'''+des+end_f+'''"'''
                else:
                    b_command = "xcopy /V /H /y /C /Z "+'''"\\\\'''+rip+"\\"+src+'''" "'''+des+'''"'''
                print "CMD:",b_command
                sub_process = subprocess.Popen(b_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                all_itm=''
                for line in iter(sub_process.stdout.readline, ''):
                    try:
                        can_signal = back_up.get_nowait()
                        if can_signal == "cancel":
                            self.pushButton_4.setText("BACKUP")
                            self.label_66.setText("   CANCELED   ")
                            return None
                    except Exception as e:
                        pass;
                    #print "OUT>",line
                    val = line.split("\\")
                    val.reverse()
                    self.label_22.setText("Copying> "+str(val[0]))
                    self.listWidget_3.addItem(str(val[0]))
                    if str(line).find("Invalid drive specification") != -1:
                        self.listWidget_3.addItem(rip+":Invalid drive specification")
                        self.label_22.setText("Invalid drive specification")
                        faild = 1
                        break;
                    if str(line).find("network name is no longer available") != -1:
                        self.listWidget_3.addItem(rip+":network name is no longer available")
                        self.label_22.setText("network name is no longer available")
                        faild = 1
                        break;
                    if faild == 1 :
                        print "FAILD>",faild
                        continue;
                    else:
                        print "ERROR>"
                        all_itm = all_itm+"<br>"+line
                good,bad = sub_process.communicate()
                print "INFO>",good
                print "ERROR>",bad
                if len(bad)>4:
                    self.listWidget_3.addItem("NOT COPYED:"+src+" "+bad)
                else:
                    pass;
            try:
                time1 = self.label_48.text()
                time2 = datetime.datetime.now().strftime("%d-%m-%Y  %H:%M:%S")
                print "timeee..."
                self.label_49.setText("END:"+unicode(time2))
                time3 = unicode(time1)+"<br> FINISHED: "+unicode(time2)
                con4 = sqlite3.connect(c_d+'\\backup.db')
                cursor4 = con4.cursor()
                l_ip=socket.gethostbyname(socket.gethostname())
                l_ip = unicode(l_ip)
                #print "DBBB>",('''INSERT INTO log(username, time, remote_ip, remote_path, local_path,local_ip,item)VALUES(?,?,?,?,?,?,?)''', (unicode(self.b_usr),unicode(time3),unicode(self.b_rip),unicode(self.b_src),unicode(self.b_des),unicode(l_ip),unicode(0)))
                cursor4.execute('''INSERT INTO log(username, time, remote_ip, remote_path, local_path,local_ip,item)VALUES(?,?,?,?,?,?,?)''', (unicode(self.b_usr),unicode(time3),unicode(self.b_rip),unicode(self.b_src),unicode(self.b_des),unicode(l_ip),unicode(all_itm)))
                con4.commit()
                con4.close()
                #all_mail = {'USERNAME':unicode(self.b_usr),'Time':unicode(time3),'REMOTE IP':unicode(self.b_rip),'SOURCE FILE':unicode(self.b_src),'DESTINATION FILE':unicode(self.b_des),'LOCAL IP':unicode(l_ip),'BACKUP FILES':unicode(val)}
                f2=''
                #all_mail =OrderedDict([ {'USERNAME':unicode(self.b_usr),'Time':unicode(time3),'REMOTE IP':unicode(self.b_rip),'SOURCE FILE':unicode(self.b_src),'DESTINATION FILE':unicode(self.b_des),'LOCAL IP':unicode(l_ip),'BACKUP FILES':unicode(val)}])
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">UserName</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(self.b_usr))
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Date</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(time3))
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Source ip</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(l_ip))
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Source Path</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(self.b_src))
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Destination ip</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(self.b_rip))
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Destination Path</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(self.b_des))
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Item Information</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=all_itm)
                f2= f2 + f1
                processThread = threading.Thread(target=mail2, args=(f2,"BACKUP",))
                processThread.start()
            except Exception as e:
                print "Backup Db Error",e
            
            
        except Exception as e:
            print "BACKUP ERROR>",e
        finally:
            self.pushButton_4.setText("BACKUP")
            self.label_66.setText("JOB FINISHED")

class file_backup2(QtCore.QThread):
    def __init__(self,b_rip,b_usr,b_pass,b_src,b_des,label_22,pushButton_4,listWidget_3,label_48,label_49,pushButton_21,listWidget_6,label_66):
        self.b_rip = b_rip
        self.b_usr = b_usr
        self.b_pass = b_pass
        self.b_src = b_src
        self.b_des = b_des
        self.label_22 = label_22
        self.label_48 = label_48
        self.label_49 = label_49
        self.pushButton_21 = pushButton_21
        self.listWidget_3 = listWidget_3
        self.pushButton_4 = pushButton_4
        self.listWidget_6 = listWidget_6
        self.label_66 = label_66
       
#         finally:
#             self.pushButton_4.setText("BACKUP")
#             self.label_66.setText("JOB FINISHED")
#             if val == None:
#                 self.label_66.setText("JOB FINISHED")
#                 return
#             if len(val) > 0:
#                 self.label_66.setText("BACKUP COMPLETED")
#                 time1 = self.label_48.text()
#                 time2 = datetime.datetime.now().strftime("%d-%m-%Y  %H:%M:%S")
#                 print "timeee..."
#                 self.label_49.setText("END:"+unicode(time2))
#                 time3 = unicode(time1)+"<br> FINISHED: "+unicode(time2)
#                 try:
#                     con4 = sqlite3.connect(c_d+'\\backup.db')
#                     cursor4 = con4.cursor()
#                     l_ip=socket.gethostbyname(socket.gethostname())
#                     l_ip = unicode(l_ip)
#                     #print "DBBB>",('''INSERT INTO log(username, time, remote_ip, remote_path, local_path,local_ip,item)VALUES(?,?,?,?,?,?,?)''', (unicode(self.b_usr),unicode(time3),unicode(self.b_rip),unicode(self.b_src),unicode(self.b_des),unicode(l_ip),unicode(0)))
#                     cursor4.execute('''INSERT INTO log(username, time, remote_ip, remote_path, local_path,local_ip,item)VALUES(?,?,?,?,?,?,?)''', (unicode(self.b_usr),unicode(time3),unicode(self.b_rip),unicode(self.b_src),unicode(self.b_des),unicode(l_ip),unicode(val)))
#                     con4.commit()
#                     con4.close()
#                     all_mail = {'USERNAME':unicode(self.b_usr),'Time':unicode(time3),'REMOTE IP':unicode(self.b_rip),'SOURCE FILE':unicode(self.b_src),'DESTINATION FILE':unicode(self.b_des),'LOCAL IP':unicode(l_ip),'BACKUP FILES':unicode(val)}
#                     processThread = threading.Thread(target=mail2, args=(all_mail,"BACKUP",))
#                     processThread.start()
#                 except Exception as e:
#                     print "Backup Db Error",e
            
    def downloadFiles(self,h2,destination,h1,hd):
    #path & destination are str of the form "/dir/folder/something/"
    #path should be the abs path to the root FOLDER of the file tree to download
        try:
            os.chdir(destination)
            mk = destination[0:len(destination)-1]+"\\"+h2.replace("/","\\")
            #print ">",mk
            os.mkdir(mk)
        except OSError as e:
            pass
        except Exception as e:
            self.label_22.setText("CHECK SOURCE DESTINATION PATH")
            return
        try:
            filelist = self.conn.listPath(hd,unicode("\\"+h1+"\\"+h2+"\\*"))
        except Exception as e:
            #print "E1",e
            self.label_22.setText("SOURCE PATH NOT FOUND")
            return
        for file2 in filelist:
            try:
                if file2.get_longname() == '.' or file2.get_longname() == '..':
                    continue;
                ff = h1+"\\"+h2+"\\"+"\\"+file2.get_longname()+"\\*"
                gg = ff.replace("/","\\")
                self.conn.listPath(hd,unicode(gg))
                self.downloadFiles(h2+"\\"+file2.get_longname()+"\\",destination,h1,hd)
            except Exception as e:
                #print "eeee",e
                try:
                    os.chdir(destination[0:len(destination)-1]+"\\"+h2)
                except Exception as e:
                    #print "e3",e
                    self.label_22.setText("DESTINATION PATH NOT FOUND")
                    return
                aa = destination+"\\"+h2+"\\"+file2.get_longname()
                bb = aa.replace("/","\\")
                cc = "\\"+h1+"\\"+h2+"\\"+file2.get_longname()
                dd = cc
                #print ">!",unicode(dd)
                #print "?<",bb
                try:
                    self.total_file = unicode(self.total_file)+","+unicode(dd)
                    self.label_22.setText(unicode(dd))
                    try:
                        can_signal = back_up.get_nowait()
                        if can_signal == "cancel":
                            back_up.put_nowait("cancel")
                            #print "KILL SIGNAL"
                            self.pushButton_4.setText("BACKUP")
                            self.label_22.setText("CANCELED")
                            return None
                    except Exception as e:
                        pass;
                        #print "NO KILL SIGNAL"
                    self.conn.getFile(hd,unicode(dd),open(bb,"wb").write)
                    self.listWidget_3.addItem(unicode(dd))
                except Exception as e:
                    print "E2",e
                    self.label_22.setText("GETTING FILE ERROR")
                    return
        
        return self.total_file
    def exr(self,msg):
        self.msg = msg
        self.label_22.setText(self.msg)
        self.pushButton_4.setText("BACKUP")
        return
class test(QtCore.QThread):
    def __init__(self,l_file,r_file,r_ip,r_pro,r_usr,r_pass,listWidget,listWidget_4,label_6,label_17,label_15,pushButton,pushButton_11,listWidget_5,label_42,pushButton_6,listWidget_2):
        print "Start ....."
        threadLock.acquire()
        QtCore.QThread.__init__(self)
        self.l_file = l_file
        self.pushButton_11=pushButton_11
        r_file=r_file.replace("/","\\")
        self.r_file = r_file
        self.listWidget_5 = listWidget_5
        self.r_ip = r_ip
        self.r_pro = r_pro
        self.r_usr = r_usr
        self.r_pass = r_pass
        self.label_6 = label_6
        self.label_17 = label_17
        self.label_42 = label_42
        self.label_15 = label_15
        self.listWidget_2 = listWidget_2
        self.listWidget = listWidget
        self.pushButton=pushButton
        self.pushButton_6 = pushButton_6
        threadLock.release()
        #self.pushButton_6.clicked.connect(self.cancan)
        
    def run(self):
        try:
            good_ip=[]
            remote_file=[]
            self.label_17.setText("")
            failed_ip=[]
            tmp2 = ''
            rr_ip = self.r_ip.split("\n")
            for re_ip in rr_ip:
                faild = 0
                self.label_17.setText("")
                self.label_15.setText("    "+re_ip)
                my_command2 = "net use \\\\"+re_ip+''' "'''+self.r_pass+'''" '''+"/user:"+self.r_usr
                #print "CONNECT>",my_command2
                try:
                    sub_process3 = subprocess.Popen("net use * /d /y", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                except Exception as e:
                    print "DELETING NET USE >",e
                sub_process2 = subprocess.Popen(my_command2, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                good2,bad2 = sub_process2.communicate()
                if bad2 == None:
                    pass;
                else:
                    print "AUTH ERROR>",bad2
                    if bad2.find("Logon failure")!= -1:
                        failed_ip.append(re_ip)
                        self.listWidget_5.addItem(re_ip+":AUTHENDICATION FAILED")
                        self.label_17.setText("AUTHENDICATION FAILED")
                        continue;
                    else:
                        self.label_17.setText(bad2)
                if good2.find("successfully")!=-1:
                    print "Connected>",re_ip
                else:
                    faild = 1
                    failed_ip.append(re_ip)
                    print "Connection Failed>",re_ip
                    self.listWidget_5.addItem(re_ip+":CONNECTION FAILED")
                    print "Reasion>",good2
                    continue;
                for path_ex in self.l_file:
                    end_folder=''
                    end_folder = path_ex.split("\\")
                    end_folder.reverse()
                    if len(end_folder) > 0:
                        end_folder = end_folder[0]
                    else:
                        faild = 1
                        failed_ip.append(re_ip)
                        print "CHECK SOURCE PATH"
                        continue;
                    if os.path.isfile(path_ex)==True:
                        my_command = "xcopy /V /H /y /C /Z "+'''"'''+path_ex+'''" '''+'''"\\\\'''+re_ip+"\\"+self.r_file+"\\"+'''"'''
                    else:
                        my_command = "xcopy /V /E /H /y /I /C /Z "+'''"'''+path_ex+'''" '''+'''"\\\\'''+re_ip+"\\"+self.r_file+"\\"+end_folder+'''\\"'''
                    print "CMD:",my_command
                    sub_process = subprocess.Popen(my_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                    for line in iter(sub_process.stdout.readline, ''):
                        try:
                            can_signal = dep_up.get_nowait()
                            if can_signal == "cancel":
                                self.pushButton.setText("DEPLOY")
                                self.label_15.setText("")
                                self.label_17.setText("       CANCELED  ")
                                return None
                        except Exception as e:
                            pass;
                        print "OUT>",line
                        val = line.split("\\")
                        val.reverse()
                        self.label_17.setText("Copying> "+str(val[0]))
                        if str(line).find("Invalid drive specification") != -1:
                            self.listWidget_5.addItem(re_ip+":Invalid drive specification")
                            self.label_17.setText("Invalid drive specification")
                            faild = 1
                            break;
                        if str(line).find("network name is no longer available") != -1:
                            self.listWidget_5.addItem(re_ip+":network name is no longer available")
                            self.label_17.setText("network name is no longer available")
                            faild = 1
                            break;
                        if str(line).find("0 File(s) copied") == -1:
                            print "APPEND REMOTE FILE>",line
                            remote_file.append(line)
                        else:
                            faild = 1
                            failed_ip.append(re_ip)
                            self.listWidget_5.addItem(re_ip+":ACCESS ERROR:"+line)
                            print "APPEND REMOTE FILE>",line
                            continue;
                    good,bad = sub_process.communicate()
                    print "INFO>",good
                    print "ERROR>",bad
                    path_ex
                    if line.find("File(s) copied") != -1 and str(line).find("0 File(s) copied") == -1:
                        self.listWidget_2.addItem("[OK] "+re_ip+" "+end_folder)
                    else:
                        self.listWidget_2.addItem("[MISSED] "+re_ip+" "+end_folder)
                if faild == 1 :
                    failed_ip.append(re_ip)
                    print "FAILD ip>",re_ip
                else:
                    print "Deployed ip >",re_ip
                    self.listWidget.addItem(re_ip)
                    good_ip.append(re_ip)
                            
                        
            self.label_15.setText("")
            self.label_17.setText("              JOB FINISHED")
            time_1 = self.label_6.text()
            time_2 = datetime.datetime.now().strftime("%d-%m-%Y  %H:%M:%S")
            all_time = unicode(time_1)+'<br> FINISHED:'+unicode(time_2)
            self.label_42.setText("FINISHED:"+str(time_2))
            try:
                con4 = sqlite3.connect(c_d+'\\log.db')
                cursor4 = con4.cursor()
                cursor4.execute('update user_log set l_time='+'\''+all_time+'\''+',status='+'\''+"Not Checked"+'\''+' where l_time='+'\''+unicode(time_1)+'\'')
                con4.commit()
                con4.close()
            except Exception as e:
                print "DATABASE ERROR",e
        #DATABASE UPDATE
            try:
                all_time = self.label_6.text()
                all_time = unicode(all_time)
                g_ip=''
                f_ip=''
                print "GOOD IP",good_ip
                for g in good_ip:
                    g_ip = unicode(g_ip)+"<br>"+unicode(g)
                for f in failed_ip:
                    f_ip = unicode(f_ip) +"<br>"+ unicode(f)
                #FIND SIZE:
                total_item=0
                folder_size = 0
                for folder in self.l_file:
                    if os.path.isdir(folder) == True:
                        folder_size = 0
                        for (path, dirs, files) in os.walk(folder):
                            for file in files:
                                total_item=total_item+1
                                
                                filename = os.path.join(path, file)
                                folder_size += os.path.getsize(filename)
                    else:
                        total_item=total_item+1
                        
                        folder_size += os.path.getsize(folder)
                total_size = folder_size
                if int(total_size) > 1073741825:
                    total_size = total_size / float(1073741824)
                    total_size = ("%.2f" % round(total_size,2))
                    total_size = unicode(total_size)+" GB"
                    print "TOTAL SIZE >>"+total_size
                    print "TOTAL FILE >>"+unicode(total_item)
                elif int(total_size) > 1048575:
                    total_size = total_size / float(1048576)
                    total_size = ("%.2f" % round(total_size,2))
                    total_size = unicode(total_size)+" MB"
                    print "TOTAL SIZE >>"+total_size
                    print "TOTAL FILE >>"+unicode(total_item)
                elif int(total_size) > 1023:
                    total_size = total_size / float(1024)
                    total_size = ("%.2f" % round(total_size,2))
                    total_size = unicode(total_size)+" KB"
                    print "TOTAL SIZE >>"+total_size
                    print "TOTAL FILE >>"+unicode(total_item)
                else:
                    total_size = unicode(total_size)+" Bytes"
                stat_all = "Total item "+unicode(total_item)+" Total Size "+unicode(total_size)
                print stat_all
                con4 = sqlite3.connect(c_d+'\\log.db')
                cursor4 = con4.cursor()
                file_all = ''
                file_all2=''
                for ff in remote_file:
                    file_all2 = file_all2+"<br>"+ff
                print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>",file_all2
                cursor4.execute('update user_log set fail='+'\''+f_ip+'\''+',status='+'\''+file_all2+"<br>"+stat_all+'\''+',success='+'\''+unicode(g_ip)+'\''+' where l_time LIKE '+'\'%'+unicode(all_time)+'%\'')
                con4.commit()
                con4.close()
                con5 = sqlite3.connect(c_d+'\\log.db')
                cursor5 = con5.cursor()
                cursor5.execute("select name,l_file,r_file,local_ip,application from user_log where l_time LIKE \"%"+unicode(all_time)+"%\"")
                mm_mm = cursor5.fetchone()
                con5.close()
                m_name = mm_mm[0]
                m_l_file = mm_mm[1]
                m_r_file = mm_mm[2]
                m_local_ip = mm_mm[3]
                application_1 = mm_mm[4]
                f2=''
                #all_mail =OrderedDict([ {'USERNAME':unicode(self.b_usr),'Time':unicode(time3),'REMOTE IP':unicode(self.b_rip),'SOURCE FILE':unicode(self.b_src),'DESTINATION FILE':unicode(self.b_des),'LOCAL IP':unicode(l_ip),'BACKUP FILES':unicode(val)}])
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">UserName</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(m_name))
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Date</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(all_time))
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Source ip</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(m_local_ip))
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Source Path</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(m_l_file))
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Destination ip</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(g_ip))
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Destination Path</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(m_r_file))
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Failed ip</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=f_ip)
                f2= f2 + f1
                #r_list
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Item information</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(stat_all))
                f2= f2 + f1
                f1 = str("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue">Application</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=str(application_1))
                f2= f2 + f1
                #d = OrderedDict([('first', 1), ('second', 2),('third', 3)])
                #all_mail = {'UserName':unicode(m_name),'Date':unicode(all_time),'Source ip':unicode(m_local_ip),'Source Path':unicode(m_l_file),'Destination ip':unicode(g_ip),'Destination Path':unicode(m_r_file),'Item information':unicode(stat_all),'Deployed ip':unicode(g_ip),'Failed ip':unicode(f_ip),'APPLICATION':unicode(application_1)}
                #sorted(all_mail.items())
                
                processThread = threading.Thread(target=mail2, args=(f2,"DEPLOY",))
                processThread.start()
                
                
                
            except Exception as e:
                print "ERRRRRRR>",e
        except Exception as e:
            print "Error Unknown on Deploy >",e
        finally:
            self.pushButton.setText("DEPLOY")      
    def cancan(self):
        print "Killing>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
        self.exit()
        self.terminate()
        self.quit()
        #self.terminate()
        self.pushButton.setText("DEPLOY")
        self.label_15.setText("")
        self.label_17.setText("    CANCELED")
    def db_faild_ip(self,faild_ip,time_start):
        try:
            p_val=''
            con_l = sqlite3.connect(c_d+'\\log.db')
            cursor_l = con_l.cursor()
            cursor_l.execute('select fail from user_log where l_time="'+unicode(time_start)+'"')
            fail_ip = cursor_l.fetchone()
            print "FAILD IP",fail_ip
            for ff in fail_ip:
                p_val = unicode(ff)
            p_val = unicode(p_val)
            if p_val < 1:
                print "Check FAILED IP IN DATABASE"
            if p_val.find("None")==0:
                faild_ip=unicode(faild_ip)
            else:
                faild_ip = p_val+','+unicode(faild_ip)
            cursor_l.execute('update user_log set fail='+'\''+faild_ip+'\''+',status='+'\''+"Not Checked"+'\''+' where l_time='+'\''+unicode(time_start)+'\'')
            con_l.commit()
            con_l.close()
        except Exception as e:
            print "DB UPDATE FAILED[failed ip]",e

        
class MyApp(QtGui.QTabWidget,QtGui.QMainWindow, Ui_TabWidget):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        QtGui.QTabWidget.__init__(self)
        Ui_TabWidget.__init__(self)
        self.setupUi(self)
        self.html = ""
        self.html2 = ""
        #self.progressBar.setValue(0)
        self.textEdit.setPlainText("")
        self.pushButton_7.clicked.connect(self.log_dis)
        #print sys.argv[1],"uuuuu"
        if sys.argv[1]=="Administrator":
            self.addTab(self.tab_5, _fromUtf8(""))
            self.setTabText(self.indexOf(self.tab_5), "BACKUP LOG")
            self.addTab(self.tab2, _fromUtf8(""))
            self.setTabText(self.indexOf(self.tab2), "DEPLOY LOG")
            self.addTab(self.tab_4, _fromUtf8(""))
            self.setTabText(self.indexOf(self.tab_4), "ADMIN PANEL")
        #t1=threading.Thread(target=self.calluser,name="sr  un")
        self.addTab(self.tab_3, _fromUtf8(""))
        self.setTabText(self.indexOf(self.tab_3), "UPDATE PROFILE")
        self.pushButton.clicked.connect(self.calluser)
        self.pushButton_2.clicked.connect(self.brows)
        self.pushButton_12.clicked.connect(self.usr_mgm)
        self.pushButton_13.clicked.connect(self.del_usr_mgm)
        self.pushButton_14.clicked.connect(self.up_usr_mgm)
        self.pushButton_3.clicked.connect(self.brows_file)
        self.pushButton_8.clicked.connect(self.rem_file)
        self.pushButton_9.clicked.connect(self.comparef)
        self.pushButton_10.clicked.connect(self.back_save)
        self.pushButton_11.clicked.connect(self.profile)
        self.pushButton_4.clicked.connect(self.backup)
        self.pushButton_15.clicked.connect(self.pprint_file)
        self.listWidget.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.listWidget_4.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.listWidget_7.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.tableWidget_2.cellClicked.connect(self.disp_user_info)
        self.tableWidget.cellClicked.connect(self.disp_item_info)
        self.pushButton_5.clicked.connect(self.retry_all)
        self.pushButton_6.clicked.connect(self.cancel_dep)
        self.pushButton_16.clicked.connect(self.show_app)
        self.pushButton_17.clicked.connect(self.del_app)
        self.pushButton_18.clicked.connect(self.add_app)
        self.pushButton_19.clicked.connect(self.log_dis_backup)
        self.pushButton_20.clicked.connect(self.pprint_backup)
        self.tableWidget_3.cellClicked.connect(self.disp_backup_info)
        self.pushButton_21.clicked.connect(self.cancel_back)
        self.pushButton_22.clicked.connect(self.mail_update)
        self.pushButton_23.clicked.connect(self.mail_show)
        self.pushButton_30.clicked.connect(self.back_add_itm)
        self.pushButton_31.clicked.connect(self.back_rem_itm)
        self.application_fetch()
    def application_fetch(self):
        #self.comboBox_3
        try:
            con2 = sqlite3.connect(c_d+'\\app_name.db')
            cursor2 = con2.cursor()
            rowcount = cursor2.execute('''SELECT name FROM app_name''')
            row2 = rowcount.fetchall()
            for app_name in row2:
                self.comboBox_3.addItem(unicode(app_name[0]))
        except Exception as ee:
            print "app_name.db Error :",ee
#       
    def brows(self):
        filename = QtGui.QFileDialog.getExistingDirectory(self, 'Select Folder', '.')
        #self.textEdit_2.setText(filename)
        #t1 = self.textEdit_2.toPlainText()
        if len(filename)>0:
            filename = unicode(filename)
            self.listWidget_4.addItem(filename)
    
    def brows_file(self):
        filename = QtGui.QFileDialog.getOpenFileNames(self, 'Open File', '.')
        for f_name in filename:
            self.listWidget_4.addItem(f_name)
    def back_save(self):
        b_s = QtGui.QFileDialog.getExistingDirectory(self, 'BackUp','.')
        self.lineEdit_8.setText(unicode(b_s))
    
    def back_add_itm(self):
        filename = self.lineEdit_7.text()
        filename = unicode(filename)
        if len(filename)>0:
            filename = unicode(filename)
            self.listWidget_7.addItem(filename)
    
    def back_rem_itm(self):
        for item in self.listWidget_7.selectedItems():
            self.listWidget_7.takeItem(self.listWidget_7.row(item))
    def calluser(self):
        try:
            dep_up.get_nowait()
        except Exception as e:
            pass;
        if unicode(self.pushButton.text())=="DEPLOY":
            if self.listWidget_4.count() == 0:
                self.label_17.setText("             SOURCE FILE PLEASE !!!")
                return None
            if len(unicode(self.lineEdit.text())) == 0:
                self.label_17.setText("             DESTINATION PATH PLEASE !!!")
                return None
            if len(unicode(self.lineEdit_2.text())) == 0:
                self.label_17.setText("             USER NAME !!!")
                return None
            if len(unicode(self.lineEdit_3.text())) == 0:
                self.label_17.setText("             PASSWORD PLEASE !!!")
                return None
            if unicode(self.comboBox_3.currentText()) == "SELECT APPLICATION":
                self.label_17.setText("    PLEASE SELECT APPLICATION")
                return None
            self.listWidget_5.clear()
            self.label_42.setText("")
            self.listWidget.clear()
            self.listWidget_2.clear()
            #self.listWidget_5.clear()
            #self.listWidget.clear()
            #self.listWidget.addItem("File name:")
            self.label_6.setText(" ")
            self.threads=[]
            #r_proto=self.comboBox.currentText()
            r_proto="Auto"
            #self.textEdit.setPlainText(tx)
            r_ip=self.textEdit.toPlainText()
            
    #         l_file=self.textEdit_2.toPlainText()
    #         print l_file
            lfile_items = []
            for index in xrange(self.listWidget_4.count()):
                ff = self.listWidget_4.item(index).text()
                #print ff
                lfile_items.append(unicode(ff))
            r_file = self.lineEdit.text()
            r_file = unicode(r_file)
            r_file = r_file.replace("/","\\")
            tmp_rf = r_file.split("\\")
            print tmp_rf
            rrr_f=''
            for ttmp in tmp_rf:
                if ttmp !='':
                    rrr_f = rrr_f+"\\"+ttmp
                print rrr_f
            #REMOVE FIRST SLASH IN PATH NAME
            if rrr_f[0] == "\\":
                rrr_f=rrr_f[1:]
            #REMOVE LAST SLASH IN PATH NAME
            if rrr_f.rfind == "\\":
                rrr_f=rrr_f[:-1]
            r_file = unicode(rrr_f)
            r_user=self.lineEdit_2.text()
            r_pass=self.lineEdit_3.text()
            l_file=lfile_items
            app_name = self.comboBox_3.currentText()
            app_name = unicode(app_name)
            try:
                print "Db Check ok...."
                con = sqlite3.connect(c_d+'\\log.db')
                time = datetime.datetime.now().strftime("%d-%m-%Y  %H:%M:%S")
                l_time = unicode(time)
                self.label_6.setText("STARTED:"+unicode(l_time))
                l_time = "STARTED:"+unicode(l_time)
                cursor = con.cursor()
                l_file2=""
                for file1 in l_file:
                    l_file2=unicode(l_file2)+unicode("<br>")+unicode(file1)
                try:
                    l_ip=''
                    l_ip=socket.gethostbyname(socket.gethostname())
                    l_ip = unicode(l_ip)
                except Exception as e:
                    print e
                t_ip2 = unicode(r_ip).split("\n")
                tt3_ip=""
                for tt2_ip in t_ip2:
                    tt3_ip = tt3_ip+"<br>"+tt2_ip
                cursor.execute('''INSERT INTO user_log(name, l_time, r_ip, l_file, r_file,application,local_ip)VALUES(?,?,?,?,?,?,?)''', (unicode(r_user),unicode(l_time),unicode(tt3_ip),unicode(l_file2),unicode(r_file),unicode(app_name),unicode(l_ip)))
                con.commit()
                con.close()
            except Exception as e:
                print "Place 2",e
            t_ip = unicode(r_ip).split("\n")
            for tt_ip in t_ip:
                print tt_ip
            if len(t_ip) > 100:
                print "TOTAL IP",len(t_ip)
                self.label_17.setText("THIS VERSION SUPPORT 100 SYSTEM ONLY")
                return None
                #self.listWidget_4.addItem(unicode(tt_ip)+" FILE: "+l_file)
            #r_port=self.textEdit_6.toPlainText()
            try:
                t1 = test(l_file,unicode(r_file),unicode(r_ip),unicode(r_proto),unicode(r_user),unicode(r_pass),self.listWidget,self.listWidget_4,self.label_6,self.label_17,self.label_15,self.pushButton,self.pushButton_11,self.listWidget_5,self.label_42,self.pushButton_6,self.listWidget_2)
                self.threads.append(t1)
                t1.start()
                #t2 = resolve_name(self.textEdit_2,t_ip)
                #self.threads.append(t2)
                #t2.start()
                self.pushButton.setText("DEPLOING...")
            except Exception as e:
                self.pushButton.setText("DEPLOY")
                print "Thread Error...."

    def log_dis(self):
        
        print "Log Display"
        con = sqlite3.connect(c_d+'\\log.db')
        con2 = sqlite3.connect(c_d+'\\log.db')
        cursor = con.cursor()
        cursor2 = con2.cursor()
        rowcount = cursor2.execute('''SELECT * FROM user_log''')
        row2 = rowcount.fetchall()
        print len(row2)
        self.tableWidget.setRowCount(len(row2))
        self.tableWidget.setColumnCount(11)
        cursor.execute('''SELECT * FROM user_log''')
        self.tableWidget.setHorizontalHeaderLabels(['ID', 'USER', 'DATE', 'DESTINATION IP', 'SOURCE FILE','DETINATION FILE','FILE INFO','FAILED IP','DEPLOYED IP','APPLICATION','LOCAL IP'])
        for row, form in enumerate(cursor):
            for column, item in enumerate(form):
                self.tableWidget.setItem(row, column, QtGui.QTableWidgetItem(unicode(item)))
    
    def log_dis_backup(self):
        
        print "Log Display"
        con = sqlite3.connect(c_d+'\\backup.db')
        con2 = sqlite3.connect(c_d+'\\backup.db')
        cursor = con.cursor()
        cursor2 = con2.cursor()
        rowcount = cursor2.execute('''SELECT * FROM log''')
        row2 = rowcount.fetchall()
        print len(row2)
        self.tableWidget_3.setRowCount(len(row2))
        self.tableWidget_3.setColumnCount(7)
        cursor.execute('''SELECT * FROM log''')
        self.tableWidget_3.setHorizontalHeaderLabels(['USERNAME', 'TIME', 'REMOTE IP', 'REMOTE PATH', 'LOCAL PATH','LOCAL IP','ITEM'])
        for row, form in enumerate(cursor):
            for column, item in enumerate(form):
                self.tableWidget_3.setItem(row, column, QtGui.QTableWidgetItem(unicode(item)))
        con.close()
        con2.close()
    def rem_file(self):
        for item in self.listWidget_4.selectedItems():
            self.listWidget_4.takeItem(self.listWidget_4.row(item))
            
    def backup(self):
        try:
            try:
                back_up.get_nowait()
            except Exception as e:
                pass;
            self.label_22.setText('')
            self.label_66.setText('')
            self.listWidget_3.clear()
            print "BACKUP"
            all_items = []
            for index in xrange(self.listWidget_7.count()):
                ff2 = self.listWidget_7.item(index).text()
                #print ff
                all_items.append(unicode(ff2))
            print "ALL BACKUP ITM >",all_items
            if unicode(self.pushButton_4.text())=="BACKUP":
                self.listWidget_3.clear()
                self.threads=[]
                b_rip = self.lineEdit_4.text() 
                b_usr = self.lineEdit_5.text()
                b_pass = self.lineEdit_6.text()
                b_src = self.lineEdit_7.text()
                b_des = self.lineEdit_8.text()
                if len(unicode(b_rip)) < 5:
                    self.label_22.setText("Enter Ip Address")
                    return None
                if len(unicode(b_usr)) < 1:
                    self.label_22.setText("Enter UserName")
                    return None
                if len(unicode(b_pass)) < 1:
                    self.label_22.setText("Enter passwors")
                    return None
                if len(unicode(b_src)) < 1:
                    self.label_22.setText("Enter Local File Path")
                    return None
                if len(unicode(b_des)) < 1:
                    self.label_22.setText("Enter Destination Path")
                    return None
                self.pushButton_4.setText("Plz Wait...")
                time = datetime.datetime.now().strftime("%d-%m-%Y  %H:%M:%S")
                self.label_48.setText("STARTED: "+unicode(time))
                self.label_22.setText("")
                b_src = unicode(b_src)
                b_src = b_src.replace("/","\\")
                end_s = 0
                if b_src[-1:] ==  "\\":
                    end_s = 1
                tmp_rf = b_src.split("\\")
                rrr_f=''
                for ttmp in tmp_rf:
                    if ttmp !='':
                        rrr_f = rrr_f+"\\"+ttmp
                    print rrr_f
                #REMOVE FIRST SLASH IN PATH NAME
                if rrr_f[0] == "\\":
                    rrr_f=rrr_f[1:]
                #REMOVE LAST SLASH IN PATH NAME
                if rrr_f.rfind == "\\":
                    rrr_f=rrr_f[:-1]
                b_src = unicode(rrr_f)
                if end_s == 1:
                    b_src=b_src+"\\"
                try:
                    thread1 = threading.Thread(target=file_backup,args=(b_rip,b_usr,b_pass,b_src,b_des,self.label_22,self.pushButton_4,self.listWidget_3,self.label_48,self.label_49,self.pushButton_21,self.listWidget_6,self.label_66,all_items))
                    #self.threads.append(thread1)
                    thread1.start()
                except Exception as e:
                    self.pushButton_4.setText("BACKUP")
                    print "Thread Error....",e
        except Exception as e:
            print e
            self.pushButton_4.setText("BACKUP")
    def comparef(self):
        if self.pushButton_9.text()=="COMPARE FILES":
            try:
                self.pushButton_9.setText("COMPARING....")
                self.listWidget_2.clear()
                r_file=self.lineEdit.text()
                r_user=self.lineEdit_2.text()
                r_pass=self.lineEdit_3.text()
                r_ip=self.textEdit.toPlainText()
                r_file = unicode(r_file)
                r_file=r_file.replace("/","\\")
                tmp_rf = r_file.split("\\")
                print tmp_rf
                rrr_f=''
                for ttmp in tmp_rf:
                    if ttmp !='':
                        rrr_f = rrr_f+"\\"+ttmp
                        print rrr_f
                if rrr_f[0] == "\\":
                    rrr_f=rrr_f[1:]
                if rrr_f.rfind == "\\":
                    rrr_f=rrr_f[:-1]
                r_file = rrr_f
                lfile_items = []
                for index in xrange(self.listWidget_4.count()):
                    ff = self.listWidget_4.item(index).text()
                    print ff
                    lfile_items.append(ff)
                l_file=lfile_items
                thread1 = threading.Thread(target=com_file,args=(r_ip,r_user,r_pass,r_file,l_file,self.listWidget_2,self.label_6,self.pushButton_9,self.checkBox_8))
                thread1.start()
            except Exception as e:
                self.pushButton_9.setText("COMPARE FILES")
                print e
    def profile(self):
        u_name = unicode(self.lineEdit_9.text())
        u_old_pass = unicode(self.lineEdit_10.text())
        u_pass = unicode(self.lineEdit_11.text())
        u_pass2 = unicode(self.lineEdit_12.text())
        if u_pass != u_pass2:
            self.label_28.setText("New Password Not Matched")
        else:
            try:
                con2 = sqlite3.connect(c_d+'\\auth.db')
                cursor2 = con2.cursor()
                cursor2.execute('update auth set password='+'\''+u_pass+'\''+' where username='+'\''+u_name+'\''+'and password='+'\''+u_old_pass+'\'')
                print 'update auth set password='+'\''+u_pass+'\''+' where username='+'\''+u_name+'\''+'and password='+'\''+u_pass+'\''
                con2.commit()
                con2.close()
                if cursor2.rowcount==1:
                    self.label_28.setText("UPDATE SUCCESS")
                    self.lineEdit_9.setText('')
                    self.lineEdit_10.setText('')
                    self.lineEdit_11.setText('')
                    self.lineEdit_12.setText('')
                else:
                    print cursor2.rowcount
                    self.label_28.setText("Check username or password")
            except Exception as e:
                print e
                self.label_28.setText("Error while updating..")
    def disp_user_info(self,row, column):
        ttrow = row
        item = self.tableWidget_2.item(ttrow, 0)
        username = item.text()
        item = self.tableWidget_2.item(ttrow, 1)
        name = item.text()
        item = self.tableWidget_2.item(ttrow, 2)
        id2 = item.text()
        item = self.tableWidget_2.item(ttrow, 3)
        type2 = item.text()
        item = self.tableWidget_2.item(ttrow, 4)
        status = item.text()
        self.lineEdit_13.setText(username)
        self.lineEdit_14.setText(name)
        self.lineEdit_15.setText(unicode(id2))
        self.comboBox.clear()
        self.comboBox.addItem(type2)
        self.comboBox.addItem("Administrator")
        self.comboBox.addItem("normal")
        self.comboBox_2.clear()
        self.comboBox_2.addItem(status)
        self.comboBox_2.addItem("ACTIVATE")
        self.comboBox_2.addItem("DEACTIVATE")
    
    def mail_update(self):
        try:
            self.label_61.setText("")
            active = self.comboBox_5.currentText()
            mail_on = self.comboBox_6.currentText()
            ttls = self.comboBox_7.currentText()
            ttls = unicode(ttls)
            mail_on = unicode(mail_on)
            active = unicode(active)
            f_mail = unicode(self.lineEdit_17.text())
            t_mail = unicode(self.lineEdit_18.text())
            passwd = unicode(self.lineEdit_21.text())
            ccc = unicode(self.lineEdit_19.text())
            sub = unicode(self.lineEdit_22.text())
            smtp_server = unicode(self.lineEdit_20.text())
            if f_mail < 1:
                self.label_61.setText("Enter From Mail")
            if t_mail < 1:
                self.label_61.setText("Enter To Mail")
            if passwd < 1:
                self.label_61.setText("Enter Password")
            if passwd < 1:
                self.label_61.setText("Enter smtp Server")
            con2 = sqlite3.connect(c_d+'\\mail.db')
            cursor2 = con2.cursor()
            cursor2.execute('update smb set from_mail=\"'+f_mail+'\",to_mail=\"'+t_mail+'\",password=\"'+passwd+'\",cc=\"'+ccc+'\",subject=\"'+sub+'\",'+'smtp_server=\"'+smtp_server+'\",'+'active=\"'+active+'\",'+'mail_on=\"'+mail_on+'\",'+'ttls=\"'+ttls+'\" where id=\"1\"')
            con2.commit()
            self.label_61.setText("Update Success")
            con2.close()
        except Exception as e:
            print e
    
    def mail_show(self):
        try:
            self.label_61.setText("")
            self.comboBox_5.clear()
            self.comboBox_6.clear()
            self.comboBox_7.clear()
            con = sqlite3.connect(c_d+'\\mail.db')
            cursor = con.cursor()
            cursor.execute('select from_mail,to_mail,password,cc,subject,smtp_server,active,mail_on,ttls from smb')
            mail_1 = cursor.fetchone()
            con.close()
            from_mail = mail_1[0]
            to_mail = mail_1[1]
            password = mail_1[2]
            cc = mail_1[3]
            subject = mail_1[4]
            smtp_server = mail_1[5]
            active = mail_1[6]
            mail_on = mail_1[7]
            ttls = mail_1[8]
            self.comboBox_7.addItem(ttls)
            self.comboBox_7.addItem("YES")
            self.comboBox_7.addItem("NO")
            self.comboBox_6.addItem(mail_on)
            self.comboBox_6.addItem("BACKUP")
            self.comboBox_6.addItem("DEPLOY")
            self.comboBox_6.addItem("DEPLOY&BACKUP")
            self.comboBox_5.addItem(active)
            self.comboBox_5.addItem("No")
            self.comboBox_5.addItem("Yes")
            self.lineEdit_17.setText("frolllllllllllm_mail")
            self.lineEdit_17.setText(from_mail)
            self.lineEdit_18.setText(to_mail)
            self.lineEdit_21.setText(password)
            self.lineEdit_19.setText(cc)
            self.lineEdit_22.setText(subject)
            self.lineEdit_20.setText(smtp_server)
        except Exception as e:
            print e
    
    def disp_item_info(self,row, column):
        html=""
        username=''
        d_date=''
        des_ip=''
        src_file=''
        des_file=''
        itm_det=''
        dep_ip=''
        f1=''
        f2=''
        code=''
        self.checkBox.checkState()
        ttrow = row
        item = self.tableWidget.item(ttrow, 1)
        username = item.text()
        print "username",username
        item = self.tableWidget.item(ttrow, 2)
        d_date = item.text()
        print "date",d_date
        item = self.tableWidget.item(ttrow, 3)
        des_ip = item.text()
        d_val = des_ip.split(",")
        des_ip=''
        if len(d_val) > 0:
            for ddr2 in d_val:
                des_ip=des_ip+"<br>"+ddr2
        print "des_ip",des_ip
        item = self.tableWidget.item(ttrow, 4)
        src_file = item.text()
        src_file = unicode(src_file)
        aaa = src_file.split(",")
        src_file = ''
        for ssr in aaa:
            src_file=unicode(src_file+"<br>"+ssr)
        #print "src_file",src_file
        item = self.tableWidget.item(ttrow, 5)
        des_file = item.text()
        #print "des_file",des_file
        item = self.tableWidget.item(ttrow, 6)
        itm_det = item.text()
        itm_val = itm_det.split(" ")
        if len(itm_val)<1:
            tval=itm_val
        else:
            tval=''
        for vvvl in itm_val:
            tval = tval+"<br>"+vvvl
        itm_val=tval
        print "item_det",itm_det
        item = self.tableWidget.item(ttrow, 8)
        dep_ip = item.text()
        d_val2 = dep_ip.split(",")
        if len(d_val2) > 0:
            dep_ip=''
            for ddr in d_val2:
                dep_ip=dep_ip+"<br>"+ddr
        item = self.tableWidget.item(ttrow, 7)
        failed_ip = item.text()
        item = self.tableWidget.item(ttrow, 9)
        app = item.text()
        item = self.tableWidget.item(ttrow, 10)
        local_iip = item.text()
        if self.checkBox.isChecked():
            f1=unicode("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue"> NAME</font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""").format(code=unicode(username))
            f2=f2+f1
        if self.checkBox_2.isChecked():
            f1=unicode("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue"> DATE & TIME </font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}<h3></td>""").format(code=unicode(d_date))
            f2=f2+f1
        if self.checkBox_11.isChecked():
            f1=unicode("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue"> SOURCE IP </font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td>""").format(code=unicode(local_iip))
            f2=f2+f1
        if self.checkBox_4.isChecked():
            f1=unicode("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue"> SOURCE PATH </font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td>""").format(code=unicode(src_file))
            f2=f2+f1
        if self.checkBox_3.isChecked():
            f1=unicode("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue"> DESTINATION IP </font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td>""").format(code=unicode(des_ip))
            f2=f2+f1
        if self.checkBox_5.isChecked():
            f1=unicode("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue"> DESTINATION PATH </font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td>""").format(code=unicode(des_file))
            f2=f2+f1
        if self.checkBox_6.isChecked():
            f1=unicode("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue"> TOTAL ITEM </font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td>""").format(code=unicode(itm_det))
            f2=f2+f1
        if self.checkBox_7.isChecked():
            f1=unicode("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue"> DEPLOYED IP </font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td>""").format(code=unicode(dep_ip))
            f2=f2+f1
        if self.checkBox_9.isChecked():
            f1=unicode("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue"> FAILED IP </font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td>""").format(code=unicode(failed_ip))
            f2=f2+f1
        if self.checkBox_10.isChecked():
            f1=unicode("""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue"> APPLICATION </font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td>""").format(code=unicode(app))
            f2=f2+f1
        time = datetime.datetime.now().strftime("%d-%m-%Y  %H:%M:%S")
        l_time = unicode(time)
        html =unicode("""<!doctype html><html><head>
        <table>
                        <tr><td><img src="logo.jpg" alt="some_text"></td><td><h1><font color="blue">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Patch deployment Report</font></h1></td><td><p align="right"><h5>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{report2}</p></h5></td></table>
                        <br><br><br>
        
        
        <table style="border:2px solid #0000FF; margin:0 auto; " cellpadding="20px" width="75%">
       
        {code}
      
        </table><br><br><br><br><br><br><table width="100%"><tr><td><div dir="ltr">Internal Purpose</div></td><td><div dir="rtl">Signature  </div></td></tr></table></html>""").format(code=f2,report2=l_time)
        try:
            self.webView.setHtml(html)
            self.html = html
            #self.printer = QtGui.QPrinter()  
            #self.printer.setOutputFormat(self.printer.PdfFormat)
            #self.printer.setOutputFileName("outtt.pdf")
            #self.webView.print_(self.printer)
        except Exception as e:
            pass;
    def pprint_file(self):
        try:
            fill = open(c_d+"\\pdf\\deploy_pdf.html","wb")
            fill.write(self.html)
            fill.close()
            print "EXE>",c_d+"\\pd\\wkhtmltopdf.exe "+c_d+"\\pdf\\deploy_pdf.html "+c_d+"\\pdf\\deploy_pdf.pdf"
            subprocess.call(c_d+"\\pd\\wkhtmltopdf.exe "+c_d+"\\pdf\\deploy_pdf.html "+c_d+"\\pdf\\deploy_pdf.pdf")
            subprocess.Popen([c_d+"\\pdf\\deploy_pdf.pdf"],shell=True)
        except Exception as e:
            print "PRINT PDF ERROR>",e
        
    def pprint_backup(self):
        try:
            path1 = c_d+"\\pdf\\backup_pdf.html"
            print "PATH>",path1 
            fill = open(path1,"wb")
            fill.write(self.html2)
            fill.close()
            subprocess.call(c_d+"\\pd\\wkhtmltopdf.exe "+c_d+"\\pdf\\backup_pdf.html "+c_d+"\\pdf\\backup_pdf.pdf")
            subprocess.Popen([c_d+"\\pdf\\backup_pdf.pdf"],shell=True)
        except Exception as e:
            print "PRINT PDF ERROR>",e
        subprocess.Popen([c_d+"\\pdf\\backup_pdf.pdf"],shell=True)
    def usr_mgm(self):
        print "Log Display"
        con = sqlite3.connect(c_d+'\\auth.db')
        con2 = sqlite3.connect(c_d+'\\auth.db')
        cursor = con.cursor()
        cursor2 = con2.cursor()
        rowcount = cursor2.execute('''SELECT username,name,id,type,status FROM auth''')
        row2 = rowcount.fetchall()
        print len(row2)
        self.tableWidget_2.setRowCount(len(row2))
        self.tableWidget_2.setColumnCount(5)
        cursor.execute('''SELECT username,name,id,type,status FROM auth''')
        self.tableWidget_2.setHorizontalHeaderLabels(['USERNAME', 'NAME', 'ID', 'TYPE','STATUS'])
        for row, form in enumerate(cursor):
            for column, item in enumerate(form):
                self.tableWidget_2.setItem(row, column, QtGui.QTableWidgetItem(unicode(item)))
    def del_usr_mgm(self):
        user_name = self.lineEdit_13.text()
        user_name = unicode(user_name)
        con3 = sqlite3.connect(c_d+'\\auth.db')
        cursor3 = con3.cursor()
        cursor3.execute('delete from auth where username='+'\''+user_name+'\'')
        con3.commit()
        if cursor3.rowcount==1:
            self.label_34.setText("DELETE SUCCESS")
        else:
            self.label_34.setText("DELETE FAILED")
        con3.close()
    def up_usr_mgm(self):
        u_name = self.lineEdit_13.text()
        u_name = unicode(u_name)
        u_type = self.comboBox.currentText()
        u_type = unicode(u_type)
        u_stat = self.comboBox_2.currentText()
        u_stat = unicode(u_stat)
        con4 = sqlite3.connect(c_d+'\\auth.db')
        cursor4 = con4.cursor()
        cursor4.execute('update auth set type='+'\''+u_type+'\''+',status='+'\''+u_stat+'\''+' where username='+'\''+u_name+'\'')
        con4.commit()
        if cursor4.rowcount==1:
            self.label_34.setText("UPDATE SUCCESS")
        else:
            self.label_34.setText("UPDATE FAILED")
        con4.close()
    def retry_all(self):
        old=''
        self.textEdit.clear()
        for item in self.listWidget_5.selectedItems():
            aa = unicode(item.text())
            aa = aa.split(":")
            aa = aa[0]
            old = unicode(aa)+"\n"+old
            self.textEdit.setText(unicode(old))
            self.listWidget_5.takeItem(self.listWidget_5.row(item))
    def cancel_dep(self):
        dep_up.put_nowait("cancel")
    def cancel_back(self):
        back_up.put_nowait("cancel")
    def show_app(self):
        try:
            self.comboBox_4.clear()
            con = sqlite3.connect(c_d+'\\app_name.db')
            cur = con.cursor()
            cur.execute('select name from app_name')
            n = cur.fetchall()
            for app_name in n:
                app = app_name[0]
                if app != "SELECT APPLICATION":
                    self.comboBox_4.addItem(app)
            con.close()
        except Exception as e:
            print e
    def add_app(self):
        app = self.lineEdit_16.text()
        app = unicode(app)
        if len(app)>0:
            try:
                con = sqlite3.connect(c_d+'\\app_name.db')
                cur = con.cursor()
                cur.execute('''insert into app_name(name)values(?)''',(app,))
                con.commit()
                con.close()
                self.label_45.setText("ADD SUCCESS")
                self.comboBox_4.clear()
            except Exception as e:
                self.label_45.setText("ADD FAILED")
                print e
    def del_app(self):
        app = self.comboBox_4.currentText()
        app = unicode(app)
        if len(app)>0:
            try:
                con = sqlite3.connect(c_d+'\\app_name.db')
                cur = con.cursor()
                cur.execute('delete from app_name where name='+'"'+app+'"')
                con.commit()
                con.close()
                self.label_45.setText("DELETE SUCCESS")
                self.comboBox_4.clear()
            except Exception as e:
                self.label_45.setText("DELETE FAILED")
                print e
    
    def disp_backup_info(self,row, column):
        html=""
        username=''
        time=''
        r_ip=''
        r_path=''
        l_path=''
        l_ip=''
        all_itm=''
        f1=''
        f2=''
        code=''
        ttrow = row
        item = self.tableWidget_3.item(ttrow, 0)
        username = item.text()
        item = self.tableWidget_3.item(ttrow, 1)
        time = item.text()
        item = self.tableWidget_3.item(ttrow, 2)
        r_ip = item.text()
        item = self.tableWidget_3.item(ttrow, 3)
        r_path = item.text()
        item = self.tableWidget_3.item(ttrow, 4)
        l_path = item.text()
        item = self.tableWidget_3.item(ttrow, 5)
        l_ip = item.text()
        item = self.tableWidget_3.item(ttrow, 6)
        all_itm = item.text()
        if self.checkBox_12.isChecked():
            f1="""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue"> NAME </font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""".format(code=unicode(username))
            f2=f2+f1
        if self.checkBox_13.isChecked():
            f1="""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue"> DATE & TIME </font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""".format(code=unicode(time))
            f2=f2+f1
        if self.checkBox_17.isChecked():
            f1="""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue"> SOURCE IP </font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""".format(code=unicode(l_ip))
            f2=f2+f1
        if self.checkBox_16.isChecked():
            f1="""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue"> SOURCE PATH </font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""".format(code=unicode(l_path))
            f2=f2+f1
        if self.checkBox_14.isChecked():
            f1="""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue"> DESTINATION IP </font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""".format(code=unicode(r_ip))
            f2=f2+f1
        if self.checkBox_15.isChecked():
            f1="""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue"> DESTINATION PATH </font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""".format(code=unicode(r_path))
            f2=f2+f1
        if self.checkBox_18.isChecked():
            f1="""<tr><td style="border:1px solid #0000FF; valign="top"><h3><font color="blue"> TOTAL ITEMS </font></strong></td><td style="border:1px solid #0000FF; valign="top"><h3>{code}</h3></td></tr>""".format(code=unicode(all_itm))
            f2=f2+f1
        time = datetime.datetime.now().strftime("%d-%m-%Y  %H:%M:%S")
        l_time = unicode(time)
        html ="""<!doctype html><html><head>
        <table>
                        <tr><td><img src="logo.jpg" alt="some_text"></td><td><h1><font color="blue">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Patch Backup Report</font></h1></td><td><p align="right"><h5>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{report2}</p></h5></td></table>
                        <br><br><br>
        
        
        <table style="border:2px solid #0000FF; margin:0 auto; " cellpadding="20px" width="75%">
       
        {code}
      
        </table><br><br><br><br><br><br><table width="100%"><tr><td><div dir="ltr">Internal Purpose</div></td><td><div dir="rtl">Signature  </div></td></tr></table></html>""".format(code=f2,report2=l_time)
        try:
            self.webView_2.setHtml(html)
            #self.printer = QtGui.QPrinter()
            #self.printer.setOutputFormat(self.printer.PdfFormat)
            #self.printer.setOutputFileName("backup.pdf")
            #self.webView_2.print_(self.printer)
            self.html2=html
        except Exception as e:
            print e
if __name__ == "__main__":
        print sys.argv
        app = QtGui.QApplication(sys.argv)
        app.setStyle(QtGui.QStyleFactory.create("plastique"))
        window = MyApp()
        window.show()
        sys.exit(app.exec_())