-
Notifications
You must be signed in to change notification settings - Fork 11
/
restHelpers.ts
2673 lines (2528 loc) · 82.3 KB
/
restHelpers.ts
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
/** @license
* Copyright 2018 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.
*/
/**
* Provides common functions involving the arcgis-rest-js library.
*
* @module restHelpers
*/
import {
removeLayerOptimization,
setDefaultSpatialReference,
validateSpatialReferenceAndExtent,
processContingentValues
} from "./featureServiceHelpers";
import {
appendQueryParam,
blobToJson,
blobToText,
checkUrlPathTermination,
deleteProp,
deleteProps,
fail,
getProp,
getUniqueTitle,
setCreateProp
} from "./generalHelpers";
import {
IAddFolderResponse,
IAddGroupResponse,
IAdditionalGroupSearchOptions,
ICreateItemResponse,
ICreateServiceResult,
IDependency,
IExtent,
IFeatureServiceProperties,
IFolderStatusResponse,
IGroup,
IGroupAdd,
IItem,
IItemTemplate,
IItemUpdate,
IPostProcessArgs,
IRelatedItems,
ISpatialReference,
IStatusResponse,
ItemRelationshipType,
IUpdate,
IUpdateItemResponse,
UserSession
} from "./interfaces";
import { createZip } from "./libConnectors";
import { getItemBase, getItemDataAsJson } from "./restHelpersGet";
import { IUserSessionOptions } from "@esri/arcgis-rest-auth";
import {
addItemData as portalAddItemData,
addItemRelationship,
addItemResource,
createFolder,
createGroup,
createItemInFolder,
getItem,
IAddItemDataOptions,
ICreateItemOptions,
IFolderIdOptions,
IGroupSharingOptions,
IItemResourceOptions,
IItemResourceResponse,
IManageItemRelationshipOptions,
IMoveItemOptions,
IMoveItemResponse,
IPagingParams,
ISearchGroupContentOptions,
ISearchOptions,
ISearchResult,
ISetAccessOptions,
ISharingResponse,
IUpdateItemOptions,
IUserGroupOptions,
IUserItemOptions,
moveItem as portalMoveItem,
removeFolder as portalRemoveFolder,
removeGroup as portalRemoveGroup,
removeGroupUsers as portalRemoveGroupUsers,
removeItem as portalRemoveItem,
searchGroupContent,
searchGroups as portalSearchGroups,
searchItems as portalSearchItems,
SearchQueryBuilder,
setItemAccess,
shareItemWithGroup,
updateItem as portalUpdateItem,
updateGroup as portalUpdateGroup,
IUpdateGroupOptions
} from "@esri/arcgis-rest-portal";
import { IParams, IRequestOptions, request } from "@esri/arcgis-rest-request";
import {
ICreateServiceParams,
addToServiceDefinition as svcAdminAddToServiceDefinition,
createFeatureService as svcAdminCreateFeatureService
} from "@esri/arcgis-rest-service-admin";
import {
getWorkflowManagerUrlRoot
} from "./workflowHelpers";
import {
getWorkforceDependencies,
isWorkforceProject,
getWorkforceServiceInfo
} from "./workforceHelpers";
import { hasUnresolvedVariables, replaceInTemplate } from "./templatization";
import {
isTrackingViewTemplate,
setTrackingOptions
} from "./trackingHelpers";
// ------------------------------------------------------------------------------------------------------------------ //
export { request as rest_request } from "@esri/arcgis-rest-request";
// ------------------------------------------------------------------------------------------------------------------ //
export function addItemData(
id: string,
data: any,
authentication: UserSession
): Promise<IUpdateItemResponse> {
const addDataOptions: IAddItemDataOptions = {
id,
data,
authentication
};
return portalAddItemData(addDataOptions);
};
/**
* Creates a UserSession via a function so that the global arcgisSolution variable can access authentication.
*
* @param options See https://esri.github.io/arcgis-rest-js/api/auth/IUserSessionOptions/
* @returns UserSession
*/
export function getUserSession(
options: IUserSessionOptions = {}
): UserSession {
return new UserSession(options);
}
/**
* Adds a forward relationship between two items.
*
* @param originItemId Origin of relationship
* @param destinationItemId Destination of relationship
* @param relationshipType Type of relationship
* @param authentication Credentials for the request
* @returns A Promise to add item resources.
*/
export function addForwardItemRelationship(
originItemId: string,
destinationItemId: string,
relationshipType: ItemRelationshipType,
authentication: UserSession
): Promise<IStatusResponse> {
return new Promise<IStatusResponse>(resolve => {
const requestOptions: IManageItemRelationshipOptions = {
originItemId,
destinationItemId,
relationshipType,
authentication
};
addItemRelationship(requestOptions).then(
response => {
resolve({
success: response.success,
itemId: originItemId
} as IStatusResponse);
},
() => {
resolve({
success: false,
itemId: originItemId
} as IStatusResponse);
}
);
});
}
/**
* Adds forward relationships for an item.
*
* @param originItemId Origin of relationship
* @param destinationRelationships Destinations
* @param authentication Credentials for the request
* @returns A Promise to add item resources.
*/
export function addForwardItemRelationships(
originItemId: string,
destinationRelationships: IRelatedItems[],
authentication: UserSession
): Promise<IStatusResponse[]> {
return new Promise<IStatusResponse[]>(resolve => {
// Set up relationships using updated relationship information
const relationshipPromises = new Array<Promise<IStatusResponse>>();
destinationRelationships.forEach(relationship => {
relationship.relatedItemIds.forEach(relatedItemId => {
relationshipPromises.push(
addForwardItemRelationship(
originItemId,
relatedItemId,
relationship.relationshipType as ItemRelationshipType,
authentication
)
);
});
});
// eslint-disable-next-line @typescript-eslint/no-floating-promises
Promise.all(relationshipPromises).then((responses: IStatusResponse[]) =>
resolve(responses)
);
});
}
/**
* Adds a token to the query parameters of a URL.
*
* @param url URL to use as base
* @param authentication Credentials to be used to generate token for URL
* @returns A promise that will resolve with the supplied URL with `token=<token>` added to its query params
* unless either the URL doesn't exist or the token can't be generated
*/
export function addTokenToUrl(
url: string,
authentication: UserSession
): Promise<string> {
return new Promise<string>(resolve => {
if (!url || !authentication) {
resolve(url);
} else {
authentication.getToken(url).then(
token => {
/* istanbul ignore else */
if (token) {
url = appendQueryParam(url, "token=" + token);
}
resolve(url);
},
() => resolve(url)
);
}
});
}
/**
* Calls addToDefinition for the service.
*
* Added retry due to some solutions failing to deploy in specific orgs/hives due to timeouts.
* On the first pass we will use the quicker sync request to add.
* If it fails we will use an async request that will avoid the timeout errors.
*
* @param url URL to use as base
* @param options the info to add to the services definition
* @param skipRetry a boolean to control if retry logic will be used. Defaults to false.
* @param useAsync a boolean to control if we will use an async request
* @returns A promise that will resolve when the request has completed
*/
export function addToServiceDefinition(
url: string,
options: any,
skipRetry: boolean = false,
useAsync: boolean = false
): Promise<void> {
/* istanbul ignore else */
if (useAsync) {
options.params = { ...options.params, async: true };
}
return new Promise((resolve, reject) => {
svcAdminAddToServiceDefinition(url, options).then(
(result: any) => {
checkRequestStatus(result, options.authentication).then(
() => resolve(null),
e => reject(fail(e))
);
},
e => {
if (!skipRetry) {
addToServiceDefinition(url, options, true, true).then(
() => resolve(null),
e => reject(e)
);
} else {
reject(fail(e));
}
}
);
});
}
/**
* When using an async request we need to poll the status url to know when the request has completed or failed.
*
* @param result the result returned from the addToDefinition request.
* This will contain a status url or the standard sync result.
* @param authentication Credentials to be used to generate token for URL
* @returns A promise that will resolve when the request has completed
*/
export function checkRequestStatus(
result: any,
authentication: any
): Promise<void> {
return new Promise((resolve, reject) => {
const url = result.statusURL || result.statusUrl;
if (url) {
const checkStatus = setInterval(() => {
request(url, { authentication }).then(
r => {
/* istanbul ignore else */
if (["completed", "success"].indexOf(r.status.toLowerCase()) > -1) {
clearInterval(checkStatus);
resolve();
} else if (r.status.toLowerCase() === "failed") {
clearInterval(checkStatus);
reject(r);
}
},
e => {
clearInterval(checkStatus);
reject(e);
}
);
}, 2000);
} else {
resolve();
}
});
}
/**
* Converts a general search into an ISearchOptions structure.
*
* @param search Search specified in one of three ways
* @returns Recast search
*/
export function convertToISearchOptions(
search: string | ISearchOptions | SearchQueryBuilder
): ISearchOptions {
// Convert the search into an ISearchOptions
let searchOptions: ISearchOptions = {
q: "",
start: 1,
num: 100
};
if (typeof search === "string") {
// Insert query into defaults
searchOptions.q = search;
} else if (search instanceof SearchQueryBuilder) {
// Insert query into defaults
searchOptions.q = search.toParam();
} else { // search is ISearchOptions
searchOptions = {
...searchOptions, // defaults
...search // request
}
}
// Remove the sortField if it's "relevance"; that's the default option and is not meant to be specified
if (searchOptions.sortField === "relevance") {
delete searchOptions.sortField;
}
return searchOptions;
}
/**
* Simple validate function to ensure all coordinates are numbers
* In some cases orgs can have null or undefined coordinate values associated with the org extent
*
* @param extent the extent to validate
* @returns the provided extent or a default global extent if some coordinates are not numbers
* @private
*/
export function _validateExtent(extent: IExtent): IExtent {
// in some cases orgs can have invalid extents defined
// this is a simple validate function that will ensure coordiantes are numbers
// using -179,-89,179,89 because the project call is returning "NaN" when using -180,-90,180,90
const hasInvalid =
typeof extent.xmin !== "number" ||
typeof extent.xmax !== "number" ||
typeof extent.ymax !== "number" ||
typeof extent.ymin !== "number";
if (hasInvalid) {
extent.xmin = -179;
extent.xmax = 179;
extent.ymax = 89;
extent.ymin = -89;
extent.spatialReference = { wkid: 4326 };
}
return extent;
}
/**
* If the request to convert the extent fails it has commonly been due to an invalid extent.
* This function will first attempt to use the provided extent. If it fails it will default to
* the source items extent and if that fails it will then use a default global extent.
*
* @param extent the extent to convert
* @param fallbackExtent the extent to convert if the main extent does not project to the outSR
* @param outSR the spatial reference to project to
* @param geometryServiceUrl the service url for the geometry service to use
* @param authentication the credentials for the requests
* @returns the extent projected to the provided spatial reference
* or the world extent projected to the provided spatial reference
* @private
*/
export function convertExtentWithFallback(
extent: IExtent,
fallbackExtent: any,
outSR: ISpatialReference,
geometryServiceUrl: string,
authentication: UserSession
): Promise<any> {
return new Promise((resolve, reject) => {
const defaultExtent = {
xmin: -179,
xmax: 179,
ymin: -89,
ymax: 89,
spatialReference: { wkid: 4326 }
};
convertExtent(
_validateExtent(extent),
outSR,
geometryServiceUrl,
authentication
).then(
extentResponse => {
// in some cases project will complete successfully but return "NaN" values
// check for this and call convert again if it does
const extentResponseString = JSON.stringify(extentResponse);
const validatedExtent = JSON.stringify(_validateExtent(extentResponse));
if (extentResponseString === validatedExtent) {
resolve(extentResponse);
} else {
convertExtent(
fallbackExtent || defaultExtent,
outSR,
geometryServiceUrl,
authentication
).then(resolve, e => reject(fail(e)));
}
},
// if convert fails try again with default global extent
() => {
convertExtent(
defaultExtent,
outSR,
geometryServiceUrl,
authentication
).then(resolve, e => reject(fail(e)));
}
);
});
}
/**
* Converts an extent to a specified spatial reference.
*
* @param extent Extent object to check and (possibly) to project
* @param outSR Desired spatial reference
* @param geometryServiceUrl Path to geometry service providing `findTransformations` and `project` services
* @param authentication Credentials for the request
* @returns Original extent if it's already using outSR or the extents projected into the outSR
*/
export function convertExtent(
extent: IExtent,
outSR: ISpatialReference,
geometryServiceUrl: string,
authentication: UserSession
): Promise<any> {
const _requestOptions: any = { authentication };
return new Promise<any>((resolve, reject) => {
if (extent.spatialReference.wkid === outSR?.wkid || !outSR) {
resolve(extent);
} else {
_requestOptions.params = {
f: "json",
inSR: extent.spatialReference.wkid,
outSR: outSR.wkid,
extentOfInterest: JSON.stringify(extent)
};
request(
checkUrlPathTermination(geometryServiceUrl) + "findTransformations",
_requestOptions
).then(
response => {
const transformations =
response && response.transformations
? response.transformations
: undefined;
let transformation: any;
if (transformations && transformations.length > 0) {
// if a forward single transformation is found use that...otherwise check for and use composite
transformation = transformations[0].wkid
? transformations[0].wkid
: transformations[0].geoTransforms
? transformations[0]
: undefined;
}
_requestOptions.params = {
f: "json",
outSR: outSR.wkid,
inSR: extent.spatialReference.wkid,
geometries: {
geometryType: "esriGeometryPoint",
geometries: [
{ x: extent.xmin, y: extent.ymin },
{ x: extent.xmax, y: extent.ymax }
]
},
transformation: transformation
};
request(
checkUrlPathTermination(geometryServiceUrl) + "project",
_requestOptions
).then(
projectResponse => {
const projectGeom: any =
projectResponse.geometries.length === 2
? projectResponse.geometries
: undefined;
if (projectGeom) {
resolve({
xmin: projectGeom[0].x,
ymin: projectGeom[0].y,
xmax: projectGeom[1].x,
ymax: projectGeom[1].y,
spatialReference: outSR
});
} else {
resolve(undefined);
}
},
e => reject(fail(e))
);
},
e => reject(fail(e))
);
}
});
}
/**
* Publishes a feature service as an AGOL item; it does not include its layers and tables
*
* @param newItemTemplate Template of item to be created
* @param authentication Credentials for the request
* @param templateDictionary Hash of facts: org URL, adlib replacements, user; .user.folders property contains a list
* @returns A promise that will resolve with an object reporting success and the Solution id
*/
export function createFeatureService(
newItemTemplate: IItemTemplate,
authentication: UserSession,
templateDictionary: any
): Promise<ICreateServiceResult> {
return new Promise((resolve, reject) => {
// Create item
_getCreateServiceOptions(
newItemTemplate,
authentication,
templateDictionary
).then(
createOptions => {
svcAdminCreateFeatureService(createOptions).then(
createResponse => {
// Federated servers may have inconsistent casing, so lowerCase it
createResponse.encodedServiceURL = _lowercaseDomain(createResponse.encodedServiceURL);
createResponse.serviceurl = _lowercaseDomain(createResponse.serviceurl);
resolve(createResponse);
},
e => reject(fail(e))
);
},
e => reject(fail(e))
);
});
}
/**
* Publishes an item and its data, metadata, and resources as an AGOL item.
*
* @param itemInfo Item's `item` section
* @param folderId Id of folder to receive item; null indicates that the item goes into the root
* folder; ignored for Group item type
* @param destinationAuthentication Credentials for for requests to where the item is to be created
* @param itemThumbnailUrl URL to image to use for item thumbnail
* @param itemThumbnailAuthentication Credentials for requests to the thumbnail source
* @param dataFile Item's `data` section
* @param metadataFile Item's metadata file
* @param resourcesFiles Item's resources
* @param access Access to set for item: "public", "org", "private"
* @returns A promise that will resolve with an object reporting success or failure and the Solution id
*/
export function createFullItem(
itemInfo: any,
folderId: string | undefined,
destinationAuthentication: UserSession,
itemThumbnailUrl?: string,
itemThumbnailAuthentication?: UserSession,
dataFile?: File,
metadataFile?: File,
resourcesFiles?: File[],
access = "private"
): Promise<ICreateItemResponse> {
return new Promise((resolve, reject) => {
// Create item
const createOptions: ICreateItemOptions = {
item: {
...itemInfo
},
folderId,
authentication: destinationAuthentication
};
// eslint-disable-next-line @typescript-eslint/no-floating-promises
addTokenToUrl(itemThumbnailUrl, itemThumbnailAuthentication).then(
updatedThumbnailUrl => {
/* istanbul ignore else */
if (updatedThumbnailUrl) {
createOptions.item.thumbnailUrl = appendQueryParam(
updatedThumbnailUrl,
"w=400"
);
}
createItemInFolder(createOptions).then(
createResponse => {
if (createResponse.success) {
let accessDef: Promise<ISharingResponse>;
// Set access if it is not AGOL default
// Set the access manually since the access value in createItem appears to be ignored
// Need to run serially; will not work reliably if done in parallel with adding the data section
if (access !== "private") {
const accessOptions: ISetAccessOptions = {
id: createResponse.id,
access: access === "public" ? "public" : "org", // need to use constants rather than string
authentication: destinationAuthentication
};
accessDef = setItemAccess(accessOptions);
} else {
accessDef = Promise.resolve({
itemId: createResponse.id
} as ISharingResponse);
}
// Now add attached items
accessDef.then(
() => {
const updateDefs: Array<Promise<any>> = [];
// Add the data section
if (dataFile) {
updateDefs.push(
_addItemDataFile(
createResponse.id,
dataFile,
destinationAuthentication
)
);
}
// Add the resources via a zip because AGO sometimes loses resources if many are added at the
// same time to the same item
if (
Array.isArray(resourcesFiles) &&
resourcesFiles.length > 0
) {
updateDefs.push(
new Promise<IItemResourceResponse>(
(rsrcResolve, rsrcReject) => {
createZip("resources.zip", resourcesFiles).then(
(zipfile: File) => {
const addResourceOptions: IItemResourceOptions = {
id: createResponse.id,
resource: zipfile,
authentication: destinationAuthentication,
params: {
archive: true
}
};
addItemResource(addResourceOptions).then(
rsrcResolve,
rsrcReject
);
},
rsrcReject
);
}
)
);
}
// Add the metadata section
if (metadataFile) {
updateDefs.push(
_addItemMetadataFile(
createResponse.id,
metadataFile,
destinationAuthentication
)
);
}
// Wait until all adds are done
Promise.all(updateDefs).then(
() => resolve(createResponse),
e => reject(fail(e))
);
},
e => reject(fail(e))
);
} else {
reject(fail());
}
},
e => reject(fail(e))
);
}
);
});
}
/**
* Publishes an item and its data as an AGOL item.
*
* @param itemInfo Item's `item` section
* @param dataInfo Item's `data` section
* @param authentication Credentials for the request
* @param folderId Id of folder to receive item; null indicates that the item goes into the root
* folder; ignored for Group item type
* @param access Access to set for item: "public", "org", "private"
* @returns A promise that will resolve with an object reporting success and the Solution id
*/
export function createItemWithData(
itemInfo: any,
dataInfo: any,
authentication: UserSession,
folderId: string | undefined,
access = "private"
): Promise<ICreateItemResponse> {
return new Promise((resolve, reject) => {
// Create item
const createOptions: ICreateItemOptions = {
item: {
title: "_", // provide backup title
...itemInfo,
data: dataInfo
},
folderId,
authentication: authentication
};
if (itemInfo.thumbnail) {
createOptions.params = {
// Pass thumbnail file in via params because item property is serialized, which discards a blob
thumbnail: itemInfo.thumbnail
};
delete createOptions.item.thumbnail;
}
createItemInFolder(createOptions).then(
createResponse => {
if (createResponse.success) {
if (access !== "private") {
// Set access if it is not AGOL default
// Set the access manually since the access value in createItem appears to be ignored
const accessOptions: ISetAccessOptions = {
id: createResponse.id,
access: access === "public" ? "public" : "org", // need to use constants rather than string
authentication: authentication
};
setItemAccess(accessOptions).then(
() => {
resolve({
folder: createResponse.folder,
id: createResponse.id,
success: true
});
},
e => reject(fail(e))
);
} else {
resolve({
folder: createResponse.folder,
id: createResponse.id,
success: true
});
}
} else {
reject(fail());
}
},
e => reject(fail(e))
);
});
}
/**
* Creates a folder using a numeric suffix to ensure uniqueness if necessary.
*
* @param title Folder title, used as-is if possible and with suffix otherwise
* @param templateDictionary Hash of facts: org URL, adlib replacements, user; .user.folders property contains a list
* of known folder names; function updates list with existing names not yet known, and creates .user.folders if it
* doesn't exist in the dictionary
* @param authentication Credentials for creating folder
* @returns Id of created folder
*/
export function createUniqueFolder(
title: string,
templateDictionary: any,
authentication: UserSession
): Promise<IAddFolderResponse> {
return new Promise<IAddFolderResponse>((resolve, reject) => {
// Get a title that is not already in use
const folderTitle: string = getUniqueTitle(
title,
templateDictionary,
"user.folders"
);
const folderCreationParam = {
title: folderTitle,
authentication: authentication
};
createFolder(folderCreationParam).then(
ok => resolve(ok),
err => {
// If the name already exists, we'll try again
const errorDetails = getProp(err, "response.error.details") as string[];
if (Array.isArray(errorDetails) && errorDetails.length > 0) {
const nameNotAvailMsg =
"Folder title '" + folderTitle + "' not available.";
if (errorDetails.indexOf(nameNotAvailMsg) >= 0) {
// Create the user.folders property if it doesn't exist
/* istanbul ignore else */
if (!getProp(templateDictionary, "user.folders")) {
setCreateProp(templateDictionary, "user.folders", []);
}
templateDictionary.user.folders.push({
title: folderTitle
});
createUniqueFolder(title, templateDictionary, authentication).then(
resolve,
reject
);
} else {
reject(err);
}
} else {
// Otherwise, error out
reject(err);
}
}
);
});
}
/**
* Creates a group using numeric suffix to ensure uniqueness.
*
* @param title Group title, used as-is if possible and with suffix otherwise
* @param templateDictionary Hash of facts: org URL, adlib replacements, user
* @param authentication Credentials for creating group
* @param owner Optional arg for the Tracking owner
* If the tracking owner is not the one deploying the solution
* tracker groups will be created under the deployment user but
* will be reassigned to the tracking owner.
* @returns Information about created group
*/
export function createUniqueGroup(
title: string,
groupItem: IGroupAdd,
templateDictionary: any,
authentication: UserSession,
owner?: string
): Promise<IAddGroupResponse> {
return new Promise<IAddGroupResponse>((resolve, reject) => {
let groupsPromise: Promise<any>;
// when working with tracker we need to consider the groups of the deploying user as well as the groups
// of the tracking user...must be unique for both
if (owner && owner !== authentication.username) {
groupsPromise = searchAllGroups(`(owner:${owner}) orgid:${templateDictionary.organization.id}`, authentication);
} else {
groupsPromise = Promise.resolve([]);
}
// first get the tracker owner groups
groupsPromise.then(groups => {
templateDictionary["allGroups"] =
groups.concat(getProp(templateDictionary, "user.groups"));
// Get a title that is not already in use
groupItem.title = getUniqueTitle(title, templateDictionary, "allGroups");
const groupCreationParam = {
group: groupItem,
authentication: authentication
};
createGroup(groupCreationParam).then(resolve, err => {
// If the name already exists, we'll try again
const errorDetails = getProp(err, "response.error.details") as string[];
if (Array.isArray(errorDetails) && errorDetails.length > 0) {
const nameNotAvailMsg =
"You already have a group named '" +
groupItem.title +
"'. Try a different name.";
if (errorDetails.indexOf(nameNotAvailMsg) >= 0) {
templateDictionary.user.groups.push({
title: groupItem.title
});
createUniqueGroup(
title,
groupItem,
templateDictionary,
authentication
).then(resolve, reject);
} else {
reject(err);
}
} else {
// Otherwise, error out
reject(err);
}
});
}, e => reject(e));
});
}
/**
* Gets the ids of the dependencies of an AGOL feature service item.
* Dependencies will only exist when the service is a view.
*
* @param itemTemplate Template of item to be created
* @param authentication Credentials for the request
* @returns A promise that will resolve a list of dependencies
*/
export function extractDependencies(
itemTemplate: IItemTemplate,
authentication?: UserSession
): Promise<IDependency[]> {
const dependencies: any[] = [];
return new Promise((resolve, reject) => {
// Get service dependencies when the item is a view
// This step is skipped for tracker views as they will already have a source service in the org
if (itemTemplate.properties.service.isView && itemTemplate.item.url && !isTrackingViewTemplate(itemTemplate)) {
request(
checkUrlPathTermination(itemTemplate.item.url) + "sources?f=json",
{
authentication: authentication
}
).then(
response => {
/* istanbul ignore else */
if (response && response.services) {
response.services.forEach((layer: any) => {
dependencies.push({
id: layer.serviceItemId,
name: layer.name
});
});
}
resolve(dependencies);
},
e => reject(fail(e))
);
} else if (isWorkforceProject(itemTemplate)) {
resolve(getWorkforceDependencies(itemTemplate, dependencies));
} else {
resolve(dependencies);
}
});
}
/**
* Get json info for the services layers
*
* @param serviceUrl the url for the service
* @param layerList list of base layer info