-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.py
1843 lines (1520 loc) · 91.4 KB
/
functions.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
import ast
import binascii
import calendar
import inspect
import math
import random
import shutil
import sys
import time
import zlib
import base64
import json
import os
import pickle
import sqlite3
from Crypto.Hash import SHA256
from Crypto.Signature.pkcs1_15 import PKCS115_SigScheme
from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from datetime import datetime, timedelta
from geopy.geocoders import Nominatim
from geopy import distance as geopydist
import gzip
import ntplib
import re
import zipfile
def dprint(*args):
"""debugprint with file and linelumber from where it is called"""
frame = inspect.stack()[1]
_, filename = os.path.split(frame[1])
print (f"{filename}:{frame[2]}", *args)
def haversine(coord1, coord2):
R = 6371 # Earth radius in kilometers
lat1, lon1 = math.radians(coord1[0]), math.radians(coord1[1])
lat2, lon2 = math.radians(coord2[0]), math.radians(coord2[1])
dlat = lat2 - lat1
dlon = lon2 - lon1
a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
return R * c
def cluster_representative(cities, max_cluster_radius):
"""
This function takes a list of cities with their coordinates and a maximum cluster radius as input.
It clusters the cities based on the maximum cluster radius and finds the representative city for
each cluster. The representative city is the one with the minimum sum of distances to other cities
within the same cluster. The function returns a list of representative cities with their postal codes,
names, and coordinates.
Args:
cities (list): List of cities with their postal codes, names, and coordinates.
Example: [[10115, 'Berlin', '52.53, 13.38'], ...]
max_cluster_radius (float): Maximum radius of a cluster in kilometers.
Returns:
cluster_representatives (list): List of representative cities with their postal codes, names, and coordinates.
"""
# Convert the coordinates string to a list of floats
coords = [list(map(float, city[2].split(', '))) for city in cities]
# Calculate the number of neighbors for each city within the max_cluster_radius
neighbors_count = []
for i, coord in enumerate(coords):
neighbors = sum(1 for other_coord in coords if haversine(coord, other_coord) <= max_cluster_radius)
neighbors_count.append((i, neighbors))
# Sort the cities by the number of neighbors in descending order
neighbors_count.sort(key=lambda x: x[1], reverse=True)
# Initialize the list of clusters
clusters = []
# Iterate over the cities sorted by the number of neighbors
for i, _ in neighbors_count:
city, coord = cities[i], coords[i]
added = False
# Iterate over the existing clusters
for cluster in clusters:
# Check if the city is within the max_cluster_radius of the first city in the cluster
if haversine(coord, cluster[0][1]) <= max_cluster_radius:
# Add the city to the cluster
cluster.append((city, coord))
added = True
break
# If the city was not added to an existing cluster, create a new cluster
if not added:
clusters.append([(city, coord)])
# Initialize the list of cluster representatives
cluster_representatives = []
# Iterate over the clusters
for cluster in clusters:
# Initialize variables to track the minimum distance and the representative city
min_distance = float('inf')
representative = None
# Iterate over the cities in the cluster
for city, coord in cluster:
# Calculate the sum of distances from the current city to other cities in the cluster
distance_sum = sum(haversine(coord, other_coord) for _, other_coord in cluster)
# Update the minimum distance and the representative city if needed
if distance_sum < min_distance:
min_distance = distance_sum
representative = city
# Add the representative city to the list of cluster representatives
cluster_representatives.append(representative)
return cluster_representatives
def backup_data_directory(backup_source_folder, backup_destination_folder):
'''
This function creates backup files of specific frequencies in a given source folder, and stores them in a
specified destination folder while maintaining a maximum number of backups for each frequency.
'''
# Define the maximum number of backups to keep for each frequency
max_backups = {
'backup': 5,
'stundenbackup': 5,
'tagesbackup': 5,
'wochenbackup': 4,
'monatsbackup': 6
}
# Define the backup frequency directories
backup_types = {
'backup': datetime.now().strftime('%Y-%m-%d_%H-%M'),
'stundenbackup': datetime.now().strftime('%Y-%m-%d_%H') + 'Uhr',
'tagesbackup': datetime.now().strftime('%Y-%m-%d'),
'wochenbackup': datetime.now().strftime('%Y-%U'),
'monatsbackup': datetime.now().strftime('%Y-%m')
}
# Define the backup directory
backup_dir = os.path.join(backup_destination_folder)
os.makedirs(backup_dir, exist_ok=True)
backup_file_name = 'letztes-backup.zip'
last_backup = os.path.join(backup_dir, backup_file_name)
file_extensions = ['.db', '.dat', '.json'] # zip only this files
with zipfile.ZipFile(last_backup, 'w') as zipf:
for file in os.listdir(backup_source_folder):
if os.path.isfile(os.path.join(backup_source_folder, file)) and \
any(file.lower().endswith(ext) for ext in file_extensions):
zipf.write(os.path.join(backup_source_folder, file), file)
for freq, backup_type in backup_types.items():
backup_file = os.path.join(backup_dir, f'{freq}_{backup_type}.zip')
# create backup file only when file not exist (beginning of month, week ,..)
if not os.path.isfile(backup_file):
shutil.copy(last_backup, backup_file)
# Check if the maximum number of backups has been reached
backups = [f for f in os.listdir(backup_dir) if f.startswith(f'{freq}_')]
while len(backups) > max_backups[freq]:
backups.sort()
os.remove(os.path.join(backup_dir, backups[0]))
backups = [f for f in os.listdir(backup_dir) if f.startswith(f'{freq}_')]
def shred_file(file):
"""overwirtes a file with random pattern and deletes it"""
file_size = os.path.getsize(file)
with open(file, "wb") as f:
random_data = bytearray([random.randint(0, 255) for i in range(file_size)]) # Generate random data
f.write(random_data) # overwrite file
os.remove(file) # delete file
def order_dict(input_dict: dict, key_order: list) -> dict:
""" Orders a dictionary based on the specified key order. Keys not present in the key_order will be appended
to the end of the result. If a key from the key_order is not in the input_dict, it will be ignored.
{'x': 7, 'b': 1, 'c': 5, 'a': 6} with list ['a', 'b'] returns {'a': 6, 'b': 1, 'x': 7, 'c': 5}
:param input_dict: dict which have to be ordered
:param key_order_list: a list of keys in the specific order
:return: the orderd dict
"""
ordered_dict = {}
for key in key_order:
if key in input_dict:
ordered_dict[key] = input_dict[key]
# append rest of missing keys
for key, val in input_dict.items():
if key not in ordered_dict:
ordered_dict[key] = val
return ordered_dict
def parse_mail_text(text: str) -> dict:
"""
parse the mail text from the webform for import
"""
occur = [m.start() for m in re.finditer('<card_type>', text)]
if len(occur) != 2: # element must occur 2 times, else there is an error
return "<card_type> nicht gefunden"# card type not found
card_type = text[(occur[0] + len('<card_type>')):occur[1]].replace('/>', '>') # in php > is escape by /
#dprint("card_type=", card_type)
if not card_type == 'business_card':
return f"Unbekannter card_type: {card_type}" # if not business_card exit
content_dict = {'card_type': '', 'name': '', 'family_name': '', 'street': '', 'zip_code': '', 'city': '',
'country': '', 'radius_of_activity': '', 'company_profession': '', 'phone': '', 'website': '',
'email': '', 'other_contact': '', 'interests_hobbies': '', 'skills_offers': '', 'requests': '',
'tags': ''}
content_elements = re.findall(r"<[a-z_]+>", text) # find all content_elements
elements = [i for n, i in enumerate(content_elements) if i not in content_elements[:n]] # remove duplicates & keep order
for el in elements:
occur =[m.start() for m in re.finditer(el, text)]
if len(occur) != 2: # element must occur 2 times, else there is an error
continue
elementtext = text[(occur[0] + len(el)):occur[1]].replace('/>','>') # in php > is escape by /
content_dict[el[1:-1]] = elementtext
return content_dict
def adapt_dist(string, length = 6):
"""takes the dist and adds whitespace and unit. needed for sorting in gui table that uknown distance is at the end"""
if len(string) == 0:
return " ?"
spaces = ' ' * (length - len(string))
return spaces + string + ' km'
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
def get_coordinates(location):
""" Determines the coordinates for a searched location with the help of openstreetmaps
:param location: searched location e.g. "berlin"
:return:
"""
geolocator = Nominatim(user_agent="TalentTalent")
try:
result = geolocator.geocode(location)
found_address = result.address
coordinates = f"""{round(result.latitude, 2)}, {round(result.longitude, 2)}"""
return True, found_address, coordinates
except:
return False, 0, 0
def geo_distance(two_coordinates, string_mode = True):
"""calculates distance between two coordinates
:param two_coordinates: string with coordinates eparated by semicolon like: '53.1, 10.5;52.1, 13.3'
:return: string with distance in kilometers or empty string on error
"""
if len(two_coordinates.split(";")) != 2:
if string_mode:
return ""
else:
return 999999
if isValidCoordinate(two_coordinates.split(";")[0]) and isValidCoordinate(two_coordinates.split(";")[1]):
point_A = (two_coordinates.split(";")[0])
point_B = (two_coordinates.split(";")[1])
if string_mode:
return str(round(geopydist.distance(point_A, point_B).kilometers, 0)).split(".")[0]
else:
return round(geopydist.distance(point_A, point_B).kilometers, 1)
else:
if string_mode:
return ""
else:
return 999999
def system_clock_ntp_difference():
"""returns the time diff in seconds between local time an ntp (time-server) time.
:return: time diff in seconds, returns 0 at error (time server connection failed)
"""
time_server = '0.pool.ntp.org'
ntp = ntplib.NTPClient()
try:
ntpResponse = ntp.request(time_server, timeout=2)
except:
return 0
if (ntpResponse):
now = float(int(time.time()))
diff = now-ntpResponse.tx_time
return round(float(diff), 6)
return 0
def format_date_string(datestring) -> str:
""" format the database date time format to to an ordinary format
:param datestring: date in form: "2020-12-18 17:11:09" or "2020-12-18"
:return: formatet date, for example: "18.12.2020 17:11:09"
"""
newdatestring = str(datestring).strip() # leading and trailing whitespace removed
# check format of string ("2020-12-18 17:11:09" or "2020-12-18")
if re.fullmatch(r'([0-9]{4}(-[0-9]{2}){2}( [0-9]{2}(:[0-9]{2}){2}){0,1})', newdatestring):
if newdatestring.find(" ") > 7: # long format with time
dt = datetime.strptime(newdatestring, "%Y-%m-%d %H:%M:%S")
return dt.strftime('%d.%m.%Y %H:%M:%S')
else: # shot format, only date, no time
dt = datetime.strptime(newdatestring, "%Y-%m-%d")
return dt.strftime('%d.%m.%Y')
return datestring # on error return don't format string
def dict_to_friendship_string(dictionary, linelen=64):
"""Converts a dictionary with friendship information like pubkey ect. into a string which can send to friend"""
if isinstance(dictionary, dict):
byte = json.dumps(dictionary).encode('utf-8')
else:
pass # fehlermeldung
byte = zlib.compress(byte)
base32 = base64.b32encode(byte) # base64.b64encode(byte)
bstring = base32.decode("utf8")
# fill with 890 that all lines will have same length, 089 easy can filtered out because not in base32-set
random.seed(str(dictionary)) # use seed the the fill will always be the same
while len(bstring) % linelen != 0:
rand = random.randrange(len(bstring))
bstring = bstring[:rand] + '089'[random.randrange(3)] + bstring[rand:]
# insert newline after linelen
bstring = "".join(bstring[i:i + linelen] + "\n" for i in range(0, len(bstring), linelen))
return str(bstring)
def friendship_string_to_dict(string):
"""Converts friendship string back to the dict with friendship information. like pubkey etc."""
# remove non base32 chars (for litle failure tolerance of wrong user input)
base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567="
for char in string:
if char not in base32chars:
string = string.replace(char, "")
encoded = string.encode("utf8")
decoded = base64.b32decode(encoded)
try:
decompressed = zlib.decompress(decoded)
except:
raise Exception("checksum mismatch")
decoded_dict = json.loads(decompressed.decode('utf-8'))
return decoded_dict
def PWGen(pwlength=10, alphabet=''):
if alphabet == "":
alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ0123456789" # without I and O preventing miss
mypw = ""
for i in range(pwlength):
index = random.randrange(len(alphabet))
mypw = mypw + alphabet[index]
return mypw
def isValidEmail(email):
# mthis regexp match not exact rfc mail format, but will catch a lot of errors
if re.fullmatch(r'([A-Za-z0-9]+[.\-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+', email):
return True
return False
def isValidCoordinate(string) -> bool:
"""
this regexp check if string is a coordinate (ex: "50.98, 11.03"(
:param string:
:return:
"""
if re.fullmatch(r'^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$', string):
return True
return False
def short_SHA256(msg, length=16):
return SHA256.new(msg.encode("utf8")).hexdigest()[:length]
def special_hash_from_dict(data_card):
# todo beschreibung einfügen
# order of content can be ignored (hash of elements are sorted)
hash_list = []
# calc hash from header
header = data_card['dc_head']
temp_hash_list = []
for element in header:
temp_hash_list.append(short_SHA256(str(header[element])))
temp_hash_list.sort() # when sorted the order of the elements in the header can be ignored
header_string = ""
for element in temp_hash_list:
header_string += element
header_string += str(data_card['dc_dynamic_head']['salts'][-1]) # + salt
hash_list.append(short_SHA256(header_string))
content = data_card['data']
max_hop = data_card['dc_head']['maxhop']
current_hop = max_hop
for salt in reversed(data_card['dc_dynamic_head']['salts']):
for element in content:
if content[element][1] == current_hop:
if (content[element][2] == '0'): # if not deleted calc hash
temp_string = str(content[element][0]) + str(content[element][1]) + str(salt)
hash_list.append(short_SHA256(temp_string)) # gekürzer sha256 reicht
else: # else hash is saved in content
# when deleted hash is in deleted
hash_list.append(content[element][2])
current_hop -= 1
hash_list.sort() # when sorted the order of the elements in the header can be ignored
temp_string = ""
for element in hash_list:
temp_string += element
specialhash = SHA256.new(temp_string.encode("utf8")).hexdigest()
return specialhash
def add_months(time: timedelta, number_of_months: int) -> timedelta:
""" Add a given number of months to a timedelta object.
If the day of the resulting date is out of range for the new month (e.g. the 31st of a month with only 30 days),
the day is set to the last day of the month.
:param time: The timedelta object to add months to.
:param number_of_months: The number of months to add. Must be a positive integer.
:return: The resulting timedelta object.
"""
if not isinstance(number_of_months, int) or number_of_months < 1:
raise ValueError("number_of_months must be a positive integer")
year, month = divmod(time.month - 1 + number_of_months, 12)
newyear = time.year + year
newmonth = month + 1
last_day_of_month = calendar.monthrange(newyear, newmonth)[1]
newday = min(time.day, last_day_of_month)
return time.replace(year=newyear, month=newmonth, day=newday)
def add_years(time, number_of_years):
"""add a years to a """
newtime = time
for year in range(number_of_years):
newtime += timedelta(days=365)
if newtime.day != time.day: # leap year +1 day
newtime += timedelta(days=1)
return newtime
def str_to_date(datestring):
"""
converts a datestring in to datetime object.
:param date_string: string in this both '2020-12-18 15:11:09' or '2020-12-18'
:return: datatime object
"""
if not re.search("^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{1,2}:[0-9]{2}:[0-9]{2}$", datestring) == None:
format = "%Y-%m-%d %H:%M:%S"
return datetime.strptime(datestring, "%Y-%m-%d %H:%M:%S")
if not re.search("^[0-9]{4}-[0-9]{2}-[0-9]{2}$", datestring) == None:
return datetime.strptime(datestring, "%Y-%m-%d")
raise Exception("datestring has wrong format:", datestring)
def save_in_json(filename, data):
with open(filename, 'w', encoding='utf8') as outfile:
json.dump(data, outfile, indent=1, sort_keys=True, ensure_ascii=False)
def load_from_json(filename):
with open(filename, encoding='utf8') as json_data_file:
data = json.load(json_data_file)
return data
#todo codeimproving: func also in cryptofunctions
def sign(msg, keyPair):
# Sign the message using the PKCS#1 v1.5 signature scheme (RSASP1)
hash = SHA256.new(msg)
signer = PKCS115_SigScheme(keyPair)
signature = signer.sign(hash)
return binascii.hexlify(signature)
class config():
def __init__(self, filename='config.json'):
# temporäre globale variablen / Einstellungen, die nicht Datei gespeichert werden
self.TEMP_STARTUP_PASSWORD = ""
self.PROGRAMM_FOLDER = 'TalentData' # Verzeichnis wo Daten gespeichert werden
self.BACKUP_FOLDER = 'TalentBackups' # Verzeichnis wo Daten gespeichert werden
self.EXPORT_FOLDER = 'TalentExport' # folder where data is exported
self.IMPORT_FOLDER = 'TalentImport' # folder from where data is imported
self.IMPORT_DONE_SUBFOLDER = os.path.join(self.IMPORT_FOLDER, 'importiert') # imported files
self.IMPORT_FAILED_SUBFOLDER = os.path.join(self.IMPORT_FOLDER, 'import_fehlgeschlagen') # failed import-files
self.STATUS_BACKUP_NEEDED = False # status var which sets to true on db changes to do backup
if not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), self.PROGRAMM_FOLDER)):
os.makedirs(os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), self.PROGRAMM_FOLDER))
if not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), self.PROGRAMM_FOLDER)):
os.makedirs(os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), self.BACKUP_FOLDER))
if not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), self.EXPORT_FOLDER)):
os.makedirs(os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), self.EXPORT_FOLDER))
if not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), self.IMPORT_FOLDER)):
os.makedirs(os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), self.IMPORT_FOLDER))
if not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), self.IMPORT_DONE_SUBFOLDER)):
os.makedirs(os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), self.IMPORT_DONE_SUBFOLDER))
if not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), self.IMPORT_FAILED_SUBFOLDER)):
os.makedirs(os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), self.IMPORT_FAILED_SUBFOLDER))
self.confchanged = False # bei änderungen der config auf True, damit dann settings gespeichert werden
pass
def read(self, filename=('config.json')):
configfilename = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), self.PROGRAMM_FOLDER, filename)
# wenn keine config existiernt mit passwort anlegen
if not os.path.isfile(configfilename):
self.load_default_settings()
save_in_json(configfilename, self.data)
print('Config existiert nicht. Default Config angelegt.')
else:
self.data = load_from_json(configfilename)
self.PROFILE_SET_PROFILE_NAME = self.data['profile_settings']['profile_name']
self.PROFILE_SET_NAME = self.data['profile_settings']['name']
self.PROFILE_SET_FAMILIY_NAME = self.data['profile_settings']['family_name']
self.PROFILE_SET_EMAIL = self.data['profile_settings']['email']
self.PROFILE_SET_STREET = self.data['profile_settings']['street']
self.PROFILE_SET_ZIP_CODE = self.data['profile_settings']['zip_code']
self.PROFILE_SET_CITY = self.data['profile_settings']['city']
self.PROFILE_SET_COUNTRY = self.data['profile_settings']['country']
self.PROFILE_SET_COMPANY_PROFESSION = self.data['profile_settings']['company_profession']
self.PROFILE_SET_RADIUS_OF_ACTIVITY = self.data['profile_settings']['radius_of_activity']
self.PROFILE_SET_COORDINATES = self.data['profile_settings']['coordinates']
self.PROFILE_SET_PHONE = self.data['profile_settings']['phone']
self.PROFILE_SET_WEBSITE = self.data['profile_settings']['website']
self.PROFILE_SET_INTERESTS_HOBBIES = self.data['profile_settings']['interests_hobbies']
self.GUI_COLUMN_SELECTION = ast.literal_eval(str(self.data['gui']['column_selection'])) # interpret string as python-list
self.HTML_EXPORT_COLUMN_SELECTION = self.data['gui']['html_export_column_selection'] = ast.literal_eval(str(self.data['gui']['html_export_column_selection'])) # interpret string as python-list
self.DATABASE_ENCRYPT_ON_EXIT = bool(self.data['database']['encrypt_on_exit'])
def write(self, filename='config.json'):
configfilename = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), self.PROGRAMM_FOLDER, filename)
self.data['profile_settings']['profile_name'] = self.PROFILE_SET_PROFILE_NAME
self.data['profile_settings']['name'] = self.PROFILE_SET_NAME
self.data['profile_settings']['family_name'] = self.PROFILE_SET_FAMILIY_NAME
self.data['profile_settings']['email'] = self.PROFILE_SET_EMAIL
self.data['profile_settings']['street'] = self.PROFILE_SET_STREET
self.data['profile_settings']['zip_code'] = self.PROFILE_SET_ZIP_CODE
self.data['profile_settings']['city'] = self.PROFILE_SET_CITY
self.data['profile_settings']['country'] = self.PROFILE_SET_COUNTRY
self.data['profile_settings']['company_profession'] = self.PROFILE_SET_COMPANY_PROFESSION
self.data['profile_settings']['radius_of_activity'] = self.PROFILE_SET_RADIUS_OF_ACTIVITY
self.data['profile_settings']['coordinates'] = self.PROFILE_SET_COORDINATES
self.data['profile_settings']['phone'] = self.PROFILE_SET_PHONE
self.data['profile_settings']['website'] = self.PROFILE_SET_WEBSITE
self.data['profile_settings']['interests_hobbies'] = self.PROFILE_SET_INTERESTS_HOBBIES
self.data['gui']['column_selection'] = str(self.GUI_COLUMN_SELECTION)
self.data['gui']['html_export_column_selection'] = str(self.HTML_EXPORT_COLUMN_SELECTION)
self.data['database']['encrypt_on_exit'] = bool(self.DATABASE_ENCRYPT_ON_EXIT)
save_in_json(configfilename, self.data)
self.confchanged = False # nach speicherung wieder auf false setzen
print('Config saved')
def load_default_settings(self):
# Neue Settings auch die obige write Funktion anpassen, sonnst werden änderungen innerhalb des Programms nicht gespeichert
self.data = {'profile_settings': {'profile_name': '', 'name': '', 'family_name': '', 'street': '', 'zip_code': '',
'city': '', 'country': '', 'company_profession': '', 'email': '',
'radius_of_activity': '', 'coordinates': '', 'phone': '', 'website': '',
'interests_hobbies': ''},
'gui': {'column_selection': [], 'html_export_column_selection': []},
'database': {'encrypt_on_exit': 1}
}
# zum abfragen ob config gespeichert werden muss
def config_changed(self):
return self.confchanged
def set_config_changed(self):
self.confchanged = True
def save_var_to_file(variable, filename):
""" Saves variable like a dict to a file
:param variable: var to save
:param filename: name for the file
"""
with open(filename, 'wb') as file:
pickle.dump(variable, file)
def load_var_from_file(filename):
""" Saves variable like a dict to a file
:param variable: var to save
:param filename: name of the file
:return: variable
"""
with open(filename, 'rb') as file:
# Call load method to deserialize
myvar = pickle.load(file)
return myvar
def rand_hex(length):
"""
:param length: determines the length of the string
:return: rand string of hex values
"""
return binascii.hexlify(os.urandom(length)).decode()[:length]
class local_card_db:
def __init__(self, file, folder):
# self.filename = file
self.encrypted_db_file = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), folder, "crypted_" + file)
self.db_file = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), folder, file)
#self.db_filename = self.decrypted_db_filename
self.password = ''
def hide_data_card(self,card_id):
"""
marks the content as hidden if it is considered locally inappropriate.
:param card_id:
:return:
"""
self.sql("UPDATE local_card_info SET hidden = 1 WHERE card_id = ?;", (card_id, ))
def unhide_data_card(self,card_id):
"""
marks the content as not hidden (for example, if it was wrongly considered inadequate)
:param card_id: ID of the car
:return:
"""
self.sql("UPDATE local_card_info SET hidden = 0 WHERE card_id = ?;", (card_id, ))
def recalculate_local_ids(self,fast_mode = False):
""" Calculates an unique local id ford every card_id in local_card_info sorted by distance of the card_id.
Is needed to have an short local unique_id)
"""
if fast_mode: # fast mode ignores the distance fo card_id
card_ids_without_local_id = self.sql_list("SELECT card_id FROM local_card_info WHERE local_id IS NULL OR local_id = ''")
# find next free id beginning with one
used_local_ids = self.sql_list("""SELECT local_id FROM local_card_info""")
use_id = 0
# set local_ids for cards without local id
for card_id in card_ids_without_local_id:
use_id += 1
while use_id in used_local_ids:
use_id += 1
self.sql(f"UPDATE local_card_info SET local_id = {use_id} WHERE card_id ='{card_id}'")
self.calculate_friend_ids(fast_mode=True)
return
self.sql("""WITH ordered_rows AS ( SELECT card_id, ROW_NUMBER() OVER (ORDER BY distance) AS new_order
FROM local_card_info ) UPDATE local_card_info SET local_id =
( SELECT new_order FROM ordered_rows WHERE ordered_rows.card_id = local_card_info.card_id );""")
self.calculate_friend_ids()
def calculate_friend_ids(self, fast_mode=False):
"""Determines from a data-card (business_Card) the local ID of the friends datacard.
To know from where (which friend) is the data card from. If there are multiple friends then the
closest friend (regarding to the local profile coordinates) is choosed as friend"""
local_card_ids = self.sql_list("SELECT card_id from local_card_info;")
local_ids = self.sql_tuble_to_dict(self.sql("SELECT card_id, local_id FROM local_card_info;"))
foreign_card_id = self.sql_tuble_to_dict(self.sql("SELECT card_id, foreign_card FROM dc_head;")) # stores if card_id is foreign_card
creators_card_ids = self.sql_tuble_to_dict(self.sql("""SELECT creator, card_id FROM dc_head
WHERE foreign_card = False AND type = 'business_card';"""))
card_id_creators = self.sql_tuble_to_dict(self.sql("""SELECT card_id, creator FROM dc_head;"""))
card_id_distances = self.sql_tuble_to_dict(self.sql("SELECT card_id, distance FROM local_card_info;"))
creators_friends = self.sql_tuble_to_dict(self.sql("""SELECT creator_id, friends_ids FROM friends_of_friends;"""))
# check if there are cards with friends_id but local_id does not exists (on deletion it can happen)
# then full recalculation of all local_ids with
if fast_mode:
# on fast mode only calc friends for cards without friends or wrong friend id
local_card_ids = self.sql_list(
"SELECT card_id from local_card_info WHERE friend_ids IS NULL OR friend_ids = '';")
# determine friends with wrong friend id
used_friend_ids = self.sql_list("""SELECT friend_ids from local_card_info
WHERE NOT (friend_ids IS NULL OR friend_ids = '');""")
#convert comma separated items (when multiple friends) to list items ([2, 6, '7,9', 1] -> [2, 6, 7, 9, 1]
used_friend_ids = [int(num) for item in used_friend_ids for num in str(item).split(',')]
used_friend_ids = [*set(used_friend_ids)] # remove duplicates
all_local_ids = self.sql_list("SELECT local_id from local_card_info;")
for friend_id in used_friend_ids:
if friend_id not in all_local_ids:
local_card_ids += self.sql_list(f"SELECT card_id FROM local_card_info WHERE friend_ids = {friend_id}")
# determine friends of all local cards ids or when fast mode -> only cards without friends or wrong friend id
for card_id in local_card_ids:
if foreign_card_id[card_id] == 0:
# card is the personal card of the creator itself so all friends must be determined
# then the business cards (if exists) of the friends are need to get the local id (which is the friends number in gui)
creator = card_id_creators[card_id]
friends_of_creator = str(creators_friends.get(creator, 'nocreator')).split(',')
min_distance = "~~~~~~~~~" # distance is string in database and ~ represents a high value (need to get minimum)
friends_local_id = ""
# determine of all friends which business_card is the closest to choose this card creator as friend
for friend_creator_id in friends_of_creator:
creators_card_id = creators_card_ids.get(friend_creator_id, 'noid')
distance = card_id_distances.get(creators_card_id, '~~~~~~~~~~~~~~')
if distance < min_distance:
min_distance = distance
friends_local_id = [local_ids.get(creators_card_id, '')]
# add rest of friends
for friend_creator_id in friends_of_creator:
creators_card_id = creators_card_ids.get(friend_creator_id, 'noid')
if local_ids.get(creators_card_id, '') not in friends_local_id:
friends_local_id += [local_ids.get(creators_card_id, '')]
friends_local_id = [x for x in friends_local_id if x != ''] # remove empty strings
self.sql("UPDATE local_card_info SET friend_ids = ? WHERE card_id = ?;",
(",".join(str(x) for x in friends_local_id), card_id,)) # add comma separated ids to db
else:
# foreign_card -> the creator of the card is the friend -> set local ID of creator and set as friend
creator = card_id_creators[card_id]
creators_card_id = creators_card_ids.get(creator, 'noid')
friends_local_id = local_ids.get(creators_card_id, '') # empty string if no card_id found
self.sql("UPDATE local_card_info SET friend_ids = ? WHERE card_id = ?;", (friends_local_id, card_id,))
def datacard_to_sql_update(self, datacard):
""" Generate from a datacard the sql commands for needed tables to update the existing datacard in the sql database.
:param datacard: datacard dict
:return: sql-commands for the update of the datacards
"""
# newsalts = ""
# for salt in datacard['dc_dynamic_head']['salts']:
# newsalts += f"{str(salt)},"
# datacard['dc_dynamic_head']['salts'] = newsalts[:-1]
# convert salts back from list to comma separated string
datacard['dc_dynamic_head']['salts'] = ','.join(str(salt) for salt in datacard['dc_dynamic_head']['salts'])
commands = []
for tablename in datacard.keys():
sql_command = "UPDATE "
# sql_values = ""
sql_data_tuble = ()
table = tablename
if table == 'data':
table = datacard['dc_head']['type']
sql_command += f"{table} SET "
for column in datacard[tablename].keys():
if column == "card_id":
continue # ignore card_id here, card_id is set on the end
data = datacard[tablename][column]
if tablename == 'data':
sql_command += f"{column} = ?, "
sql_data_tuble += (data[0],)
sql_command += f"HOPS_{column} = ?, "
sql_data_tuble += (data[1],)
sql_command += f"DELETED_{column} = ?, "
sql_data_tuble += (data[2],)
else:
sql_command += f"{column} = ?, "
sql_data_tuble += (data,)
sql_command = sql_command[:-2] # remove the last 2 elements in the string
card_id = datacard['dc_head']['card_id']
sql_command += f" WHERE card_id = ?;"
sql_data_tuble += (card_id,)
commands.append([sql_command, sql_data_tuble])
return commands
def datacard_to_sql_insert(self, datacard):
""" Generate from a datacard the sql insert commands for the needed tables to import a new non existing
datacard to the sql database.
:param datacard: datacard dict
:return: sql-commands for the import of the datacards
"""
# convert salts back from list to comma separated string
newsalts = ""
for salt in datacard['dc_dynamic_head']['salts']:
newsalts += f"{str(salt)},"
datacard['dc_dynamic_head']['salts'] = newsalts[:-1]
commands = []
for tablename in datacard.keys():
table = tablename
sql_command = "INSERT INTO "
sql_values = ""
sql_data_tuble = ()
if table == 'data':
table = datacard['dc_head']['type']
sql_command += f"{table} ( "
for column in datacard[tablename].keys():
data = datacard[tablename][column]
if tablename == 'data':
sql_command += f"{column}, "
sql_data_tuble += (data[0],)
sql_command += f"HOPS_{column}, "
sql_data_tuble += (data[1],)
sql_command += f"DELETED_{column}, "
sql_data_tuble += (data[2],)
sql_values += "?, ?, ?, "
else:
sql_command += f"{column}, "
sql_data_tuble += (data,)
sql_values += "?, "
# add card_id to data part
if tablename == 'data':
card_id = datacard['dc_head']['card_id']
sql_command += "card_id, "
sql_data_tuble += (card_id,)
sql_values += "?, "
sql_command = sql_command[:-2] # remove the last 2 elements in the string
sql_values = sql_values[:-2] # remove the last 2 elements in the string
sql_command += f") VALUES ( {sql_values} );"
commands.append([sql_command, sql_data_tuble])
# insert card_id in local_card_info table if needed (for example publickey not needed)
types_needed_local_card_info = ["business_card"] # all type which need local card info
if datacard['dc_head']['type'] in types_needed_local_card_info:
sql_command = f"INSERT INTO local_card_info ( card_id ) VALUES ( ? );"
sql_data_tuble = (card_id,)
commands.append([sql_command, sql_data_tuble])
return commands
def convert_db_to_dict(self, card_id, increase_hop=False, add_hops_info=True):
"""
Convert an sqlite DB entry to an dictionary (which is send to friends)
:param card_id: ID of the card which will be converted to a datacard dict
:param increase_hop if True the hop counter will be increased (i.e. when exported to friend)
:param add_hops_info adds the hops info to the data part in form of a list, if not only content is added
:return:
"""
# create head dict
columns = self.list_tables_colums('dc_head')
cursor = self.conn.execute(f"select * from dc_head WHERE card_id = '{card_id}'")
output = cursor.fetchall()[0]
cursor.close()
dc_head = {}
for i in range(len(columns)):
dc_head[columns[i]] = output[i]
# create content dict
columns = self.list_tables_colums(dc_head['type'])
cursor = self.conn.execute(f"select * from {dc_head['type']} WHERE card_id = '{card_id}'")
output = cursor.fetchall()[0]
cursor.close()
card_type_content = {}
hops_info = {}
for i in range(len(columns)):
if (str(columns[i]).find("DELETED_") > -1 or str(columns[i]).find("HOPS_") > -1):
hops_info[columns[i]] = output[i]
continue
if columns[i] != "card_id":
if add_hops_info:
card_type_content[columns[i]] = [output[i]]
else:
card_type_content[columns[i]] = output[i]
if add_hops_info:
# add hops info to content
for element in card_type_content:
card_type_content[element].append(hops_info[("HOPS_" + str(element))])
card_type_content[element].append(hops_info[("DELETED_" + str(element))])
if not add_hops_info:
for element in card_type_content:
if hops_info[('DELETED_' + str(element))] != '0':
card_type_content[element] = "" # delete content if deleted
columns = self.list_tables_colums('dc_dynamic_head')
cursor = self.conn.execute(f"select * from dc_dynamic_head WHERE card_id = '{card_id}'")
output = cursor.fetchall()[0]
cursor.close()
dc_dynamic_head = {}
for i in range(len(columns)):
dc_dynamic_head[columns[i]] = output[i]
dc_dynamic_head['salts'] = str(dc_dynamic_head['salts']).split(',')
# hop counter needs to increased when the data is exported for friends
if increase_hop:
simulate_hops = 1 # normaly set to 1, for debug (simulate more hops) you can set higher
for loop in range(simulate_hops):
dc_dynamic_head['hops'] += 1
hops = dc_dynamic_head['hops']
# elemente der datenkarte löschen wenn der freund zu weit entfernt
# salt festlegen der genutzt wird.
for sal in dc_dynamic_head['salts']:
if sal != "-":
salt = sal
break
delete_salt = False
for data_element in card_type_content:
# wenn hops größer als für das element erlaubt, dann läschen
if hops > card_type_content[data_element][1]:
delete_salt = True
if card_type_content[data_element][2] == '0': # marked as not deleted (when deleted hash is content)
temp_string = str(card_type_content[data_element][0]) + str(
card_type_content[data_element][1]) + str(salt)
card_type_content[data_element][0] = "" # delete content
card_type_content[data_element][2] = short_SHA256(temp_string) # write hash to deleted val
# salt löschen mit den inhalt gesaltet wurde (damit kurzer ihhalt nicht per Brutforce
if delete_salt:
dc_dynamic_head['salts'] = ["-" if i == salt else i for i in dc_dynamic_head['salts']]
data_card = {}
data_card['dc_head'] = dc_head
data_card[
'dc_dynamic_head'] = dc_dynamic_head # parts that are not hashed (are changed by friends / neigbors and which are not static)
data_card['data'] = card_type_content
return data_card
def datacard_exist(self, card_id):
"""
check if the datacard with the id exists
:param card_id:
:return: True or False
"""
cursor = self.conn.execute(f"select * from dc_head WHERE card_id = '{card_id}'")
output = cursor.fetchall()
cursor.close()
if len(output) > 0:
return True
return False
def friend_exist(self, pubkey_id):
"""
check if the friend with the pubkey_id exists
:param pubkey_id: pubkey_id of the friend
:return: True or False
"""