This repository has been archived by the owner on Apr 7, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathclone_items.py
3235 lines (2804 loc) · 160 KB
/
clone_items.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
"""
-------------------------------------------------------------------------------
| Copyright 2017 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
------------------------------------------------------------------------------
"""
import json, uuid, re, tempfile, os, copy, zipfile, shutil
from functools import reduce
from urllib.parse import urlparse
from arcgis import gis
from arcgis.features import FeatureLayerCollection
from arcgis.features import FeatureLayer
COPY_DATA = False
USE_DEFAULT_BASEMAP = False
ADD_GPS_METADATA_FIELDS = False
SEARCH_ORG_FOR_EXISTING_ITEMS = True
ITEM_EXTENT = None
SPATIAL_REFERENCE = None
ADD_TAGS = []
REMOVE_TAGS = []
#region Group and Item Definition Classes
class _GroupDefinition(object):
"""
Represents the definition of a group within ArcGIS Online or Portal.
"""
def __init__(self, info, thumbnail=None, portal_group=None):
self.info = info
self.thumbnail = thumbnail
self.portal_group = portal_group
def clone(self, target):
"""Clone the group in the target organization.
Keyword arguments:
target - The instance of arcgis.gis.GIS (the portal) to group to."""
try:
new_group = None
original_group = self.info
title = original_group['title']
tags = original_group['tags']
for tag in list(tags):
if tag.startswith("source-") or tag.startswith("sourcefolder-"):
tags.remove(tag)
original_group['tags'].append("source-{0}".format(original_group['id']))
tags = ','.join(original_group['tags'])
#Find a unique name for the group
i = 1
while True:
search_query = 'title:"{0}" AND owner:{1}'.format(title, target.users.me.username)
groups = [group for group in target.groups.search(search_query, outside_org=False) if group['title'] == title]
if len(groups) == 0:
break
i += 1
title = "{0} {1}".format(original_group['title'], i)
thumbnail = self.thumbnail
if not thumbnail and self.portal_group:
temp_dir = os.path.join(_TEMP_DIR.name, original_group['id'])
if not os.path.exists(temp_dir):
os.makedirs(temp_dir)
thumbnail = self.portal_group.download_thumbnail(temp_dir)
new_group = target.groups.create(title, tags, original_group['description'], original_group['snippet'],
'private', thumbnail, True, original_group['sortField'], original_group['sortOrder'], True)
return new_group
except Exception as ex:
raise _ItemCreateException("Failed to create group '{0}': {1}".format(original_group['title'], str(ex)), new_group)
class _ItemDefinition(object):
"""
Represents the definition of an item within ArcGIS Online or Portal.
"""
def __init__(self, info, data=None, sharing=None, thumbnail=None, portal_item=None):
self.info = info
self._data = data
self.sharing = sharing
if not self.sharing:
self.sharing = {"access": "private", "groups": []}
self.thumbnail = thumbnail
self._item_property_names = ['title', 'type', 'description',
'snippet', 'tags', 'culture',
'accessInformation', 'licenseInfo', 'typeKeywords', 'extent']
self.portal_item = portal_item
@property
def data(self):
"""Gets the data of the item"""
return copy.deepcopy(self._data)
def _get_item_properties(self):
"""Get a dictionary of item properties used in create and update operations."""
item_properties = {}
for property_name in self._item_property_names:
item_properties[property_name] = self.info[property_name]
type_keywords = item_properties['typeKeywords']
for keyword in list(type_keywords):
if keyword.startswith('source-'):
type_keywords.remove(keyword)
tags = item_properties['tags']
tags.extend(ADD_TAGS)
expressions = [re.compile(x) for x in REMOVE_TAGS]
item_properties['tags'] = [t for t in tags if all(not ex.match(t) for ex in expressions)]
if _TARGET_MUST_EXIST_TAG in item_properties['tags']:
item_properties['tags'].remove(_TARGET_MUST_EXIST_TAG)
if _MAINTAIN_SPATIAL_REF in item_properties['tags']:
item_properties['tags'].remove(_MAINTAIN_SPATIAL_REF)
if _COPY_ONLY_TAG in item_properties['tags']:
item_properties['tags'].remove(_COPY_ONLY_TAG)
type_keywords.append('source-{0}'.format(self.info['id']))
item_properties['typeKeywords'] = ','.join(item_properties['typeKeywords'])
item_properties['tags'] = ','.join(item_properties['tags'])
extent = _deep_get(item_properties, 'extent')
if ITEM_EXTENT is not None and extent is not None and len(extent) > 0:
item_properties['extent'] = ITEM_EXTENT
return item_properties
def clone(self, target, folder, item_mapping):
"""Clone the item in the target organization.
Keyword arguments:
target - The instance of arcgis.gis.GIS (the portal) to clone the item to.
folder - The folder to create the item in
item_mapping - Dictionary containing mapping between new and old items.
"""
try:
new_item = None
original_item = self.info
# Get the item properties from the original item to be applied when the new item is created
item_properties = self._get_item_properties()
temp_dir = os.path.join(_TEMP_DIR.name, original_item['id'])
if not os.path.exists(temp_dir):
os.makedirs(temp_dir)
data = self.data
if not data and self.portal_item:
data = self.portal_item.download(temp_dir)
# The item's name will default to the name of the data, if it already exists in the folder we need to rename it to something unique
name = os.path.basename(data)
item = next((item for item in target.users.me.items(folder=_deep_get(folder, 'title')) if item['name'] == name), None)
if item:
new_name = "{0}_{1}{2}".format(os.path.splitext(name)[0], str(uuid.uuid4()).replace('-', ''), os.path.splitext(name)[1])
new_path = os.path.join(temp_dir, new_name)
os.rename(data, new_path)
data = new_path
thumbnail = self.thumbnail
if not thumbnail and self.portal_item:
thumbnail = self.portal_item.download_thumbnail(temp_dir)
# Add the new item
new_item = target.content.add(item_properties=item_properties, data=data, thumbnail=thumbnail, folder=_deep_get(folder, 'title'))
return [new_item]
except Exception as ex:
raise _ItemCreateException("Failed to create {0} {1}: {2}".format(original_item['type'], original_item['title'], str(ex)), new_item)
class _TextItemDefinition(_ItemDefinition):
"""
Represents the definition of a text based item within ArcGIS Online or Portal.
"""
def clone(self, target, folder, item_mapping):
"""Clone the item in the target organization.
Keyword arguments:
target - The instance of arcgis.gis.GIS (the portal) to clone the item to.
folder- The folder to create the item in
item_mapping - Dictionary containing mapping between new and old items.
"""
try:
new_item = None
original_item = self.info
# Get the item properties from the original item to be applied when the new item is created
item_properties = self._get_item_properties()
data = self.data
if data:
item_properties['text'] = json.dumps(data)
thumbnail = self.thumbnail
if not thumbnail and self.portal_item:
temp_dir = os.path.join(_TEMP_DIR.name, original_item['id'])
if not os.path.exists(temp_dir):
os.makedirs(temp_dir)
thumbnail = self.portal_item.download_thumbnail(temp_dir)
new_item = target.content.add(item_properties=item_properties, thumbnail=thumbnail, folder=_deep_get(folder, 'title'))
return [new_item]
except Exception as ex:
raise _ItemCreateException("Failed to create {0} {1}: {2}".format(original_item['type'], original_item['title'], str(ex)), new_item)
class _FeatureCollectionDefinition(_TextItemDefinition):
"""
Represents the definition of a feature collection within ArcGIS Online or Portal.
"""
def clone(self, target, folder, item_mapping):
"""Clone the item in the target organization.
Keyword arguments:
target - The instance of arcgis.gis.GIS (the portal) to clone the item to.
folder - The folder to create the item in
item_mapping - Dictionary containing mapping between new and old items.
"""
try:
new_item = None
original_item = self.info
# Get the item properties from the original item to be applied when the new item is created
item_properties = self._get_item_properties()
data = self.data
if data:
if not COPY_DATA:
if 'layers' in data and data['layers'] is not None:
for layer in data['layers']:
if 'featureSet' in layer and layer['featureSet'] is not None:
layer['featureSet']['features'] = []
item_properties['text'] = json.dumps(data)
thumbnail = self.thumbnail
if not thumbnail and self.portal_item:
temp_dir = os.path.join(_TEMP_DIR.name, original_item['id'])
if not os.path.exists(temp_dir):
os.makedirs(temp_dir)
thumbnail = self.portal_item.download_thumbnail(temp_dir)
new_item = target.content.add(item_properties=item_properties, thumbnail=thumbnail, folder=_deep_get(folder, 'title'))
return [new_item]
except Exception as ex:
raise _ItemCreateException("Failed to create {0} {1}: {2}".format(original_item['type'], original_item['title'], str(ex)), new_item)
class _FeatureServiceDefinition(_TextItemDefinition):
"""
Represents the definition of a hosted feature service within ArcGIS Online or Portal.
"""
def __init__(self, info, service_definition, layers_definition, is_view=False, view_sources={}, view_source_fields={}, features=None, data=None, sharing=None, thumbnail=None, portal_item=None):
self._service_definition = service_definition
self._layers_definition = layers_definition
self._features = features
self._is_view = is_view
self._view_sources = view_sources
self._view_source_fields = view_source_fields
super().__init__(info, data, sharing, thumbnail, portal_item)
@property
def service_definition(self):
"""Gets the definition of the service"""
return copy.deepcopy(self._service_definition)
@property
def layers_definition(self):
"""Gets the layer and table definitions of the service"""
return copy.deepcopy(self._layers_definition)
@property
def is_view(self):
"""Gets if the service is a view"""
return self._is_view
@property
def view_sources(self):
"""Gets the sources for the view"""
return self._view_sources
@property
def view_source_fields(self):
"""Gets the original fields for the source view"""
return self._view_source_fields
@property
def features(self):
"""Gets the features for the service"""
return copy.deepcopy(self._features)
def _get_features(self, feature_layer, spatial_reference=None):
"""Get the features for the given feature layer of a feature service. Returns a list of json features.
Keyword arguments:
feature_layer - The feature layer to return the features for
spatial_reference - The spatial reference to return the features in"""
if spatial_reference is None:
spatial_reference = { 'wkid' : 3857 }
total_features = []
record_count = feature_layer.query(return_count_only=True)
max_record_count = feature_layer.properties['maxRecordCount']
if max_record_count < 1:
max_record_count = 1000
offset = 0
return_z = 'hasZ' in feature_layer.properties and feature_layer.properties['hasZ']
return_m = 'hasM' in feature_layer.properties and feature_layer.properties['hasM']
while offset < record_count:
features = feature_layer.query(out_sr=spatial_reference, result_offset=offset, result_record_count=max_record_count, return_z=return_z, return_m=return_m).features
offset += len(features)
total_features += [f.as_dict for f in features]
return total_features
def _add_features(self, layers, relationships, layer_field_mapping, spatial_reference):
"""Add the features from the definition to the layers returned from the cloned item.
Keyword arguments:
layers - Dictionary containing the id of the layer and its corresponding arcgis.lyr.FeatureLayer
relationships - Dictionary containing the id of the layer and its relationship definitions
layer_field_mapping - field mapping if the case or name of field changed from the original service
spatial_reference - The spatial reference to create the features in"""
# Get the features if they haven't already been queried
features = self.features
original_layers = []
if not features and self.portal_item:
svc = FeatureLayerCollection.fromitem(self.portal_item)
features = {}
original_layers = svc.layers + svc.tables
for layer in original_layers:
features[str(layer.properties['id'])] = self._get_features(layer, spatial_reference)
else:
return
# Update the feature attributes if field names have changed
for layer_id in features:
if int(layer_id) in layer_field_mapping:
field_mapping = layer_field_mapping[int(layer_id)]
for feature in features[layer_id]:
_update_feature_attributes(feature, field_mapping)
# Add in chunks of 2000 features
chunk_size = 2000
layer_ids = [id for id in layers]
object_id_mapping = {}
# Find all the relates where the layer's role is the origin and the key field is the global id field
# We want to process these first, get the new global ids that are created and update in related features before processing the relates
for layer_id in relationships:
if layer_id not in layer_ids or layer_id not in layers:
continue
properties = layers[layer_id].properties
if 'globalIdField' not in properties:
continue
global_id_field = properties['globalIdField']
object_id_field = properties['objectIdField']
relates = [relate for relate in relationships[layer_id] if relate['role'] == 'esriRelRoleOrigin' and relate['keyField'] == global_id_field]
if len(relates) == 0:
continue
layer = layers[layer_id]
layer_features = features[str(layer_id)]
if len(layer_features) == 0:
layer_ids.remove(layer_id)
continue
# Add the features to the layer in chunks
add_results = []
for features_chunk in [layer_features[i:i+chunk_size] for i in range(0, len(layer_features), chunk_size)]:
edits = layer.edit_features(adds=features_chunk)
add_results += edits['addResults']
layer_ids.remove(layer_id)
# Create a mapping between the original global id and the new global id
object_id_mapping[layer_id] = {layer_features[i]['attributes'][object_id_field] : add_results[i]['objectId'] for i in range(0, len(layer_features))}
global_id_mapping = {layer_features[i]['attributes'][global_id_field] : add_results[i]['globalId'] for i in range(0, len(layer_features))}
for relate in relates:
related_layer_id = relate['relatedTableId']
if related_layer_id not in layer_ids:
continue
related_layer_features = features[str(related_layer_id)]
if len(related_layer_features) == 0:
layer_ids.remove(related_layer_id)
continue
# Get the definition of the definition relationship
destination_relate = next((r for r in relationships[related_layer_id] if r['id'] == relate['id'] and r['role'] == 'esriRelRoleDestination'), None)
if not destination_relate:
continue
key_field = destination_relate['keyField']
# Update the relate features keyfield to the new global id
for feature in related_layer_features:
if key_field in feature['attributes']:
global_id = feature['attributes'][key_field]
if global_id in global_id_mapping:
feature['attributes'][key_field] = global_id_mapping[global_id]
# Add the related features to the layer in chunks
add_results = []
for features_chunk in [related_layer_features[i:i+chunk_size] for i in range(0, len(layer_features), chunk_size)]:
edits = layers[related_layer_id].edit_features(adds=features_chunk)
add_results += edits['addResults']
layer_ids.remove(related_layer_id)
object_id_field = layers[related_layer_id].properties['objectIdField']
object_id_mapping[related_layer_id] = {related_layer_features[i]['attributes'][object_id_field] : add_results[i]['objectId'] for i in range(0, len(related_layer_features))}
# Add features to all other layers and tables
for layer_id in layer_ids:
layer_features = features[str(layer_id)]
if len(layer_features) == 0:
continue
add_results = []
for features_chunk in [layer_features[i:i+chunk_size] for i in range(0, len(layer_features), chunk_size)]:
edits = layers[layer_id].edit_features(adds=features_chunk)
add_results += edits['addResults']
object_id_field = layers[layer_id].properties['objectIdField']
object_id_mapping[layer_id] = {layer_features[i]['attributes'][object_id_field] : add_results[i]['objectId'] for i in range(0, len(layer_features))}
# Add attachments
for original_layer in original_layers:
properties = original_layer.properties
layer_id = properties['id']
if 'hasAttachments' in properties and properties['hasAttachments']:
if str(layer_id) in features and features[str(layer_id)] is not None:
original_attachments = original_layer.attachments
attachments = layers[layer_id].attachments
object_id_field = layers[layer_id].properties['objectIdField']
layer_features = features[str(layer_id)]
if layer_id not in object_id_mapping:
continue
for feature in layer_features:
original_oid = feature['attributes'][object_id_field]
if original_oid not in object_id_mapping[layer_id]:
continue
oid = object_id_mapping[layer_id][original_oid]
attachment_infos = original_attachments.get_list(original_oid)
if len(attachment_infos) > 0:
temp_dir = os.path.join(_TEMP_DIR.name, 'attachments')
if not os.path.exists(temp_dir):
os.makedirs(temp_dir)
for attachment_info in attachment_infos:
attachment_file = original_attachments.download(original_oid, attachment_info['id'], temp_dir)
attachments.add(oid, attachment_file)
def _get_unique_name(self, target, name, item_mapping, force_add_guid_suffix):
"""Create a new unique name for the service.
Keyword arguments:
target - The instance of arcgis.gis.GIS (the portal) to clone the feature service to.
name - The original name.
item_mapping - Dictionary containing mapping between new and old items.
force_add_guid_suffix - Indicates if a guid suffix should automatically be added to the end of the service name
"""
if name[0].isdigit():
name = '_' + name
name = name.replace(' ', '_')
if not force_add_guid_suffix:
guids = re.findall('[0-9A-F]{32}', name, re.IGNORECASE)
for guid in guids:
if guid in item_mapping['Group IDs']:
name = name.replace(guid, item_mapping['Group IDs'][guid])
elif guid in item_mapping['Item IDs']:
name = name.replace(guid, item_mapping['Item IDs'][guid])
else:
new_guid = str(uuid.uuid4()).replace('-', '')
name = name.replace(guid, new_guid)
while True:
if target.content.is_service_name_available(name, 'featureService'):
break
guid = str(uuid.uuid4()).replace('-', '')
ends_with_guid = re.findall('_[0-9A-F]{32}$', name, re.IGNORECASE)
if len(ends_with_guid) > 0:
name = name[:len(name) - 32] + guid
else:
name = "{0}_{1}".format(name, guid)
else:
guid = str(uuid.uuid4()).replace('-', '')
ends_with_guid = re.findall('_[0-9A-F]{32}$', name, re.IGNORECASE)
if len(ends_with_guid) > 0:
name = name[:len(name) - 32] + guid
else:
name = "{0}_{1}".format(name, guid)
return name
def clone(self, target, folder, item_mapping):
"""Clone the feature service in the target organization.
Keyword arguments:
target - The instance of arcgis.gis.GIS (the portal) to clone the feature service to.
folder - The name of the folder to create the item in
item_mapping - Dictionary containing mapping between new and old items.
"""
try:
new_item = None
original_item = self.info
# Get the definition of the original feature service
service_definition = self.service_definition
# Modify the definition before passing to create the new service
name = original_item['name']
if name is None:
name = os.path.basename(os.path.dirname(original_item['url']))
name = self._get_unique_name(target, name, item_mapping, False)
service_definition['name'] = name
for key in ['layers', 'tables', 'fullExtent', 'hasViews']:
if key in service_definition:
del service_definition[key]
# Set the extent and spatial reference of the service
original_extent = service_definition['initialExtent']
spatial_reference = None
if _MAINTAIN_SPATIAL_REF not in original_item['tags']:
spatial_reference = SPATIAL_REFERENCE
new_extent = _get_extent_definition(original_extent, ITEM_EXTENT, spatial_reference)
service_definition['initialExtent'] = new_extent
service_definition['spatialReference'] = new_extent['spatialReference']
if self.is_view:
properties = ['name', 'isView', 'sourceSchemaChangesAllowed', 'isUpdatableView', 'capabilities']
service_definition_copy = copy.deepcopy(service_definition)
for key, value in service_definition_copy.items():
if key not in properties:
del service_definition[key]
# Remove any unsupported capabilities from layer for Portal
supported_capabilities = ['Create','Query','Editing','Update','Delete','Uploads','Sync','Extract']
if target.properties.isPortal:
capabilities = _deep_get(service_definition, 'capabilities')
if capabilities is not None:
service_definition['capabilities'] = ','.join([x for x in capabilities.split(',') if x in supported_capabilities])
# Create a new feature service
# In some cases isServiceNameAvailable returns true but fails to create the service with error that a service with the name already exists.
# In these cases catch the error and try again with a unique name.
try:
new_item = _create_service(target, 'featureService', service_definition, self.is_view, _deep_get(folder, 'title'))
except RuntimeError as ex:
if "already exists" in str(ex):
name = self._get_unique_name(target, name, item_mapping, True)
service_definition['name'] = name
new_item = target.content.create_service(name, service_type='featureService', create_params=service_definition, folder=_deep_get(folder, 'title'))
elif "managed database" in str(ex):
raise Exception("The target portal's managed database must be an ArcGIS Data Store.")
else:
raise
# Check if tool has been canceled, raise exception with new_item so it can be cleaned up
_check_cancel_status(new_item)
# Get the layer and table definitions from the original service and prepare them for the new service
layers_definition = self.layers_definition
gps_metadata = json.loads(_GPS_METADATA_FIELDS)
relationships = {}
for layer in layers_definition['layers'] + layers_definition['tables']:
# Need to remove relationships first and add them back individually
# after all layers and tables have been added to the definition
if 'relationships' in layer and layer['relationships'] is not None and len(layer['relationships']) != 0:
relationships[layer['id']] = layer['relationships']
layer['relationships'] = []
# Need to remove all indexes duplicated for fields.
# Services get into this state due to a bug in 10.4 and 1.2
field_names = [f['name'].lower() for f in layer['fields']]
unique_fields = []
if 'indexes' in layer:
for index in list(layer['indexes']):
fields = index['fields'].lower()
if fields in unique_fields or fields not in field_names:
layer['indexes'].remove(index)
else:
unique_fields.append(fields)
# Due to a bug at 10.5.1 any domains for a double field must explicitly have a float code rather than int
for field in layer['fields']:
field_type = _deep_get(field, 'type')
if field_type == "esriFieldTypeDouble":
coded_values = _deep_get(field, 'domain', 'codedValues')
if coded_values is not None:
for coded_value in coded_values:
code = _deep_get(coded_value, 'code')
if code is not None:
coded_value['code'] = float(code)
# Add GPS Metadata fields to layer definition
if ADD_GPS_METADATA_FIELDS:
if 'geometryType' in layer and layer['geometryType'] == 'esriGeometryPoint':
metadata_fields = gps_metadata['fields']
for metadata_field in metadata_fields:
if metadata_field['name'].lower() not in field_names:
if target.properties.isPortal:
metadata_field['name'] = metadata_field['name'].lower()
layer['fields'].append(metadata_field)
# Set the extent of the feature layer to the specified default extent
if layer['type'] == 'Feature Layer':
layer['extent'] = new_extent
# Remove hasViews property if exists
if 'hasViews' in layer:
del layer['hasViews']
# Update the view layer source properties
if self.is_view:
url = self.view_sources[layer['id']]
original_feature_service = os.path.dirname(url)
original_id = os.path.basename(url)
admin_layer_info = {}
layer['adminLayerInfo'] = admin_layer_info
for key, value in item_mapping['Feature Services'].items():
if _compare_url(key, original_feature_service):
new_service = value
view_layer_definition = {}
view_layer_definition['sourceServiceName'] = os.path.basename(os.path.dirname(new_service['url']))
view_layer_definition['sourceLayerId'] = new_service['layer_id_mapping'][int(original_id)]
view_layer_definition['sourceLayerFields'] = '*'
admin_layer_info['viewLayerDefinition'] = view_layer_definition
break
# Remove any unsupported capabilities from layer for Portal
if target.properties.isPortal:
capabilities = _deep_get(layer, 'capabilities')
if capabilities is not None:
layer['capabilities'] = ','.join([x for x in capabilities.split(',') if x in supported_capabilities])
# Add the layer and table definitions to the service
# Explicitly add layers first and then tables, otherwise sometimes json.dumps() reverses them and this effects the output service
feature_service = FeatureLayerCollection.fromitem(new_item)
feature_service_admin = feature_service.manager
layers = []
tables = []
if len(layers_definition['layers']) > 0:
layers = copy.deepcopy(layers_definition['layers'])
if self.is_view:
for layer in layers:
del layer['fields']
if len(layers_definition['tables']) > 0:
tables = copy.deepcopy(layers_definition['tables'])
if self.is_view:
for table in tables:
del table['fields']
definition = '{{"layers" : {0}, "tables" : {1}}}'.format(json.dumps(layers), json.dumps(tables))
_add_to_definition(feature_service_admin, definition)
# Check if tool has been canceled, raise exception with new_item so it can be cleaned up
_check_cancel_status(new_item)
# Create a lookup between the new and old layer ids
layer_id_mapping = {}
layer_fields = {}
original_layers = layers_definition['layers'] + layers_definition['tables']
i = 0
for layer in feature_service.layers + feature_service.tables:
layer_id_mapping[original_layers[i]['id']] = layer.properties['id']
layer_fields[layer.properties['id']] = layer.properties.fields
i += 1
# Create a lookup for the layers and tables using their id
new_layers = {}
for layer in feature_service.layers + feature_service.tables:
for key, value in layer_id_mapping.items():
if value == layer.properties['id']:
new_layers[key] = layer
break
# Create a field mapping object if the case or name of the field has changes
layer_field_mapping = {}
for layer in layers_definition['layers'] + layers_definition['tables']:
layer_id = layer['id']
fields = layer['fields']
if self.is_view:
fields = self.view_source_fields[layer_id]
new_layer = new_layers[layer_id]
field_mapping = {}
if len(fields) <= len(new_layer.properties['fields']):
for i in range(0, len(fields)):
if fields[i]['name'] != new_layer.properties['fields'][i]['name']:
field_mapping[fields[i]['name']] = new_layer.properties['fields'][i]['name']
if len(field_mapping) > 0:
layer_field_mapping[layer_id] = field_mapping
# If editor tracking fields changed from original layer we need to update the layer field mapping
del_fields = []
if 'editFieldsInfo' in layer and layer['editFieldsInfo'] is not None and 'editFieldsInfo' in new_layer.properties and new_layer.properties['editFieldsInfo'] is not None:
new_edit_fields_info = new_layer.properties['editFieldsInfo']
for key, old_field in layer['editFieldsInfo'].items():
if key in new_edit_fields_info:
new_field = new_edit_fields_info[key]
if old_field != new_field:
new_delete_field = old_field
if old_field in field_mapping:
new_delete_field = field_mapping[old_field]
for field in new_layer.properties['fields']:
if field['name'] == new_delete_field and self.is_view == False:
del_fields.append(new_delete_field)
break
if layer_id in layer_field_mapping:
layer_field_mapping[layer_id][old_field] = new_field
else:
field_mapping = {old_field : new_field}
layer_field_mapping[layer_id] = field_mapping
update_definition = {}
delete_definition = {}
if len(del_fields) > 0 or layer_id in layer_field_mapping:
# Delete the old editor tracking fields from the layer
if len(del_fields) > 0:
layer_admin = new_layer.manager
delete_definition_fields = []
for field in del_fields:
delete_definition_fields.append({'name': field})
delete_definition['fields'] = delete_definition_fields
# Update editing templates if field mapping is required
if layer_id in layer_field_mapping:
field_mapping = layer_field_mapping[layer_id]
if 'templates' in new_layer.properties and new_layer.properties['templates'] is not None:
templates = new_layer.properties['templates']
for template in templates:
if 'prototype' in template and template['prototype'] is not None:
_update_feature_attributes(template['prototype'], field_mapping)
update_definition['templates'] = templates
if 'types' in new_layer.properties and new_layer.properties['types'] is not None:
types = new_layer.properties['types']
for layer_type in types:
if 'templates' in layer_type and layer_type['templates'] is not None:
for template in layer_type['templates']:
if 'prototype' in template and template['prototype'] is not None:
_update_feature_attributes(template['prototype'], field_mapping)
update_definition['types'] = types
# Update field visibility for views
if self.is_view:
if 'viewDefinitionQuery' in layer and layer['viewDefinitionQuery']:
update_definition['viewDefinitionQuery'] = layer['viewDefinitionQuery']
if layer_id in layer_field_mapping:
update_definition['viewDefinitionQuery'] = _find_and_replace_fields(update_definition['viewDefinitionQuery'], layer_field_mapping[layer_id])
field_visibility = []
need_update = False
view_field_names = [f['name'].lower() for f in layer['fields']]
for source_field in self.view_source_fields[layer_id]:
source_field_name = source_field['name']
visible = source_field_name.lower() in view_field_names
if not visible:
need_update = True
field_name = source_field_name
if layer_id in layer_field_mapping:
if source_field_name in layer_field_mapping[layer_id]:
field_name = layer_field_mapping[layer_id][source_field_name]
field_visibility.append({'name' : field_name, 'visible' : visible})
if need_update:
update_definition['fields'] = field_visibility
# Update the definition of the layer
if len(update_definition) > 0 or len(delete_definition) > 0:
layer_admin = new_layer.manager
if len(update_definition) > 0:
layer_admin.update_definition(update_definition)
if len(delete_definition) > 0:
layer_admin.delete_from_definition(delete_definition)
# Check if tool has been canceled, raise exception with new_item so it can be cleaned up
_check_cancel_status(new_item)
# Add the relationships back to the layers
relationship_field_mapping = {}
if len(relationships) > 0 and self.is_view == False:
for layer_id in relationships:
for relationship in relationships[layer_id]:
if layer_id in layer_field_mapping:
field_mapping = layer_field_mapping[layer_id]
if relationship['keyField'] in field_mapping:
relationship['keyField'] = field_mapping[relationship['keyField']]
related_table_id = relationship['relatedTableId']
if related_table_id in layer_field_mapping:
field_mapping = layer_field_mapping[related_table_id]
if layer_id not in relationship_field_mapping:
relationship_field_mapping[layer_id] = {}
relationship_field_mapping[layer_id][relationship['id']] = field_mapping
relationships_copy = copy.deepcopy(relationships)
for layer_id in relationships_copy:
for relationship in relationships_copy[layer_id]:
relationship['relatedTableId'] = layer_id_mapping[relationship['relatedTableId']]
if target.properties.isPortal:
relationships_definition = {'layers' : []}
for key, value in layer_id_mapping.items():
if key in relationships_copy:
relationships_definition['layers'].append({'id' : value, 'relationships' : relationships_copy[key]})
else:
relationships_definition['layers'].append({'id' : value, 'relationships' : []})
feature_service_admin.add_to_definition(relationships_definition)
else:
for layer_id in relationships_copy:
layer = new_layers[layer_id]
layer.manager.add_to_definition({'relationships' : relationships_copy[layer_id]})
# Check if tool has been canceled, raise exception with new_item so it can be cleaned up
_check_cancel_status(new_item)
# Get the item properties from the original item
item_properties = self._get_item_properties()
# Merge type keywords from what is created by default for the new item and what was in the original item
type_keywords = list(new_item['typeKeywords'])
type_keywords.extend(item_properties['typeKeywords'].split(','))
type_keywords = list(set(type_keywords))
# Replace type keyword if it references an item id of cloned item, ex. Survey123
for keyword in list(type_keywords):
if keyword in item_mapping['Item IDs']:
type_keywords.remove(keyword)
type_keywords.append(item_mapping['Item IDs'][keyword])
item_properties['typeKeywords'] = ','.join(type_keywords)
# Get the collection of layers and tables from the item data
data = self.data
layers = []
if data and 'layers' in data and data['layers'] is not None:
layers += [layer for layer in data['layers']]
if data and 'tables' in data and data['tables'] is not None:
layers += [layer for layer in data['tables']]
# Update any pop-up, labeling or renderer field references
for layer_id in layer_field_mapping:
layer = next((layer for layer in layers if layer['id'] == layer_id), None)
if layer:
_update_layer_fields(layer, layer_field_mapping[layer_id])
for layer_id in relationship_field_mapping:
layer = next((layer for layer in layers if layer['id'] == layer_id), None)
if layer:
_update_layer_related_fields(layer, relationship_field_mapping[layer_id])
# Update the layer id
for layer in layers:
layer['id'] = layer_id_mapping[layer['id']]
# Add GPS Metadata field infos to the pop-up of the layer
if ADD_GPS_METADATA_FIELDS:
gps_metadata_field_infos = gps_metadata['popup']
for layer in layers:
field_infos = _deep_get(layer, 'popupInfo', 'fieldInfos')
if field_infos is not None:
fields = layer_fields[layer['id']]
field_names = [f['name'].lower() for f in fields]
field_info_names = [_deep_get(f, 'fieldName').lower() for f in field_infos]
for gps_metadata_field_info in gps_metadata_field_infos:
gps_field_name = gps_metadata_field_info['fieldName'].lower()
if gps_field_name in field_names and gps_field_name not in field_info_names:
i = field_names.index(gps_field_name)
gps_metadata_field_info['fieldName'] = fields[i]['name']
field_infos.append(gps_metadata_field_info)
# Set the data to the text properties of the item
if data:
item_properties['text'] = json.dumps(data)
# If the item title has a guid, check if it is in the item_mapping and replace if it is.
guids = re.findall('[0-9A-F]{32}', item_properties['title'], re.IGNORECASE)
for guid in guids:
if guid in item_mapping['Group IDs']:
item_properties['title'] = item_properties['title'].replace(guid, item_mapping['Group IDs'][guid])
elif guid in item_mapping['Item IDs']:
item_properties['title'] = item_properties['title'].replace(guid, item_mapping['Item IDs'][guid])
# Update the item definition of the service
thumbnail = self.thumbnail
if not thumbnail and self.portal_item:
temp_dir = os.path.join(_TEMP_DIR.name, original_item['id'])
if not os.path.exists(temp_dir):
os.makedirs(temp_dir)
thumbnail = self.portal_item.download_thumbnail(temp_dir)
new_item.update(item_properties=item_properties, thumbnail=thumbnail)
# Check if tool has been canceled, raise exception with new_item so it can be cleaned up
_check_cancel_status(new_item)
# Copy features from original item
if COPY_DATA and not self.is_view:
self._add_features(new_layers, relationships, layer_field_mapping, feature_service.properties['spatialReference'])
return [new_item, layer_field_mapping, layer_id_mapping, layer_fields, relationship_field_mapping]
except _CustomCancelException as ex:
raise ex
except Exception as ex:
raise _ItemCreateException("Failed to create {0} {1}: {2}".format(original_item['type'], original_item['title'], str(ex)), new_item)
class _WebMapDefinition(_TextItemDefinition):
"""
Represents the definition of a web map within ArcGIS Online or Portal.
"""
def clone(self, target, folder, item_mapping):
"""Clone the web map in the target organization.
Keyword arguments:
target - The instance of arcgis.gis.GIS (the portal) to clone the web map to
folder - The folder to create the item in
item_mapping - Dictionary containing mapping between new and old items.
"""
try:
new_item = None
original_item = self.info
# Get the item properties from the original web map which will be applied when the new item is created
item_properties = self._get_item_properties()
# Swizzle the item ids and URLs of the feature layers and tables in the web map
webmap_json = self.data
layers = []
feature_collections = []
if 'operationalLayers' in webmap_json:
layers += [layer for layer in webmap_json['operationalLayers'] if 'layerType' in layer and layer['layerType'] == "ArcGISFeatureLayer" and 'url' in layer]
feature_collections += [layer for layer in webmap_json['operationalLayers'] if 'layerType' in layer and layer['layerType'] == "ArcGISFeatureLayer" and 'type' in layer and layer['type'] == "Feature Collection"]
if 'tables' in webmap_json:
layers += [table for table in webmap_json['tables'] if 'url' in table]
gps_metadata_field_infos = json.loads(_GPS_METADATA_FIELDS)['popup']
for layer in layers:
feature_service_url = os.path.dirname(layer['url'])
for original_url in item_mapping['Feature Services']:
if _compare_url(feature_service_url, original_url):
new_service = item_mapping['Feature Services'][original_url]
layer_id = int(os.path.basename(layer['url']))
new_id = new_service['layer_id_mapping'][layer_id]
layer['url'] = "{0}/{1}".format(new_service['url'], new_id)
layer['itemId'] = new_service['id']
if layer_id in new_service['layer_field_mapping']:
_update_layer_fields(layer, new_service['layer_field_mapping'][layer_id])
if layer_id in new_service['relationship_field_mapping']:
_update_layer_related_fields(layer, new_service['relationship_field_mapping'][layer_id])
# If layer contains gps metadata fields, but are not in the popup definition add them
if ADD_GPS_METADATA_FIELDS and new_id in new_service['layer_fields']:
fields = new_service['layer_fields'][new_id]
field_names = [f['name'].lower() for f in fields]
field_infos = _deep_get(layer, 'popupInfo', 'fieldInfos')
if field_infos is not None:
field_info_names = [_deep_get(f, 'fieldName').lower() for f in field_infos]
for gps_metadata_field_info in gps_metadata_field_infos:
gps_field_name = gps_metadata_field_info['fieldName'].lower()
if gps_field_name in field_names and gps_field_name not in field_info_names:
i = field_names.index(gps_field_name)
gps_metadata_field_info['fieldName'] = fields[i]['name']
field_infos.append(gps_metadata_field_info)
break
for feature_collection in feature_collections:
if 'itemId' in feature_collection and feature_collection['itemId'] is not None and feature_collection['itemId'] in item_mapping['Item IDs']:
feature_collection['itemId'] = item_mapping['Item IDs'][feature_collection['itemId']]
# Change the basemap to the default basemap defined in the target organization
if USE_DEFAULT_BASEMAP:
properties = target.properties
if 'defaultBasemap' in properties and properties['defaultBasemap'] is not None:
default_basemap = properties['defaultBasemap']
if 'title' in default_basemap and 'baseMapLayers' in default_basemap and default_basemap['baseMapLayers'] is not None:
for key in [k for k in default_basemap]:
if key not in ['title', 'baseMapLayers']:
del default_basemap[key]
for basemap_layer in default_basemap['baseMapLayers']:
if 'resourceInfo' in basemap_layer:
del basemap_layer['resourceInfo']