-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmapsafe_dialog.py
2068 lines (1703 loc) · 90 KB
/
mapsafe_dialog.py
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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
MapsafeDialog
A QGIS plugin
export vector layers to common format and crs
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2018-12-08
git sha : $Format:%H$
copyright : (C) 2018 by Zoltan Siki
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* 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 option) any later version. *
* *
***************************************************************************/
"""
import os
# for swich button - https://github.com/yjg30737/pyqt-switch
# https://github.com/mpetroff/qgsazimuth/issues/23
import sip
sip.setapi("QVariant", 2)
from PyQt5 import (uic, QtWidgets, QtCore)
from osgeo import ogr
# imports
from random import uniform
from math import pi, sin, cos
from qgis.core import QgsVectorLayer, QgsGeometry, QgsFeature, QgsProject
# from PyQt5.QtWidgets import QApplication, QWidget, QComboBox, QPushButton, QVBoxLayout
# from PyQt5.QtCore import Qt
from qgis.PyQt.QtWidgets import QAction, QApplication, QLabel, QComboBox, QFileDialog
from qgis.PyQt.QtGui import *
from pathlib import Path
from qgis.utils import iface
# generate passphrase
#import random
#import xkcdpass.xkcd_password as xp
# encryption decryption
from zipfile import ZipFile
from cryptography.fernet import Fernet
from datetime import datetime
from .encryptiondecryption import EncryptionDecryption
# Python program to find SHA256 hexadecimal hash string of a file
import hashlib
#binning
#from .hexagonal_binning import HexagonalBinning
from .algorithms import (
CreateH3GridProcessingAlgorithm,
CreateH3GridInsidePolygonsProcessingAlgorithm,
CountPointsOnH3GridProcessingAlgorithm
)
#from .protect_passphrase import ProtectPassphrase
#public key encryption
from .encryptRSA import PublicKeyEncryption
# passphrase
from .passphrase import Passphrase
#geomasking
from .masking import GeoMasking
#from .h3_grid_from_layer import HexTest
import os
from qgis.utils import iface
from qgis.core import (
QgsCoordinateReferenceSystem,
QgsCoordinateTransform,
QgsFeature,
QgsField,
QgsFields,
QgsGeometry,
QgsPointXY,
QgsProject,
QgsProcessingFeedback,
QgsMessageLog,
QgsVectorFileWriter,
QgsVectorLayer,
QgsWkbTypes,
)
from qgis.PyQt.QtCore import QVariant
import processing
import h3
# end hex
# for progressbar
from PyQt5.QtWidgets import (QApplication, QDialog, QProgressBar, QPushButton)
import time
from reportlab.pdfgen import canvas
#notarisation
from .notarisation import Notarisation
# binning
from .h3binning import H3Binning
import ctypes # An included library with Python install.
#import easygui
# python should be installed on the machine
# e.g. from windows - https://www.python.org/downloads/windows/ - select windows installer
# along with pip
# In home pc, run OSGeo4W.bat in this directory 'D:\QGIS' not from 'D\OSGEO4W'
# required pip install in qgis
## Use D:\QGIS\OSGEO.bat
# D:\QGIS>pip install cryptography
# pip install cryptography
# pip install web3
# pip install python-dotenv
# pip install xkcdpass
# pip install easygui or python -m pip install easygui
# pip install python-dotenv
# (python -m) pip install pyqt-switch
# hash value
# this can be of the final encrypted volume (containing 1,2 or 3 levels),
# original dataset or the masked dataset
main_hash_value_to_mint = ''
# read environment variables
from os import environ
from dotenv import load_dotenv
# for toggle
from PyQt5.QtWidgets import QWidget, QFormLayout, QApplication, QLabel
from pyqt_switch import PyQtSwitch
from PyQt5.QtTest import QTest
from PyQt5.QtCore import Qt
import json
import h3
from qgis.PyQt.QtCore import QCoreApplication, QVariant
from qgis.core import (
QgsFeatureSink,
QgsProcessing,
QgsProcessingException,
QgsProcessingAlgorithm,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterNumber,
QgsProcessingParameterExtent,
QgsPointXY,
QgsGeometry,
QgsFeature,
QgsField,
QgsFields,
QgsCoordinateReferenceSystem,
QgsCoordinateTransform,
QgsWkbTypes,
QgsFeatureRequest,
QgsCoordinateTransformContext,
QgsVectorLayer,
QgsProject,
QgsMapLayerType,
)
from qgis import processing
from .singlepartGeo import singlepartGeometries
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtCore import *
# open window to save env variables
from .envvariables import envvariables
FORM_CLASS, _ = uic.loadUiType(os.path.join(
os.path.dirname(__file__), 'mapsafe_dialog_base.ui'))
class MapSafeDialog(QtWidgets.QDialog, FORM_CLASS):
# default masking parameter values
minimum_distance = 0
maximum_distance = 0
filename1 = ''
filename2 = ''
filename3 = ''
# passphrase
passphrase =''
passphrase_file_to_encrypt =''
passphrase_to_decrypt_filename =''
passphrase_generated = False
# public key encryption
PKE = ''
public_key_for_encryption =''
private_key_for_encryption =''
debug = ''
min_resolution = 0
max_resolution = 9
out_name_prefix = ''
projectPath = ''
geo_csrs = ''
out_csrs = ''
mylayer = ''
geographic_coordsys =''
output_projection = ''
dataPath = ''
#verification aspect
encrypted_volume_filename = ''
label_encrypted_volume = ''
levels_to_encrypt = 1
#encrypt_layers = True
working_directory = ''
#compute_privacy_rating = False
encrypted_file_loaded = False
hexabinning_resolution = 6 # set a default resolution
decrypt_to_level = 1
two_geomasking_levels = False
two_binning_levels = False
working_directory_set = False
# 1 = masking, 2 = binning
obfuscation_option = 0
TIME_LIMIT = 100
# for when to enable the encrypt and decrypt button -
# enable encrypt only when the passphrase file and public key is chosen
passphrase_file_chosen = False
public_key_chosen = False
# enable decrypt only when the passphrase file and public key is chosen
encrypted_passphrase_file_chosen = False
private_key_chosen = False
# what level has been encrypted, as specified at the end of the encrypted volume
volume_encrypted_level = 1
# selected file from devrypted tree
selected_file_from_decrypted_tree = ""
# https://ethereum.stackexchange.com/questions/46706/web3-py-how-to-use-abi-in-python-when-solc-doesnt-work
env_file_loc = ""
#env_file_directory = ""
env_file_path_set = False
internal_file_loc = "" # internal txt file that contains the location of the env file
# decrypted layer that should be unloaded wheen another level is decrypted
decrypted_layer_layerName = None
# in masking with privacy rating, we do masking many times, so we dont show the masked map everytime, as it does not work
add_layer_to_canvas = True
# environment variable class object
env_var = None
# if we want to verify and automatically display the map just after decryption
to_verify_display = True
def add_action(
self,
icon_path,
text,
callback,
enabled_flag=True,
add_to_menu=True,
add_to_toolbar=True,
status_tip=None,
whats_this=None,
parent=None):
"""Add a toolbar icon to the toolbar.
:param icon_path: Path to the icon for this action. Can be a resource
path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
:type icon_path: str
:param text: Text that should be shown in menu items for this action.
:type text: str
:param callback: Function to be called when the action is triggered.
:type callback: function
:param enabled_flag: A flag indicating if the action should be enabled
by default. Defaults to True.
:type enabled_flag: bool
:param add_to_menu: Flag indicating whether the action should also
be added to the menu. Defaults to True.
:type add_to_menu: bool
:param add_to_toolbar: Flag indicating whether the action should also
be added to the toolbar. Defaults to True.
:type add_to_toolbar: bool
:param status_tip: Optional text to show in a popup when mouse pointer
hovers over the action.
:type status_tip: str
:param parent: Parent widget for the new action. Defaults None.
:type parent: QWidget
:param whats_this: Optional text to show in the status bar when the
mouse pointer hovers over the action.
:returns: The action that was created. Note that the action is also
added to self.actions list.
:rtype: QAction
"""
icon = QIcon(icon_path)
action = QAction(icon, text, parent)
action.triggered.connect(callback)
action.setEnabled(enabled_flag)
if status_tip is not None:
action.setStatusTip(status_tip)
if whats_this is not None:
action.setWhatsThis(whats_this)
return action
# open window for users to encrypt passphrase
def openWindow(self):
self.window = QtWidgets.QMainWindow()
self.ui = ProtectPassphrase()
self.ui.setupUi(self.window)
self.window.show()
def __init__(self, parent=None):
"""Constructor."""
super(MapSafeDialog, self).__init__(parent)
self.setupUi(self)
self.btn_mask.clicked.connect(self.request_geomasking) #geomasking_function
# try auto determine best min and max distances for provided privacy rating
#self.btn_use_pr.clicked.connect(self.mask_based_on_privacy_rating) #geomasking_function
#self.btn_bin.clicked.connect(self.binning_function)
self.btn_bin.clicked.connect(self.request_binning_function) # request_binning_function
#passphrase
self.btnGeneratePassphrase.clicked.connect(self.request_passphrase)
self.btnENVFileDir.clicked.connect(self.set_env_file_location) #requestENVFileDirectory) #requestWorkingDirectory)
# TOOLTIPS
# env file
self.btnENVFileDir.setToolTip('Essential parameters for this plugin to work.')
# about working directory
self.label_working_dir_text.setToolTip('Used by plugin to save files.')
self.label_working_dir.setToolTip('Used by plugin to save files.')
# masking
# second level masking
self.groupBox_4.setToolTip('You can choose to add a second (more) masked layer. \n Generallly these use double the min and max values.')
self.chkBox_privRating.setToolTip('Keep adjusting the minimum and maximum values for a high privacy rating. ')
self.btnSaveMasked.setToolTip('Save the masked layer(s).')
self.btn_saved_masked_layers_loc.setToolTip('Open the directory where the masked layer is saved.')
self.masking_next_pushButton.setToolTip('Proceed to encrypt the saved layers.')
# binning two levels
self.chkBox_binning_two_levels.setToolTip('Create two hexabinned layers, \n with the second one binned at one more resolution.')
self.btn_bin.setToolTip('Perform Hexabinning using the chosen resolution.')
self.btnSaveBinned.setToolTip('Save the binned layer(s).')
self.btn_saved_binned_layers_loc.setToolTip('Open the directory where the binned layer is saved.')
self.label_8.setToolTip('Choose a hexabinning resolution.')
self.binning_next_pushButton.setToolTip('Proceed to encrypt the saved layer(s).')
# encryption
self.btnGeneratePassphrase.setToolTip('Passphrase is needed for encryption')
self.groupBox.setToolTip('You can choose one, two or three files to encrypt')
self.encryption_next_pushButton.setToolTip('Proceed to notarise the encrypted volume.')
self.btnEncrypt.setToolTip('Encrypt the chosen file(s) into a single encrypted volume.')
# notarise
self.button_notarise.setToolTip('Notarise the filename and hash value \n of the encrypted volume on the Blockchain.')
# verification display
self.btn_upload_encrypted_vol.setToolTip('Upload the encrypted volume. \n Its hash value will be displayed for verification. ')
self.verify_next_pushButton.setToolTip('Proceed to decrypt the volume.')
# decryption
self.btn_readPassphrase.setToolTip('Read the passphrase file.')
self.btnDecrypt.setToolTip('Decrypt to the specified level.')
self.btn_dec_volume_location.setToolTip('Directory where the decrypted file(s) are saved.')
self.decrypt_next_pushButton.setToolTip('Proceed to display the decrypted dataset(s).')
# display
self.treeWidget.setToolTip('Choose the decrypted dataset to display')
self.btn_displaymap.setToolTip('Display the chosen dataset')
# shield
self.btn_generate_keys.setToolTip('Generate a public and private key pair.')
self.btn_select_passphrase_file.setToolTip('The passphrase used to encrypt the volume')
self.btn_select_public_key.setToolTip('The passphrase is to be encrypted using the public key \n of an intended recipient of the encrypted volume')
self.btn_encrypt_passphrase.setToolTip('Encrypt using the public key')
# The recipeint of the encrypted volume can use their
self.btn_select_encrypted_passphrase_file.setToolTip('File containing the encrypted passphrase')
self.btn_select_private_key.setToolTip('The private key decrypts the encrypted passphrase \n'
+ ' for decrypting the encrypted volume.')
self.btn_decrypt_passphrase.setToolTip('Decrypt the encrypted passphrase using the private ley key')
self.btnEncrypt.clicked.connect(self.request_encryption)
self.btnDecrypt.clicked.connect(self.request_decryption)
# encrypt passphrase
self.btn_select_passphrase_file.clicked.connect(self.readPassphraseFileForEncryption)
self.btn_select_public_key.clicked.connect(self.readPublicKeyForEncryption)
self.btn_encrypt_passphrase.clicked.connect(self.request_encrypt_passphrase)
# Decrypt encrypted Passphrase file
#self.pushButton = QtWidgets.QPushButton(self.btnEncrypt_passphrase, clicked = lambda: self.openWindow())
#self.btnEncrypt_passphrase.clicked.connect(self.openWindow)
self.btn_select_encrypted_passphrase_file.clicked.connect(self.readPassphraseFileForDecryption)
self.btn_select_private_key.clicked.connect(self.readPrivateKeyForDecryption)
self.btn_decrypt_passphrase.clicked.connect(self.request_decrypt_passphrase)
#self.pushButton.setGeometry(QtCore.QRect(90, 80, 261, 71))
# public key encryption for the passphrase
self.PKE = PublicKeyEncryption()
# if user wants to encrypt OS files
self.btn_osfiles_level1.clicked.connect(self.getOSFile_level1)
self.btn_osfiles_level2.clicked.connect(self.getOSFile_level2)
self.btn_osfiles_level3.clicked.connect(self.getOSFile_level3)
self.chkBox_privRating_two_levels.clicked.connect(self.onStateChanged)
self.label_minimum_offset.setEnabled(False)
self.label_maximum_offset.setEnabled(False)
self.text_minimum_offset.setEnabled(False)
self.text_maximum_offset.setEnabled(False)
self.btnSaveMasked.clicked.connect(self.request_saveLayers)
self.btnSaveBinned.clicked.connect(self.request_saveLayers)
# notarise
self.button_notarise.clicked.connect(self.request_notarisation)
# Verification aspect
self.btn_upload_encrypted_vol.clicked.connect(self.get_encrypted_volume)
self.btn_readPassphrase.clicked.connect(self.readPassphraseFile)
self.btn_generate_keys.clicked.connect(self.generate_keys)
self.btn_displaymap.clicked.connect(self.display)
# if user wants to notarise OS files
self.btn_osfile_to_notarise.clicked.connect(self.getOSFile_to_notarise)
#config = dotenv_values(".env")
#print(config) # outputs OrderedDict([('VARIABLE1', 'test')])
# read environment file location
#self.button_read_env_file_location.clicked.connect(self.read_env_file_location)
#self.button_set_env_file_location.clicked.connect(self.set_env_file_location)
# set the environment file location and load it in the next line
# #env_file = f'{self.plugin_dir}/.env'
### Add Icon
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
print('self.plugin_dir ' + str(self.plugin_dir))
icon_path = ':/plugins/mapsafe/icon.png'
self.add_action(
icon_path,
#add_to_menu=True,
#add_to_toolbar=True,
text=self.tr(u'MapSafe Complete Geoprivacy Plugin'),
callback=self.run
#parent=self.iface.mainWindow()
)
# this file location is also passed to the notarisation class upon its initialisation
# the class will use the file to read the location of the env file and read the parameters
#self.internal_file_loc = f'{self.plugin_dir}/loc.txt'
#print('self.internal_file_loc: ' + self.internal_file_loc)
# the location of the env file is within the internal file
# we simply read the location from the internal file and then pass that location to this function
# f = open(self.internal_file_loc, "r") # In this example, we will be opening a file to read-only.
# env_file_loc = f.readline()
# f.close() # closing the file
# print('env_file_loc: ' + env_file_loc)
# env_file_loc = self.read_env_file_location()
# print('env_file_loc: ' + env_file_loc)
self.plugin_dir = os.path.dirname(__file__)
self.internal_envfile_loc = f'{self.plugin_dir}/parameters.txt'
print('self.internal_envfile_loc: ' + self.internal_envfile_loc)
#load_dotenv(self.internal_envfile_loc ) #"D:\\datasets\\.env") #load_dotenv("D:\\datasets\\.env")
# initialise the env object - which will read the variables
self.env_var = envvariables(self)
print('loaded env variables from file: ' + str(self.internal_envfile_loc))
# Read and set the Working directory
wd = self.env_var.get_working_dir()
self.set_working_directory(wd)
self.btnEncrypt.setEnabled(False)
self.encryption_next_pushButton.setEnabled(False)
#self.btnEncrypt_passphrase.setEnabled(False)
#self.btn_encrypt_passphrase.setEnabled(False)
# disable decryption level buttons a user can choose
self.rbt_level1.setEnabled(False)
self.rbt_level2.setEnabled(False)
self.rbt_level3.setEnabled(False)
# ### Add Icon
# # initialize plugin directory
# self.plugin_dir = os.path.dirname(__file__)
# print('self.plugin_dir ' + str(self.plugin_dir))
# icon_path = ':/plugins/mapsafe/icon.png'
# self.add_action(
# icon_path,
# #add_to_menu=True,
# #add_to_toolbar=True,
# text=self.tr(u'MapSafe Complete Geoprivacy Plugin'),
# callback=self.run
# #parent=self.iface.mainWindow()
# )
# self.internal_file_loc = f'{self.plugin_dir}/loc.txt'
# load the layers for choosing in the encryption tab
self.get_layers()
# Masking Parameters sliders
self.horizontalSlider_min.setRange(0, 500) # changed from 500 to 100
self.horizontalSlider_min.setValue(100)
self.horizontalSlider_min.setSingleStep(5)
self.horizontalSlider_min.valueChanged.connect(self.on_value_changed_min)
self.horizontalSlider_max.setRange(0, 3000) # changed from 500 to 0
self.horizontalSlider_max.setValue(500)
self.horizontalSlider_max.setSingleStep(100)
self.horizontalSlider_max.valueChanged.connect(self.on_value_changed_max)
self.label_min.setText('100')
self.label_max.setText('500')
# second level default values
self.text_minimum_offset.setPlainText(str(200))
self.text_maximum_offset.setPlainText(str(1000))
# Hexabinning Parameters sliders
self.horizontalSlider_resolution.setRange(0, 14)
self.horizontalSlider_resolution.setValue(self.hexabinning_resolution)
self.horizontalSlider_resolution.setSingleStep(1)
#self.horizontalSlider_min.setPageStep(10)
self.horizontalSlider_resolution.valueChanged.connect(self.on_resolution_value_changed)
# set default values
self.label_resolution.setText(str(self.hexabinning_resolution))
# Encryption-decryption
self.key_file = 'filekey.key'
self.btn_osfiles_level2.setEnabled(False)
self.btn_osfiles_level3.setEnabled(False)
self.label_success.setHidden(True)
self.label_tranx.setHidden(True)
self.label_tranx_url.setHidden(True)
# code for switch button # https://pypi.org/project/pyqt-switch/
switch = PyQtSwitch()
# individual or combined mode
switch.setToolTip('Individual mode lets you use any of the security functions.\n' +
'Combined mode ensures these functions are executed in order')
switch.toggled.connect(self.__toggled)
# switch.setAnimation(True) # does not work for some reason
# switch.setCircleDiameter(40)
self.__label = QLabel()
self.__label.setText('Individual Mode')
lay = QFormLayout()
lay.addRow(self.__label, switch)
self.setLayout(lay)
# end for switch button
# the swict should be in combined mode by default
# Click the button
QTest.mouseClick(switch, Qt.LeftButton)
# open saved file locations
self.btn_saved_masked_layers_loc.clicked.connect(self.open_masked_layer_location) # masked layer
self.btn_enc_volume_location.clicked.connect(self.open_enc_volume_location)
self.btn_dec_volume_location.clicked.connect(self.open_dec_volume_location)
self.btn_passphrase_location.clicked.connect(self.open_passphrase_location)
self.btn_open_decrypted_folder.clicked.connect(self.open_decrypted_folder_location)
# binning
self.btn_saved_binned_layers_loc.clicked.connect(self.open_binned_layer_location) # masked layer
# set the Safeguard tabs disabled
self.tabWidget_2.setTabEnabled(1,False) #enable/disable the encryption tab
self.tabWidget_2.setTabEnabled(2,False) #enable/disable the encryption tab
# set the Verification - decryption and display tab disabled
self.tabWidget_3.setTabEnabled(1,False) #enable/disable the decryption tab
self.tabWidget_3.setTabEnabled(2,False) #enable/disable the display tab
# during safeguarding, show encryption tab after masking or binning
self.masking_next_pushButton.clicked.connect(self.change_safeguarding_tab)
self.binning_next_pushButton.clicked.connect(self.change_safeguarding_tab)
# during safeguarding, show notarisation tab after encryption
self.encryption_next_pushButton.clicked.connect(self.change_safeguarding_tab3)
# the next buttons are initially disabled, enabled if the security function on the tab is executed
self.masking_next_pushButton.setEnabled(False)
self.binning_next_pushButton.setEnabled(False)
self.encryption_next_pushButton.setEnabled(False)
self.verify_next_pushButton.setEnabled(False)
self.decrypt_next_pushButton.setEnabled(False)
# hide these tow until dataset decrypted
self.label_decrypted_volume.hide()
self.btn_dec_volume_location.hide()
# during verification, next buton call decryption tab
self.verify_next_pushButton.clicked.connect(self.change_verification_tab)
self.decrypt_next_pushButton.clicked.connect(self.change_verification_tab2)
# hide the groupbox
self.separatefile_notarisation_groupBox.hide()
self.label_osfile_to_notarise.hide()
self.btn_osfile_to_notarise.hide()
# shielding passphrase
self.btn_encrypt_passphrase.setEnabled(False)
self.btn_decrypt_passphrase.setEnabled(False)
self.label_generated_key_pair.hide()
self.label_encrypted_passphrase.hide()
self.label_decrypted_passphrase.hide()
# Initial Mode
self.combined = True
self.safeguard_progressBar.setValue(0)
self.verification_progressBar.setValue(0)
# https://github.com/jacklam718/PyQt-ProgressDialog
# the green color we want = #4CAF50
# the grey background color = #E9E9E9
# https://stackoverflow.com/questions/72644810/how-to-edit-stylesheet-for-qprogressbar
style = """
QProgressBar {
border: 1px solid grey;
border-radius: 5px;
text-align: center;
background-color: #E9E9E9;
width: 20px;
}
QProgressBar::chunk {
background-color: #4CAF50;
}
"""
self.safeguard_progressBar.setStyleSheet(style)
self.verification_progressBar.setStyleSheet(style)
# set allignment from here, as above way doesn't work
# https://www.geeksforgeeks.org/pyqt5-how-to-change-style-and-size-of-text-progress-bar/
self.safeguard_progressBar.setAlignment(Qt.AlignCenter)
self.verification_progressBar.setAlignment(Qt.AlignCenter)
# treeview display
self.treeWidget.itemClicked.connect(self.onItemClicked)
self.tabWidget_2.tabBarClicked.connect(self.handle_tabbar_clicked)
# on label anonymise text click event
self.label_safeguard_options.mousePressEvent = self.doSomething
# show help website
self.btn_help.clicked.connect(self.onHelp)
def set_working_directory(self, wd):
print("environ[WORKING_DIR]: " + str(wd)) # str(environ["WORKING_DIR"]))
self.working_directory = wd #environ["WORKING_DIR"]
print("self.working_directory: " + str(wd)) #self.working_directory))
if(self.working_directory):
self.working_directory_set = True
print('\t### working_directory ' + str(self.working_directory))
self.label_working_dir.setText(self.working_directory)
else:
print('\t### working_directory not set' + str(self.working_directory))
def doSomething(self, event):
print('anonymise')
def onHelp(self):
"""
Open the help documentation in a web browser.
"""
docDir = "https://sharmapn.github.io/MapSafeQGISGeoPrivPlugin/"
QDesktopServices.openUrl(QUrl(docDir))
# upon selection of any safeguard options in the tab
def handle_tabbar_clicked(self, index):
print(index)
# only in individual mode and certain index level
if(self.combined == False and index == 0):
self.label_safeguard_options.setText("The original dataset can be anonymised.")
self.label_safeguard_options.show()
elif(self.combined == False and index == 1):
self.label_safeguard_options.setText("Any dataset can be encrypted: original or anonymised.")
self.label_safeguard_options.show()
elif(self.combined == False and index == 2):
self.label_safeguard_options.setText("Any dataset can be notarised: original, anonymised or encrypted..")
self.label_safeguard_options.show()
#print("x2:", index * 2)
# individual or combined mode actions based on switch button
def __toggled(self, f):
if f:
print('Combined Mode')
self.combined = True
self.__label.setText('Combined Mode')
self.masking_next_pushButton.show()
self.binning_next_pushButton.show()
self.encryption_next_pushButton.show()
#notarisation
self.separatefile_notarisation_groupBox.hide()
self.label_osfile_to_notarise.hide()
self.btn_osfile_to_notarise.hide()
# disable encryption tab
self.tabWidget_2.setTabEnabled(1, False) #enable/disable the encryption tab
self.tabWidget_2.setTabEnabled(2, False) #enable/disable the encryption tab
# show progress bar
self.safeguard_progressBar.show()
self.label_2.show()
self.label_3.show()
self.label_9.show()
# show the label with information
self.label_safeguard_options.hide()
else:
print('Individual Mode')
self.combined = False
self.__label.setText('Individual Mode')
self.masking_next_pushButton.hide()
self.binning_next_pushButton.hide()
self.encryption_next_pushButton.hide()
#notarisation
self.separatefile_notarisation_groupBox.show()
self.label_osfile_to_notarise.show()
self.btn_osfile_to_notarise.show()
# enable encryption tab
self.tabWidget_2.setTabEnabled(1,True) #enable/disable the encryption tab
self.tabWidget_2.setTabEnabled(2,True) #enable/disable the encryption tab
# hide progress bar
self.safeguard_progressBar.hide()
self.label_2.hide() # hide the workflow stops: anonymise, encrypt and notarise
self.label_3.hide()
self.label_9.hide()
# show the label with information
# making it multi line
self.label_safeguard_options.setWordWrap(True)
self.label_safeguard_options.setText("The original dataset can be anonymised, directly encrypted, or directly notarised.")
self.label_safeguard_options.show()
def change_safeguarding_tab(self):
self.tabWidget_2.setCurrentIndex(1)
def change_safeguarding_tab2(self):
self.tabWidget_2.setCurrentIndex(2)
def change_safeguarding_tab3(self):
self.tabWidget_2.setCurrentIndex(2)
def change_verification_tab(self):
self.tabWidget_3.setCurrentIndex(1)
def change_verification_tab2(self):
self.tabWidget_3.setCurrentIndex(2)
#def run(self):
# print ('here run')
def onStateChanged(self):
if(self.chkBox_privRating_two_levels.isChecked()):
self.label_minimum_offset.setEnabled(True)
self.label_maximum_offset.setEnabled(True)
self.text_minimum_offset.setEnabled(True)
self.text_maximum_offset.setEnabled(True)
else:
self.label_minimum_offset.setEnabled(False)
self.label_maximum_offset.setEnabled(False)
self.text_minimum_offset.setEnabled(False)
self.text_maximum_offset.setEnabled(False)
# Encryption
# local file that contains the location of env file
# env file is contained in a text file named 'loc.txt' within the plugin directory
def read_env_file_location(self): #, env_file_loc):
try:
if(self.internal_file_loc is None or self.internal_file_loc == ""):
print('Internal file containing ENV file location not supplied')
QMessageBox.information(None, "DEBUG:", 'Please specify location of file with ENV file location. ')
else:
#open and read the file after the overwriting:
f = open(self.internal_file_loc, "r") # "loc.txt"
env_file_loc = f.read() # get the location of tyhe env file
print(env_file_loc)
f.close()
return env_file_loc
except Exception as e:
print(f"Exception reading env file - {e}")
QMessageBox.information(None, "DEBUG:", 'Exception reading env file . ')
# sets the location of the env file, overwriting whatever is there
# # <-- Here, we create *and connect* the sub window's signal to the main window's slot
def set_env_file_location(self): #, env_file_loc):
#internal_file_loc = f'{self.plugin_dir}/loc.txt'
# call the signal
# https://stackoverflow.com/questions/68453805/how-to-pass-values-from-one-window-to-another-pyqt
self.env_var.submitClicked.connect(self.on_sub_window_confirm)
self.env_var.show()
#return
def on_sub_window_confirm(self, url): # <-- This is the main window's slot
print(f"Saved Working dir : {url}")
self.label_working_dir.setText(str(url))
# try:
# filepath = QFileDialog.getOpenFileName()
# env_file_loc = filepath[0]
# print("User chosen ENV File: " + env_file_loc)
# if(env_file_loc is None or env_file_loc == ""):
# print('ENV file location not supplied')
# QMessageBox.information(None, "DEBUG:", 'Please specify ENV file location. ')
# else:
# print('read_env_file_location: ' + str(env_file_loc))
# f = open(self.internal_file_loc, "w") # "demofile3.txt"
# f.write(env_file_loc) #"Woops! I have deleted the content!")
# f.close()
# #load the enviornment variable again from the env file
# load_dotenv(env_file_loc) #self.internal_file_loc)
# # assign the env variable to the variable used in our script
# self.set_working_directory()
# print('Set ENV file location in internal_file_loc: ' + self.internal_file_loc)
# #open and read the file after the overwriting:
# #f = open(env_file_loc, "r") # "demofile3.txt"
# #print(f.read())
# except Exception as e:
# print(f"Exception setting env file - {e}")
# QMessageBox.information(None, "DEBUG:", 'Exception reading env file . ')
# let user choose the passphrase file - note three passphrase files are created by the plugin after encryption
def readPassphraseFileForEncryption(self):
print('Read Passphrase file for Encryption')
try:
filepath = QFileDialog.getOpenFileName()
filename = filepath[0]
if filename != "":
print(filename)
self.passphrase_file_to_encrypt = filename
print('self.passphrase_file_to_encrypt')
print(self.passphrase_file_to_encrypt)
self.passphrase_file_chosen = True
else:
self.passphrase_file_chosen = False
self.passphrase_file_to_encrypt = ""
QMessageBox.information(None, "DEBUG:", 'Please specify Passphrase file for Encryption. ')
except Exception as e:
print(f'Error opening file + {e}')
# read the public key of recipient
def readPublicKeyForEncryption(self):
print('Read Public Key for Passphrase Encryption')
try:
filepath = QFileDialog.getOpenFileName()
filename = filepath[0]
if filename != "":
print(filename)
self.public_key_for_encryption = open(filename).read()
print('self.public_key_for_encryption')
print(self.public_key_for_encryption)
self.PKE.read_PubKey(filename)
self.public_key_chosen = True
else:
self.public_key_for_encryption = ""
QMessageBox.information(None, "DEBUG:", 'Please specify Public Key for Passphrase Encryption. ')
# enable encrypt button
if(self.passphrase_file_chosen and self.public_key_chosen):
self.btn_encrypt_passphrase.setEnabled(True)
except Exception as e:
print(f'Error opening file as {e}')
def request_encrypt_passphrase(self):
pke = self.PKE.encrypt(self.working_directory, self.passphrase_file_to_encrypt, self.label_encrypted_passphrase, self.label_encrypted_passphrase_file)
print('Calling encryption of passphrase')
# Decryption
# if passphrase is already in plaintext, let the user choose the passphrase file
# in this case, no decryption of passphrase is required
def readPassphraseFile(self):
print('Read Pasphrase File')
try:
filepath = QFileDialog.getOpenFileName()
filename_pp = filepath[0]
if filename_pp != "":
print('passphrase file: ' + str(filename_pp))
self.passphrase = open(filename_pp).read()
self.txt_passphrase.setText(self.passphrase)
else:
print("self.passphrase: " + str(self.passphrase))
except Exception as e:
print(f'Error opening file + {e}')
# if passphrase is provided in encrypted form, let user choose the encrypted file
def readPassphraseFileForDecryption(self):
print('Read Passphrase file for Decryption')
try:
filepath = QFileDialog.getOpenFileName()
filename_pp = filepath[0]
if filename_pp != "":
print('passphrase file: ' + str(filename_pp))
self.passphrase_to_decrypt_filename = filename_pp
print('self.passphrase_to_decrypt_filename')
print(self.passphrase_to_decrypt_filename)
self.encrypted_passphrase_file_chosen = True
else:
print("self.passphrase_to_decrypt_filename: " + str(self.passphrase_to_decrypt_filename))
except Exception as e:
print(f"Error Reading Passphrase file for Decryption + {e}")
QMessageBox.information(None, "DEBUG:", 'Error Reading Passphrase file for Decryption. ')
#read the current user's private key for decryption of passphrase
def readPrivateKeyForDecryption(self):
print('Read Private Key for Passphrase Decryption')
try:
filepath = QFileDialog.getOpenFileName()
filename_pk = filepath[0]
if filename_pk != "":
print('pk filename:' + str(filename_pk))
self.private_key_for_decryption = open(filename_pk).read()
print('self.private_key_for_encryption')
print(self.private_key_for_encryption)
self.PKE.read_PriKey(filename_pk)
self.private_key_chosen = True
else:
print("self.private_key_for_encryption: " + str(self.private_key_for_encryption))
# enable decrypt button
if(self.encrypted_passphrase_file_chosen and self.private_key_chosen):
self.btn_decrypt_passphrase.setEnabled(True)