-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathease.py
More file actions
executable file
·1966 lines (1675 loc) · 76.2 KB
/
ease.py
File metadata and controls
executable file
·1966 lines (1675 loc) · 76.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# coding=utf-8
# EASE: Encrypt and Send with EASE
# Simple utility for symmetric encryption of files or file archives
# prior to distribution over untrusted services (like e-mail).
#
# Copyright (C) 2020 Sigbjørn "sigg3" Smelror <git@sigg3.net>.
#
# EASE 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, version 3 of the License.
#
# EASE 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.
# URL: <https://www.gnu.org/licenses/old-licenses/gpl-3.0.txt>
#
# Submit issues at: <https://github.com/sigg3/ease>
# Graphical User Interface
import PySimpleGUIQt as sg
# Cryptography
from pyAesCrypt import encryptFile
from pyAesCrypt import decryptFile
# Password stuff
from password_strength import PasswordStats
from zxcvbn import zxcvbn
# Operations
from pathlib import Path
from typing import Tuple, Type
from threading import Thread
import datetime
import time
import zipfile
import tarfile
import webbrowser
# Translations
import gettext
_ = gettext.gettext
# List of issues, todos and bugs (by priority)
# TODO password evaluation
# zxcvbn-python, add "evaluate" button under passphrase entry on Encrypt
#
# TODO OOP branch
# It's time to re-do this project OOP
#
# TODO sending
# Using selenium is not recommended at this stage, because we will need
# a separate geckodriver install (and probably break ToS).
# Using webbrowser instead, we can serve a number of convenient links
# for sharing file(s), and also a button to attach to e-mail message.
#
# TODO
# in pysimplegui june 2020, signalling windows from other threads was added.
# Look into whether this is a worthwhile change to ease.
# In the meantime, existing is_alive method in Thread objects is sufficient.
# cf. create_spinner() and run_in_the_background()
# TODO keyfiles
# while we want to keep things simple, it's only a matter of time before
# someone requests asymmetric encryption
#
# TODO Functional branch
# If we are going to learn methodology, better do it functionally too.
def setup_transmitters() -> dict:
"""
Returns dict of online file transfer sites (for sending over WWW).
Separated into its own function for maintenance reasons.
Use _('string encapsulation') for strings that should be translated.
Each entry must contain:
- short name (e.g. URL without protocol)
- URL (preferably https)
- date (changed/updated/added)
- file expire (in days)
- max file size for any single file in GB
- require login (bool)
- known limitations (short string)
- working URL to faq or help page (used for reference)
- automation enabled (bool)
Automation disabled at the time of writing.
Setting automated to True entails writing and linking a function
that accepts .aes input file and sends it across the desired site
(using e.g. selenium) and returning the URL created to the end-user.
Use _('string encapsulation') for strings that should be translated.
"""
# setup return
sites = {}
# sendgb.com (added 2020-09-07)
name = "sendgb.com"
sites[name] = {}
sites[name]["changed"] = "2020-09-07"
sites[name]["site_url"] = f"https://www.{name}"
sites[name]["days_expire"] = "7"
sites[name]["max_size_gb"] = "5 GB"
sites[name]["require_login"] = False
sites[name]["automated"] = False
sites[name]["limitations"] = _("files stored for 90 days.")
sites[name]["faq"] = "https://www.sendgb.com/en/faq.html"
# sendgb.com (added 2020-09-07)
name = "fromsmash.com"
sites[name] = {}
sites[name]["changed"] = "2020-09-07"
sites[name]["site_url"] = f"https://{name}"
sites[name]["days_expire"] = "14"
sites[name]["max_size_gb"] = _("None")
sites[name]["require_login"] = False
sites[name]["automated"] = False
sites[name]["limitations"] = _("files 0-2 GB in size must queue.")
sites[name]["faq"] = "https://faq.fromsmash.com/"
# sendgb.com (added 2020-09-07)
name = "surgesend.com"
sites[name] = {}
sites[name]["changed"] = "2020-09-07"
sites[name]["site_url"] = f"https://{name}"
sites[name]["days_expire"] = "7"
sites[name]["max_size_gb"] = "3 GB"
sites[name]["require_login"] = False
sites[name]["automated"] = False
sites[name]["limitations"] = _("store up to 5GB per month")
sites[name]["faq"] = "https://surgesend.com/help"
# dropbox (added 2020-09-08)
name = "dropbox.com"
sites[name] = {}
sites[name]["changed"] = "2020-09-08"
sites[name]["site_url"] = f"https://{name}"
sites[name]["days_expire"] = "N/A"
sites[name]["max_size_gb"] = "2 GB"
sites[name]["require_login"] = True
sites[name]["automated"] = False
sites[name]["limitations"] = _("free account gives 2GB storage total")
sites[name]["faq"] = "https://www.dropbox.com/basic"
# add-more-here (date added)
# name = "tld.tld"
# sites[name]["changed"] = "date added"
# sites[name]["site_url"] = f"https://{name}"
# sites[name]["days_expire"] = "N/A"
# sites[name]["max_size_gb"] = "X GB"
# sites[name]["require_login"] = True
# sites[name]["automated"] = False
# sites[name]["limitations"] = _("small note on limitations")
# sites[name]["faq"] = "<url to faq>"
# return any hits
return sites
def create_main_window() -> Type[sg.Window]:
"""
Create (and re-create) main (or initial) window
Return window object to allow for assignment to variable in main.
"""
# Set icons
icon_encrypt = ease["icon_encrypt"]
icon_decrypt = ease["icon_decrypt"]
icon_send = ease["icon_sendenc"]
icon_about = ease["icon_easehlp"]
# Set icon text
caption_encrypt = _("Encrypt")
caption_decrypt = _("Decrypt")
caption_send = _("Send")
caption_about = _("About")
# Justify icons using stringName.center(width,fillChar)
# TODO
caption_send = f" {caption_send}" # space added for English
caption_about = f" {caption_about}" # Qt justification :( # TODO
# Set layout
WelcomeLayout = [
[sg.Text(f"{ease['title']}", font=("Sans serif", 16))],
[sg.Text(" ")],
[sg.Text(
_("Encrypt a file or files securely so it's safe \
to distribute, or decrypt files you have received.")
)
],
[sg.Text(
_("This utility uses AES256-CBC (pyAesCrypt) to \
encrypt/decrypt files in the AES Crypt file format v.2.")
)
],
[sg.Text(" ")],
[sg.Button(
caption_encrypt,
image_data=icon_encrypt,
key="-button_encrypt-",
font=("Helvetica", 16)
),
sg.Button(
caption_decrypt,
image_data=icon_decrypt,
key="-button_decrypt-",
font=("Helvetica", 16)
)
],
[sg.Button(
caption_send,
image_data=icon_send,
key="-button_send-",
font=("Helvetica", 16)
),
sg.Button(
caption_about,
image_data=icon_about,
key="-button_about-",
font=("Helvetica", 16)
)
],
[sg.Text(" ")]
]
# Window object
Welcome = sg.Window(
ease["title"],
layout=WelcomeLayout,
resizable=True,
return_keyboard_events=False,
finalize=True
)
# return object to var
return Welcome
def create_enc_window() -> Type[sg.Window]:
"""
Helper function to create (and re-create) encryption window
Return window object to allow for assignment
"""
# Set tables
encrypt_options = [
[
sg.CBox(
_("Enable compression (smaller file size)"),
default=False,
key="compression"
)
],
[
sg.Radio(
"tarball",
"archive_radio",
key="tar"
),
sg.Radio(
"zip",
"archive_radio",
key="zip"
)
]
]
encrypt_input = [
[
sg.InputText(
key="enc_uinput_files",
enable_events=True
),
sg.FilesBrowse(
target="enc_uinput_files"
)
]
]
encrypt_output = [
[
sg.InputText(
ease["output_dir"],
disabled=True,
key="output_preview_str"
),
sg.FolderBrowse(
target="output_preview_str"
)
]
]
# Set layout
EncryptLayout = [
[sg.Text(
f"{ease['title']}", font=("Sans serif", 16)
)
],
[sg.Text(" ")],
[sg.Text(
_("Securely encrypt file(s), so it is safe to distribute \
over untrusted service (like e-mail).")
)
],
[sg.Text(
_("If you select more than one file, they will be gathered \
in an encrypted archive.")
)
],
[sg.Text(
_("If your recipient uses Windows, consider using zip \
instead of tar.")
)
],
[sg.T(" ")],
[sg.Frame(
layout=encrypt_input,
title=_("Select input file(s):")
)
],
[sg.Frame(
layout=encrypt_output,
title=_("Specify where to save the output")
)
],
[sg.Frame(
layout=encrypt_options,
title=_("Archiving options (for groups of files)")
)
],
[sg.Frame(layout=[
[sg.T(_("It is recommended to use a full sentence as \
the passphrase."))],
[sg.In("", key="uinput_passphrase")],
[sg.T(get_password_strength(""), key="uinput_ppstrength")]
],
title=_("Passphrase")
)
],
[
sg.Button(_("Encrypt"), key="-enc_encrypt-"),
sg.Cancel(_("Cancel"), key="-enc_cancel-")
]
]
Encrypt = sg.Window(
ease["title"],
layout=EncryptLayout,
resizable=True,
return_keyboard_events=True,
finalize=True
)
return Encrypt
def create_dec_window() -> Type[sg.Window]:
"""
Helper function to create (and re-create) decryption window
Return window object to allow for assignment
"""
# Set tables
decrypt_input = [
[
sg.InputText(key="dec_uinput_file", enable_events=True),
sg.FileBrowse(target="dec_uinput_file")
]
]
decrypt_options = [
[sg.CBox(
_("Automatically decompress decrypted archives"),
default=True,
key="uncompress"
)
],
[sg.CBox(
_("Remove source .aes file after decryption"),
default=False,
key="removesrc"
)
]
]
decrypt_output = [
[
sg.InputText(
ease["output_dir"],
disabled=True,
key="dec_output_preview_str"
),
sg.FolderBrowse(
target="dec_output_preview_str"
)
]
]
decrypt_passphrase = [
[sg.In(
"",
key="uinput_passphrase"
)
]
]
# Set layout
DecryptLayout = [
[sg.Text(
f"{ease['title']}",
font=("Sans serif", 16)
)
],
[sg.Text(" ")],
[sg.Text(
_("Decrypt any encrypted .aes file you have received.")
)
],
[sg.Text(
_("If the decrypted file is a tarball or zip archive, \
it will be extracted.")
)
],
[sg.T(" ")],
[sg.Frame(
layout=decrypt_input,
title=_("Select input file(s)")
)
],
[sg.Frame(
layout=decrypt_options,
title=_("Decryption options")
)
],
[sg.Frame(
layout=decrypt_output,
title=_("Specify where to save the output")
)
],
[sg.Frame(
layout=decrypt_passphrase,
title=_("Passphrase")
)
],
[
sg.Button(_("Decrypt"), key="-dec_decrypt-"),
sg.Cancel(_("Cancel"), key="-dec_cancel-")
]
]
Decrypt = sg.Window(
ease["title"],
layout=DecryptLayout,
resizable=True,
return_keyboard_events=False,
finalize=True
)
return Decrypt
def create_send_window() -> Type[sg.Window]:
"""
Helper function to create (and re-create) file send window.
Return window object to allow assignment
"""
# Fetch latest transmitter info
sites = ease["sites"]
# Set first item as default
for sitename in sites.keys():
siteinfo = get_infostring_from_key(sitename)
break # we just need the first one for creation
site_sentence = siteinfo[0]
site_cap = siteinfo[1]
site_faq = siteinfo[2]
xfer_disabled = siteinfo[3]
# File xfer site info table
xfer_site = [
[sg.T(
f"URL: {sites[sitename]['site_url']}",
key="-provider_url-"
)
],
[sg.T(
site_faq,
key="-provider_faq-"
)
],
[sg.T(
site_sentence,
key="-provider_info-"
)
],
[sg.T(
site_cap,
key="-provider_capinfo-"
)
]
]
# Window layout
SendfileLayout = [
[sg.Text(
f"{ease['title']}",
font=("Sans serif", 16)
)
],
[sg.Text(" ")],
[sg.Text(
_("Sometimes files are too big for attaching to e-mails.")
)
],
[sg.Text(
_("Most of these online file transfer services do not require a login.")
)
],
[sg.Text(
_("Select any provider to visit their website or attempt sending.")
)
],
[sg.Text(" ")],
[
sg.Text(
_("Choose file transfer service: ")
),
sg.Combo(
list(sites.keys()),
default_value=sitename,
key="-send_combo-",
readonly=True,
enable_events=True)
],
[sg.Frame(
layout=xfer_site,
title=" " # title is workaround
)
],
[sg.Text(" ")],
[
sg.Button(
_("Send"),
key="-send_send-",
disabled=xfer_disabled
),
sg.Button(
_("Open URL"),
key="-visit_url-"
),
sg.Button(
_("Cancel"),
key="-send_cancel-"
)
]
]
SendFile = sg.Window(
ease["title"],
layout=SendfileLayout,
resizable=True,
return_keyboard_events=False,
finalize=True
)
return SendFile
def create_about_window() -> Type[sg.Window]:
"""
Helper function to create (and re-create) an about window.
Returns a window object to allow assignment
"""
contrib = _("Submit issues and new translations at")
# Window layout
AboutLayout = [
[sg.Text(f"{ease['title']}", font=("Sans serif", 16))],
[sg.Text(" ")],
[sg.Text(_("EASE is written by Sigbjørn Smelror (c) 2020, GNU GPL v.3+, to provide"))],
[sg.Text(_("a hopefully user-friendly graphical interface to the pyAesCrypt module."))],
[sg.Text(_("It is distributed in the hope that it will be useful, but without any warranty."))],
[sg.Text(_("See the GNU General Public License for more details."))],
[sg.Text(f"{contrib}: {ease['git']}")],
[sg.Text(" ")],
[sg.Text(_("Usage should be fairly straight-forward: Encrypt -> Send -> Decrypt"))],
[sg.Text(" ")],
[sg.Text(_("Encrypting"), font=("Sans serif", 12))],
[sg.Text(_("The sender clicks the Encrypt button, selects the file(s) to encrypt,"))],
[sg.Text(_("and encrypts them using a passphrase (password) of his or her choosing."))],
[sg.Text(_("It is recommended to use a full sentence as the passphrase."))],
[sg.Text(_("This produces an encrypted AES Crypt v.2 file that has an .aes suffix."))],
[sg.Text(" ")],
[sg.Text(_("Sending"), font=("Sans serif", 12))],
[sg.Text(_("The encrypted .aes file can be distributed over untrusted services like"))],
[sg.Text(_("e-mail or any of the file transfer services available when clicking Send."))],
[sg.Text(_("Some services will provide a download link (URL) the recipient can use."))],
[sg.Text(_("Remember: never send an encrypted file and its passphrase together!"))],
[sg.Text(" ")],
[sg.Text(_("Decrypting"), font=("Sans serif", 12))],
[sg.Text(_("Having received the encrypted .aes file through e-mail or a service (above),"))],
[sg.Text(_("the recipient simply clicks the Decrypt button, selects the (.aes) file and"))],
[sg.Text(_("enters the passphrase (password) provided separately by the sender."))],
[sg.Text(_("And that's it!"))],
[sg.Text(" ")],
[sg.Text(_("EASE Crypto relies on pyAesCrypt, password_strength and zxcvbn-python"))],
[sg.Text(_("Graphical interface is provided by PySimpleGUIQt, translations use gettext."))],
[sg.Text(_("EASE is not affiliated with any of the file transfer services mentioned, and"))],
[sg.Text(_("please submit an issue if any of the services are terminated or changed."))],
[sg.Text(" ")],
[
sg.Button(
_("Homepage"),
key="-github-"
),
sg.Button(
_("OK"),
key="-about_ok-"
)
]
]
About = sg.Window(
ease["title"],
layout=AboutLayout,
resizable=False,
return_keyboard_events=False,
finalize=False
)
return About
def get_infostring_from_key(key: str) -> Tuple[str, str, str, bool]:
"""
Build string from sites[] dict in setup_transmitters()
Returns a tuple: f-string of general site info, and a bool
"""
# fetch data
sites = ease["sites"]
# automated "send" action button disabled/enabled status
# bool value opposite of bool in sites[key]["automated"]
xfer_disabled = False if sites[key]["automated"] else True
# build site info string
site_sentence = _("Max file size")
site_sentence += f": {sites[key]['max_size_gb']}, "
site_sentence += _("Expires (days)")
site_sentence += f": {sites[key]['days_expire']}, "
# finish info string
site_sentence += _("Require log-in")
site_sentence += ": "
if sites[key]["require_login"]:
site_sentence += _("Yes")
xfer_disabled = True # override (avoids this whole bag of bugs)
else:
site_sentence += _("No")
# get site cap (limitations) info
limitations = _("Limitations")
site_cap = sites[key]["limitations"]
if site_cap is None:
site_cap = f"{limitations}: N/A"
else:
site_cap = f"{limitations}: {site_cap}"
# get faq (URL)
site_faq = _("FAQ")
site_faq += ": "
site_faq += sites[key]["faq"]
return site_sentence, site_cap, site_faq, xfer_disabled
def get_folder_from_infiles(input_files: str) -> str:
"""
Return string of path object's parent if indeed the input is a
valid path else return safe default from settings.
"""
try:
if Path.is_file(Path(input_files)):
return str(Path(input_files).parent)
elif Path.is_file(Path(input_files.split(sep=";")[0])):
return str(Path(input_files.split(sep=";")[0]).parent)
else:
return ease["output_dir"]
except:
return ease["output_dir"]
def get_unique_middlefix() -> int:
"""
Returns a "unique" middle name for use in non-unique filenames
use: my_var = f"{my_file.stem}-{get_unique_suffix()}{my_file.suffix}"
Requires that my_file is path object and, of course, datetime.
"""
return int(datetime.datetime.timestamp(datetime.datetime.now()))
def get_password_strength(uinput_passphrase: str) -> str:
"""
We're not evaluating password policies, just providing feedback
Use: get_password_strength(Encrypt_value['uinput_passphrase'])
"""
# string wrangling
entropy = _("Passphrase entropy bits")
complexity = _("complexity")
score = _("score")
if uinput_passphrase is None or uinput_passphrase == "":
return f"{entropy}: 0.0, {complexity}: 0.00, {score}: 0"
stats = PasswordStats(uinput_passphrase)
pass_c = f"{stats.strength():0.2f}"
pass_e = f"{stats.entropy_bits:0.1f}"
pass_s = zxcvbn(uinput_passphrase)["score"]
return f"{entropy}: {pass_e}, {complexity}: {pass_c}, {score}: {pass_s}"
def evaluate_password(input_pass: str):
"""
Evaluates user passphrase (string) using zxcvbn
zxcvbn uses gettext, so no need to duplicate translations.
Until further notice, cf. translate_zxcvbn_strings(). # TODO
"""
# Evaluate input
pass_check = zxcvbn(input_pass)
# Expose selected strings to gettext
# Password strings
# debug
print(f"pass_check = {pass_check}")
print(pass_check["feedback"]["suggestions"][0])
# Crack times
# General
# str_feed = _("Feedback")
# str_warn = _("Warning")
# str_sugg = _("suggestions")
# Suggestion strings
str_addword = _("Add another word or two. Uncommon words are better.")
return str_addword
pass
def translate_zxcvbn_strings():
"""
Helper function to expose strings from imported module
zxcvbn's feedback.py to local gettext extraction
This dummy function provides a stale workaround. # TODO
"""
str_null = _("Use a few words, avoid common phrases."),
str_null = _("No need for symbols, digits, or uppercase letters.")
str_null = _("Add another word or two. Uncommon words are better.")
str_null = _("Straight rows of keys are easy to guess.")
str_null = _("Short keyboard patterns are easy to guess.")
str_null = _("Use a longer keyboard pattern with more turns.")
str_null = _("Repeats like \"aaa\" are easy to guess.")
str_null = _("Repeats like \"abcabcabc\" are only slightly harder to guess than \"abc\".")
str_null = _("Avoid repeated words and characters.")
str_null = _("Sequences like \"abc\" or \"6543\" are easy to guess."),
str_null = _("Recent years are easy to guess."),
str_null = _("Avoid recent years."),
str_null = _("Avoid years that are associated with you."),
str_null = _("Dates are often easy to guess."),
str_null = _("Avoid dates and years that are associated with you."),
str_null = _("This is a top-10 common password.")
str_null = _("This is a top-100 common password.")
str_null = _("This is a very common password.")
str_null = _("This is similar to a commonly used password.")
str_null = _("A word by itself is easy to guess.")
str_null = _("Names and surnames by themselves are easy to guess.")
str_null = _("Common names and surnames are easy to guess.")
str_null = _("Capitalization doesn't help very much.")
str_null = _("All-uppercase is almost as easy to guess as all-lowercase.")
str_null = _("Reversed words aren't much harder to guess.")
str_null = _("Predictable substitutions like '@' instead of 'a' don't help very much.")
pass
def archive(file_basename: str,
use_tar: bool,
use_compression: bool,
input_files: list) -> Tuple[list, str]:
"""
Write tar or zip file, depending on use_tar bool, containing items
in input_files list with optional (medium) compression. The function
handles filename too, given a basename. Returns tuple with a list
of file(s) successfully archived and the final filename we wrote.
Requires tarfile, zipfile, zlib, Path (pathlib)
"""
# Setup return vals
return_list = []
archive_filename = ""
# configure parameters for archiving procedure
if use_tar:
archivist = tarfile.open
if use_compression:
ftype="tar.gz"
compression = "w:gz"
else:
ftype="tar"
compression = "w"
use_mode = compression
else:
archivist = zipfile.ZipFile
ftype="zip"
compression = zipfile.ZIP_STORED
if use_compression:
try:
import zlib
compression = zipfile.ZIP_DEFLATED
except (ImportError, AttributeError):
compression = zipfile.ZIP_STORED
except Exception as e:
print(f"Unhandled exception in archive(): {e}")
use_mode = "w"
# Set output file (make unique if necessary)
archive_filename = f"{file_basename}.{ftype}"
if Path.is_file(Path(archive_filename)):
archive_filename = f"{file_basename}-{get_unique_middlefix()}.{ftype}"
# archive input files into archive_file using procedure set
with archivist(archive_filename, mode=use_mode) as new_archive:
for file_to_archive in input_files:
try:
file_arcname = str(Path(file_to_archive).stem)
if use_tar:
new_archive.add(
file_to_archive,
arcname=file_arcname # arcname=stem here did not work..
)
else:
new_archive.write(
file_to_archive,
arcname=file_arcname,
compress_type=compression
)
return_list.append(file_to_archive)
except Exception as e:
print(f"{archivist} could not add {file_to_archive}: {e}")
pass
return return_list, archive_filename
def unarchive(archive_filename: str, output_dir: str) -> Tuple[list, list]:
"""
Extract archive, whether zip or tar to output dir
Returns lists of file(s) extracted into output dir and skipped files
"""
# Setup return vals
extracted = []
skipped = []
# Detect what kind of input we have here
if tarfile.is_tarfile(archive_filename):
archivist = tarfile.open
is_tar = True
use_mode = "r:*"
elif zipfile.is_zipfile(archive_filename):
archivist = zipfile.ZipFile
is_tar = False
use_mode = "r"
else:
raise TypeError(f"Input {archive_filename} not tar or zip.")
return extracted, skipped
with archivist(archive_filename, use_mode) as input_archive:
# get content list
if is_tar:
archive_contents = input_archive.getnames()
else:
archive_contents = input_archive.namelist()
# extract 'em
for archived_item in archive_contents:
try:
input_archive.extract(archived_item, path=f"{output_dir}")
extracted.append(archived_item)
except:
skipped.append(archived_item)
return extracted, skipped
# Threading functions
# The functions below are related to / used by threading
def create_spinner(show_text: str, show_time: float) -> Type[sg.Window]:
"""
Helper function to create (and re-create) "Working..." popup
Returns window object. Will be re-created if the user hits X.
"""
# Make strings available to gettext :P
patience = _("This might take a while.")
elapsed = _("Elapsed time")
secs = _("seconds")
# create spinner
spinner_layout = [
[sg.T(
f"{show_text}.. {patience}.\n{elapsed}: {show_time} {secs}",
key="-spinner_text-"
)
]
]
return sg.Window(
f"{show_text} ..",
layout=spinner_layout,
grab_anywhere=True,
keep_on_top=True,
finalize=True
)
def unarchive_worker(
archive_filename: str,
output_dir: str,
out_dict: dict,
out_index: str):
"""
Helper function to run unarchive() in a separate thread using Thread.
Will save return values from archive into out_dict <dict> index <index>
"""
try:
extracted, skipped = unarchive(
archive_filename,
output_dir
)
except TypeError:
# not an error, input not an archive. we will not unarchive it
# use might have sent a file with .tar extension that is not tar ..
extracted, skipped = [], []
except Exception as e:
extracted, skipped = "error", e # export error str to thread dict
out_dict[out_index] = extracted, skipped
def archive_worker(file_basename: str,
use_tar: bool,
use_compression: bool,
input_files: list,
out_dict: dict,
out_index: str):
"""
Helper function to run archive() in a separate thread using Thread.
Will save return values from archive into out_dict <dict> index <index>
"""
out_dict[out_index] = archive(
file_basename,
use_tar,