-
Notifications
You must be signed in to change notification settings - Fork 353
/
WebMapServiceCapabilitiesStratum.ts
1069 lines (940 loc) · 34.8 KB
/
WebMapServiceCapabilitiesStratum.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
import i18next from "i18next";
import { computed, makeObservable } from "mobx";
import CesiumMath from "terriajs-cesium/Source/Core/Math";
import Rectangle from "terriajs-cesium/Source/Core/Rectangle";
import URI from "urijs";
import { JsonObject, isJsonArray, isJsonString } from "../../../Core/Json";
import TerriaError from "../../../Core/TerriaError";
import containsAny from "../../../Core/containsAny";
import createDiscreteTimesFromIsoSegments from "../../../Core/createDiscreteTimes";
import filterOutUndefined from "../../../Core/filterOutUndefined";
import isDefined from "../../../Core/isDefined";
import isReadOnlyArray from "../../../Core/isReadOnlyArray";
import { terriaTheme } from "../../../ReactViews/StandardUserInterface/StandardTheme";
import {
InfoSectionTraits,
MetadataUrlTraits
} from "../../../Traits/TraitsClasses/CatalogMemberTraits";
import {
KeyValueTraits,
WebCoverageServiceParameterTraits
} from "../../../Traits/TraitsClasses/ExportWebCoverageServiceTraits";
import { FeatureInfoTemplateTraits } from "../../../Traits/TraitsClasses/FeatureInfoTraits";
import LegendTraits from "../../../Traits/TraitsClasses/LegendTraits";
import { RectangleTraits } from "../../../Traits/TraitsClasses/MappableTraits";
import WebMapServiceCatalogItemTraits, {
GetFeatureInfoFormat,
SUPPORTED_CRS_3857,
SUPPORTED_CRS_4326,
WebMapServiceAvailableLayerDimensionsTraits,
WebMapServiceAvailableLayerStylesTraits,
WebMapServiceAvailableStyleTraits
} from "../../../Traits/TraitsClasses/WebMapServiceCatalogItemTraits";
import LoadableStratum from "../../Definition/LoadableStratum";
import Model, { BaseModel } from "../../Definition/Model";
import StratumFromTraits from "../../Definition/StratumFromTraits";
import createStratumInstance from "../../Definition/createStratumInstance";
import proxyCatalogItemUrl from "../proxyCatalogItemUrl";
import { CapabilitiesStyle } from "./OwsInterfaces";
import WebMapServiceCapabilities, {
CapabilitiesContactInformation,
CapabilitiesDimension,
CapabilitiesLayer,
MetadataURL,
getRectangleFromLayer
} from "./WebMapServiceCapabilities";
import WebMapServiceCatalogItem from "./WebMapServiceCatalogItem";
import { Complete } from "../../../Core/TypeModifiers";
const dateFormat = require("dateformat");
/** Transforms WMS GetCapabilities XML into WebMapServiceCatalogItemTraits */
export default class WebMapServiceCapabilitiesStratum extends LoadableStratum(
WebMapServiceCatalogItemTraits
) {
static async load(
catalogItem: WebMapServiceCatalogItem,
capabilities?: WebMapServiceCapabilities
): Promise<WebMapServiceCapabilitiesStratum> {
if (!isDefined(catalogItem.getCapabilitiesUrl)) {
throw new TerriaError({
title: i18next.t("models.webMapServiceCatalogItem.missingUrlTitle"),
message: i18next.t("models.webMapServiceCatalogItem.missingUrlMessage")
});
}
if (!isDefined(capabilities))
capabilities = await WebMapServiceCapabilities.fromUrl(
proxyCatalogItemUrl(
catalogItem,
catalogItem.getCapabilitiesUrl,
catalogItem.getCapabilitiesCacheDuration
)
);
return new WebMapServiceCapabilitiesStratum(catalogItem, capabilities);
}
constructor(
readonly catalogItem: WebMapServiceCatalogItem,
readonly capabilities: WebMapServiceCapabilities
) {
super();
makeObservable(this);
}
duplicateLoadableStratum(model: BaseModel): this {
return new WebMapServiceCapabilitiesStratum(
model as WebMapServiceCatalogItem,
this.capabilities
) as this;
}
async fetchPalettes(
abstract: string,
legend:
| Complete<{
title?: string | undefined;
url?: string | undefined;
paletteUrl?: string | undefined;
imageScaling?: number | undefined;
urlMimeType?: string | undefined;
items?:
| Complete<{
title?: string | undefined;
multipleTitles?: string[] | undefined;
maxMultipleTitlesShowed: number | undefined;
titleAbove?: string | undefined;
titleBelow?: string | undefined;
color?: string | undefined;
outlineColor?: string | undefined;
outlineWidth?: number | undefined;
multipleColors?: string[] | undefined;
imageUrl?: string | undefined;
marker?: string | undefined;
rotation: number | undefined;
addSpacingAbove?: boolean | undefined;
imageHeight: number | undefined;
imageWidth: number | undefined;
}>[]
| undefined;
backgroundColor?: string | undefined;
}>
| undefined
): Promise<StratumFromTraits<WebMapServiceAvailableStyleTraits>[]> {
const paletteResult: StratumFromTraits<WebMapServiceAvailableStyleTraits>[] =
[];
const urlRegex = /(https?:\/\/[^\s]+)/g;
const urls = abstract?.match(urlRegex);
if (urls) {
const paletteUrl = proxyCatalogItemUrl(this.catalogItem, urls[0]);
const response = await fetch(paletteUrl);
const data = await response.json();
const palettes = data.palettes;
palettes.forEach((palette: any) => {
paletteResult.push({
name: palette,
title: palette,
abstract: abstract,
legend: legend
});
});
}
return paletteResult;
}
@computed get metadataUrls() {
const metadataUrls: MetadataURL[] = [];
Array.from(this.capabilitiesLayers.values()).forEach((layer) => {
if (!layer?.MetadataURL) return;
Array.isArray(layer?.MetadataURL)
? metadataUrls.push(...layer?.MetadataURL)
: metadataUrls.push(layer?.MetadataURL as MetadataURL);
});
return metadataUrls
.filter((m) => m.OnlineResource?.["xlink:href"])
.map((m) =>
createStratumInstance(MetadataUrlTraits, {
url: m.OnlineResource!["xlink:href"]
})
);
}
@computed
get layers(): string | undefined {
let layers: string | undefined;
if (this.catalogItem.uri !== undefined) {
// Try to extract a layer from the URL
const query: any = this.catalogItem.uri.query(true) ?? {};
layers = query.layers ?? query.LAYERS;
}
if (layers === undefined) {
// Use all the top-level, named layers
layers = filterOutUndefined(
this.capabilities.topLevelNamedLayers.map((layer) => layer.Name)
).join(",");
}
return layers;
}
@computed get tileWidth() {
const queryParams: any = this.catalogItem.uri?.query(true) ?? {};
if (isDefined(queryParams.width ?? queryParams.WIDTH)) {
return parseInt(queryParams.width ?? queryParams.WIDTH, 10);
}
}
@computed get tileHeight() {
const queryParams: any = this.catalogItem.uri?.query(true) ?? {};
if (isDefined(queryParams.height ?? queryParams.HEIGHT)) {
return parseInt(queryParams.height ?? queryParams.HEIGHT, 10);
}
}
/**
* **How we determine WMS legends (in order)**
1. Defined manually in catalog JSON
2. If `style` is undefined, and server doesn't support `GetLegendGraphic`, we must select first style as default - as there is no way to know what the default style is, and to request a legend for it
3. If `style` is is set and it has a `legendUrl` -> use it!
4. If server supports `GetLegendGraphic`, we can request a legend (with or without `style` parameter)
*/
@computed
get legends(): StratumFromTraits<LegendTraits>[] | undefined {
const availableStyles = this.catalogItem.availableStyles || [];
const layers = this.catalogItem.layersArray;
const styles = this.catalogItem.stylesArray;
const result: StratumFromTraits<LegendTraits>[] = [];
for (let i = 0; i < layers.length; ++i) {
const layer = layers[i];
const style = i < styles.length ? styles[i] : undefined;
let legendUri: uri.URI | undefined;
let legendUrlMimeType: string | undefined;
let legendScaling: number | undefined;
const layerAvailableStyles = availableStyles.find(
(candidate) => candidate.layerName === layer
)?.styles;
let layerStyle: Model<WebMapServiceAvailableStyleTraits> | undefined;
let paletteUrl: string | undefined;
if (isDefined(style)) {
// Attempt to find layer style based on AvailableStyleTraits
layerStyle = layerAvailableStyles?.find(
(candidate) => candidate.name === style
);
}
// If no style is selected and this WMS doesn't support GetLegendGraphics - we must use the first style if none is explicitly specified.
// (If WMS supports GetLegendGraphics we can use it and omit style parameter to get the "default" style's legend)
if (!isDefined(layerStyle) && !this.catalogItem.supportsGetLegendGraphic)
layerStyle = layerAvailableStyles?.[0];
// If legend found - proxy URL and set mimetype
if (layerStyle?.legend?.url) {
legendUri = URI(
proxyCatalogItemUrl(this.catalogItem, layerStyle.legend.url)
);
legendUrlMimeType = layerStyle.legend.urlMimeType;
}
// If no legends found and WMS supports GetLegendGraphics - make one up!
if (
!isDefined(legendUri) &&
isDefined(this.catalogItem.url) &&
this.catalogItem.supportsGetLegendGraphic
) {
legendUri = URI(
proxyCatalogItemUrl(
this.catalogItem,
this.catalogItem.url.split("?")[0]
)
);
legendUri
.setQuery("service", "WMS")
.setQuery(
"version",
this.catalogItem.useWmsVersion130 ? "1.3.0" : "1.1.1"
)
.setQuery("request", "GetLegendGraphic")
.setQuery("format", "image/png")
.setQuery("sld_version", "1.1.0")
.setQuery("layer", layer);
// From OGC — about style property for GetLegendGraphic request:
// If not present, the default style is selected. The style may be any valid style available for a layer, including non-SLD internally-defined styles.
if (style) {
legendUri.setQuery("style", style);
}
legendUrlMimeType = "image/png";
}
if (isDefined(legendUri)) {
// Add geoserver related LEGEND_OPTIONS to match terria styling (if supported)
if (
this.catalogItem.isGeoServer &&
legendUri.hasQuery("request", "GetLegendGraphic")
) {
let legendOptions =
"fontName:Courier;fontStyle:bold;fontSize:12;forceLabels:on;fontAntiAliasing:true;labelMargin:5";
// Geoserver fontColor must be a hex value - use `textLight` theme colour
let fontColor = terriaTheme.textLight.split("#")?.[1];
if (isDefined(fontColor)) {
// If fontColor is a 3-character hex -> turn into 6
if (fontColor.length === 3) {
fontColor = `${fontColor[0]}${fontColor[0]}${fontColor[1]}${fontColor[1]}${fontColor[2]}${fontColor[2]}`;
}
legendOptions += `;fontColor:0x${fontColor}`;
}
legendOptions += ";dpi:182"; // enable if we can scale the image back down by 50%.
legendScaling = 0.5;
legendUri.setQuery("LEGEND_OPTIONS", legendOptions);
legendUri.setQuery("transparent", "true");
}
// Add colour scale range params if supported
if (
this.catalogItem.supportsColorScaleRange &&
this.catalogItem.colorScaleRange
) {
legendUri.setQuery(
"colorscalerange",
this.catalogItem.colorScaleRange
);
}
result.push(
createStratumInstance(LegendTraits, {
url: legendUri.toString(),
urlMimeType: legendUrlMimeType,
imageScaling: legendScaling,
paletteUrl: paletteUrl
})
);
}
}
return result;
}
@computed
get capabilitiesLayers(): ReadonlyMap<string, CapabilitiesLayer | undefined> {
const lookup: (name: string) => [string, CapabilitiesLayer | undefined] = (
name
) => [name, this.capabilities && this.capabilities.findLayer(name)];
return new Map(this.catalogItem.layersArray.map(lookup));
}
@computed get availableCrs() {
// Get set of supported CRS from layer hierarchy
const layerCrs = new Set<string>();
this.capabilitiesLayers.forEach((layer) => {
if (layer) {
const srs = this.capabilities.getInheritedValues(layer, "SRS");
const crs = this.capabilities.getInheritedValues(layer, "CRS");
[
...(Array.isArray(srs) ? srs : [srs]),
...(Array.isArray(crs) ? crs : [crs])
].forEach((c) => layerCrs.add(c));
}
});
return Array.from(layerCrs);
}
@computed get crs() {
// Note order is important here, the first one found will be used
const supportedCrs = [...SUPPORTED_CRS_3857, ...SUPPORTED_CRS_4326];
// First check to see if URL has CRS or SRS
const queryParams: any = this.catalogItem.uri?.query(true) ?? {};
const urlCrs =
queryParams.crs ?? queryParams.CRS ?? queryParams.srs ?? queryParams.SRS;
if (urlCrs && supportedCrs.includes(urlCrs)) return urlCrs;
// If nothing is supported, ask for EPSG:3857, and hope for the best.
return (
supportedCrs.find((crs) => this.availableCrs.includes(crs)) ?? "EPSG:3857"
);
}
@computed
get availableDimensions(): StratumFromTraits<WebMapServiceAvailableLayerDimensionsTraits>[] {
const result: StratumFromTraits<WebMapServiceAvailableLayerDimensionsTraits>[] =
[];
if (!this.capabilities) {
return result;
}
const capabilitiesLayers = this.capabilitiesLayers;
for (const layerTuple of capabilitiesLayers) {
const layerName = layerTuple[0];
const layer = layerTuple[1];
const dimensions: ReadonlyArray<CapabilitiesDimension> = layer
? this.capabilities.getInheritedValues(layer, "Dimension")
: [];
result.push({
layerName: layerName,
dimensions: dimensions
.filter((dim) => dim.name !== "time")
.map((dim) => {
return {
name: dim.name,
units: dim.units,
unitSymbol: dim.unitSymbol,
default: dim.default,
multipleValues: dim.multipleValues,
current: dim.current,
nearestValue: dim.nearestValue,
values: dim.text?.split(",")
};
})
});
}
return result;
}
@computed
get availableStyles(): StratumFromTraits<WebMapServiceAvailableLayerStylesTraits>[] {
const result: StratumFromTraits<WebMapServiceAvailableLayerStylesTraits>[] =
[];
const capabilitiesLayers = this.capabilitiesLayers;
for (const layerTuple of capabilitiesLayers) {
const layerName = layerTuple[0];
const layer = layerTuple[1];
const styles: ReadonlyArray<CapabilitiesStyle> = layer
? this.capabilities.getInheritedValues(layer, "Style")
: [];
result.push({
layerName: layerName,
styles: styles.map((style) => {
const wmsLegendUrl = isReadOnlyArray(style.LegendURL)
? style.LegendURL[0]
: style.LegendURL;
let legendUri, legendMimeType;
if (
wmsLegendUrl &&
wmsLegendUrl.OnlineResource &&
wmsLegendUrl.OnlineResource["xlink:href"]
) {
legendUri = new URI(
decodeURIComponent(wmsLegendUrl.OnlineResource["xlink:href"])
);
legendMimeType = wmsLegendUrl.Format;
}
const legend = !legendUri
? undefined
: createStratumInstance(LegendTraits, {
url: legendUri.toString(),
urlMimeType: legendMimeType,
title:
(capabilitiesLayers.size > 1 && layer?.Title) || undefined // Add layer Title as legend title if showing multiple layers
});
return {
name: style.Name,
title: style.Title,
abstract: style.Abstract,
legend: legend
};
})
});
}
return result;
}
/** There is no way of finding out default style if no style has been selected :(
* If !supportsGetLegendGraphic - we have to just use the first available style (for each layer)
* This is because, to request a "default" legend we need GetLegendGraphics
**/
@computed get styles() {
if (this.catalogItem.uri !== undefined) {
// Try to extract a styles from the URL
const query: any = this.catalogItem.uri.query(true) ?? {};
if (isDefined(query.styles ?? query.STYLES))
return query.styles ?? query.STYLES;
}
if (!this.catalogItem.supportsGetLegendGraphic) {
return this.catalogItem.availableStyles
.map((layer) => {
if (layer.layerName && layer.styles.length > 0) {
return layer.styles[0].name ?? "";
}
return "";
})
.join(",");
}
}
@computed
get info(): StratumFromTraits<InfoSectionTraits>[] {
const result: StratumFromTraits<InfoSectionTraits>[] = [];
let firstDataDescription: string | undefined;
result.push(
createStratumInstance(InfoSectionTraits, {
name: i18next.t("models.webMapServiceCatalogItem.serviceDescription"),
contentAsObject: this.capabilities.Service as JsonObject,
// Hide big ugly table by default
show: false
})
);
const onlyHasSingleLayer = this.catalogItem.layersArray.length === 1;
if (onlyHasSingleLayer) {
// Clone the capabilitiesLayer as we'll modify it in a second
const out = Object.assign(
{},
this.capabilitiesLayers.get(this.catalogItem.layersArray[0])
) as any;
if (out !== undefined) {
// The Dimension object is really weird and has a bunch of stray text in there
if ("Dimension" in out) {
const goodDimension: any = {};
Object.keys(out.Dimension).forEach((k: any) => {
if (isNaN(k)) {
goodDimension[k] = out.Dimension[k];
}
});
out.Dimension = goodDimension;
}
// remove a circular reference to the parent
delete out._parent;
try {
result.push(
createStratumInstance(InfoSectionTraits, {
name: i18next.t(
"models.webMapServiceCatalogItem.dataDescription"
),
contentAsObject: out as JsonObject,
// Hide big ugly table by default
show: false
})
);
} catch (e) {
console.log(
`FAILED to create InfoSection with WMS layer Capabilities`
);
console.log(e);
}
}
}
for (const layer of this.capabilitiesLayers.values()) {
if (
!layer ||
!layer.Abstract ||
containsAny(layer.Abstract, WebMapServiceCatalogItem.abstractsToIgnore)
) {
continue;
}
const suffix =
this.capabilitiesLayers.size === 1 ? "" : ` - ${layer.Title}`;
const name = `Web Map Service Layer Description${suffix}`;
result.push(
createStratumInstance(InfoSectionTraits, {
name,
content: layer.Abstract
})
);
firstDataDescription = firstDataDescription || layer.Abstract;
}
// Show the service abstract if there is one and if it isn't the Geoserver default "A compliant implementation..."
const service = this.capabilities && this.capabilities.Service;
if (service) {
if (service.ContactInformation !== undefined) {
result.push(
createStratumInstance(InfoSectionTraits, {
name: i18next.t("models.webMapServiceCatalogItem.serviceContact"),
content: getServiceContactInformation(service.ContactInformation)
})
);
}
result.push(
createStratumInstance(InfoSectionTraits, {
name: i18next.t("models.webMapServiceCatalogItem.getCapabilitiesUrl"),
content: this.catalogItem.getCapabilitiesUrl
})
);
if (
service &&
service.Abstract &&
!containsAny(
service.Abstract,
WebMapServiceCatalogItem.abstractsToIgnore
) &&
service.Abstract !== firstDataDescription
) {
result.push(
createStratumInstance(InfoSectionTraits, {
name: i18next.t(
"models.webMapServiceCatalogItem.serviceDescription"
),
content: service.Abstract
})
);
}
// Show the Access Constraints if it isn't "none" (because that's the default, and usually a lie).
if (
service.AccessConstraints &&
!/^none$/i.test(service.AccessConstraints)
) {
result.push(
createStratumInstance(InfoSectionTraits, {
name: i18next.t(
"models.webMapServiceCatalogItem.accessConstraints"
),
content: service.AccessConstraints
})
);
}
}
return result;
}
@computed
get infoSectionOrder(): string[] {
let layerDescriptions = [`Web Map Service Layer Description`];
// If more than one layer, push layer description titles for each applicable layer
if (this.capabilitiesLayers.size > 1) {
layerDescriptions = [];
this.capabilitiesLayers.forEach((layer) => {
if (
layer &&
layer.Abstract &&
!containsAny(
layer.Abstract,
WebMapServiceCatalogItem.abstractsToIgnore
)
) {
layerDescriptions.push(
`Web Map Service Layer Description - ${layer.Title}`
);
}
});
}
return [
i18next.t("preview.disclaimer"),
i18next.t("description.name"),
...layerDescriptions,
i18next.t("preview.datasetDescription"),
i18next.t("preview.serviceDescription"),
i18next.t("models.webMapServiceCatalogItem.serviceDescription"),
i18next.t("preview.resourceDescription"),
i18next.t("preview.licence"),
i18next.t("preview.accessConstraints"),
i18next.t("models.webMapServiceCatalogItem.accessConstraints"),
i18next.t("preview.author"),
i18next.t("preview.contact"),
i18next.t("models.webMapServiceCatalogItem.serviceContact"),
i18next.t("preview.created"),
i18next.t("preview.modified"),
i18next.t("preview.updateFrequency"),
i18next.t("models.webMapServiceCatalogItem.getCapabilitiesUrl")
];
}
@computed
get shortReport() {
const catalogItem = this.catalogItem;
if (catalogItem.isShowingDiff) {
const format = "yyyy/mm/dd";
const d1 = dateFormat(catalogItem.firstDiffDate, format);
const d2 = dateFormat(catalogItem.secondDiffDate, format);
return `Showing difference image computed for ${catalogItem.diffStyleId} style on dates ${d1} and ${d2}`;
}
}
@computed
get rectangle(): StratumFromTraits<RectangleTraits> | undefined {
const layers: CapabilitiesLayer[] = [...this.capabilitiesLayers.values()]
.filter((layer) => layer !== undefined)
.map((l) => l!);
// Get union of bounding rectangles for all layers
const allLayersRectangle = layers.reduce<Rectangle | undefined>(
(unionRectangle, layer) => {
// Convert to cesium Rectangle (so we can use Rectangle.union)
const latLonRect = getRectangleFromLayer(layer);
if (
!isDefined(latLonRect?.west) ||
!isDefined(latLonRect?.south) ||
!isDefined(latLonRect?.east) ||
!isDefined(latLonRect?.north)
)
return;
const cesiumRectangle = Rectangle.fromDegrees(
latLonRect?.west,
latLonRect?.south,
latLonRect?.east,
latLonRect?.north
);
if (!unionRectangle) {
return cesiumRectangle;
}
return Rectangle.union(unionRectangle, cesiumRectangle);
},
undefined
);
if (
allLayersRectangle &&
isDefined(allLayersRectangle.west) &&
isDefined(allLayersRectangle.south) &&
isDefined(allLayersRectangle.east) &&
isDefined(allLayersRectangle.north)
) {
return {
west: CesiumMath.toDegrees(allLayersRectangle.west),
south: CesiumMath.toDegrees(allLayersRectangle.south),
east: CesiumMath.toDegrees(allLayersRectangle.east),
north: CesiumMath.toDegrees(allLayersRectangle.north)
};
}
}
@computed
get isGeoServer(): boolean | undefined {
const keyword = this.capabilities?.Service?.KeywordList?.Keyword;
return (
(isReadOnlyArray(keyword) && keyword.indexOf("GEOSERVER") >= 0) ||
keyword === "GEOSERVER" ||
this.catalogItem.url?.toLowerCase().includes("geoserver")
);
}
// TODO - There is possibly a better way to do this
@computed
get isThredds(): boolean {
if (
this.catalogItem.url &&
(this.catalogItem.url.indexOf("thredds") > -1 ||
this.catalogItem.url.indexOf("tds") > -1)
) {
return true;
}
return false;
}
// TODO - Geoserver also support NCWMS via a plugin, just need to work out how to detect that
@computed
get isNcWMS(): boolean {
if (this.catalogItem.isThredds) return true;
return false;
}
@computed
get isEsri(): boolean {
if (this.catalogItem.url !== undefined)
return (
this.catalogItem.url.toLowerCase().indexOf("mapserver/wmsserver") > -1
);
return false;
}
@computed
get supportsGetLegendGraphic(): boolean {
const capabilities = this.capabilities?.json?.Capability;
return (
isDefined(this.capabilities?.json?.["xmlns:sld"]) ||
isDefined(capabilities?.Request?.GetLegendGraphic) ||
(Array.isArray(capabilities?.ExtendedCapabilities?.ExtendedRequest) &&
capabilities.ExtendedCapabilities.ExtendedRequest.find(
(r: JsonObject) => r?.Request === "GetLegendGraphic"
)) ||
(this.catalogItem.isGeoServer ?? false) ||
(this.catalogItem.isNcWMS ?? false)
);
}
@computed
get supportsGetTimeseries() {
// Don't use GetTimeseries if there is only one timeslice
if ((this.catalogItem.discreteTimes?.length ?? 0) <= 1) return false;
const capabilities = this.capabilities?.json?.Capability;
return !!(
isDefined(capabilities?.Request?.GetTimeseries) ||
(Array.isArray(capabilities?.ExtendedCapabilities?.ExtendedRequest) &&
capabilities.ExtendedCapabilities.ExtendedRequest.find(
(r: JsonObject) => r?.Request === "GetTimeseries"
))
);
}
@computed
get supportsColorScaleRange(): boolean {
return this.catalogItem.isNcWMS;
}
@computed
get discreteTimes(): { time: string; tag: string | undefined }[] | undefined {
const result = [];
for (const layer of this.capabilitiesLayers.values()) {
if (!layer) {
continue;
}
const dimensions = this.capabilities.getInheritedValues(
layer,
"Dimension"
);
const timeDimension = dimensions.find(
(dimension) => dimension.name.toLowerCase() === "time"
);
if (!timeDimension) {
continue;
}
let extent: string = timeDimension;
// WMS 1.1.1 puts dimension values in an Extent element instead of directly in the Dimension element.
const extentElements = this.capabilities.getInheritedValues(
layer,
"Extent"
);
const extentElement = extentElements.find(
(extent) => extent.name.toLowerCase() === "time"
);
if (extentElement) {
extent = extentElement;
}
if (!extent || !extent.split) {
continue;
}
const values = extent.split(",");
for (let i = 0; i < values.length; ++i) {
const value = values[i];
const isoSegments = value.split("/");
if (isoSegments.length === 1) {
result.push({
time: values[i],
tag: undefined
});
} else {
createDiscreteTimesFromIsoSegments(
result,
isoSegments[0],
isoSegments[1],
isoSegments[2],
this.catalogItem.maxRefreshIntervals
);
}
}
}
return result;
}
@computed get initialTimeSource() {
return "now";
}
@computed get currentTime() {
// Get default times for all layers
const defaultTimes = filterOutUndefined(
Array.from(this.capabilitiesLayers).map(([layerName, layer]) => {
if (!layer) return;
const dimensions = this.capabilities.getInheritedValues(
layer,
"Dimension"
);
const timeDimension = dimensions.find(
(dimension) => dimension.name.toLowerCase() === "time"
);
return timeDimension?.default;
})
);
// From WMS 1.3.0 spec:
// For the TIME parameter, the special keyword “current” may be used if the <Dimension name="time"> service metadata element includes a nonzero value for the “current” attribute, as described in C.2.
// The expression “TIME=current” means “send the most current data available”.
// Here we return undefined, because WebMapServiceCapabilitiesStratum.initialTimeSource is set to "now"
if (defaultTimes[0] === "current") {
return undefined;
}
// Return first default time
return defaultTimes[0];
}
/** Prioritize format of GetFeatureInfo:
* - JSON/GeoJSON
* - If ESRI, then we prioritise XML next
* - HTML
* - GML
* - XML
* - Plain text
*
* If no matching format can be found in GetCapabilities, then Cesium will use defaults (see `WebMapServiceImageryProvider.DefaultGetFeatureInfoFormats`)
*
* If supportsGetTimeseries, use CSV
*/
@computed get getFeatureInfoFormat():
| StratumFromTraits<GetFeatureInfoFormat>
| undefined {
const formats: string | string[] | undefined =
this.capabilities.json?.Capability?.Request?.GetFeatureInfo?.Format;
const formatsArray = isJsonArray(formats)
? formats
: isJsonString(formats)
? [formats]
: [];
if (this.catalogItem.supportsGetTimeseries) {
return { format: "text/csv", type: "text" };
}
if (formatsArray.includes("application/json"))
return { format: "application/json", type: "json" };
if (formatsArray.includes("application/geo+json"))
return { format: "application/geo+json", type: "json" };
if (formatsArray.includes("application/vnd.geo+json"))
return { format: "application/vnd.geo+json", type: "json" };
// Special case for Esri WMS, use XML before HTML/GML
// as HTML includes <table> with rowbg that is hard to read
if (this.isEsri && formatsArray.includes("text/xml")) {
return { format: "text/xml", type: "xml" };
}
if (formatsArray.includes("text/html"))
return { format: "text/html", type: "html" };
if (formatsArray.includes("application/vnd.ogc.gml"))
return { format: "application/vnd.ogc.gml", type: "xml" };
// For non-Esri services, we use XML after HTML/GML
if (formatsArray.includes("text/xml")) {
return { format: "text/xml", type: "xml" };
}
if (formatsArray.includes("text/plain"))
return { format: "text/plain", type: "text" };
}
/** If supportsGetTimeseries, override the "request" parameter in GetFeatureInfo to be "GetTimeseries".
* We also set time to empty, so we get values for all times (as opposed to just the current time)
*/
@computed get getFeatureInfoParameters() {
if (this.catalogItem.supportsGetTimeseries) {
return { request: "GetTimeseries", time: "" };
}
return undefined;
}
/** If getFeatureInfoFormat is text/csv, set featureInfoTemplate to show chart. */
@computed
get featureInfoTemplate() {
if (this.catalogItem.getFeatureInfoFormat.format === "text/csv")
return createStratumInstance(FeatureInfoTemplateTraits, {
template: `{{terria.timeSeries.chart}}`,
showFeatureInfoDownloadWithTemplate: true
});
}
@computed get linkedWcsParameters() {
// Get outputCrs
// Note: this will be overridden by `WebCoverageServiceDescribeCoverageStratum` if a better outputCrs is found
let outputCrs = this.availableCrs[0];
// Unless it is Web Mercator of course - that would be stupid
// If this is the case - use 4326
outputCrs =
outputCrs && SUPPORTED_CRS_3857.includes(outputCrs)
? "EPSG:4326"
: outputCrs;
// Get WCS subsets from time and WMS dimensions
// These are used to "subset" WCS coverage (dataset)
// This is used to flag subsets (dimensions) which have multiple values
// Each element in this array represents the **actual** value used for a subset which has multiple values
const duplicateSubsetValues: StratumFromTraits<KeyValueTraits>[] = [];