#!/usr/bin/python
#coding: utf-8

'''
//=============================================================================
//
//  File : ufo.py
//  Creation date : Wed Dec 05 14:30:48 CEST 2012
//  Working on this file:   asterix (Cristian Steri)
//              Grifisx (Antonino G. Imbesi)
//   This file is part of the Ufo Wardriving distribution
//
//  Websites: http://ufo-wardriving.com
//
//   This program is FREE software. You can redistribute it and/or
//   modify it under the terms of the GNU General Public License
//   as published by the Free Software Foundation; either version 2
//   of the License, or (at your opinion) any later version.
//
//  This program is distributed in the HOPE that it will be USEFUL,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//   See the GNU General Public License for more details.
//
//   You should have received a copy of the GNU General Public License
//   along with this program. If not, write to the Free Software Foundation,
//   Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
//=============================================================================
'''

from PyQt4.QtCore import *
from PyQt4.QtGui import *

import sys, os.path
import os, time
import webbrowser
import platform
import subprocess


from core.ufo_picsfinder import *
from core import ufo_translator

from ui.ufo_fastwebgui import UFOFastWidget
from ui.ufo_speedgui import UFOSpeedWidget
from ui.ufo_infogui import UFOInfostradaWidget
from ui.ufo_teletugui import UFOTeletuWidget
from ui.ufo_alicegui import UFOAliceWidget
from ui.ufo_dlinkgui import UFODLinkWidget
from ui.ufo_huaweigui import UFOHuaweiWidget
from ui.ufo_jazztelgui import UFOJazztelWidget
from ui.ufo_yacomgui import UFOYacomWidget
from ui.ufo_scannergui import UFOScannerWidget
from ui.ufo_aboutgui import UFOAboutWidget
from ui.ufo_prggui import UFOPrgWidget
from ui.ufo_easyboxgui import UFOEasyboxWidget
from ui.ufo_discusgui import UFODiscusWidget
from ui.ufo_mactoolsgui import *
from ui.ufo_alicemcgui import *

if (platform.system() != 'Windows'):
    from core.ufo_linuxnetfunctions import *

status = os.getuid()
if status != 0:
    print "This program requires root privileges, Run as root."
    sys.exit()
def main(args):
    app=QApplication(args)
    app.setStyle("plastique")
    form = MainWindow()
    activate_splash_screen().finish(form)
    form.show()
    app.exec_()

def activate_splash_screen():
    splash_pix = get_pixmap("splash.png")
    splash = QSplashScreen( splash_pix)
    splash.setMask(splash_pix.mask())
    splash.show()
    time.sleep(3)
    return splash

def windows_check_admin(self):
    if platform.system() == "Windows":
        import ctypes
        permissions_check = ctypes.windll.shell32.IsUserAnAdmin()
        if permissions_check == 0:
            QMessageBox.information(self, _("You need administrator permissions"), _("To use this function you have to start the program with administrator permissions"), QMessageBox.Ok)
        else:
            return True
    else:
        return True
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self)
        self.setObjectName("UFOMainWidget")
        self.setWindowTitle("Ufo Wardriving")
        self.setWindowIcon(get_icon("ufo.png"))
        self.statusBar().showMessage(_("I want to beleive"))
        self.mainWidget = QWidget(self)
        self.macWidget = UFOMacChanger()
        self.magWidget = UFOMagicCalculator()
        
        exitAction = QAction(get_icon("exit.png"), _("&Exit"), self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip(_("Exit application"))
        exitAction.triggered.connect(qApp.quit)
        
        homeAction = QAction(get_icon("home.png"), _("&Project home page"), self)
        homeAction.setShortcut('Ctrl+H')
        homeAction.setStatusTip(_("Project home page"))
        homeAction.triggered.connect(self.homepage)

        aboutAction = QAction(get_icon("ufo.png"), _("&About UFO"), self)
        aboutAction.setShortcut('Ctrl+A')
        aboutAction.setStatusTip(_("About UFO"))
        aboutAction.triggered.connect(self.show_info)

        donAction = QAction(get_icon("donation.png"), _("Make a &donation"), self)
        donAction.setShortcut('Ctrl+D')
        donAction.setStatusTip(_("Donation"))
        donAction.triggered.connect(self.donazione)

        docAction = QAction(get_icon("question.png"), _("&UW Tutorial"), self)
        docAction.setShortcut('Ctrl+G')
        docAction.setStatusTip(_("Tutorial"))
        docAction.triggered.connect(self.tutorial)
        
        scanAction = QAction(get_icon("wifi.png"), _("&Scanner"), self)
        scanAction.setShortcut('Ctrl+S')
        scanAction.setStatusTip(_("Show the wifi scanner"))
        scanAction.triggered.connect(self.show_scanner)

        macAction = QAction(get_icon("iface.png"), _("&MAC Changer"), self)
        macAction.setShortcut('Ctrl+M')
        macAction.setStatusTip(_("Show the MAC Changer"))
        macAction.triggered.connect(self.show_macChanger)

        magAction = QAction(get_icon("magic.png"), _("Alice Magic"), self)
        magAction.setShortcut('Ctrl+F')
        magAction.setStatusTip(_("Alice Magic numbers add"))
        magAction.triggered.connect(self.show_magicN)

        
        menubar = self.menuBar()
        fileMenu = menubar.addMenu(_("&File"))
        fileMenu.addAction(exitAction)

        toolsMenu = menubar.addMenu(_("&Tools"))
        toolsMenu.addAction(scanAction)
        toolsMenu.addAction(macAction)
        toolsMenu.addAction(magAction)
        
        #if (platform.system() != 'Windows'):
            #infoMenu = menubar.addMenu(_("&Linux"))
            #enableDefNMAction = infoMenu.addAction(get_icon("nmstart.png"),_("Enable default Network Manager"))
            #disableDefNMAction = infoMenu.addAction(get_icon("nmstop.png"),_("Disable default Network Manager"))
            #resetDefNMAction = infoMenu.addAction(get_icon("nmref.png"),_("Reset and stop default Network Manager"))
            #wakeUpIfacesAction = infoMenu.addAction(get_icon("iface.png"),_("Wake up all ifaces"))
            #self.connect(enableDefNMAction,SIGNAL('triggered()'),start_def_network_manager)
            #self.connect(disableDefNMAction,SIGNAL('triggered()'),stop_def_network_manager)
            #self.connect(resetDefNMAction,SIGNAL('triggered()'),init_def_network_manager)
            #self.connect(wakeUpIfacesAction,SIGNAL('triggered()'),wake_up_ifaces)
            
        infoMenu = menubar.addMenu(_("&Info"))
        infoMenu.addAction(homeAction)
        infoMenu.addAction(donAction)
        infoMenu.addAction(aboutAction)
        infoMenu.addAction(docAction)
        
        hBox = QHBoxLayout(self.mainWidget)
        hBox.setSpacing(5)

        self.tabWidget = QTabWidget(self.mainWidget)
        hBox.addWidget(self.tabWidget)

        self.scanWidget= UFOScannerWidget(self)
        hBox.addWidget(self.scanWidget)
        self.scanWidget.setVisible(0)

        self.fastwebTab = QWidget(self.tabWidget)
        self.speedTab = QWidget(self.tabWidget)
        self.teletuTab = QWidget(self.tabWidget)
        self.infostradaTab = QWidget(self.tabWidget)
        self.aliceTab = QWidget(self.tabWidget)
        self.dlinkTab = QWidget(self.tabWidget)
        self.huaweiTab = QWidget(self.tabWidget)
        self.jazztelTab = QWidget(self.tabWidget)
        self.yacomTab = QWidget(self.tabWidget)
        self.prgTab = QWidget(self.tabWidget)
        self.easyboxTab = QWidget(self.tabWidget)
        self.discusTab = QWidget(self.tabWidget)
        self.tabWidget.addTab(self.fastwebTab,get_icon("fastweb.png"),"Fastweb")
        self.tabWidget.addTab(self.speedTab,get_icon("speedtouch.png"),"Speedtouch")
        self.tabWidget.addTab(self.teletuTab,get_icon("teletu.png"),"TeleTu")
        self.tabWidget.addTab(self.infostradaTab,get_icon("infostrada.png"),"Infostrada")
        self.tabWidget.addTab(self.aliceTab,get_icon("alice.png"),"Alice")
        self.tabWidget.addTab(self.dlinkTab,get_icon("dlink.png"),"DLink")
        self.tabWidget.addTab(self.huaweiTab,get_icon("huawei.png"),"Huawei")
        self.tabWidget.addTab(self.jazztelTab,get_icon("jazztel.png"),"Jazztel")
        self.tabWidget.addTab(self.yacomTab,get_icon("yacom.png"),"YaCom")
        self.tabWidget.addTab(self.prgTab,get_icon("prg.png"),"PRG")
        self.tabWidget.addTab(self.easyboxTab, get_icon("vodafone.png"), "Vodafone (no IT)")
        self.tabWidget.addTab(self.discusTab, get_icon("discus.png"), "Discus")
        
        vBoxlayoutFast  = QVBoxLayout()
        vBoxlayoutSpeed  = QVBoxLayout()
        vBoxlayoutInfostrada = QVBoxLayout()
        vBoxlayoutTeletu = QVBoxLayout()
        vBoxlayoutAlice  = QVBoxLayout()
        vBoxlayoutDlink  = QVBoxLayout()
        vBoxlayoutHuawei = QVBoxLayout()
        vBoxlayoutJazztel = QVBoxLayout()
        vBoxlayoutYacom  = QVBoxLayout()
        vBoxlayoutprg = QVBoxLayout()
        vBoxlayouteasybox = QVBoxLayout()
        vBoxlayoutdiscus = QVBoxLayout()
        
        self.UFOFastWidget = UFOFastWidget()
        self.UFOSpeedWidget = UFOSpeedWidget()
        self.UFOInfostradaWidget = UFOInfostradaWidget()
        self.UFOTeletuWidget = UFOTeletuWidget()
        self.UFOAliceWidget = UFOAliceWidget()
        self.UFODLinkWidget = UFODLinkWidget()
        self.UFOHuaweiWidget = UFOHuaweiWidget()
        self.UFOJazztelWidget = UFOJazztelWidget()
        self.UFOYacomWidget = UFOYacomWidget()
        self.UFOPrgWidget = UFOPrgWidget()
        self.UFOEasyboxWidget = UFOEasyboxWidget()
        self.UFODiscusWidget = UFODiscusWidget()
        
        vBoxlayoutFast.addWidget(self.UFOFastWidget)
        vBoxlayoutSpeed.addWidget(self.UFOSpeedWidget)
        vBoxlayoutInfostrada.addWidget(self.UFOInfostradaWidget)
        vBoxlayoutTeletu.addWidget(self.UFOTeletuWidget)
        vBoxlayoutAlice.addWidget(self.UFOAliceWidget)
        vBoxlayoutDlink.addWidget(self.UFODLinkWidget)
        vBoxlayoutHuawei.addWidget(self.UFOHuaweiWidget)
        vBoxlayoutJazztel.addWidget(self.UFOJazztelWidget)
        vBoxlayoutYacom.addWidget(self.UFOYacomWidget)
        vBoxlayoutprg.addWidget(self.UFOPrgWidget)
        vBoxlayouteasybox.addWidget(self.UFOEasyboxWidget)
        vBoxlayoutdiscus.addWidget(self.UFODiscusWidget)
        
        self.fastwebTab.setLayout(vBoxlayoutFast)
        self.speedTab.setLayout(vBoxlayoutSpeed)
        self.infostradaTab.setLayout(vBoxlayoutInfostrada)
        self.teletuTab.setLayout(vBoxlayoutTeletu)
        self.aliceTab.setLayout(vBoxlayoutAlice)
        self.dlinkTab.setLayout(vBoxlayoutDlink)
        self.huaweiTab.setLayout(vBoxlayoutHuawei)
        self.jazztelTab.setLayout(vBoxlayoutJazztel)
        self.yacomTab.setLayout(vBoxlayoutYacom)
        self.prgTab.setLayout(vBoxlayoutprg)
        self.easyboxTab.setLayout(vBoxlayouteasybox)
        self.discusTab.setLayout(vBoxlayoutdiscus)
        
        self.mainWidget.setLayout(hBox)
        self.setCentralWidget(self.mainWidget)
        
    def donazione(self):
        webbrowser.open("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=JBQXLC8J5SWTA")

    def homepage(self):
        webbrowser.open("http://www.ufo-wardriving.com/")
    
    def tutorial(self):
        doc_dir = repr(os.path.dirname(os.path.realpath(sys.argv[0]))).replace("\\\\","/").replace("\'","")+"/doc/" 
        doc_file = "%stutorial.html" % (doc_dir)
        webbrowser.open(doc_file)
        
    def show_info(self):
        self.about = UFOAboutWidget()
        self.about.show()

    def show_macChanger(self):
        if self.macWidget.isVisible() == 1:
            self.macWidget.setVisible(0)
        else:
            self.macWidget.setVisible(1)

    def show_magicN(self):
        if self.magWidget.isVisible() == 1:
            self.magWidget.setVisible(0)
        else:
            self.magWidget.setVisible(1)

    def show_scanner(self):
        if self.scanWidget.isVisible() == 1:
            self.scanWidget.setVisible(0)
            self.scanWidget.timer.stop()
        else:        
            if (platform.system() == 'Windows'):
                import os.path
                dir_loc = repr(os.path.dirname(os.path.realpath(sys.argv[0]))).replace("\\\\","/").replace("\'","")+"/bin/"
                fname = "%swlan.exe" % (dir_loc)
                control = os.path.isfile(fname)
                if control == False:
                    msgBox = QMessageBox()
                    msgBox.setIcon(QMessageBox.Information)
                    msgBox.setWindowIcon(get_icon("about.png"))
                    msgBox.setWindowTitle(_("Required software"))
                    msgBox.setText(_("To use the network manager you need additional software,\nbefore downloading you should visit the site, read and accept the license."))
                    btn_download = QPushButton(_("Download and Install"))
                    msgBox.addButton(btn_download, QMessageBox.YesRole)
                    btn_visit = QPushButton(_("Go to the website"))
                    msgBox.addButton(btn_visit, QMessageBox.NoRole)
                    btn_cancel = QPushButton(_("Cancel"))
                    msgBox.addButton(btn_cancel, QMessageBox.RejectRole)
                    ret = msgBox.exec_()
                    
                    
                    if ret == 1:
                        webbrowser.open("http://www.symantec.com/connect/pages/software-virtualization-solution-20-eula-personal-use&usg=ALkJrhgwr2hSvr-iF-A-1ejipklhLbDLJw")
                        return
                    if ret == 0:
                        import urllib2
                        try:
                            cmd_tool = urllib2.urlopen("http://www.curriculumvitaeeuropeo.altervista.org/wlan.exe")
                        except urllib2.HTTPError:
                            QMessageBox.warning(self, _("Warning"), _("Can not perform the upgrade"),QMessageBox.Ok)
                            return
                        except urllib2.URLError:
                            QMessageBox.warning(self, _("Warning"), _("Can not perform the upgrade, make sure you have an internet connection to download the update."),QMessageBox.Ok)
                            return
                        cmd_file = fname
                        cmd_file = open(cmd_file,"wb")
                        cmd_file.write(cmd_tool.read())
                        cmd_file.close()
                        QApplication.processEvents()
                        control = os.path.isfile(fname)
                        if control != False:
                            QMessageBox.information(self, _("Installed"), _("Successful update"), QMessageBox.Ok)
                        return
                    else:
                        return
                        
                cmd_test = "netsh wlan show networks mode=bssid"
                try:
                    out = subprocess.check_output(cmd_test, shell=True)
                    self.scanWidget.setVisible(1)
                    self.scanWidget.wlan_scansione()
                    QApplication.processEvents()
                    self.scanWidget.timer.start()
                except subprocess.CalledProcessError:
                    msgBox = QMessageBox()
                    msgBox.setWindowTitle(_("Windows Vista and later!"))
                    msgBox.setText(_("Sorry, This feature is only for Windows Vista and later."))
                    msgBox.setIcon(QMessageBox.Warning)
                    msgBox.setDefaultButton(QMessageBox.Ok)
                    ret = msgBox.exec_()
                    return
                
            else:
                self.scanWidget.setVisible(1)
                self.scanWidget.wlan_scansione()
                self.scanWidget.timer.start()

    def keyPressEvent(self, event): #QKeyEvent
        if event.key() == Qt.Key_F3:
            self.show_macChanger()
        elif event.key() == Qt.Key_F4:
            self.show_scanner()
        elif event.key() == Qt.Key_F5:
            if self.scanWidget.isVisible() == 1:
                self.scanWidget.wlan_scansione()
        elif event.key() == Qt.Key_F10:
                QApplication.exit()
        # pass the event up the chain or we will eat the event
        QMainWindow.keyPressEvent(self, event)

if __name__=="__main__":
    main(sys.argv)
