-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexport.py
81 lines (62 loc) · 2.55 KB
/
export.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
import json
import os
import subprocess
import click
KrakenCryptoToolsPath = "~/go/bin/KrakenCryptoTools"
def get_credentials(creds_path, cred_type):
# Open directory and recursively yield json decoded content of all json files.
# Return an error if content is not json decodable.
for root, dirs, files in os.walk(creds_path):
if cred_type not in root:
continue
for file in files:
if file.endswith(".json"):
with open(os.path.join(root, file)) as f:
try:
yield json.load(f)
except json.decoder.JSONDecodeError:
click.echo(f"Error: {file} is not valid json.")
# Get all keys of a dict and return them as list.
def get_keys(cred):
for key in cred.keys():
yield key
if isinstance(cred[key], dict):
yield from get_keys(cred[key])
def get_fields_for_credential_type(cred_type):
if cred_type == "course-grades":
return ['id', 'name', 'grade']
if cred_type == "diploma":
return ['id', 'academicDegree', 'name']
raise Exception(f"Unknown credential type: {cred_type}")
def get_line(cred, cred_fields):
return [str(cred.get(field, "")) for field in cred_fields]
def write_to_csv(fields, data, output):
# Write data to csv file.
with open(output, "w") as f:
f.write(", ".join(fields) + "\n")
for line in data:
f.write(", ".join(line) + "\n")
def sign_csv(output, key_name):
binary = os.path.expanduser(KrakenCryptoToolsPath)
subprocess.run([binary, "zk-sig", "sign", "-dataset", output, "--keyName", key_name])
@click.command()
@click.option('--path', default='instance/uploads', help='Path to directory with credentials')
@click.option('--cred_type', default='course-grades', help='course-grades or diplomas')
@click.option('--output', default='data.csv', help='Path to output file')
@click.option('--field', default='grade', help='Only export this field')
@click.option('--sign', default='zk-keys/kraken-edu-exporter-key1',
help='Key to be used with KrakenCryptoTools to sign resulting CSV file')
def main(path, cred_type, output, field, sign):
if field:
fields = [field]
else:
fields = get_fields_for_credential_type(cred_type)
lines = []
for cred in get_credentials(path, cred_type):
line = get_line(cred['credentialSubject'], fields)
lines.append(line)
write_to_csv(fields, lines, output)
if sign:
sign_csv(output, sign)
if __name__ == '__main__':
main()