-
Notifications
You must be signed in to change notification settings - Fork 0
/
EDC_OGC.py
1436 lines (1145 loc) · 55.5 KB
/
EDC_OGC.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
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
#
# Project: Euro Data Cube <http://eurodatacube.com>
#
#
#-------------------------------------------------------------------------------
# Copyright (C) 2020 EOX IT Services GmbH <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This code was developed based on SentinelHub plugin by Sinergise ltd.
# Original SentinelHub plugin : <https://github.com/sinergise/qgis_sentinel_hub/tree/master/SentinelHub>.
# copyright : (C) 2017 by Sentinel Hub, Sinergise ltd.
# email : [email protected]
#-------------------------------------------------------------------------------
# This looks like the best way to make plugin compatible for QGIS versions 2.* and 3.0
from sys import version_info
def is_qgis_version_3():
return version_info[0] >= 3
import os.path
import requests
import time
import calendar
import datetime
import math
import re
import ast
import json
from xml.etree import ElementTree
try:
from urllib.parse import quote_plus
except ImportError:
from urllib import quote_plus
from . import resources # this import is used because it imports resources.qrc
from .EDC_OGC_dockwidget import EDC_OGC_DockWidget
from . import Settings
from qgis.core import QgsRasterLayer, QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsRectangle, QgsMessageLog, QgsApplication
if is_qgis_version_3():
from qgis.utils import Qgis
from qgis.core import QgsProject
from PyQt5.QtCore import QSettings, QTranslator, qVersion, QCoreApplication, Qt, QDate
from PyQt5.QtGui import QIcon, QTextCharFormat
from PyQt5.QtWidgets import QAction, QFileDialog
else:
from qgis.utils import QGis as Qgis
from qgis.core import QgsMapLayerRegistry as QgsProject
from qgis.gui import QgsMessageBar
from PyQt4.QtCore import QSettings, QTranslator, qVersion, QCoreApplication, Qt, QDate
from PyQt4.QtGui import QIcon, QAction, QTextCharFormat, QFileDialog
POP_WEB = 'EPSG:3857'
WGS84 = 'EPSG:4326'
class InvalidInstanceId(ValueError):
pass
class Message: # Don't use Enum classes as some older Python versions don't have them
INFO = ('Info', Qgis.Info if is_qgis_version_3() else QgsMessageBar.INFO)
WARNING = ('Warning', Qgis.Warning if is_qgis_version_3() else QgsMessageBar.WARNING)
CRITICAL = ('Error', Qgis.Critical if is_qgis_version_3() else QgsMessageBar.CRITICAL)
SUCCESS = ('Success', Qgis.Success if is_qgis_version_3() else QgsMessageBar.SUCCESS)
class Capabilities:
""" Stores info about capabilities of EDC-OGC services
"""
class Layer:
""" Stores info about EDC-OGC WMS layer
"""
def __init__(self, layer_id, name, styles=None, info='', data_source=None):
self.id = layer_id
self.name = name
self.info = info
self.data_source = data_source
self.styles = styles
class CRS:
""" Stores info about available CRS at EDC-OGC Hub WMS
"""
def __init__(self, crs_id, name):
self.id = crs_id
self.name = name
def __init__(self, base_url=''):
self.base_url = base_url
self.wavelengths = {}
self.dimensions = {}
self.layers = {}
self.collections=[]
self.collection_list = {}
self.crs_list = []
def map_layers(self, layer, name_space, layers_group):
info_node = layer.find('{}Abstract'.format(name_space))
style_list= []
styles = layer.findall('./{0}Style'.format(name_space))
for style in styles:
style_list.append(style.find('{}Name'.format(name_space)).text)
layers_group.append(self.Layer(layer.find('{}Name'.format(name_space)).text,
layer.find('{}Title'.format(name_space)).text,
style_list,
info_node.text if info_node is not None else ''))
layers_group.sort(key=lambda l: l.name)
def load_xml(self, xml_root):
""" Loads info from getCapabilities.xml
"""
if xml_root.tag.startswith('{'):
namespace = '{}}}'.format(xml_root.tag.split('}')[0])
else:
namespace = ''
for layer in xml_root.findall('./{0}Capability/{0}Layer/{0}Layer'.format(namespace)):
layer_name = layer.find('{}Title'.format(namespace)).text
sub_layers = layer.findall('./{0}Layer'.format(namespace))
dimensions = layer.find('{}Dimension[@name="dim_bands"]'.format(namespace))
wavelengths = layer.find('{}Dimension[@name="dim_wavelengths"]'.format(namespace))
self.wavelengths[layer_name] = wavelengths.text.split(',') if wavelengths is not None else []
self.dimensions[layer_name] = dimensions.text.split(',') if dimensions is not None else []
self.collection_list[layer_name] = layer.find('{}Name'.format(namespace)).text
self.map_layers(layer, namespace, self.collections)
sublayers= []
if len(sub_layers) == 0 :
self.map_layers(layer, namespace, sublayers)
else :
for sub_layer in sub_layers:
self.map_layers(sub_layer, namespace, sublayers)
self.layers[layer_name]= sublayers
self.crs_list = []
for crs in xml_root.findall('./{0}Capability/{0}Layer/{0}CRS'.format(namespace)):
self.crs_list.append(self.CRS(crs.text, crs.text.replace(':', ': ')))
self._sort_crs_list()
def load_json(self, json_dict):
""" Loads info from getCapabilities.json
"""
try:
json_layers = {json_layer['id']: json_layer for json_layer in json_dict['layers']}
for layer in self.layers:
json_layer = json_layers.get(layer.id)
if json_layer:
layer.data_source = json_layer['dataset']
except KeyError:
pass
def _sort_crs_list(self):
""" Sorts list of CRS so that 3857 and 4326 are on the top
"""
new_crs_list = []
for main_crs in [POP_WEB, WGS84]:
for index, crs in enumerate(self.crs_list):
if crs and crs.id == main_crs:
new_crs_list.append(crs)
self.crs_list[index] = None
for crs in self.crs_list:
if crs:
new_crs_list.append(crs)
self.crs_list = new_crs_list
class EDC_OGC:
def __init__(self, iface):
"""Constructor.
"""
# Save reference to the QGIS interface
self.iface = iface
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
self.plugin_version = self.get_plugin_version()
"""
# This could be used for translating plugin into user's local language
locale = QSettings().value('locale/userLocale') # Some OS will return None
locale = locale[0:2] if locale else 'en'
locale_path = os.path.join(
self.plugin_dir,
'i18n',
'Euro Data Cube{}.qm'.format(locale))
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
if qVersion() > '4.3.3':
QCoreApplication.installTranslator(self.translator)
"""
# Declare instance attributes
self.actions = []
self.menu = self.translate(u'&Euro Data Cube')
self.toolbar = self.iface.addToolBar(u'Euro Data Cube')
self.toolbar.setObjectName(u'Euro Data Cube')
self.pluginIsActive = False
self.dockwidget = None
self.instances = {'Default (pre-configured layers)': ''}
self.base_url = None
self.service_url = None
self.data_source = None
# Set value
self.base_url = QSettings().value(Settings.service_url_location, '')
self.download_folder = QSettings().value(Settings.download_folder_location, '')
self._check_local_variables()
self.service_type = 'wms'
self.qgis_layers = []
self.capabilities = Capabilities('')
self.active_time = 'time0'
self.time0 = ''
self.time1 = ''
self.time1 = ''
self.isDimensionsSelected = False
self.dim_bands = ''
self.dim_wavelengths = ''
self.download_current_window = True
self.custom_bbox_params = {}
for name in ['latMin', 'latMax', 'lngMin', 'lngMax']:
self.custom_bbox_params[name] = ''
self.layer_selection_event = None
@staticmethod
def translate(message):
"""Get the translation for a string using Qt translation API.
"""
return QCoreApplication.translate('Euro Data Cube', message)
def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True,
status_tip=None, whats_this=None, parent=None):
"""Add a toolbar icon to the toolbar.
"""
icon = QIcon(icon_path)
action = QAction(icon, text, parent)
action.triggered.connect(callback)
action.setEnabled(enabled_flag)
if status_tip is not None:
action.setStatusTip(status_tip)
if whats_this is not None:
action.setWhatsThis(whats_this)
if add_to_toolbar:
self.toolbar.addAction(action)
if add_to_menu:
self.iface.addPluginToWebMenu(
self.menu,
action)
self.actions.append(action)
return action
def initGui(self): # This method is called by QGIS
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
icon_path = ':/plugins/Euro Data Cube/favicon.ico'
self.add_action(
icon_path,
text=self.translate(u'Euro Data Cube'),
callback=self.run,
parent=self.iface.mainWindow())
def init_gui_settings(self):
"""Fill combo boxes:
Layers - Renderers
Priority
"""
self.update_instance_props(instance_changed=True)
self.dockwidget.baseUrl.setText(self.base_url)
self.dockwidget.destination.setText(self.download_folder)
self.set_values()
self.dockwidget.priority.clear()
self.dockwidget.priority.addItems([priority[1] for priority in Settings.priorities])
self.dockwidget.format.clear()
self.dockwidget.format.addItems([image_format[1] for image_format in Settings.image_formats])
def _check_local_variables(self):
""" Checks if local variables are of type string or unicode. If they are not it sets them to ''
"""
valid_types = str
if not isinstance(self.base_url, valid_types):
self.base_url = ''
QSettings().setValue(Settings.service_url_location, self.base_url)
if not isinstance(self.download_folder, valid_types):
self.download_folder = ''
QSettings().setValue(Settings.download_folder_location, self.download_folder)
def set_values(self):
""" Updates some values for the wcs download request
"""
self.dockwidget.inputResX.setText(Settings.parameters_wcs['resx'])
self.dockwidget.inputResY.setText(Settings.parameters_wcs['resy'])
self.dockwidget.latMin.setText(self.custom_bbox_params['latMin'])
self.dockwidget.latMax.setText(self.custom_bbox_params['latMax'])
self.dockwidget.lngMin.setText(self.custom_bbox_params['lngMin'])
self.dockwidget.lngMax.setText(self.custom_bbox_params['lngMax'])
def get_plugin_version(self):
"""
:return: Plugin version
:rtype: str
"""
try:
with open(os.path.join(self.plugin_dir, 'metadata.txt')) as metadata_file:
for line in metadata_file:
if line.startswith('version'):
return line.split("=")[1].strip()
except IOError:
return '?'
# --------------------------------------------------------------------------
def show_message(self, message, message_type):
""" Show message for user
:param message: Message for user
:param message: str
:param message_type: Type of message
:param message_type: Attributes of Message class
"""
self.iface.messageBar().pushMessage(message_type[0], message, level=message_type[1])
def missing_url(self):
"""Show message about missing URL"""
self.show_message("Please set ogc-edc URL first.", Message.INFO)
# --------------------------------------------------------------------------
def update_instance_props(self, instance_changed=False):
""" Update lists of layers and CRS available with current ogc-edc url
:param instance_changed: True if url has changed, False otherwise
:type instance_changed: bool
"""
self.dockwidget.createLayerLabel.setText('Create new WMS layer')
if self.capabilities:
collection_index = self.dockwidget.collections.currentIndex()
self.dockwidget.collections.clear()
self.dockwidget.collections.addItems([collection.name for collection in self.capabilities.collections])
if not instance_changed:
self.dockwidget.collections.setCurrentIndex(collection_index)
# layer_index = self.dockwidget.layers.currentIndex()
# self.dockwidget.layers.clear()
# self.dockwidget.layers.addItems([layer.name for layer in self.capabilities.layers[self.dockwidget.collections.currentText()]])
# if not instance_changed:
# self.dockwidget.layers.setCurrentIndex(layer_index)
self.dockwidget.epsg.clear()
self.dockwidget.epsg.addItems([crs.name for crs in self.capabilities.crs_list])
def update_current_wms_layers(self, selected_layer=None):
"""
Updates List of Qgis layers
:return:
"""
self.qgis_layers = self.get_qgis_layers()
layer_names = []
for layer in self.qgis_layers:
layer_names.append(layer.name())
self.dockwidget.qgisLayerList.clear()
self.dockwidget.qgisLayerList.addItems(layer_names)
if selected_layer:
for index, layer in enumerate(self.qgis_layers):
if layer == selected_layer:
self.dockwidget.qgisLayerList.setCurrentIndex(index)
def get_qgis_layers(self):
"""
:return: List of existing QGIS layers in the same order as they are in the QGIS menu
:rtype: list(QgsMapLayer)
"""
if is_qgis_version_3():
return [tree_layer.layer() for tree_layer in QgsProject.instance().layerTreeRoot().findLayers()]
return self.iface.legendInterface().layers()
# --------------------------------------------------------------------------
def on_close_plugin(self):
"""Cleanup necessary items here when plugin dockwidget is closed"""
# disconnects
self.dockwidget.closingPlugin.disconnect(self.on_close_plugin)
self.pluginIsActive = False
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI."""
for action in self.actions:
self.iface.removePluginWebMenu(
self.translate(u'&Euro Data Cube'),
action)
self.iface.removeToolBarIcon(action)
del self.toolbar
# --------------------------------------------------------------------------
def get_wms_uri(self):
""" Generate URI for WMS request from parameters """
uri = ''
additional_parameters = ''
if self.dockwidget.wave_check.isChecked():
additional_parameters = '&dim_wavelengths={}'.format(self.dim_wavelengths)
elif self.dockwidget.dim_check.isChecked():
additional_parameters = '&dim_bands={}'.format(self.dim_bands)
request_parameters = list(Settings.parameters_wms.items()) + list(Settings.parameters.items())
for parameter, value in request_parameters:
uri += '{}={}&'.format(parameter, value)
# Every parameter that QGIS layer doesn't use by default must be in url
# And url has to be encoded
url = '{}?Time={}{}& &priority={}&maxcc={}'.format(self.service_url, self.get_time(),additional_parameters,
Settings.parameters['priority'], Settings.parameters['maxcc'])
return '{}url={}'.format(uri, quote_plus(url))
def get_wcs_url(self, bbox, crs=None):
""" Generate URL for WCS request from parameters
:param bbox: Bounding box in form of "xmin,ymin,xmax,ymax"
:type bbox: str
:param crs: CRS of bounding box
:type crs: str or None
"""
url = '{}?'.format(self.service_url)
request_parameters = list(Settings.parameters_wcs.items()) + list(Settings.parameters.items())
for parameter, value in request_parameters:
if parameter in ('resx', 'resy'):
value = value.strip('m') + 'm'
if parameter == 'crs':
value = crs if crs else Settings.parameters['crs']
url += '{}={}&'.format(parameter, value)
return '{}bbox={}'.format(url, bbox)
def get_wfs_url(self, time_range):
""" Generate URL for WFS request from parameters """
url = '{}?'.format(self.service_url)
for parameter, value in Settings.parameters_wfs.items():
url += '{}={}&'.format(parameter, value)
return '{}bbox={}&time={}&srsname={}'.format(url, self.bbox_to_string(self.get_bbox()), time_range,
Settings.parameters['crs'])
@staticmethod
def get_capabilities_url(base_url, service, get_json=False):
""" Generates url for obtaining service capabilities
"""
url = '{}?service={}&request=GetCapabilities&version=1.3.0'.format(base_url, service)
if get_json:
return url + '&format=application/json'
return url
def get_instances_list(self, base_url):
if base_url != '' :
url = base_url + '/instances.json'
else:
return
response = self.download_from_url(url, raise_invalid_id=True)
if not response:
return None
instances = json.loads(response.text)
for instance in instances:
self.instances[instance['name']] = instance['id']
self.dockwidget.instanceId.clear()
self.dockwidget.instanceId.addItems([name for name in self.instances.keys()])
self.dockwidget.instanceId.setCurrentIndex(0)
def change_instance_ID(self, url):
if not url or isinstance(url, int):
if url == '' or self.base_url == '' :
self.show_message("Please provide a valid URL", Message.INFO)
return
url = self.base_url
if self.dockwidget.instanceId.currentIndex() >= 0:
instance_extension = self.instances[self.dockwidget.instanceId.currentText()]
self.service_url = url + instance_extension
capabilities = self.get_capabilities(self.service_url)
if capabilities:
self.capabilities = capabilities
self.update_instance_props(instance_changed=True)
if self.service_url:
self.show_message("New URL and layers set.", Message.SUCCESS)
self.update_selected_collection()
return capabilities
def get_capabilities(self, base_url, service='wms'):
""" Get capabilities of desired service
:param base_url: EDC-OGC service url
:type base_url: str
:param service: Service (wms, wfs, wcs)
:type service: str
:return: Capabilities class or none
:rtype: Capabilities or None
"""
response = self.download_from_url(self.get_capabilities_url(base_url, service), raise_invalid_id=True)
if not response:
return None
capabilities = Capabilities(base_url)
xml_root = ElementTree.fromstring(response.content)
capabilities.load_xml(xml_root)
json_response = self.download_from_url(self.get_capabilities_url(base_url, service, get_json=True), raise_invalid_id=True)
if json_response:
try:
capabilities.load_json(json_response.json())
except ValueError:
pass
return capabilities
def download_wcs_data(self, url, filename):
"""
Download image from provided URL WCS request
:param url: WCS url request with specified bounding box
:param filename: filename of image
:return:
"""
with open(os.path.join(self.download_folder, filename), "wb") as download_file:
response = self.download_from_url(url, stream=True)
if response:
total_length = response.headers.get('content-length')
if total_length is None:
download_file.write(response.content)
else:
for data in response.iter_content(chunk_size=4096):
download_file.write(data)
downloaded = True
else:
downloaded = False
if downloaded:
self.show_message("Done downloading to {}".format(filename), Message.SUCCESS)
time.sleep(1)
else:
self.show_message("Failed to download from {} to {}".format(url, filename), Message.CRITICAL)
def download_from_url(self, url, stream=False, raise_invalid_id=False, ignore_exception=False):
""" Downloads data from url and handles possible errors
:param url: download url
:type url: str
:param stream: True if download should be streamed and False otherwise
:type stream: bool
:param raise_invalid_id: If True an InvalidInstanceId exception will be raised in case service returns HTTP 400
:type raise_invalid_id: bool
:param ignore_exception: If True no error messages will be shown in case of exceptions
:type ignore_exception: bool
:return: download response or None if download failed
:rtype: requests.response or None
"""
try:
proxy_dict, auth = self.get_proxy_config()
response = requests.get(url, stream=stream,
headers={'User-Agent': 'sh_qgis_plugin_{}'.format(self.plugin_version)},
proxies=proxy_dict, auth=auth)
response.raise_for_status()
except requests.RequestException as exception:
if ignore_exception:
return
if raise_invalid_id and isinstance(exception, requests.HTTPError) and exception.response.status_code == 400:
raise InvalidInstanceId()
self.show_message(self.get_error_message(exception), Message.CRITICAL)
response = None
return response
@staticmethod
def get_proxy_config():
""" Get proxy config from QSettings and builds proxy parameters
:return: dictionary of transfer protocols mapped to addresses, also authentication if set in QSettings
:rtype: (dict, requests.auth.HTTPProxyAuth) or (dict, None)
"""
enabled, host, port, user, password = EDC_OGC.get_proxy_from_qsettings()
proxy_dict = {}
if enabled and host:
port_str = ':{}'.format(port) if port else ''
for protocol in ['http', 'https', 'ftp']:
proxy_dict[protocol] = '{}://{}{}'.format(protocol, host, port_str)
auth = requests.auth.HTTPProxyAuth(user, password) if enabled and user and password else None
return proxy_dict, auth
@staticmethod
def get_proxy_from_qsettings():
""" Gets the proxy configuration from QSettings
:return: Proxy settings: flag specifying if proxy is enabled, host, port, user and password
:rtype: tuple(str)
"""
settings = QSettings()
settings.beginGroup('proxy')
enabled = str(settings.value('proxyEnabled')).lower() == 'true' # to be compatible with QGIS 2 and 3
# proxy_type = settings.value("proxyType")
host = settings.value('proxyHost')
port = settings.value('proxyPort')
user = settings.value('proxyUser')
password = settings.value('proxyPassword')
settings.endGroup()
return enabled, host, port, user, password
@staticmethod
def get_error_message(exception):
""" Creates an error message from the given exception
:param exception: Exception obtained during download
:type exception: requests.RequestException
:return: error message
:rtype: str
"""
message = '{}: '.format(exception.__class__.__name__)
if isinstance(exception, requests.ConnectionError):
message += 'Cannot access service, check your internet connection.'
enabled, host, port, _, _ = EDC_OGC.get_proxy_from_qsettings()
if enabled:
message += ' QGIS is configured to use proxy: {}'.format(host)
if port:
message += ':{}'.format(port)
return message
if isinstance(exception, requests.HTTPError):
try:
server_message = ''
for elem in ElementTree.fromstring(exception.response.content):
if 'ServiceException' in elem.tag:
server_message += elem.text.strip('\n\t ')
except ElementTree.ParseError:
server_message = exception.response.text.strip('\n\t ')
server_message = server_message.encode('ascii', errors='ignore').decode('utf-8')
if 'Config instance "instance.' in server_message:
url = server_message.split('"')[1][9:]
server_message = 'Invalid url: {}'.format(url)
return message + 'server response: "{}"'.format(server_message)
return message + str(exception)
# ----------------------------------------------------------------------------
def add_qgis_layer(self, on_top=False):
"""
Add WMS raster layer to canvas,
:param on_top: If True the layer will be added on top of all layers, if False it will be added on top of
currently selected layer.
:return: new layer
"""
if not self.service_url:
return self.missing_url()
self.update_parameters()
uri = self.get_wms_uri()
name = self.get_qgis_layer_name()
new_layer = QgsRasterLayer(uri, name, 'wms')
interface = self.iface
def errorCatcher(msg, tag, level):
if tag == 'WMS' and level != 0:
result = re.search('BAD REQUEST url: (.*)]', msg)
if result :
error_url = result.group(1)
response = requests.get(error_url)
dict_error = re.search(r'({.+})', response.text)
if dict_error :
error_content = dict_error.group(0)
message = ast.literal_eval(error_content)
interface.messageBar().pushMessage('Warning', '{}'.format(message["error"]["message"]), Qgis.Warning)
if is_qgis_version_3():
QgsApplication.messageLog().messageReceived.connect(errorCatcher)
else :
QgsMessageLog.instance().messageReceived.connect(errorCatcher)
if new_layer.isValid():
if on_top and self.get_qgis_layers():
self.iface.setActiveLayer(self.get_qgis_layers()[0])
QgsProject.instance().addMapLayer(new_layer)
self.update_current_wms_layers()
else:
self.show_message('Failed to create layer {}.'.format(name), Message.CRITICAL)
return new_layer
def get_bbox(self, crs=None):
"""
Get window bbox
"""
bbox = self.iface.mapCanvas().extent()
target_crs = QgsCoordinateReferenceSystem(crs if crs else Settings.parameters['crs'])
if is_qgis_version_3():
current_crs = QgsCoordinateReferenceSystem(self.iface.mapCanvas().mapSettings().destinationCrs().authid())
else:
current_crs = QgsCoordinateReferenceSystem(self.iface.mapCanvas().mapRenderer().destinationCrs().authid())
if current_crs != target_crs:
if is_qgis_version_3():
xform = QgsCoordinateTransform(current_crs, target_crs, QgsProject.instance())
else:
xform = QgsCoordinateTransform(current_crs, target_crs)
bbox = xform.transform(bbox) # if target CRS is UTM and bbox is out of UTM bounds this fails, not sure how to fix
return bbox
@staticmethod
def bbox_to_string(bbox, crs=None):
""" Transforms BBox object into string
"""
target_crs = QgsCoordinateReferenceSystem(crs if crs else Settings.parameters['crs'])
if target_crs.authid() == WGS84:
precision = 6
bbox_list = [bbox.yMinimum(), bbox.xMinimum(), bbox.yMaximum(), bbox.xMaximum()]
else:
precision = 2
bbox_list = [bbox.xMinimum(), bbox.yMinimum(), bbox.xMaximum(), bbox.yMaximum()]
return ','.join(map(lambda coord: str(round(coord, precision)), bbox_list))
def get_custom_bbox(self):
""" Creates BBox from values set by user
"""
lat_min = min(float(self.custom_bbox_params['latMin']), float(self.custom_bbox_params['latMax']))
lat_max = max(float(self.custom_bbox_params['latMin']), float(self.custom_bbox_params['latMax']))
lng_min = min(float(self.custom_bbox_params['lngMin']), float(self.custom_bbox_params['lngMax']))
lng_max = max(float(self.custom_bbox_params['lngMin']), float(self.custom_bbox_params['lngMax']))
return QgsRectangle(lng_min, lat_min, lng_max, lat_max)
def take_window_bbox(self):
"""
From Custom extent get values, save them and show them in UI
:return:
"""
bbox = self.get_bbox(crs=WGS84)
bbox_list = self.bbox_to_string(bbox, crs=WGS84).split(',')
self.custom_bbox_params['latMin'] = bbox_list[0]
self.custom_bbox_params['lngMin'] = bbox_list[1]
self.custom_bbox_params['latMax'] = bbox_list[2]
self.custom_bbox_params['lngMax'] = bbox_list[3]
self.set_values()
def get_bbox_size(self, bbox, crs=None):
""" Returns approximate width and height of bounding box in meters
"""
bbox_crs = QgsCoordinateReferenceSystem(crs if crs else Settings.parameters['crs'])
utm_crs = QgsCoordinateReferenceSystem(self.lng_to_utm_zone(
(bbox.xMinimum() + bbox.xMaximum()) / 2,
(bbox.yMinimum() + bbox.yMaximum()) / 2))
if is_qgis_version_3():
xform = QgsCoordinateTransform(bbox_crs, utm_crs, QgsProject.instance())
else:
xform = QgsCoordinateTransform(bbox_crs, utm_crs)
bbox = xform.transform(bbox)
width = abs(bbox.xMaximum() - bbox.xMinimum())
height = abs(bbox.yMinimum() - bbox.yMaximum())
return width, height
@staticmethod
def lng_to_utm_zone(longitude, latitude):
""" Calculates UTM zone from latitude and longitude"""
zone = int(math.floor((longitude + 180) / 6) + 1)
hemisphere = 6 if latitude > 0 else 7
return 'EPSG:32{0}{1:02d}'.format(hemisphere, zone)
def update_qgis_layer(self):
""" Updating layer in pyqgis somehow doesn't work therefore this method creates a new layer and deletes the
old one
"""
if not self.service_url:
return self.missing_url()
selected_index = self.dockwidget.qgisLayerList.currentIndex()
if selected_index < 0:
return
for layer in self.get_qgis_layers():
# QgsMessageLog.logMessage(str(layer.name()) + ' ' + str(self.qgis_layers[selected_index].name()))
if layer == self.qgis_layers[selected_index]:
self.iface.setActiveLayer(layer)
new_layer = self.add_qgis_layer()
if new_layer.isValid():
QgsProject.instance().removeMapLayer(layer)
self.update_current_wms_layers(selected_layer=new_layer)
return
self.show_message('Chosen layer {} does not exist anymore.'
''.format(self.dockwidget.qgisLayerList.currentText()), Message.INFO)
self.update_current_wms_layers()
def update_parameters(self):
"""
Update parameters from GUI
:return:
"""
if self.capabilities:
self.update_selected_crs()
self.update_selected_style()
Settings.parameters['time'] = self.get_time()
Settings.parameters['priority'] = Settings.priorities[self.dockwidget.priority.currentIndex()][0]
Settings.parameters['maxcc'] = str(self.dockwidget.maxcc.value())
def update_selected_crs(self):
""" Updates crs with selected EDC-OGC CRS
"""
crs_index = self.dockwidget.epsg.currentIndex()
wms_crs = self.capabilities.crs_list
if 0 <= crs_index < len(wms_crs):
Settings.parameters['crs'] = wms_crs[crs_index].id
def set_dimensions(self):
self.dim_bands = str(self.dockwidget.dimension_1.currentText()) + ',' + str(self.dockwidget.dimension_2.currentText()) + ',' + str(self.dockwidget.dimension_3.currentText())
def set_wavelengths(self):
self.dim_wavelengths = str(self.dockwidget.wavelength_1.currentText()) + ',' + str(self.dockwidget.wavelength_2.currentText()) + ',' + str(self.dockwidget.wavelength_3.currentText())
def clear_wavelengths_boxes(self):
self.dockwidget.wavelength_1.clear()
self.dockwidget.wavelength_2.clear()
self.dockwidget.wavelength_3.clear()
self.dim_wavelengths =''
def clear_dim_boxes(self):
self.dockwidget.dimension_1.clear()
self.dockwidget.dimension_2.clear()
self.dockwidget.dimension_3.clear()
self.dim_bands =''
def fill_dim_boxes(self):
self.dockwidget.dimension_1.addItems(self.capabilities.dimensions[self.dockwidget.collections.currentText()])
self.dockwidget.dimension_2.addItems(self.capabilities.dimensions[self.dockwidget.collections.currentText()])
self.dockwidget.dimension_3.addItems(self.capabilities.dimensions[self.dockwidget.collections.currentText()])
self.set_dimensions()
def fill_wave_boxes(self):
self.dockwidget.wavelength_1.addItems(self.capabilities.wavelengths[self.dockwidget.collections.currentText()])
self.dockwidget.wavelength_2.addItems(self.capabilities.wavelengths[self.dockwidget.collections.currentText()])
self.dockwidget.wavelength_3.addItems(self.capabilities.wavelengths[self.dockwidget.collections.currentText()])
self.set_wavelengths()
def update_selected_collection(self):
# for box in (self.dockwidget.horizontalLayout_13.itemAt(i) for i in range(self.dockwidget.horizontalLayout_13.count())):
# print(dir(box.widget()))
if self.dockwidget.collections.currentText() != "":
self.dockwidget.layers.clear()
self.clear_wavelengths_boxes()
self.clear_dim_boxes()
self.dockwidget.dim_check.setChecked(False)
self.dockwidget.wave_check.setChecked(False)
self.dockwidget.layers_check.setChecked(True)
# uncheck layers, dimension and wavelengths
self.check_layer_box()
self.check_dim_box()
self.check_wave_box()
def update_styles(self, layers, index):
self.dockwidget.styles.clear()
self.dockwidget.styles.addItems([style for style in layers[index].styles])
def update_selected_style(self):
wms_layers = self.capabilities.layers[self.dockwidget.collections.currentText()]
layer_index = self.dockwidget.layers.currentIndex()
styles = wms_layers[layer_index].styles
if 0 <= self.dockwidget.styles.currentIndex() < len(styles) :
Settings.parameters_wms['styles'] = self.dockwidget.styles.currentText()
def update_selected_layer(self):
""" Updates properties of selected OGC layer
"""
layers_index = self.dockwidget.layers.currentIndex()
if self.dockwidget.collections.currentText() != "":
wms_layers = self.capabilities.layers[self.dockwidget.collections.currentText()]
if 0 <= layers_index < len(wms_layers):
self.update_styles(wms_layers, layers_index)
self.update_parameters()
Settings.parameters['layers'] = wms_layers[layers_index].id
Settings.parameters_wcs['coverage'] = wms_layers[layers_index].id
Settings.parameters['title'] = wms_layers[layers_index].name
def update_maxcc_label(self):
"""
Update Max Cloud Coverage Label when slider value change
:return:
"""
self.dockwidget.maxccLabel.setText('Cloud coverage {}%'.format(self.dockwidget.maxcc.value()))
def get_time(self):
"""
Format time parameter according to settings
:return:
"""
if self.dockwidget.exactDate.isChecked():
return '{}/{}/P1D'.format(self.time0, self.time0)
if self.time0 == '':
return self.time1
if self.time1 == '':
return '{}/{}/P1D'.format(self.time0, datetime.datetime.now().strftime("%Y-%m-%d"))
return '{}/{}/P1D'.format(self.time0, self.time1)
def add_time(self):
"""
Add / update time parameter from calendar regrading which time was chosen and paint calendar
time0 - starting time
time1 - ending time