PDF-Embanner/pdfembannersrc/encrypt.py

200 lines
9.1 KiB
Python
Raw Permalink Normal View History

2018-05-18 06:49:19 +00:00
# -*-coding:utf-8 -*
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
from tkinter import simpledialog
from tkinter import ttk
from pdfembannersrc import subwindows
import logging
import PyPDF2
logger = logging.getLogger()
class Interface(tk.Toplevel):
"""
Main encryption window
Allows to :
* Encrypt a pdf
* Decrypt a pdf
"""
def __init__(self, parent, **kwargs):
tk.Toplevel.__init__(self, parent)
self.transient(parent)
self.grab_set()
self.title("PDF Embanner : encryption")
self.geometry("800x300")
self.protocol("WM_DELETE_WINDOW", self.close)
self.bind("<Escape>", self.close)
self.enc_file = None
self.dec_file = None
self.enc_saveas = None
self.dec_saveas = None
self.f = tk.Frame(self, width=768, height=576, **kwargs)
self.f.pack(fill=tk.BOTH)
# Création de nos widgets
self.f.columnconfigure(1, weight=1)
self.f.rowconfigure(12, weight=1)
tk.Label(self.f, text="Encryption...", bg="blue", fg="white", padx=20).grid(row=0, column=0, columnspan=3, sticky=tk.W)
tk.Button(self.f, text="Open", command=self.enc_open).grid(row=1, column=0)
self.enc_open_label = tk.Label(self.f, text="-" if self.enc_file is None else self.enc_file)
self.enc_open_label.grid(row=1, column=1, columnspan=3, sticky=tk.W)
tk.Button(self.f, text="Save as", command=self.set_enc_saveas).grid(row=2, column=0)
self.enc_save_label = tk.Label(self.f, text="-" if self.enc_saveas is None else self.enc_saveas)
self.enc_save_label.grid(row=2, column=1, columnspan=3, sticky=tk.W)
tk.Button(self.f, text="Encrypt", command=self.enc_do, fg="blue").grid(row=4, column=3)
ttk.Separator(self.f, orient="horizontal").grid(row=5, column=0, columnspan=4, sticky=tk.W+tk.E, padx=5, pady=10)
tk.Label(self.f, text="Decrypt...", bg="blue", fg="white", padx=20).grid(row=6, column=0, columnspan=3, sticky=tk.W)
tk.Button(self.f, text="Open", command=self.dec_open).grid(row=7, column=0)
self.dec_open_label = tk.Label(self.f, text="-" if self.dec_file is None else self.dec_file)
self.dec_open_label.grid(row=7, column=1, columnspan=3, sticky=tk.W)
tk.Button(self.f, text="Save as", command=self.set_dec_saveas).grid(row=8, column=0)
self.dec_save_label = tk.Label(self.f, text="-" if self.dec_saveas is None else self.dec_saveas)
self.dec_save_label.grid(row=8, column=1, columnspan=3, sticky=tk.W)
tk.Button(self.f, text="Decrypt", command=self.dec_do, fg="blue").grid(row=9, column=3)
ttk.Separator(self.f, orient="horizontal").grid(row=10, column=0, columnspan=4, sticky=tk.W+tk.E, padx=5, pady=10)
tk.Button(self.f, text="Close", command=self.close).grid(row=11, column=3)
self.message = tk.Label(self.f, text="Welcome!")
self.message.grid(row=13, column=0, columnspan=4, sticky=tk.W)
def enc_open(self, *args):
ftypes = [('PDF files (Portable Document Format)', '*.pdf'), ('All files', '*')]
fl = filedialog.askopenfilename(filetypes = ftypes)
if fl!='':
self.enc_file = fl
self.enc_open_label["text"] = fl
def dec_open(self, *args):
ftypes = [('PDF files (Portable Document Format)', '*.pdf'), ('All files', '*')]
fl = filedialog.askopenfilename(filetypes = ftypes)
if fl!='':
self.dec_file = fl
self.dec_open_label["text"] = fl
def enc_do(self, *args):
if(self.enc_file is None):
messagebox.showwarning(title="PDF Output", message="Please open the PDF to encrypt before !")
elif(self.enc_saveas is None):
messagebox.showwarning(title="PDF Output", message="Please define the 'Save As' path before !")
else:
pwd1 = simpledialog.askstring("Encryption", "Password:", show='*')
if(pwd1 is not None):
pwd2 = simpledialog.askstring("Encryption", "Re-type password:", show='*')
if(pwd2 is None):
return
elif(pwd1==pwd2):
pwd=pwd1
else:
messagebox.showwarning(title="Encryption", message="Passwords do not match!")
return
else:
return
currentf = self.enc_file
progress = subwindows.Progress(self, 4, "Producing PDF...")
progress.message["text"] = 'Reading files'
self.message["text"] = "Encrypting"
try:
with open(self.enc_file, 'rb') as in_f:
inpdf = PyPDF2.PdfFileReader(in_f)
progress.next()
output = PyPDF2.PdfFileWriter()
output.addMetadata(inpdf.getDocumentInfo())
output.appendPagesFromReader(inpdf)
progress.next()
output.encrypt(pwd)
progress.next()
currentf = self.enc_saveas
with open(self.enc_saveas, 'wb') as out_f:
logger.debug("Encrypt : Writing into file : start")
progress.message["text"] = 'Encryption and writing file'
output.write(out_f)
logger.debug("Encrypt : Writing into file : done")
self.message["text"] = "Done"
progress.next()
except IOError:
logger.warn("Encrypt : Could not open one of the files :: {} {} {}".format(currentf, e.errno, e.strerror))
messagebox.showerror(title="Error",
message="IO Error occured :\nImpossible to open one of the files ({})\nNo output produced!".format(currentf))
except Exception as e:
logger.warn("Encrypt : Unknown error occured during PDF production. {}".format(str(e)))
messagebox.showerror(title="Error",
message="An Error occured :\n{}\nNo output produced!".format(e))
finally:
progress.close()
def dec_do(self, *args):
if(self.dec_file is None):
messagebox.showwarning(title="PDF Output", message="Please open the PDF to encrypt before !")
elif(self.dec_saveas is None):
messagebox.showwarning(title="PDF Output", message="Please define the 'Save As' path before !")
else:
pwd = simpledialog.askstring("Encrypted", "Password:", show='*')
if(pwd is None):
return
currentf = self.dec_file
progress = subwindows.Progress(self, 4, "Producing PDF...")
progress.message["text"] = 'Reading file'
self.message["text"] = "Decrypting"
try:
with open(self.dec_file, 'rb') as in_f:
inpdf = PyPDF2.PdfFileReader(in_f)
progress.next()
okpwd = inpdf.decrypt(pwd)
if(okpwd==0):
messagebox.showwarning(title="Encrypted", message="Incorrect password!")
return
progress.next()
output = PyPDF2.PdfFileWriter()
output.addMetadata(inpdf.getDocumentInfo())
output.appendPagesFromReader(inpdf)
progress.next()
currentf = self.dec_saveas
with open(self.dec_saveas, 'wb') as out_f:
logger.debug("Decrypt : Writing into file : start")
output.write(out_f)
logger.debug("Decrypt : Writing into file : done")
self.message["text"] = "Done"
progress.next()
except IOError as e:
logger.warn("Encrypt : Could not open one of the files :: {} {} {}".format(currentf, e.errno, e.strerror))
messagebox.showerror(title="Error",
message="IO Error occured :\nImpossible to open one of the files ({})\nNo output produced!".format(currentf))
except NotImplementedError as e:
logger.warn("Decrypt : Not supported encryption method :: {}".format(e))
messagebox.showerror(title="Error",
message="The encryption method is not supported! Sorry :(")
except Exception as e:
logger.warn("Encrypt : Unknown error occured during PDF production. {}".format(str(e)))
messagebox.showerror(title="Error",
message="An Error occured :\n{}\nNo output produced!".format(e))
finally:
progress.close()
def set_enc_saveas(self, *args):
fsas = filedialog.asksaveasfilename()
if fsas != '':
self.enc_saveas = fsas
self.enc_save_label["text"] = fsas
def set_dec_saveas(self, *args):
fsas = filedialog.asksaveasfilename()
if fsas != '':
self.dec_saveas = fsas
self.dec_save_label["text"] = fsas
def close(self, *args):
self.destroy()