GdalAlgorithm.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. """
  2. ***************************************************************************
  3. GdalAlgorithm.py
  4. ---------------------
  5. Date : August 2012
  6. Copyright : (C) 2012 by Victor Olaya
  7. Email : volayaf at gmail dot com
  8. ***************************************************************************
  9. * *
  10. * This program is free software; you can redistribute it and/or modify *
  11. * it under the terms of the GNU General Public License as published by *
  12. * the Free Software Foundation; either version 2 of the License, or *
  13. * (at your option) any later version. *
  14. * *
  15. ***************************************************************************
  16. """
  17. __author__ = 'Victor Olaya'
  18. __date__ = 'August 2012'
  19. __copyright__ = '(C) 2012, Victor Olaya'
  20. import os
  21. import re
  22. import numpy as np
  23. from PyQt5.QtGui import QIcon
  24. from qgis.PyQt.QtCore import QUrl, QCoreApplication
  25. from qgis.core import (QgsApplication,
  26. QgsProject,
  27. QgsVectorFileWriter,
  28. QgsProcessingFeatureSourceDefinition,
  29. QgsProcessingAlgorithm,
  30. QgsProcessingContext,
  31. QgsProcessingFeedback,
  32. QgsProviderRegistry,
  33. QgsDataSourceUri)
  34. from processing.algs.gdal.GdalAlgorithmDialog import GdalAlgorithmDialog
  35. from processing.algs.gdal.GdalUtils import GdalUtils
  36. from processing.tools.PostgreSQL.PostgreSQL import PostgreSQL
  37. from processing.tools.GeoServer.Geoserver import Geoserver
  38. from processing.tools.GeoServer.GeoService import GeoService
  39. from processing.tools.QGS.QgsProjectUtils import QgsProjectUtils
  40. from processing.tools.PrintUtils import getLastPrint
  41. from processing.tools.requestUtils import (spotfileUpload, downloadspotfile, deletespotfile)
  42. from processing.tools.FileListPrintUtils import getFileListPrint
  43. from processing.tools.SubprocessUtils import RunSubprocess
  44. import processing.tools.QGS.load
  45. from qgis.PyQt.QtCore import NULL
  46. pluginPath = os.path.normpath(os.path.join(
  47. os.path.split(os.path.dirname(__file__))[0], os.pardir))
  48. class GdalAlgorithm(QgsProcessingAlgorithm):
  49. def __init__(self):
  50. super().__init__()
  51. # TODO wanger GdalAlgorithm全局参数配置
  52. self.output_values = {}
  53. self.spatialite_db_path = "D:\\temp\\output.sqlite"
  54. self.pgcoon = {
  55. "host": "127.0.0.1",
  56. "schema": "vector",
  57. "port": "5432",
  58. "user": "postgres",
  59. "password": "postgres",
  60. "dbname": "real3d"
  61. }
  62. self.geoservercoon = {
  63. "url": "http://127.0.0.1:28085/geoserver",
  64. "username": "admin",
  65. "password": "geoserver",
  66. "defaultworkspace": "demo",
  67. "cachestart": "0",
  68. "cacheend": "15"
  69. }
  70. def icon(self):
  71. return QIcon(os.path.join(pluginPath, 'images', 'dbms', 'tool.png'))
  72. # return QgsApplication.getThemeIcon("/providerGdal.svg")
  73. def tags(self):
  74. return ['ogr', 'gdal', self.commandName()]
  75. def svgIconPath(self):
  76. return os.path.join(pluginPath, 'images', 'dbms', 'tool.png')
  77. # return QgsApplication.iconPath("providerGdal.svg")
  78. def createInstance(self, config={}):
  79. return self.__class__()
  80. def createCustomParametersWidget(self, parent):
  81. return GdalAlgorithmDialog(self, parent=parent)
  82. def getConsoleCommands(self, parameters, context, feedback, executing=True):
  83. return None
  84. def getOgrCompatibleSource(self, parameter_name, parameters, context, feedback, executing):
  85. """
  86. Interprets a parameter as an OGR compatible source and layer name
  87. :param executing:
  88. """
  89. if not executing and parameter_name in parameters and isinstance(parameters[parameter_name],
  90. QgsProcessingFeatureSourceDefinition):
  91. # if not executing, then we throw away all 'selected features only' settings
  92. # since these have no meaning for command line gdal use, and we don't want to force
  93. # an export of selected features only to a temporary file just to show the command!
  94. parameters = {parameter_name: parameters[parameter_name].source}
  95. input_layer = self.parameterAsVectorLayer(parameters, parameter_name, context)
  96. ogr_data_path = None
  97. ogr_layer_name = None
  98. if input_layer is None or input_layer.dataProvider().name() == 'memory':
  99. if executing:
  100. # parameter is not a vector layer - try to convert to a source compatible with OGR
  101. # and extract selection if required
  102. ogr_data_path = self.parameterAsCompatibleSourceLayerPath(parameters, parameter_name, context,
  103. QgsVectorFileWriter.supportedFormatExtensions(),
  104. QgsVectorFileWriter.supportedFormatExtensions()[
  105. 0],
  106. feedback=feedback)
  107. ogr_layer_name = GdalUtils.ogrLayerName(ogr_data_path)
  108. else:
  109. # not executing - don't waste time converting incompatible sources, just return dummy strings
  110. # for the command preview (since the source isn't compatible with OGR, it has no meaning anyway and can't
  111. # be run directly in the command line)
  112. ogr_data_path = 'path_to_data_file'
  113. ogr_layer_name = 'layer_name'
  114. elif input_layer.dataProvider().name() == 'ogr':
  115. if executing and (
  116. isinstance(parameters[parameter_name], QgsProcessingFeatureSourceDefinition) and parameters[
  117. parameter_name].selectedFeaturesOnly) \
  118. or input_layer.subsetString():
  119. # parameter is a vector layer, with OGR data provider
  120. # so extract selection if required
  121. ogr_data_path = self.parameterAsCompatibleSourceLayerPath(parameters, parameter_name, context,
  122. QgsVectorFileWriter.supportedFormatExtensions(),
  123. feedback=feedback)
  124. parts = QgsProviderRegistry.instance().decodeUri('ogr', ogr_data_path)
  125. ogr_data_path = parts['path']
  126. if 'layerName' in parts and parts['layerName']:
  127. ogr_layer_name = parts['layerName']
  128. else:
  129. ogr_layer_name = GdalUtils.ogrLayerName(ogr_data_path)
  130. else:
  131. # either not using the selection, or
  132. # not executing - don't worry about 'selected features only' handling. It has no meaning
  133. # for the command line preview since it has no meaning outside of a QGIS session!
  134. ogr_data_path = GdalUtils.ogrConnectionStringAndFormatFromLayer(input_layer)[0]
  135. ogr_layer_name = GdalUtils.ogrLayerName(input_layer.dataProvider().dataSourceUri())
  136. elif input_layer.dataProvider().name().lower() == 'wfs':
  137. uri = QgsDataSourceUri(input_layer.source())
  138. baseUrl = uri.param('url').split('?')[0]
  139. ogr_data_path = f"WFS:{baseUrl}"
  140. ogr_layer_name = uri.param('typename')
  141. else:
  142. # vector layer, but not OGR - get OGR compatible path
  143. # TODO - handle "selected features only" mode!!
  144. ogr_data_path = GdalUtils.ogrConnectionStringFromLayer(input_layer)
  145. ogr_layer_name = GdalUtils.ogrLayerName(input_layer.dataProvider().dataSourceUri())
  146. return ogr_data_path, ogr_layer_name
  147. def setOutputValue(self, name, value):
  148. self.output_values[name] = value
  149. def processAlgorithm(self, parameters, context, feedback):
  150. # TODO wanger 拓扑检查
  151. if parameters.get("INPUTVECTOR") is not None:
  152. res = self.topologycheck(parameters, context, feedback, executing=True)
  153. return res
  154. # TODO wanger 生成许可文件
  155. if parameters.get("LICENSEHOST") is not None:
  156. self.generateLicense(parameters)
  157. return {
  158. "许可文件路径": parameters.get("OUTPUT")
  159. }
  160. # TODO wanger 上传图斑文件数据包
  161. if parameters.get("SPOTFILE") is not None:
  162. filepath = parameters.get("SPOTFILE")
  163. print(filepath)
  164. json_obj = spotfileUpload(filepath=filepath)
  165. status = int(json_obj["statuscode"])
  166. if status == 200:
  167. return {
  168. "状态": "上传成功!"
  169. }
  170. else:
  171. return {
  172. "状态": json_obj["message"]
  173. }
  174. # TODO wanger 下载图斑文件数据包
  175. if parameters.get("SPOTFILEDOWNLOAD") is not None:
  176. fileindex = parameters.get("SPOTFILEDOWNLOAD")
  177. print("spotfilelist")
  178. print(self.spotfilelist)
  179. fileparams = self.spotfilelist[fileindex]
  180. print(fileparams)
  181. filestr = downloadspotfile(filename=f'{fileparams["name"]}.{fileparams["filetype"]}',
  182. dir=parameters.get("SPOTFILEOUT"))
  183. return {
  184. "状态": filestr
  185. }
  186. # TODO wanger 删除图斑文件数据包
  187. if parameters.get("SPOTFILEDELETE") is not None:
  188. fileindex = parameters.get("SPOTFILEDELETE")
  189. print("spotfilelist")
  190. print(self.spotfilelist)
  191. fileparams = self.spotfilelist[fileindex]
  192. print(fileparams)
  193. filestr = deletespotfile(id=fileparams["id"])
  194. return {
  195. "状态": "删除成功"
  196. }
  197. # TODO wanger GeoServer服务发布
  198. if parameters.get("Publish_Service") is not None:
  199. zymlbsm = getLastPrint()
  200. if zymlbsm == None or zymlbsm == '':
  201. return {
  202. "Error": "资源目录未选择!"
  203. }
  204. print("zymlbsm====" + zymlbsm)
  205. layer_group_join = ""
  206. if parameters.get("LAYER_GROUP_JOIN") is not None:
  207. layer_group_join = self.groups[parameters.get("LAYER_GROUP_JOIN")]
  208. commands = self.getConsoleCommands(parameters, context, feedback, executing=True)
  209. geoSer = GeoService()
  210. result = None
  211. if parameters.get("INPUTRASTER") != NULL and parameters.get("INPUTRASTER") != "":
  212. # 获取输入栅格图层
  213. raster_layer = self.parameterAsRasterLayer(parameters, self.INPUTRASTER, context)
  214. file = raster_layer.source()
  215. result = geoSer.publishGeoService(parameters, context, feedback, commands, zymlbsm, layer_group_join,
  216. file)
  217. else:
  218. result = geoSer.publishGeoService(parameters, context, feedback, commands, zymlbsm, layer_group_join,
  219. None)
  220. return result
  221. # === 获取gdal命令参数执行并输出log开始 ===
  222. commands = self.getConsoleCommands(parameters, context, feedback, executing=True)
  223. # 增量更新
  224. if parameters.get("ALLOWOVERLAP") is not None and len(commands) == 0:
  225. res = self.updateVector(parameters, context, feedback, executing=True)
  226. return res
  227. # 版本回退
  228. if parameters.get("RESTORETABLE") is not None:
  229. res = self.restoreVector(parameters, context, feedback, executing=True)
  230. return res
  231. command = commands[0]
  232. if command.__contains__(" "):
  233. GdalUtils.runGdal([command], feedback)
  234. commands.remove(command)
  235. GdalUtils.runGdal(commands, feedback)
  236. else:
  237. GdalUtils.runGdal(commands, feedback)
  238. print(commands)
  239. results = {}
  240. for o in self.outputDefinitions():
  241. if o.name() in parameters:
  242. results[o.name()] = parameters[o.name()]
  243. for k, v in self.output_values.items():
  244. results[k] = v
  245. # === 获取gdal命令参数执行并输出log结束 ===
  246. # TODO wanger 元数据入库
  247. if parameters.get("Metadata_storage") is not None and parameters.get("Metadata_storage") == True:
  248. # 所属行政区划
  249. ssxzqh = getLastPrint()
  250. print("ssxzqh====" + ssxzqh)
  251. # 获取附件列表
  252. fileliststr = getFileListPrint()
  253. pgconn = PostgreSQL(schema='base')
  254. ogrLayer = ""
  255. if parameters.get("SOURCE_TYPE") == "vector":
  256. ogrLayer, layername = self.getOgrCompatibleSource(self.INPUT, parameters, context, feedback, None)
  257. elif parameters.get("SOURCE_TYPE") == "raster":
  258. raster_layer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
  259. ogrLayer = raster_layer.source()
  260. print(ogrLayer)
  261. pgconn.metadataStorage(parameters, ssxzqh, fileliststr, self.ywlxs[parameters.get("VECTOR_YWLX")],
  262. self.depts[parameters.get("VECTOR_GLBM")], ogrLayer,
  263. self.zymls[parameters.get("VECTOR_ZYML")])
  264. pgconn.close()
  265. return results
  266. def commandName(self):
  267. parameters = {
  268. param.name(): "1"
  269. for param in self.parameterDefinitions()
  270. }
  271. context = QgsProcessingContext()
  272. feedback = QgsProcessingFeedback()
  273. name = self.getConsoleCommands(parameters, context, feedback, executing=False)[0]
  274. if name.endswith(".py"):
  275. name = name[:-3]
  276. return name
  277. def tr(self, string, context=''):
  278. if context == '':
  279. context = self.__class__.__name__
  280. return QCoreApplication.translate(context, string)