-
Notifications
You must be signed in to change notification settings - Fork 12
/
ServiceSupport.pyt
1247 lines (1053 loc) · 50 KB
/
ServiceSupport.pyt
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 arcpy
from arcgis.gis import GIS
from arcgis.features import FeatureLayer
import json
from os import path
import copy
configuration_file = path.join(path.dirname(__file__), 'servicefunctions.json')
class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the
.pyt file)."""
self.label = "Crowdsource Support Tools"
self.alias = ""
# List of tool classes associated with this toolbox
self.tools = [General, Moderate, Identifiers, Emails, Enrich]
class General(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Define Connection Settings"
self.description = ""
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
portal_url = arcpy.Parameter(
displayName='ArcGIS Online organization or ArcGIS Enterprise portal URL',
name='portal_url',
datatype='GPString',
parameterType='Required',
direction='Input')
portal_url.filter.type = 'ValueList'
portal_url.filter.list = arcpy.ListPortalURLs()
portal_user = arcpy.Parameter(
displayName='Username',
name='portal_user',
datatype='GPString',
parameterType='Required',
direction='Input')
portal_pass = arcpy.Parameter(
displayName='Password',
name='portal_pass',
datatype='GPStringHidden',
parameterType='Required',
direction='Input')
try:
with open(configuration_file, 'r') as config_params:
config = json.load(config_params)
portal_url.value = config["organization url"]
portal_user.value = config['username']
portal_pass.value = config['password']
except FileNotFoundError:
newconfig = {'username':'',
'organization url':'',
'moderation settings':{'lists':[],
'substitutions':{}},
'email settings':{'smtp username':'',
'smtp server':'',
'smtp password':'',
'reply to':'',
'from address':'',
'use tls': False,
'substitutions': []},
'services':[],
'password':'',
'id sequences':[]}
with open(configuration_file, 'w') as config_params:
json.dump(newconfig, config_params)
if not portal_url.value:
portal_url.value = arcpy.GetActivePortalURL()
if portal_url.value and not portal_user.value:
try:
portal_user.value = arcpy.GetPortalDescription(portal_url.valueAsText)['user']['username']
except KeyError:
pass
params = [portal_url, portal_user, portal_pass]
return params
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
portal_url, portal_user, portal_pass = parameters
if portal_url.value and portal_user.value and portal_pass.value:
try:
GIS(portal_url.value, portal_user.value, portal_pass.value)
except:
msg = 'Invalid username or password for this portal or organization'
portal_url.setErrorMessage(msg)
return
def execute(self, parameters, messages):
"""Update the configuration JSON to match the updated properties"""
portal_url, portal_user, portal_pass = parameters
# Update credentials
with open(configuration_file, 'r') as config_params:
config = json.load(config_params)
newconfig = copy.deepcopy(config)
newconfig['username'] = portal_user.value
newconfig['organization url'] = portal_url.value
newconfig['password'] = portal_pass.value
try:
with open(configuration_file, 'w') as config_params:
json.dump(newconfig, config_params)
except:
with open(configuration_file, 'w') as config_params:
json.dump(config, config_params)
arcpy.AddError('Failed to update configuration file.')
return
class Identifiers(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Generate IDs"
self.description = ""
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
layer = arcpy.Parameter(
displayName='Layer',
name='layer',
datatype=['GPFeatureLayer'],
parameterType='Required',
direction='Input')
delete = arcpy.Parameter(
displayName='Delete existing configuration for this layer',
name='delete',
datatype='Boolean',
parameterType='Optional',
direction='Input')
delete.enabled = False
seq = arcpy.Parameter(
displayName='ID Sequence',
name='seq',
datatype='GPString',
parameterType='Required',
direction='Input')
seq.filter.type = 'Value List'
field = arcpy.Parameter(
displayName='ID Field',
name='field',
datatype='Field',
parameterType='Required',
direction='Input')
field.parameterDependencies = [layer.name]
sequences = arcpy.Parameter(
displayName='Identifier Sequences',
name='sequences',
datatype='GPValueTable',
parameterType='Required',
direction='Input',
multiValue=True)
sequences.columns = [['GPString', 'Sequence Name'],
['GPString', 'Pattern'],
['GPLong', 'Next Value'],
['GPLong', 'Interval']]
sequences.category = "General Identifier Settings"
try:
with open(configuration_file, 'r') as config_params:
config = json.load(config_params)
sequences.values = [[s['name'],
s['pattern'],
s['next value'],
s['interval']] for s in config['id sequences']]
seq.filter.list = [s['name'] for s in config['id sequences']]
except FileNotFoundError:
newconfig = {'username':'',
'organization url':'',
'moderation settings':{'lists':[],
'substitutions':{}},
'email settings':{'smtp username':'',
'smtp server':'',
'smtp password':'',
'reply to':'',
'from address':'',
'use tls': False,
'substitutions': []},
'services':[],
'password':'',
'id sequences':[]}
with open(configuration_file, 'w') as config_params:
json.dump(newconfig, config_params)
params = [layer, delete, seq, field, sequences]
return params
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
layer, delete, seq, field, sequences = parameters
if delete.value or not sequences.values:
seq.enabled = False
field.enabled = False
else:
seq.enabled = True
field.enabled = True
with open(configuration_file, 'r') as config_params:
config = json.load(config_params)
try:
val = layer.value
lyr = val.connectionProperties['connection_info']['url'] + '/' + val.connectionProperties['dataset']
except AttributeError:
lyr = layer.valueAsText
if layer.value and not layer.hasBeenValidated:
for service in config['services']:
if lyr == service['url']:
seq.value = service['id sequence']
field.value = service["id field"]
if seq.value:
delete.enabled = True
break
else:
delete.value = False
delete.enabled = False
seq.value = ""
field.value = ""
if sequences.value and not sequences.hasBeenValidated:
seq.filter.list = [s[0] for s in sequences.values]
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
layer, delete, seq, field, sequences = parameters
if not sequences.values:
layer.setWarningMessage('Define identifier sequences under General Identifier Settings before proceeding.')
if layer.value and not layer.hasBeenValidated:
try:
val = layer.value
lyr = val.connectionProperties['connection_info']['url'] + '/' + val.connectionProperties['dataset']
except AttributeError:
lyr = layer.valueAsText
if 'http' not in lyr:
layer.setErrorMessage('Layer must be hosted in an ArcGIS Online organization or ArcGIS Enterprise portal')
return
def execute(self, parameters, messages):
"""Update the configuration JSON to match the updated properties"""
layer, delete, seq, field, sequences = parameters
with open(configuration_file, 'r') as config_params:
config = json.load(config_params)
try:
val = layer.value
lyr = val.connectionProperties['connection_info']['url'] + '/' + val.connectionProperties['dataset']
except AttributeError:
lyr = layer.valueAsText
newconfig = copy.deepcopy(config)
newconfig['id sequences'] = [{"pattern": seq[1],
"interval": seq[3],
"next value": seq[2],
"name": seq[0]} for seq in sequences.value]
for service in newconfig["services"]:
if service["url"] == lyr:
if delete.value:
service["id sequence"] = ''
service["id field"] = ''
if service == {"id sequence": '',
"email": [],
"url": lyr,
"id field": '',
"moderation": [],
"enrichment": []}:
newconfig['services'].remove(service)
else:
service["id sequence"] = seq.valueAsText
service["id field"] = field.valueAsText
break
else:
newconfig["services"].append({"id sequence": seq.valueAsText,
"email": [],
"url": lyr,
"id field": field.valueAsText,
"moderation": [],
"enrichment": []})
arcpy.AddMessage(config['services'])
try:
with open(configuration_file, 'w') as config_params1:
json.dump(newconfig, config_params1)
except:
with open(configuration_file, 'w') as config_params2:
json.dump(config, config_params2)
arcpy.AddError('Failed to update configuration file.')
return
class Moderate(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Moderate Reports"
self.description = ""
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
layer = arcpy.Parameter(
displayName='Layer',
name='layer',
datatype=['DETable', 'GPFeatureLayer', "GPTableView"],
parameterType='Required',
direction='Input')
add_update = arcpy.Parameter(
displayName='Add new or update existing configuration',
name='add_update',
datatype='GPString',
parameterType='Required',
direction='Input')
add_update.filter.type = 'ValueList'
add_update.filter.list = ['Add New']
add_update.value = 'Add New'
add_update.enabled = False
delete = arcpy.Parameter(
displayName='Delete existing configuration for this layer',
name='delete',
datatype='Boolean',
parameterType='Optional',
direction='Input')
delete.enabled = False
modlist = arcpy.Parameter(
displayName='Moderation List',
name='modlist',
datatype='GPString',
parameterType='Required',
direction='Input')
modlist.filter.type = 'ValueList'
modlist.filter.list = ['configure','moderation','lists']
mod_fields = arcpy.Parameter(
displayName='Fields to Monitor',
name='mod_fields',
datatype='Field',
parameterType='Required',
direction='Input',
multiValue=True)
mod_fields.parameterDependencies = [layer.name]
sql = arcpy.Parameter(
displayName='SQL Query',
name='sql',
datatype='GPString',
parameterType='Optional',
direction='Input')
update_field = arcpy.Parameter(
displayName='Field to Update',
name='update_field',
datatype='Field',
parameterType='Required',
direction='Input')
update_field.parameterDependencies = [layer.name]
found_value = arcpy.Parameter(
displayName='Found Value',
name='found_value',
datatype='Field',
parameterType='Required',
direction='Input')
modlists = arcpy.Parameter(
displayName='Moderation Lists',
name='modlists',
datatype='GPValueTable',
parameterType='Required',
direction='Input')
modlists.columns = [['GPString', 'List Name'],
['GPString', 'Filter Type'],
['GPString', 'Words and Phrases']]
modlists.filters[1].type = 'ValueList'
modlists.filters[1].list = ['FUZZY', 'EXACT']
modlists.category = 'General Moderation Settings'
charsubs = arcpy.Parameter(
displayName='Character Substitutions',
name='charsubs',
datatype='GPValueTable',
parameterType='Optional',
direction='Input')
charsubs.columns = [['GPString', 'Letter'],
['GPString', 'Substitutions']]
charsubs.category = 'General Moderation Settings'
try:
with open(configuration_file, 'r') as config_params:
config = json.load(config_params)
words = config['moderation settings']['lists']
subs = config['moderation settings']['substitutions']
modlists.values = [[lst['filter name'],
lst['filter type'],
lst['words']] for lst in words]
charsubs.values = [[val, subs[val]] for val in subs]
moderation_lists = [lst['filter name'] for lst in words]
if moderation_lists:
modlist.filter.list = moderation_lists
except FileNotFoundError:
newconfig = {'username': '',
'organization url': '',
'moderation settings': {'lists': [],
'substitutions': {}},
'email settings': {'smtp username': '',
'smtp server': '',
'smtp password': '',
'reply to': '',
'from address': '',
'use tls': False,
'substitutions': []},
'services': [],
'password': '',
'id sequences': []}
with open(configuration_file, 'w') as config_params:
json.dump(newconfig, config_params)
params = [layer, add_update, delete, modlist, mod_fields, sql, update_field, found_value, modlists, charsubs]
return params
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
layer, add_update, delete, modlist, mod_fields, sql, update_field, found_value, modlists, charsubs = parameters
if modlists.value and not modlists.hasBeenValidated:
modlist.filter.list = [s[0] for s in modlists.values]
with open(configuration_file, 'r') as config_params:
config = json.load(config_params)
try:
val = layer.value
if str(type(val)) == "<class 'geoprocessing value object'>":
aprx = arcpy.mp.ArcGISProject("CURRENT")
currmap = aprx.activeMap
for table in currmap.listTables():
if table.name == layer.valueAsText:
val = table
break
lyr = val.connectionProperties['connection_info']['url'] + '/' + val.connectionProperties['dataset']
except (AttributeError, KeyError):
lyr = layer.valueAsText
if layer.value and not layer.hasBeenValidated:
if 'http' in lyr:
for service in config['services']:
if lyr == service['url']:
query_list = [query['list'] for query in service['moderation']]
if query_list:
add_update.enabled = True
query_list.insert(0, 'Add New')
add_update.filter.list = query_list
add_update.value = ''
else:
add_update.enabled = False
add_update.value = 'Add New'
break
if add_update.value and not add_update.hasBeenValidated:
if add_update.valueAsText == 'Add New':
delete.value = False
delete.enabled = False
mod_fields.values = []
sql.value = ''
update_field.value = ''
found_value.value = ''
modlist.value = ''
else:
delete.enabled = True
for service in config['services']:
if lyr == service['url']:
for query in service['moderation']:
if query['list'] == add_update.valueAsText:
modlist.value = query['list']
mod_fields.values = query['scan fields']
sql.value = query['sql']
update_field.value = query['field']
found_value.value = query['value']
break
break
else:
add_update.value = 'Add New'
add_update.enabled = False
delete.enabled = False
mod_fields.values = []
sql.value = ''
update_field.value = ''
found_value.value = ''
modlist.value = ''
if delete.value or not modlists.values:
modlist.enabled = False
mod_fields.enabled = False
sql.enabled = False
update_field.enabled= False
found_value.enabled = False
else:
modlist.enabled = True
mod_fields.enabled = True
sql.enabled = True
update_field.enabled= True
found_value.enabled = True
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
layer, add_update, delete, modlist, mod_fields, sql, update_field, found_value, modlists, charsubs = parameters
if not modlists.values:
layer.setWarningMessage('Define moderation list under General Moderation Settings before proceeding.')
if layer.value:
try:
val = layer.value
if str(type(val)) == "<class 'geoprocessing value object'>":
aprx = arcpy.mp.ArcGISProject("CURRENT")
currmap = aprx.activeMap
for table in currmap.listTables():
if table.name == layer.valueAsText:
val = table
break
lyr = val.connectionProperties['connection_info']['url'] + '/' + val.connectionProperties['dataset']
except (AttributeError, KeyError):
lyr = layer.valueAsText
if 'http' not in lyr:
layer.setErrorMessage('Layer must be hosted in an ArcGIS Online organization or ArcGIS Enterprise portal')
elif sql.value:# and not sql.hasBeenValidated and not layer.hasBeenValidated:
with open(configuration_file, 'r') as config_params:
config = json.load(config_params)
if config['organization url'] and config['username'] and config['password']:
gis = GIS(config['organization url'], config['username'], config['password'])
fl = FeatureLayer(lyr, gis)
validation = fl.validate_sql(sql.valueAsText)
if not validation['isValidSQL']:
messages = '\n'.join(['{}: {}'.format(msg['errorCode'], msg['description']) for msg in validation['validationErrors']])
sql.setErrorMessage(messages)
else:
sql.setWarningMessage('Cannot validate SQL. Portal/Organization URL and credentials are missing. Run the Define Connection Settings tool to validate this SQL statement.')
return
def execute(self, parameters, messages):
"""Update the configuration JSON to match the updated properties"""
lyr, add_update, delete, modlist, mod_fields, sql, update_field, found_value, modlists, charsubs = parameters
try:
val = lyr.value
layer = val.connectionProperties['connection_info']['url'] + '/' + val.connectionProperties['dataset']
except AttributeError:
layer = lyr.valueAsText
with open(configuration_file, 'r') as config_params:
config = json.load(config_params)
newconfig = copy.deepcopy(config)
subs = {}
if charsubs.values:
for sub in charsubs.values:
subs[sub[0]] = sub[1]
newconfig['moderation settings'] = {'lists': [{'filter type': mod[1], 'words': mod[2], 'filter name': mod[0]} for mod in modlists.values],
'substitutions': subs}
if sql.value:
query = sql.valueAsText
else:
query = '1=1'
newquery = {"list": modlist.valueAsText,
"sql": query,
"field": update_field.valueAsText,
"value": found_value.valueAsText,
'scan fields': mod_fields.valueAsText}
for service in newconfig["services"]:
if service["url"] == layer:
if add_update.value != 'Add New':
for query in service['moderation']:
if query['list'] == add_update.value:
service['moderation'].remove(query)
break
if not delete.value:
service['moderation'].append(newquery)
else:
if service == {"id sequence": '',
"email": [],
"url": layer,
"id field": '',
"moderation": [],
"enrichment": []}:
newconfig['services'].remove(service)
break
else:
newconfig["services"].append({"id sequence": "",
"email": [],
"url": layer,
"id field": "",
"moderation": [newquery],
"enrichment": []})
try:
with open(configuration_file, 'w') as config_params:
json.dump(newconfig, config_params)
except TypeError:
with open(configuration_file, 'w') as config_params:
json.dump(config, config_params)
arcpy.AddError('Failed to update configuration file.')
return
class Emails(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Send Emails"
self.description = ""
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
layer = arcpy.Parameter(
displayName='Layer',
name='layer',
datatype=['DETable', 'GPFeatureLayer', 'GPTableView'],
parameterType='Required',
direction='Input')
delete = arcpy.Parameter(
displayName='Delete all existing email configurations for this layer',
name='delete',
datatype='Boolean',
parameterType='Optional',
direction='Input')
delete.enabled = False
email_settings = arcpy.Parameter(
displayName='Email Settings',
name='email_settings',
datatype='GPValueTable',
parameterType='Required',
direction='Input')
email_settings.columns = [['DEFile', 'Email Template'],
['GPString', 'SQL Query'],
['GPString', 'Recipient Email Address'],
['GPString', 'Email Subject'],
['Field', 'Field to Update'],
['GPString', 'Sent Value']]
email_settings.parameterDependencies = [layer.name]
email_settings.filters[0].list = ['html']
substitutions = arcpy.Parameter(
displayName='Email Substitutions',
name='substitutions',
datatype='GPValueTable',
parameterType='Optional',
direction='Input')
substitutions.columns = [['GPString', 'Find'],
['GPString', 'Replace']]
substitutions.category = 'General Email Settings'
smtp_username = arcpy.Parameter(
displayName="SMTP Username",
name='smtp_username',
datatype='GPString',
parameterType='Optional',
direction='Input')
smtp_username.category = 'General Email Settings'
reply_address = arcpy.Parameter(
displayName="Reply Address",
name='reply_address',
datatype='GPString',
parameterType='Optional',
direction='Input')
reply_address.category = 'General Email Settings'
smtp_server = arcpy.Parameter(
displayName="SMTP Server",
name='smtp_server',
datatype='GPString',
parameterType='Required',
direction='Input')
smtp_server.category = 'General Email Settings'
smtp_password = arcpy.Parameter(
displayName="SMTP Password",
name='smtp_password',
datatype='GPString',
parameterType='Optional',
direction='Input')
smtp_password.category = 'General Email Settings'
from_address = arcpy.Parameter(
displayName="From Address",
name='from_address',
datatype='GPString',
parameterType='Optional',
direction='Input')
from_address.category = 'General Email Settings'
use_tls = arcpy.Parameter(
displayName="Use TLS",
name='use_tls',
datatype='GPBoolean',
parameterType='Optional',
direction='Input')
use_tls.category = 'General Email Settings'
try:
with open(configuration_file, 'r') as config_params:
config = json.load(config_params)
smtp_server.value = config['email settings']['smtp server']
smtp_username.value = config['email settings']['smtp username']
smtp_password.value = config['email settings']['smtp password']
from_address.value = config['email settings']['from address']
reply_address.value = config['email settings']['reply to']
use_tls.value = config['email settings']['use tls']
substitutions.values = config['email settings']['substitutions']
except FileNotFoundError:
newconfig = {'username':'',
'organization url':'',
'moderation settings':{'lists':[],
'substitutions':{}},
'email settings':{'smtp username':'',
'smtp server':'',
'smtp password':'',
'reply to':'',
'from address':'',
'use tls': False,
'substitutions': []},
'services':[],
'password':'',
'id sequences':[]}
with open(configuration_file, 'w') as config_params:
json.dump(newconfig, config_params)
params = [layer, delete, email_settings, smtp_server, smtp_username, smtp_password, from_address, reply_address, use_tls, substitutions]
return params
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
layer, delete, email_settings, smtp_server, smtp_username, smtp_password, from_address, reply_address, use_tls, substitutions = parameters
if layer.value and not layer.hasBeenValidated:
try:
val = layer.value
if str(type(val)) == "<class 'geoprocessing value object'>":
aprx = arcpy.mp.ArcGISProject("CURRENT")
currmap = aprx.activeMap
for table in currmap.listTables():
if table.name == layer.valueAsText:
val = table
break
lyr = val.connectionProperties['connection_info']['url'] + '/' + val.connectionProperties['dataset']
except (AttributeError, KeyError):
lyr = layer.valueAsText
with open(configuration_file, 'r') as config_params:
config = json.load(config_params)
for service in config['services']:
if service['url'] == lyr and service['email']:
delete.enabled = True
email_settings.value = [[info['template'],
info['sql'],
info['recipient'],
info['subject'],
info['field'],
info['sent value']] for info in service['email']]
break
else:
delete.enabled = False
email_settings.value = ""
if delete.value:
email_settings.enabled = False
else:
email_settings.enabled = True
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
layer, delete, email_settings, smtp_server, smtp_username, smtp_password, from_address, reply_address, use_tls, substitutions = parameters
if layer.value and not layer.hasBeenValidated:
try:
val = layer.value
if str(type(val)) == "<class 'geoprocessing value object'>":
aprx = arcpy.mp.ArcGISProject("CURRENT")
currmap = aprx.activeMap
for table in currmap.listTables():
if table.name == layer.valueAsText:
val = table
break
lyr = val.connectionProperties['connection_info']['url'] + '/' + val.connectionProperties['dataset']
except (AttributeError, KeyError):
lyr = layer.valueAsText
if 'http' not in lyr:
layer.setErrorMessage('Layer must be hosted in an ArcGIS Online organization or ArcGIS Enterprise portal')
return
def execute(self, parameters, messages):
"""Update the configuration JSON to match the updated properties"""
layer, delete, email_settings, smtp_server, smtp_username, smtp_password, from_address, reply_address, use_tls, substitutions = parameters
try:
val = layer.value
lyr = val.connectionProperties['connection_info']['url'] + '/' + val.connectionProperties['dataset']
except AttributeError:
lyr = layer.valueAsText
with open(configuration_file, 'r') as config_params:
config = json.load(config_params)
newconfig = copy.deepcopy(config)
newconfig['email settings'] = {'smtp username': smtp_username.valueAsText,
'smtp server': smtp_server.valueAsText,
'smtp password': smtp_password.valueAsText,
'reply to': reply_address.valueAsText,
'from address': from_address.valueAsText,
'use tls': use_tls.value,
'substitutions': substitutions.value}
emails = [{"field": query[4].value,
"sent value": query[5],
"sql": query[1],
"recipient": query[2],
"template": query[0].value,
"subject": query[3]} for query in email_settings.values]
for service in newconfig["services"]:
if service["url"] == lyr:
if delete.value:
service["email"] = []
if service == {"id sequence": '',
"email": [],
"url": lyr,
"id field": '',
"moderation": [],
"enrichment": []}:
newconfig['services'].remove(service)
else:
service["email"] = emails
break
else:
newconfig["services"].append({"id sequence": "",
"email": emails,
"url": lyr,
"id field": "",
"moderation": [],
"enrichment": []})
try:
with open(configuration_file, 'w') as config_params:
json.dump(newconfig, config_params)
except:
with open(configuration_file, 'w') as config_params:
json.dump(config, config_params)
arcpy.AddError('Failed to update configuration file.')
return
class Enrich(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Enrich Reports"
self.description = ""
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
layer = arcpy.Parameter(
displayName='Layer',
name='layer',
datatype='GPFeatureLayer',
parameterType='Required',
direction='Input')
polyconfigs = arcpy.Parameter(
displayName='Enrichment configurations',
name='polyconfigs',
datatype='GPString',
parameterType='Required',
direction='Input')
polyconfigs.filter.type = 'ValueList'
polyconfigs.filter.values = ['Add New']
polyconfigs.enabled = 'False'
polylayer = arcpy.Parameter(
displayName='Enrichment Layer',
name='polylayer',
datatype='GPFeatureLayer',
parameterType='Required',
direction='Input')
sql = arcpy.Parameter(
displayName='SQL Query',
name='sql',
datatype='GPString',