-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathusap.py
More file actions
5493 lines (4648 loc) · 235 KB
/
Copy pathusap.py
File metadata and controls
5493 lines (4648 loc) · 235 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
import math
import flask
from flask import Flask, session, render_template, redirect, url_for, request, send_from_directory, send_file, current_app, make_response
from flask_jsglue import JSGlue
from random import randint
import os
from authlib.integrations.flask_client import OAuth
import json
from urllib.request import urlopen
from urllib.parse import urlparse, unquote, urlencode
from werkzeug.utils import secure_filename
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import psycopg2
import psycopg2.extras
import requests
import re
import copy
from datetime import datetime, timedelta, date as dt_date
import csv
from collections import namedtuple
import humanize
import lib.json2sql as json2sql
import shutil
import lib.curatorFunctions as cf
from functools import partial
from services.api_v1 import blueprint as api_v1
# from services.api_v2 import blueprint as api_v2
import services.settings as rp_settings
import traceback
import pandas as pd
import pickle
from apiclient.discovery import build
from google.auth.transport.requests import Request as gRequest
import base64
import email
from email.header import decode_header
from dateutil.parser import parse
from lib.gmail_functions import send_gmail_message
import lib.difHarvest as dh
from pathlib import Path
import xml.etree.ElementTree as ET
from zoneinfo import ZoneInfo as zi
app = Flask(__name__)
jsglue = JSGlue(app)
############
# Load configuration
############
app.config.update(
SESSION_TYPE="filesystem",
SESSION_FILE_DIR="flask_session",
PERMANENT_SESSION_LIFETIME=86400,
UPLOAD_FOLDER="upload",
DATASET_FOLDER="dataset",
SUBMITTED_FOLDER="submitted",
SAVE_FOLDER="saved",
DOCS_FOLDER="doc",
AWARDS_FOLDER="awards",
METADATA_FOLDER="watch",
CROSSREF_FILE="inc/crossref_sql.txt",
OLD_CROSSREF_FILE="inc/old_crossref_sql.txt",
DOI_REF_FILE="inc/doi_ref",
PROJECT_REF_FILE="inc/project_ref",
GMAIL_PICKLE="inc/token.pickle",
AWARD_WELCOME_EMAIL="static/letters/USAP_DCwelcomeletter.html",
AWARD_FINAL_EMAIL="static/letters/USAP_DCcloseoutletter.html",
AWARD_EMAIL_BANNER="/static/letters/images/image1.png",
DEBUG=True
)
app.config.update(json.loads(open('config.json', 'r').read()))
app.debug = app.config['DEBUG']
app.secret_key = app.config['SECRET_KEY']
app.register_blueprint(api_v1)
# set up api v2 for future use
# app.register_blueprint(api_v2)
app.config['SWAGGER_UI_DOC_EXPANSION'] = rp_settings.RESTPLUS_SWAGGER_UI_DOC_EXPANSION
app.config['RESTPLUS_VALIDATE'] = rp_settings.RESTPLUS_VALIDATE
app.config['RESTPLUS_MASK_SWAGGER'] = rp_settings.RESTPLUS_MASK_SWAGGER
app.config['ERROR_404_HELP'] = rp_settings.RESTPLUS_ERROR_404_HELP
app.config['BUNDLE_ERRORS'] = rp_settings.RESTPLUS_BUNDLE_ERRORS
@app.route('/api')
def api():
return render_template('api_swagger.html', api_url=url_for('api.doc'))
oauth = OAuth(app)
google = oauth.register('google',
client_id=app.config['GOOGLE_CLIENT_ID'],
client_secret=app.config['GOOGLE_CLIENT_SECRET'],
server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
client_kwargs={'scope': 'openid profile email'})
orcid = oauth.register('orcid',
client_id=app.config['ORCID_CLIENT_ID'],
client_secret=app.config['ORCID_CLIENT_SECRET'],
server_metadata_url='https://orcid.org/.well-known/openid-configuration',
client_kwargs={'scope': 'openid '})
config = json.loads(open('config.json', 'r').read())
def connect_to_prod_db(curator=False):
info = config['PROD_DATABASE']
if curator and cf.isCurator():
user = info['USER_CURATOR']
password = info['PASSWORD_CURATOR']
else:
user = info['USER']
password = info['PASSWORD']
conn = psycopg2.connect(host=info['HOST'],
port=info['PORT'],
database=info['DATABASE'],
user=user,
password=password)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
return (conn, cur)
def connect_to_db(curator=False):
info = config['DATABASE']
if curator and cf.isCurator():
user = info['USER_CURATOR']
password = info['PASSWORD_CURATOR']
else:
user = info['USER']
password = info['PASSWORD']
conn = psycopg2.connect(host=info['HOST'],
port=info['PORT'],
database=info['DATABASE'],
user=user,
password=password)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
return (conn, cur)
def get_email_template(editing, submissionType, uid, data, hasId, doi=None):
text = "Dear %s,\n\n" % data.get('submitter_name')
if editing:
url = url_for("project_landing_page", project_id=uid, _external=True) if submissionType == "project" else url_for("landing_page", dataset_id=uid, _external=True)
text += "This is to confirm that your %s, %s, has been successfully updated.\n" % (submissionType, data.get("title"))
text += "Please check the landing page %s and contact us if there are any issues." % url
else:
if submissionType == "project":
text += "This is to confirm that your project, %s, has been successfully registered at USAP-DC.\n" % data.get("title")
text += "Please check the landing page %s and contact us ([email protected]) if there are any issues." % url_for("project_landing_page", project_id=uid, _external=True)
if hasId:
text += "\n\nWe have also prepared and submitted a catalog entry (DIF) at the Antarctic Metadata Directory (AMD)."
text += "\nThe DIF ID will be %s." % cf.getDifID(uid)
text += "\nThe direct link to the AMD record will be %s." % cf.getDifUrl(uid)
text += "\n\nIt usually takes AMD staff a few business days to review the submission before it goes live."
else:
text += "\n\nIf everything looks fine, I will also prepare and submit an entry (DIF record) to the Antarctic Metadata Directory (AMD)."
text += "\n\nYou can update the project page in the future using the 'edit' function in the top right, e.g. when new datasets or publications become available. In the case that you archive your dataset(s) at the USAP-DC repository, we will automatically link the dataset to the project."
text += "\n\nAny edits will be reviewed by a USAP-DC curator before they become live."
else:
text += "We have processed your dataset %s, and added it to the USAP-DC repository.\nThe dataset ID is %s." % (data.get("title"), uid)
#print(data)
if len(data['awards']) > 0:
query = "SELECT proj_uid FROM project_dataset_map WHERE dataset_id = %s"
(conn, cur) = connect_to_db(curator=True)
query_str = cur.mogrify(query, (uid,))
cur.execute(query_str)
proj_uids_tuples = cur.fetchall()
#print(proj_uids_tuples)
proj_uids = list(map(lambda x : x['proj_uid'], proj_uids_tuples))
#print(proj_uids)
if len(proj_uids) == 1:
text += "\n\nBased on the award number, we have linked the dataset to the project %s." % url_for("project_landing_page", project_id=proj_uids[0], _external=True)
else:
text += "\n\nBased on the award numbers, we have linked the dataset to the following %s projects:" % len(proj_uids)
for proj_uid in proj_uids:
text += "\n%s" % url_for("project_landing_page", project_id=proj_uid, _external=True)
text += "\n\nPlease check the landing page %s and let us know if everything looks good or if there are any issues.\n\n" % url_for("landing_page", dataset_id=uid, _external=True)
if hasId:
text += "The DOI for the dataset is %s." % doi
else:
text += "If everything is fine, we will create a DOI for the dataset."
text += "\n\nBest regards,\n"
return text
def get_nsf_grants(columns, award=None, only_inhabited=True):
(conn, cur) = connect_to_db()
query_string = """SELECT %s FROM award a WHERE a.award != 'XXXXXXX' and a.award != 'None' and a.award ~ '^[0-9]'
and a.award::integer<8000000 and a.award::integer>0400000""" % ','.join(columns)
if only_inhabited:
query_string += ' AND EXISTS (SELECT award_id FROM dataset_award_map dam WHERE dam.award_id=a.award)'
query_string += ' ORDER BY name,award'
cur.execute(query_string)
return cur.fetchall()
def get_datasets(dataset_ids):
if len(dataset_ids) == 0:
return []
else:
(conn, cur) = connect_to_db()
query_string = \
cur.mogrify(
'''SELECT d.*,
CASE WHEN a.awards IS NULL THEN '[]'::json ELSE a.awards END,
CASE WHEN k.keywords IS NULL THEN '[]'::json ELSE k.keywords END,
CASE WHEN par.parameters IS NULL THEN '[]'::json ELSE par.parameters END,
CASE WHEN l.locations IS NULL THEN '[]'::json ELSE l.locations END,
CASE WHEN per.persons IS NULL THEN '[]'::json ELSE per.persons END,
CASE WHEN pl.platforms IS NULL THEN '[]'::json ELSE pl.platforms END,
CASE WHEN sen.sensors IS NULL THEN '[]'::json ELSE sen.sensors END,
CASE WHEN ref.references IS NULL THEN '[]'::json ELSE ref.references END,
CASE WHEN sp.spatial_extents IS NULL THEN '[]'::json ELSE sp.spatial_extents END,
CASE WHEN tem.temporal_extents IS NULL THEN '[]'::json ELSE tem.temporal_extents END,
CASE WHEN prog.programs IS NULL THEN '[]'::json ELSE prog.programs END,
CASE WHEN proj.projects IS NULL THEN '[]'::json ELSE proj.projects END,
CASE WHEN dif.dif_records IS NULL THEN '[]'::json ELSE dif.dif_records END,
CASE WHEN rel_proj.rel_projects IS NULL THEN '[]'::json ELSE rel_proj.rel_projects END,
license.url AS license_url, license.label AS license_label
FROM
dataset d
LEFT JOIN (
SELECT dam.dataset_id, json_agg(a) awards
FROM dataset_award_map dam JOIN award a ON (a.award=dam.award_id)
WHERE a.award != 'XXXXXXX'
GROUP BY dam.dataset_id
) a ON (d.id = a.dataset_id)
LEFT JOIN (
SELECT kw.dataset_id, json_agg(kw) keywords FROM (
SELECT dkm.dataset_id, ku.keyword_label AS keyword_label, ku.keyword_description AS keyword_description
FROM dataset_keyword_map dkm JOIN keyword_usap ku ON (ku.keyword_id=dkm.keyword_id)
UNION
SELECT dkm.dataset_id, ki.keyword_label AS keyword_label, ki.keyword_description AS keyword_description
FROM dataset_keyword_map dkm JOIN keyword_ieda ki ON (ki.keyword_id=dkm.keyword_id)
) kw
GROUP BY kw.dataset_id
) k ON (d.id = k.dataset_id)
LEFT JOIN (
SELECT dparm.dataset_id, json_agg(par) parameters
FROM dataset_parameter_map dparm JOIN parameter par ON (par.id=dparm.parameter_id)
GROUP BY dparm.dataset_id
) par ON (d.id = par.dataset_id)
LEFT JOIN (
SELECT dataset_id, json_agg(keyword_label) locations
FROM vw_dataset_location vdl
GROUP BY dataset_id
) l ON (d.id = l.dataset_id)
LEFT JOIN (
SELECT dperm.dataset_id, json_agg(per) persons
FROM dataset_person_map dperm JOIN person per ON (per.id=dperm.person_id)
GROUP BY dperm.dataset_id
) per ON (d.id = per.dataset_id)
LEFT JOIN (
SELECT dplm.dataset_id, json_agg(pl) platforms
FROM dataset_platform_map dplm JOIN platform pl ON (pl.id=dplm.platform_id)
GROUP BY dplm.dataset_id
) pl ON (d.id = pl.dataset_id)
LEFT JOIN (
SELECT dsenm.dataset_id, json_agg(sen) sensors
FROM dataset_sensor_map dsenm JOIN sensor sen ON (sen.id=dsenm.sensor_id)
GROUP BY dsenm.dataset_id
) sen ON (d.id = sen.dataset_id)
LEFT JOIN (
SELECT drm.dataset_id, json_agg(ref) AS references
FROM dataset_reference_map drm JOIN reference ref ON ref.ref_uid=drm.ref_uid
GROUP BY drm.dataset_id
) ref ON (d.id = ref.dataset_id)
LEFT JOIN (
SELECT sp.dataset_id, json_agg(sp) spatial_extents
FROM dataset_spatial_map sp
GROUP BY sp.dataset_id
) sp ON (d.id = sp.dataset_id)
LEFT JOIN (
SELECT tem.dataset_id, json_agg(tem) temporal_extents
FROM dataset_temporal_map tem
GROUP BY tem.dataset_id
) tem ON (d.id = tem.dataset_id)
LEFT JOIN (
SELECT dam.dataset_id, json_agg(prog) programs
FROM dataset_award_map dam, award_program_map apm, program prog
WHERE dam.award_id = apm.award_id AND apm.program_id = prog.id
GROUP BY dam.dataset_id
) prog ON (d.id = prog.dataset_id)
LEFT JOIN (
SELECT dprojm.dataset_id, json_agg(proj) projects
FROM dataset_initiative_map dprojm JOIN initiative proj ON (proj.id=dprojm.initiative_id)
GROUP BY dprojm.dataset_id
) proj ON (d.id = proj.dataset_id)
LEFT JOIN (
SELECT ddm.dataset_id, json_agg(dif) dif_records
FROM dataset_dif_map ddm JOIN dif ON (dif.dif_id=ddm.dif_id)
GROUP BY ddm.dataset_id
) dif ON (d.id = dif.dataset_id)
LEFT JOIN (
SELECT pdm.dataset_id, json_agg(proj) rel_projects
FROM project_dataset_map pdm JOIN project proj ON (proj.proj_uid=pdm.proj_uid)
GROUP BY pdm.dataset_id
) rel_proj ON (d.id = rel_proj.dataset_id)
LEFT JOIN license ON (d.license = license.id)
WHERE d.id IN %s ORDER BY d.title''',
(tuple(dataset_ids),))
cur.execute(query_string)
return cur.fetchall()
def get_parameters(conn=None, cur=None, dataset_id=None):
if not (conn and cur):
(conn, cur) = connect_to_db()
query = 'SELECT DISTINCT id FROM gcmd_science_key'
query += ' ORDER BY id'
cur.execute(query)
return cur.fetchall()
def get_titles(conn=None, cur=None, dataset_id=None):
if not (conn and cur):
(conn, cur) = connect_to_db()
query = 'SELECT DISTINCT title FROM dataset ORDER BY title'
cur.execute(query)
return cur.fetchall()
def get_locations(conn=None, cur=None, dataset_id=None):
if not (conn and cur):
(conn, cur) = connect_to_db()
query = 'SELECT DISTINCT id FROM gcmd_location'
query += ' ORDER BY id'
cur.execute(query)
return cur.fetchall()
def get_usap_locations(conn=None, cur=None, dataset_id=None):
if not (conn and cur):
(conn, cur) = connect_to_db()
query = "SELECT * FROM vw_location"
query += ' ORDER BY keyword_label'
cur.execute(query)
return cur.fetchall()
def get_keywords(conn=None, cur=None, dataset_id=None):
if not (conn and cur):
(conn, cur) = connect_to_db()
query = 'SELECT * FROM keyword'
if dataset_id:
query += cur.mogrify(' WHERE id in (SELECT keyword_id FROM dataset_keyword_map WHERE dataset_id=%s)', (dataset_id,)).decode()
query += ' ORDER BY id'
cur.execute(query)
return cur.fetchall()
def get_platforms(conn=None, cur=None, dataset_id=None):
if not (conn and cur):
(conn, cur) = connect_to_db()
query = 'SELECT * FROM platform'
if dataset_id:
query += cur.mogrify(' WHERE id in (SELECT platform_id FROM dataset_platform_map WHERE dataset_id=%s)', (dataset_id,)).decode()
query += ' ORDER BY id'
cur.execute(query)
return cur.fetchall()
def get_persons(conn=None, cur=None, dataset_id=None, order=True):
if not (conn and cur):
(conn, cur) = connect_to_db()
query = 'SELECT * FROM person'
if dataset_id:
query += cur.mogrify(' WHERE id in (SELECT person_id FROM dataset_person_map WHERE dataset_id=%s)', (dataset_id,)).decode()
if order:
query += ' ORDER BY id'
cur.execute(query)
return cur.fetchall()
def get_project_persons(conn=None, cur=None, project_id=None):
if not (conn and cur):
(conn, cur) = connect_to_db()
query = 'SELECT * FROM person'
if project_id:
query += cur.mogrify(' WHERE id in (SELECT person_id FROM project_person_map WHERE proj_uid=%s)', (project_id,)).decode()
query += ' ORDER BY id'
cur.execute(query)
return cur.fetchall()
def get_person(person_id):
(conn, cur) = connect_to_db()
query = 'SELECT * FROM person'
if person_id:
query += cur.mogrify(' WHERE id = %s', (person_id,)).decode()
cur.execute(query)
return cur.fetchone()
def get_sensors(conn=None, cur=None, dataset_id=None):
if not (conn and cur):
(conn, cur) = connect_to_db()
query = 'SELECT * FROM sensor'
if dataset_id:
query += cur.mogrify(' WHERE id in (SELECT sensor_id FROM dataset_sensor_map WHERE dataset_id=%s)', (dataset_id,)).decode()
query += ' ORDER BY id'
cur.execute(query)
return cur.fetchall()
def get_references(conn=None, cur=None, dataset_id=None):
if not (conn and cur):
(conn, cur) = connect_to_db()
query = 'SELECT * FROM reference'
if dataset_id:
query += cur.mogrify(' WHERE ref_uid in (SELECT ref_uid FROM dataset_reference_map WHERE dataset_id=%s)', (dataset_id,)).decode()
cur.execute(query)
return cur.fetchall()
def get_spatial_extents(conn=None, cur=None, dataset_id=None):
if not (conn and cur):
(conn, cur) = connect_to_db()
query = 'SELECT * FROM dataset_spatial_map'
if dataset_id:
query += cur.mogrify(' WHERE dataset_id=%s', (dataset_id,)).decode()
cur.execute(query)
return cur.fetchall()
def get_temporal_extents(conn=None, cur=None, dataset_id=None):
if not (conn and cur):
(conn, cur) = connect_to_db()
query = 'SELECT * FROM dataset_temporal_map'
if dataset_id:
query += cur.mogrify(' WHERE dataset_id=%s', (dataset_id,)).decode()
cur.execute(query)
return cur.fetchall()
def get_programs(conn=None, cur=None):
if not (conn and cur):
(conn, cur) = connect_to_db()
query = 'SELECT * FROM program'
cur.execute(query)
return cur.fetchall()
def get_projects(conn=None, cur=None):
if not (conn and cur):
(conn, cur) = connect_to_db()
query = 'SELECT * FROM initiative ORDER BY ID'
cur.execute(query)
# need to convert from RealDictRow to dict
return [dict(row) for row in cur.fetchall()]
def get_licenses(conn=None, cur=None):
if not (conn and cur):
(conn, cur) = connect_to_db()
query = 'SELECT * FROM license WHERE valid_option = true ORDER BY ID'
cur.execute(query)
return cur.fetchall()
def get_orgs(conn=None, cur=None):
if not (conn and cur):
(conn, cur) = connect_to_db()
query = 'SELECT * FROM organizations ORDER BY name'
cur.execute(query)
return cur.fetchall()
def get_roles(conn=None, cur=None):
if not (conn and cur):
(conn, cur) = connect_to_db()
query = 'SELECT id FROM role'
cur.execute(query)
return cur.fetchall()
def get_deployment_types(conn=None, cur=None):
if not (conn and cur):
(conn, cur) = connect_to_db()
query = 'SELECT * FROM deployment_type ORDER BY deployment_type'
cur.execute(query)
return cur.fetchall()
def get_files(conn=None, cur=None, dataset_id=None):
if not (conn and cur):
(conn, cur) = connect_to_db()
query = 'SELECT * FROM dataset_file '
if dataset_id:
query += cur.mogrify(' WHERE dataset_id=%s', (dataset_id,)).decode()
query += ' ORDER BY file_name;'
cur.execute(query)
return cur.fetchall()
def get_gcmd_platforms(conn=None, cur=None):
query = "SELECT id FROM gcmd_platform WHERE id != 'Not provided' ORDER BY id"
return gcmd_id_to_json(conn, cur, query, 'GCMD Platforms', 'Not Provided')
def get_gcmd_instruments(conn=None, cur=None):
query = "SELECT id FROM gcmd_instrument WHERE id !~* 'NOT APPLICABLE' ORDER BY id"
return gcmd_id_to_json(conn, cur, query, 'GCMD Instruments', 'NOT APPLICABLE')
def get_gcmd_paleo_time(conn=None, cur=None):
query = "SELECT id FROM gcmd_paleo_time WHERE id !~* 'NOT APPLICABLE' ORDER BY id"
return gcmd_id_to_json(conn, cur, query, 'GCMD Paleo Time', 'NOT APPLICABLE')
def get_gcmd_progress():
(conn, cur) = connect_to_db()
query = 'SELECT * FROM gcmd_collection_progress'
cur.execute(query)
return cur.fetchall()
def get_product_levels():
(conn, cur) = connect_to_db()
query = "SELECT * FROM product_level WHERE id != 'Not provided'"
cur.execute(query)
return cur.fetchall()
def get_gcmd_data_types():
(conn, cur) = connect_to_db()
query = 'SELECT * FROM gcmd_collection_data_type'
cur.execute(query)
return cur.fetchall()
def get_gcmd_data_formats():
(conn, cur) = connect_to_db()
query = "SELECT * FROM gcmd_data_format WHERE short_name != 'Not Provided'"
cur.execute(query)
return cur.fetchall()
# function to convert gcmd ids from DB tables into json that can be used to populate bootstrap-treeviews
def gcmd_id_to_json(conn=None, cur=None, query=None, base_node_text=None, none_option=None):
if not (query and base_node_text):
return[]
if not (conn and cur):
(conn, cur) = connect_to_db()
cur.execute(query)
res = cur.fetchall()
json = [{'text': base_node_text, 'nodes': []}]
if none_option:
json[0]['nodes'].append({'text': none_option, 'id': none_option})
for r in res:
this_id = r['id']
parts = this_id.split(' > ')
parent_node = [p for p in json if p['text'] == base_node_text][0]
for idx, part in enumerate(parts):
if idx > 0:
parent_node = [p for p in parent_node['nodes'] if p['text'] == parts[idx-1]][0]
if idx == len(parts) - 1:
node = {'text': part, 'id': this_id}
if parent_node.get('nodes'):
parent_node['nodes'].append(node)
else:
parent_node['nodes'] = [node]
return json
def check_user_permission(user_info, uid, project=False):
# if user is a curator, always return true
if cf.isCurator():
return True
if project:
persons = get_project_persons(project_id=uid)
else:
# get users associated with this dataset
persons = get_persons(dataset_id=uid)
# check if orcid or email address from user_info matches any of these users
for p in persons:
if (p.get('email') and user_info.get('email') and p['email'].lower() == user_info['email'].lower()) \
or (p.get('id_orcid') and p['id_orcid'] == user_info.get('orcid')):
return True
return False
#sort list numerically instead of alphabetically
def sortNumerically(val, replace_str, replace_str2=''):
return int(val.replace(replace_str, '0').replace(replace_str2, ''))
#for page 1 of dataset submission/editing
@app.route('/edit/dataset/<dataset_id>', methods=['GET', 'POST'])
@app.route('/submit/dataset', methods=['GET', 'POST'])
def dataset(dataset_id=None):
error = ''
success = ''
session['error'] = False
# make some space in the session cookie by clearing any project_metadata
if session.get('project_metadata'):
del session['project_metadata']
if session.get('_flashes'):
del session['_flashes']
edit = False
template = False
template_id = None
if not dataset_id:
dataset_id = request.form.get('dataset_id')
template_id = request.args.get('template_id')
if dataset_id and dataset_id != '':
edit = True
if template_id and template_id != '':
template = True
user_info = session.get('user_info')
if user_info is None:
session['next'] = request.path
return redirect(url_for('login'))
# if editing - check user has editing permissions on this dataset
if edit and not check_user_permission(user_info, dataset_id):
return redirect(url_for('invalid_user', dataset_id=dataset_id))
if request.method == 'POST':
if request.form.get('action') == "Previous Page":
# coming from page 2
page1 = {}
page2 = request.form.to_dict()
if 'page1' in page2 and page2['page1'] != "":
page1 = eval(page2.pop('page1'))
else:
page1 = request.form.to_dict()
page2 = {}
if 'page2' in page1 and page1['page2'] != "":
page2 = eval(page1.pop('page2'))
page1 = groupPage1Fields(page1)
if request.form.get('action') == "Previous Page":
# arriving back from Page 2
return render_template('dataset.html', name=user_info['name'], email="", error=error, success=success,
dataset_metadata=page1, page2=page2, nsf_grants=get_nsf_grants(['award', 'name', 'title'], only_inhabited=False),
projects=get_projects(), persons=get_persons(), locations=get_usap_locations(), edit=edit)
elif request.form.get('action') == "save":
# save to file
if user_info.get('orcid'):
save_file = os.path.join(app.config['SAVE_FOLDER'], user_info['orcid'] + ".json")
elif user_info.get('sub'):
save_file = os.path.join(app.config['SAVE_FOLDER'], user_info['sub'] + ".json")
else:
error = "Unable to save dataset."
if save_file:
try:
save_metadata = {'page1': page1, 'page2': page2}
with open(save_file, 'w') as file:
file.write(json.dumps(save_metadata, indent=4, sort_keys=True))
success = "Saved dataset form"
except Exception as e:
error = "Unable to save dataset."
return render_template('dataset.html', name=user_info['name'], email="", error=error, success=success,
dataset_metadata=page1, page2=page2, nsf_grants=get_nsf_grants(['award', 'name', 'title'], only_inhabited=False),
projects=get_projects(), persons=get_persons(), locations=get_usap_locations(), edit=edit)
elif request.form.get('action') == "restore":
# restore from file
if user_info.get('orcid'):
saved_file = os.path.join(app.config['SAVE_FOLDER'], user_info['orcid'] + ".json")
elif user_info.get('sub'):
saved_file = os.path.join(app.config['SAVE_FOLDER'], user_info['sub'] + ".json")
else:
error = "Unable to restore dataset"
if saved_file:
try:
with open(saved_file, 'r') as file:
data = json.load(file)
page1 = data.get('page1',{})
page2 = data.get('page2',{})
if page1.get('dataset_id'):
del page1['dataset_id']
success = "Restored dataset form"
except Exception as e:
error = "Unable to restore dataset."
else:
error = "Unable to restore dataset."
return render_template('dataset.html', name=user_info['name'], email="", error=error, success=success,
dataset_metadata=page1, page2=page2, nsf_grants=get_nsf_grants(['award', 'name', 'title'],
only_inhabited=False), projects=get_projects(), persons=get_persons(), locations=get_usap_locations(), edit=edit)
if edit:
return redirect('/edit/dataset2/' + dataset_id, code=307)
return redirect(url_for('dataset2'), code=307)
else:
page1 = {}
page2 = {}
# EDIT dataset
# get the dataset ID from the URL
if edit:
page1, page2 = dataset_db2form(dataset_id)
email = page1.get('email')
name = ""
# Create new dataset using existing dataset as template
elif template:
page1, page2 = dataset_db2form(template_id)
email = ""
if user_info.get('email'):
email = user_info.get('email')
name = ""
if user_info.get('name'):
name = user_info.get('name')
# remove dataset_id when creating new submission
if page1.get('dataset_id'):
del(page1['dataset_id'])
if page2.get('dataset_id'):
del(page2['dataset_id'])
else:
page2['license'] = 'CC_BY_4.0' #default value
email = ""
if user_info.get('email'):
email = user_info.get('email')
name = ""
if user_info.get('name'):
name = user_info.get('name')
names = name.split(' ')
page1['authors'] = [{'first_name': names[0], 'last_name': names[-1]}]
page2['release_date'] = datetime.now().strftime('%Y-%m-%d')
return render_template('dataset.html', name=name, email=email, error=error, success=success,
dataset_metadata=page1, page2=page2,
nsf_grants=get_nsf_grants(['award', 'name', 'title'], only_inhabited=False), projects=get_projects(),
persons=get_persons(), locations=get_usap_locations(), edit=edit, template=template)
def groupPage1Fields(page1):
# collect publications, awards, authors, etc, and save as lists
publications_keys = [s for s in list(page1.keys()) if "publication" in s and s != "publications"]
if len(publications_keys) > 0:
page1['publications'] = []
publications_keys.sort(key=partial(sortNumerically, replace_str='publication'))
for key in publications_keys:
if page1[key] != "":
pub_text = page1.get(key)
pub_doi = page1.get(key.replace('publication', 'pub_doi'))
publication = {'text': pub_text, 'doi': pub_doi}
page1['publications'].append(publication)
del page1[key]
del page1[key.replace('publication', 'pub_doi')]
awards_keys = [s for s in list(page1.keys()) if "award" in s and "user" not in s and s != "awards"]
awards = []
if len(awards_keys) > 0:
awards_keys.sort(key=partial(sortNumerically, replace_str='award'))
for key in awards_keys:
if page1[key] != "" and page1[key] != "None":
if page1[key] == 'Not In This List':
user_award_fld = 'user_' + key
award_name = "Not_In_This_List:" + page1.get(user_award_fld)
del page1[user_award_fld]
else:
award_name = page1.get(key)
awards.append(award_name)
del page1[key]
page1['awards'] = awards
locations_keys = [s for s in list(page1.keys()) if "location" in s and "user" not in s and s != "locations"]
locations = []
if len(locations_keys) > 0:
locations_keys.sort(key=partial(sortNumerically, replace_str='location'))
for key in locations_keys:
if page1[key] != "" and page1[key] != "None":
if page1[key] == 'Not In This List':
user_loc_fld = 'user_' + key
location_name = "Not_In_This_List:" + page1.get(user_loc_fld)
del page1[user_loc_fld]
else:
location_name = page1.get(key)
locations.append(location_name)
del page1[key]
page1['locations'] = locations
author_keys = [s for s in list(page1.keys()) if "author_name_last" in s and s != "authors"]
if len(author_keys) > 0:
page1['authors'] = []
author_keys.sort(key=partial(sortNumerically, replace_str='author_name_last'))
for key in author_keys:
if page1[key] != "":
last_name = page1.get(key)
first_name = page1.get(key.replace('last', 'first'))
author = {'first_name': first_name, 'last_name': last_name}
page1['authors'].append(author)
del page1[key]
del page1[key.replace('last', 'first')]
return page1
# get dataset data from DB and convert to json that can be displayed in the Deposit/Edit Dataset page
def dataset_db2form(uid):
db_data = get_datasets([uid])[0]
if not db_data:
return {}
page1 = {
'dataset_id': uid,
'abstract': db_data.get('abstract'),
'name': db_data.get('submitter_id'),
'title': db_data.get('title'),
'submitter_name': db_data.get('submitter_id'),
'locations': db_data.get('locations')
}
page2 = {
'dataset_id': uid,
'filenames': [],
'release_date': db_data.get('release_date')
}
page1['authors'] = []
main_author = None
if db_data.get('creator'):
for author in db_data.get('creator').split('; '):
try:
last_name, first_name = author.split(', ', 1)
except:
last_name, first_name = author.split(',', 1)
if len(first_name) == 0:
first_name = ' '
if not main_author:
main_author = author
page1['authors'].append({'first_name': first_name, 'last_name': last_name})
page1['awards'] = []
for award in db_data.get('awards'):
page1['awards'].append(award.get('award') + ' ' + award.get('name'))
if db_data.get('spatial_extents'):
se = db_data.get('spatial_extents')[0]
page1['cross_dateline'] = se.get('cross_dateline')
page1['geo_e'] = str(se.get('east'))
page1['geo_n'] = str(se.get('north'))
page1['geo_s'] = str(se.get('south'))
page1['geo_w'] = str(se.get('west'))
if main_author:
creator = get_person(main_author)
if creator:
page1['email'] = creator.get('email')
page1['publications'] = []
for ref in db_data.get('references'):
page1['publications'].append({'doi': ref.get('doi'), 'text': ref.get('ref_text')})
page1['project'] = None
if db_data.get('projects') and len(db_data['projects']) > 0:
page1['project'] = db_data['projects'][0].get('id')
if db_data.get('temporal_extents') and len(db_data['temporal_extents']) > 0:
page1['start'] = db_data['temporal_extents'][0].get('start_date')
page1['stop'] = db_data['temporal_extents'][0].get('stop_date')
keywords = cf.getDatasetKeywords(uid)
page1['user_keywords'] = ''
for kw in keywords:
if kw.get('keyword_id')[0:2] == 'uk' and kw.get('keyword_label') not in page1['locations']:
if page1['user_keywords'] != '':
page1['user_keywords'] += ', '
page1['user_keywords'] += kw.get('keyword_label')
# read in more fields from the readme file and add to the page2 form_data
page2.update(dataset_readme2form(uid))
# read in remaining fields from previous submisison form and add to the page1 form_data
page1.update(dataset_oldform2form(uid))
# get uploaded files
url = db_data.get('url')
page2['uploaded_files'] = []
if url:
usap_domain = app.config['USAP_DOMAIN']
if url.startswith(usap_domain):
directory = os.path.join(current_app.root_path, url[len(usap_domain):])
file_paths = [os.path.join(dp, f) for dp, dn, fn in os.walk(directory) for f in fn]
omit = set(['readme.txt', '00README.txt', 'index.php', 'index.html', 'data.html'])
file_paths = [f for f in file_paths if os.path.basename(f) not in omit]
files = []
for f_path in file_paths:
f_size = os.stat(f_path).st_size
f_name = os.path.basename(f_path)
f_subpath = f_path[len(directory):]
files.append({'url': os.path.join(url, f_subpath), 'name': f_name, 'size': humanize.naturalsize(f_size)})
page2['filenames'].append(f_name)
page2['uploaded_files'] = files
else:
page2['uploaded_files'] = [{'url': url, 'name': os.path.basename(os.path.normpath(url))}]
page2['license'] = db_data['license']
return page1, page2
def dataset_readme2form(uid):
r = requests.get(url_for('readme', dataset_id=uid, _external=True))
form_data = {}
# check readme file is found and is plain text (not a pdf)
if r.url != url_for('not_found', _external=True) and r.headers.get('Content-Type') and r.headers['Content-Type'].find('text/plain') == 0:
text = r.text
if 'Content and processing steps' in text:
# old readme file format
start = text.find('Instruments and devices:') + len('Instruments and devices:')
end = text.find('Acquisition procedures:')
form_data['devices'] = text[start:end].replace('\n', '')
start = text.find('Acquisition procedures:') + len('Acquisition procedures:')
end = text.find('Content and processing steps:')
form_data['procedures'] = text[start:end].replace('\n', '')
start = text.find('Content and processing steps:') + len('Content and processing steps:')
end = text.find('Limitations and issues:')
c_p = text[start:end].replace('\r', '').split('\n\n')
form_data['content'] = c_p[0].replace('\n', '')
if len(c_p) > 1:
form_data['data_processing'] = c_p[1].replace('\n', '')
else:
form_data['data_processing'] = ''
start = text.find('Limitations and issues:') + len('Limitations and issues:')
end = text.find('Checkboxes:')
form_data['issues'] = text[start:end].replace('\n', '')
else:
# new readme file format
start = text.find('Instruments and devices:') + len('Instruments and devices:')
end = text.find('Acquisition procedures:')
form_data['devices'] = text[start:end].replace('\n', '').strip()
start = text.find('Acquisition procedures:') + len('Acquisition procedures:')
end = text.find('Description of data processing:')
form_data['procedures'] = text[start:end].replace('\n', '').strip()
start = text.find('Description of data processing:') + len('Description of data processing:')
end = text.find('Description of data content:')
form_data['data_processing'] = text[start:end].replace('\n', '').strip()
start = text.find('Description of data content:') + len('Description of data content:')
end = text.find('Limitations and issues:')
form_data['content'] = text[start:end].replace('\n', '').strip()
start = text.find('Limitations and issues:') + len('Limitations and issues:')
end = text.find('Checkboxes:')
form_data['issues'] = text[start:end].replace('\n', '').strip()
return form_data
def dataset_oldform2form(uid):
#get Related Field Event IDs and Region Feature Name from previous submission
submitted_dir = os.path.normpath(os.path.join(current_app.root_path, app.config['SUBMITTED_FOLDER']))
try:
if not submitted_dir.startswith(current_app.root_path):
raise Exception()
# if there is an editted file, use that one, other wise use original
if os.path.isfile(os.path.join(submitted_dir, "e" + uid + ".json")):
submitted_file = os.path.normpath(os.path.join(submitted_dir, "e" + uid + ".json"))
else:
submitted_file = os.path.normpath(os.path.join(submitted_dir, uid + ".json"))
if not submitted_file.startswith(current_app.root_path):
raise Exception()
with open(submitted_file) as infile:
submitted_data = json.load(infile)
except:
submitted_data = {}
form_data = {'related_fields': submitted_data.get('related_fields')}
return form_data
@app.route('/submit/help', methods=['GET', 'POST'])
def submit_help():