-
Notifications
You must be signed in to change notification settings - Fork 0
/
layertree2json.py
704 lines (558 loc) · 30 KB
/
layertree2json.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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
LayerTree2JSON
A QGIS plugin
Parse QGIS 3 project files and write a JSON config file with layer information.
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2022-07-05
git sha : $Format:%H$
copyright : (C) 2022 by Gerald Kogler/PSIG
email : [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. *
* *
***************************************************************************/
"""
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, QFileInfo, QUrl
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction
from qgis.core import QgsProject, Qgis, QgsLayerTreeLayer, QgsLayerTreeGroup, QgsVectorLayer, QgsAttributeEditorElement, QgsExpressionContextUtils, QgsProviderRegistry, QgsLayerNotesUtils
from qgis.gui import QgsGui
import json
import unicodedata
import webbrowser
import urllib.parse
from datetime import datetime
from .layertree2json_dialog import LayerTree2JSONDialog
from .layertree2json_dialog_settings import LayerTree2JSONDialogSettings, settings
import os.path
from tempfile import gettempdir
import paramiko
class LayerTree2JSON:
def __init__(self, iface):
# Save reference to the QGIS interface
self.iface = iface
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# initialize locale
locale = QSettings().value('locale/userLocale')[0:2]
locale_path = os.path.join(
self.plugin_dir,
'i18n',
'LayerTree2JSON_{}.qm'.format(locale))
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
QCoreApplication.installTranslator(self.translator)
# Declare instance attributes
self.actions = []
self.menu = self.tr(u'&LayerTree2JSON')
# Check if plugin was started the first time in current QGIS session
# Must be set in initGui() to survive plugin reloads
self.first_start = None
# noinspection PyMethodMayBeStatic
def tr(self, message):
"""Get the translation for a string using Qt translation API.
We implement this ourselves since we do not inherit QObject.
:param message: String for translation.
:type message: str, QString
:returns: Translated version of message.
:rtype: QString
"""
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return QCoreApplication.translate('LayerTree2JSON', 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.
:param icon_path: Path to the icon for this action. Can be a resource
path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
:type icon_path: str
:param text: Text that should be shown in menu items for this action.
:type text: str
:param callback: Function to be called when the action is triggered.
:type callback: function
:param enabled_flag: A flag indicating if the action should be enabled
by default. Defaults to True.
:type enabled_flag: bool
:param add_to_menu: Flag indicating whether the action should also
be added to the menu. Defaults to True.
:type add_to_menu: bool
:param add_to_toolbar: Flag indicating whether the action should also
be added to the toolbar. Defaults to True.
:type add_to_toolbar: bool
:param status_tip: Optional text to show in a popup when mouse pointer
hovers over the action.
:type status_tip: str
:param parent: Parent widget for the new action. Defaults None.
:type parent: QWidget
:param whats_this: Optional text to show in the status bar when the
mouse pointer hovers over the action.
:returns: The action that was created. Note that the action is also
added to self.actions list.
:rtype: QAction
"""
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:
# Adds plugin icon to Plugins toolbar
self.iface.addToolBarIcon(action)
if add_to_menu:
self.iface.addPluginToWebMenu(
self.menu,
action)
self.actions.append(action)
return action
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
self.add_action(
os.path.join(os.path.dirname(__file__), "icon.png"),
text=self.tr(u'Parse Layers and save JSON'),
callback=self.run,
parent=self.iface.mainWindow())
self.add_action(
os.path.join(os.path.dirname(__file__), "help.svg"),
text=self.tr(u'Help'),
callback=self.help,
parent=self.iface.mainWindow(),
add_to_toolbar=False)
# will be set False in run()
self.first_start = True
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI."""
for action in self.actions:
self.iface.removePluginWebMenu(
self.tr(u'&LayerTree2JSON'),
action)
self.iface.removeToolBarIcon(action)
def show_online_file(self, project_name):
# add timestamp to path to avoid cache
webbrowser.open(self.projectHost + '/' + self.projectJsonPath2 + project_name + self.projectExtension + '.json?' + str(datetime.timestamp(datetime.now())))
def show_project(self):
path = self.projectName
# exception for project ctbb which has different sub projects
if path == 'ctbb':
path += '/index'
if self.projectFilename != 'poum' and self.projectFilename != 'guia' and self.projectFilename != 'activitats':
path += '_' + self.projectFilename.replace('.qgs', '')
path += '.php'
webbrowser.open(self.projectHost + '/' + path)
def radioStateLocal(self, state):
if state.isChecked() == True:
self.dlg.radioProject.setEnabled(False)
def radioStateUpload(self, state):
if state.isChecked() == True:
self.dlg.radioProject.setEnabled(True)
def inputsFtpOk(self, host=None, user=None, password=None):
host = host or self.projectHost
user = user or self.projectUser
password = password or self.projectPassword
if host == "" or user == "" or password == "":
self.iface.messageBar().pushMessage(
"Warning", "You have to define Host, User and Password in Project Settings in order to use FTP",
level=Qgis.Warning, duration=3)
return False
else:
return True
def mk_each_dir(self, sftp, inRemoteDir):
currentDir = '/' # Slash '/' is hardcoded because ftp always uses slash
for dirElement in inRemoteDir.split('/'):
if dirElement:
currentDir += dirElement + '/'
try:
sftp.mkdir(currentDir)
except:
pass # fail silently if remote directory already exists
def connectToFtp(self, localFilePath=False, uploadPath=False, uploadFile=False, host=None, user=None, password=None):
host = host or self.projectHost
user = user or self.projectUser
password = password or self.projectPassword
try:
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(
hostname=host,
username=user,
password=password
)
ftp_client=ssh_client.open_sftp()
if localFilePath and uploadPath and uploadFile:
# Test if remote_path exists and create of not
try:
ftp_client.chdir(uploadPath)
except IOError:
try:
self.mk_each_dir(ftp_client, uploadPath)
except IOError:
pass
#print(localFilePath, "->", uploadPath + uploadFile)
ftp_client.put(localFilePath, uploadPath + uploadFile)
#self.iface.messageBar().pushMessage("Success", "File UPLOADED to host " + host, level=Qgis.Success, duration=3)
else:
self.iface.messageBar().pushMessage("Success", "FTP connection ESTABLISHED to host " + host + " without uploading file", level=Qgis.Success, duration=3)
ftp_client.close()
ssh_client.close()
except:
self.iface.messageBar().pushMessage("Warning", "FTP connection FAILED to host " + host, level=Qgis.Warning, duration=3)
def replaceSpecialChar(self, text):
chars = "!\"#$%&'()*+,./:;<=>?@[\\]^`{|}~¬·"
for c in chars:
text = text.replace(c, "")
return text
def stripAccents(self, str):
return ''.join(c for c in unicodedata.normalize('NFD', str)
if unicodedata.category(c) != 'Mn')
def getDataProvider(self, layerId, type):
# https://gis.stackexchange.com/a/447119/60146
layer = QgsProject.instance().mapLayer(layerId)
uri_components = QgsProviderRegistry.instance().decodeUri(layer.dataProvider().name(), layer.publicSource())
if type and type in uri_components:
return uri_components[type]
else:
return None
# code based on https://github.com/geraldo/qgs-layer-parser
def getLayerTree(self, node):
obj = {}
if isinstance(node, QgsLayerTreeLayer):
obj['name'] = node.name()
obj['id'] = node.layerId()
obj['provider'] = node.layer().providerType()
obj['visible'] = node.isVisible()
obj['hidden'] = node.name().startswith("@") # hide layer from layertree
if obj['hidden']:
obj['visible'] = True # hidden layers/groups have to be visible by default
obj['showlegend'] = not node.name().startswith("~") and not node.name().startswith("¬") # don't show legend in layertree
# WFS vector layers
vectorial = False
# print("Vector layers:", QgsProject.instance().readListEntry("WFSLayers", "/")[0]);
if node.layerId() in QgsProject.instance().readListEntry("WFSLayers", "/")[0]:
vectorial = True
obj['vectorial'] = vectorial
# base layer
print(node.name(), node.layer().type())
# breaking change: 'QgsMapLayerType.RasterLayer' renamed to 'LayerType.Raster'
if (str(node.layer().type()) == 'QgsMapLayerType.RasterLayer' or str(node.layer().type()) == 'LayerType.Raster') and node.layer().providerType() == 'wms':
obj['type'] = "baselayer"
obj['url'] = self.getDataProvider(node.layerId(), 'url')
else:
obj['type'] = "layer"
obj['path'] = self.getDataProvider(node.layerId(), 'path')
obj['qgisname'] = node.name() # internal qgis layer name with all special characters
obj['indentifiable'] = node.layerId() not in QgsProject.instance().nonIdentifiableLayers()
obj['fields'] = []
obj['actions'] = []
obj['external'] = node.name().startswith("¬")
layer_package_name = QgsExpressionContextUtils.layerScope(node.layer()).variable("layer_package_name")
if layer_package_name:
obj['package_name'] = layer_package_name
layer_package_format = QgsExpressionContextUtils.layerScope(node.layer()).variable("layer_package_format")
if layer_package_format:
obj['package_format'] = layer_package_format
if hasattr(self, 'projectTilecache'):
if self.projectTilecache:
obj['mapproxy'] = self.projectName + "_layer_" + self.replaceSpecialChar(self.stripAccents(obj['name'].lower().replace(' ', '_')))
# remove first character
if not obj['showlegend']:
obj['name'] = node.name()[1:]
# fetch layer directly from external server (not from QGIS nor mapproxy)
if obj['external']:
obj['name'] = node.name()[1:]
src = QgsProject.instance().mapLayer(node.layerId()).source()
# wms url
istart = src.index("url=")+4
try:
iend = src.index("&", istart)
except ValueError:
iend = len(src)
obj['wmsUrl'] = src[istart:iend]
# wms layers
istart = src.index("layers=")+7
try:
iend = src.index("&", istart)
except ValueError:
iend = len(src)
obj['wmsLayers'] = src[istart:iend]
# wms srs
istart = src.index("crs=")+4
try:
iend = src.index("&", istart)
except ValueError:
iend = len(src)
obj['wmsProjection'] = src[istart:iend]
#print("- layer: ", node.name())
layer = QgsProject.instance().mapLayer(node.layerId())
# write SLD for WFS vector layers
if vectorial:
sldFile = self.projectFolder + os.path.sep + node.name() + ".sld"
# print("write sld to:", sldFile)
layer.saveSldStyle(sldFile)
if (self.dlg.radioUpload.isChecked() or self.dlg.radioUploadFiles.isChecked()) and self.inputsFtpOk():
# upload SLD file to server by FTP
self.connectToFtp(sldFile, self.projectJsonPath + self.projectJsonPath2, node.name() + ".sld")
if obj['indentifiable'] and isinstance(layer, QgsVectorLayer):
fields = []
# get all fields like arranged using the Drag and drop designer
edit_form_config = layer.editFormConfig()
root_container = edit_form_config.invisibleRootContainer()
for field_editor in root_container.findElements(QgsAttributeEditorElement.AeTypeField):
i = field_editor.idx()
if i >= 0 and layer.editorWidgetSetup(i).type() != 'Hidden':
#print(i, field_editor.name(), layer.fields()[i].name(), layer.attributeDisplayName(i))
f = {}
f['name'] = layer.attributeDisplayName(i)
obj['fields'].append(f)
for action in QgsGui.instance().mapLayerActionRegistry().mapLayerActions(layer):
a = {}
a['name'] = action.name()
a['action'] = action.action()
obj['actions'].append(a)
# export layer notes
# for now with all formating, maybe better clean it up first
if QgsLayerNotesUtils.layerHasNotes(layer):
obj['notes'] = QgsLayerNotesUtils.layerNotes(layer)
return obj
elif isinstance(node, QgsLayerTreeGroup):
obj['name'] = node.name()
obj['qgisname'] = node.name() # internal qgis layer name with all special characters
obj['type'] = "group"
obj['visible'] = node.isVisible()
obj['hidden'] = node.name().startswith("@")
if obj['hidden']:
obj['visible'] = True # hidden layers/groups have to be visible by default
obj['showlegend'] = not node.name().startswith("~") # don't show legend in layertree
obj['children'] = []
obj['vectorial'] = False # groups can't be vectorial for now
#print("- group: ", node.name())
#print(node.children())
if hasattr(self, 'projectTilecache'):
if self.projectTilecache:
obj['mapproxy'] = self.projectName + "_group_" + self.replaceSpecialChar(self.stripAccents(obj['name'].lower().replace(' ', '_')))
# remove first character
if not obj['showlegend']:
obj['name'] = node.name()[1:]
for child in node.children():
if not child.name().startswith("¡"):
obj['children'].append(self.getLayerTree(child))
return obj
# find static layer files and upload them using FTP
def uploadFilesLayerTree(self, node):
if isinstance(node, QgsLayerTreeLayer):
path = self.getDataProvider(node.layerId(), 'path')
# get used static layer files
if path and os.path.isfile(path):
uriPath = path.replace(self.projectFolder + os.path.sep, "")
uriPathList = uriPath.split(os.path.sep)
uriFile = uriPathList[len(uriPathList)-1]
if os.path.sep in uriPath:
# file in subfolder
uriFolder = uriPath.replace(uriFile, "").strip()
remotePath = self.projectQgsPath + uriFolder
else:
remotePath = self.projectQgsPath
self.connectToFtp(path, remotePath, uriFile)
self.iface.messageBar().pushMessage("Success", "Used layer file " + uriFile + " published at " + remotePath, level=Qgis.Success, duration=3)
elif isinstance(node, QgsLayerTreeGroup):
for child in node.children():
if not child.name().startswith("¡"):
self.uploadFilesLayerTree(child)
def update_project_vars(self):
#print("update_project_vars", settings.activeProject, self.dlg.inputProjects.currentIndex())
if settings.activeProject != -1 and self.dlg.inputProjects.currentIndex() >= 0:
project = settings.userProjects[self.dlg.inputProjects.currentIndex()]
self.projectName = project[0]
self.projectFile = project[1]
self.projectQgsPath = project[2]
self.projectJsonPath = project[3]
self.projectJsonPath2 = project[4]
self.projectHost = project[5]
self.projectUser = project[6]
self.projectPassword = project[7]
# compability to migrate to plugin v0.3.1
if len(project) > 8:
self.projectTilecache = project[8]
else:
self.projectTilecache = False
self.dlg.radioUpload.setEnabled(True)
self.dlg.radioUploadFiles.setEnabled(True)
def set_active_project(self):
settings.activeProject = self.dlg.inputProjects.currentIndex()
QSettings().setValue('/LayerTree2JSON/ActiveProject', settings.activeProject)
#print("change active project to", settings.activeProject)
self.update_project_vars()
"""settings dialog"""
def settings(self):
'''Show the settings dialog box'''
self.settingsDlg.show()
def help(self):
'''Display a help page'''
url = QUrl.fromLocalFile(os.path.dirname(__file__) + "/docs/index.html").toString()
webbrowser.open(url, new=2)
def addProject(self):
self.settingsDlg.inputProjectName.clear()
self.settingsDlg.inputProjectFile.clear()
self.settingsDlg.inputQgsPath.clear()
self.settingsDlg.inputJsonPath.clear()
self.settingsDlg.inputJsonPath2.clear()
self.settingsDlg.inputHost.clear()
self.settingsDlg.inputUser.clear()
self.settingsDlg.inputPassword.clear()
self.settingsDlg.isNew = True
self.settingsDlg.show()
def editProject(self):
if self.dlg.inputProjects.count() > 0:
index = self.dlg.inputProjects.currentIndex()
if index >= 0:
userProject = settings.userProjects[index]
self.settingsDlg.inputProjectName.setText(userProject[0])
self.settingsDlg.inputProjectFile.setText(userProject[1])
self.settingsDlg.inputQgsPath.setText(userProject[2])
self.settingsDlg.inputJsonPath.setText(userProject[3])
self.settingsDlg.inputJsonPath2.setText(userProject[4])
self.settingsDlg.inputHost.setText(userProject[5])
self.settingsDlg.inputUser.setText(userProject[6])
self.settingsDlg.inputPassword.setText(userProject[7])
# compability to migrate to plugin v0.3.1
if len(userProject) > 8:
self.settingsDlg.checkBoxMapproxy.setChecked(userProject[8])
self.settingsDlg.isNew = False
self.settingsDlg.show()
def removeProject(self):
if self.dlg.inputProjects.count() > 0:
index = self.dlg.inputProjects.currentIndex()
if index >= 0:
del settings.userProjects[index]
if settings.userProjects:
QSettings().setValue('/LayerTree2JSON/UserProjects', settings.userProjects)
else:
QSettings().setValue('/LayerTree2JSON/UserProjects', 0)
if self.dlg.inputProjects.count() > 0:
QSettings().setValue('/LayerTree2JSON/ActiveProject', 0)
names = []
for item in settings.userProjects:
names.append(item[0])
self.dlg.inputProjects.clear()
self.dlg.inputProjects.addItems(names)
if len(names) == 0:
self.dlg.buttonEditProject.setEnabled(False);
self.dlg.buttonRemoveProject.setEnabled(False);
self.dlg.radioUpload.setEnabled(False)
self.dlg.radioUploadFiles.setEnabled(False)
"""Run method that performs all the real work"""
def run(self):
if (QgsProject.instance().fileName() == ""):
self.iface.messageBar().pushMessage(
"Warning", "Please open a project file in order to use this plugin",
level=Qgis.Warning, duration=3)
else:
# define global variables
self.projectFilename = QgsExpressionContextUtils.projectScope(QgsProject.instance()).variable("project_filename")
self.projectFolder = QgsExpressionContextUtils.projectScope(QgsProject.instance()).variable("project_folder")
self.projectExtension = '.qgs'
if self.projectFilename.startswith('postgresql:'):
self.projectFolder = gettempdir()
self.projectExtension = '.postgresql'
# Create the dialog with elements (after translation) and keep reference
if self.first_start:
self.first_start = False
self.dlg = LayerTree2JSONDialog()
self.settingsDlg = LayerTree2JSONDialogSettings(self, self.iface, self.iface.mainWindow())
# set Project list
names = []
for item in settings.userProjects:
names.append(item[0])
self.dlg.inputProjects.clear()
self.dlg.inputProjects.addItems(names)
#print(settings.activeProject, type(settings.activeProject), self.dlg.inputProjects.currentIndex())
if type(settings.activeProject) == int and int(settings.activeProject) >= 0:
# change selected project
self.dlg.inputProjects.setCurrentIndex(settings.activeProject)
self.set_active_project()
elif settings.activeProject != -1 and self.dlg.inputProjects.currentIndex() >= 0:
# first run when opening QGIS
self.dlg.inputProjects.setCurrentIndex(int(settings.activeProject))
self.update_project_vars()
#self.dlg.radioUpload.setEnabled(True)
#self.dlg.radioUploadFiles.setEnabled(True)
self.dlg.buttonEditProject.setEnabled(len(names) > 0);
self.dlg.buttonRemoveProject.setEnabled(len(names) > 0);
# connect GUI
self.dlg.radioLocal.toggled.connect(lambda:self.radioStateLocal(self.dlg.radioLocal))
self.dlg.radioUpload.toggled.connect(lambda:self.radioStateUpload(self.dlg.radioUpload))
self.dlg.radioUploadFiles.toggled.connect(lambda:self.radioStateUpload(self.dlg.radioUploadFiles))
self.dlg.inputProjects.currentIndexChanged.connect(self.set_active_project)
self.dlg.buttonNewProject.clicked.connect(self.addProject)
self.dlg.buttonEditProject.clicked.connect(self.editProject)
self.dlg.buttonRemoveProject.clicked.connect(self.removeProject)
self.dlg.buttonBox.helpRequested.connect(self.help)
# show the dialog
self.dlg.show()
result = self.dlg.exec_()
# See if OK was pressed
if result:
# check if active project file has same name then selected project
# ignore check for postgresql projects
if self.projectName != self.projectFilename.split(".")[0] and (not self.projectFile.startswith('postgresql:') or self.projectExtension == ".qgs") and not self.projectName.startswith("ctbb_"):
self.iface.messageBar().pushMessage("Warning", "Your active project file name '" + self.projectFilename.split(".")[0] + "' differs from selected project '" + self.projectName + "'. Please check!", level=Qgis.Warning, duration=3)
# check mode
elif ((self.dlg.radioUpload.isChecked() or self.dlg.radioUploadFiles.isChecked()) and self.inputsFtpOk()) or self.dlg.radioLocal.isChecked():
# prepare file names
project_name = self.projectName
#project_file = self.projectFilename.replace('.qgs', '')
# exception for project ctbb
if project_name.startswith("ctbb_"):
project_name = project_name[5:]
# parse QGS file to JSON
info=[]
for group in QgsProject.instance().layerTreeRoot().children():
if not group.name().startswith("¡"):
info.append(self.getLayerTree(group))
# write JSON to temporary file and show in browser
filenameJSON = self.projectFolder + os.path.sep + project_name + self.projectExtension + '.json'
file = open(filenameJSON, 'w')
file.write(json.dumps(info))
file.close()
if (self.dlg.radioUpload.isChecked() or self.dlg.radioUploadFiles.isChecked()) and self.inputsFtpOk():
# upload JSON file to server by FTP
self.connectToFtp(filenameJSON, self.projectJsonPath + self.projectJsonPath2, project_name + self.projectExtension + '.json')
# public URL of JSON file
filenameJSON = self.projectHost + '/' + self.projectJsonPath2 + project_name + self.projectExtension + '.json'
# upload QGS file to server by FTP
if not self.projectFile.startswith('postgresql:'):
self.connectToFtp(self.projectFolder + os.path.sep + self.projectFile, self.projectQgsPath, self.projectFile)
self.iface.messageBar().pushMessage(
"Success", "QGS file " + self.projectFile + " published at " + self.projectQgsPath, level=Qgis.Success, duration=3)
if self.dlg.radioUploadFiles.isChecked():
# iterate over layer tree and check if static layer files used
for group in QgsProject.instance().layerTreeRoot().children():
if not group.name().startswith("¡"):
self.uploadFilesLayerTree(group)
if self.dlg.radioProject.isChecked():
self.show_project()
elif self.dlg.radioJson.isChecked():
if self.dlg.radioUpload.isChecked() or self.dlg.radioUploadFiles.isChecked():
self.show_online_file(project_name)
else:
webbrowser.open(filenameJSON)
# message to user
self.iface.messageBar().pushMessage("Success", "JSON file published at " + filenameJSON, level=Qgis.Success, duration=3)