GdalAlgorithm.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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 QgsCoordinateTransformContext
  26. from qgis.core import (QgsApplication,
  27. QgsProject,
  28. QgsVectorFileWriter,
  29. QgsProcessingFeatureSourceDefinition,
  30. QgsProcessingAlgorithm,
  31. QgsProcessingContext,
  32. QgsProcessingFeedback,
  33. QgsProviderRegistry,
  34. QgsDataSourceUri)
  35. from processing.algs.gdal.GdalAlgorithmDialog import GdalAlgorithmDialog
  36. from processing.algs.gdal.GdalUtils import GdalUtils
  37. from processing.tools.PostgreSQL.PostgreSQL import PostgreSQL
  38. from processing.tools.GeoServer.Geoserver import Geoserver
  39. from processing.tools.GeoServer.GeoService import GeoService
  40. from processing.tools.QGS.QgsProjectUtils import QgsProjectUtils
  41. from processing.tools.PrintUtils import getLastPrint
  42. from processing.tools.requestUtils import (spotfileUpload, downloadspotfile, deletespotfile)
  43. from processing.tools.FileListPrintUtils import getFileListPrint
  44. from processing.tools.SubprocessUtils import RunSubprocess
  45. import processing.tools.QGS.load
  46. from qgis.PyQt.QtCore import NULL
  47. pluginPath = os.path.normpath(os.path.join(
  48. os.path.split(os.path.dirname(__file__))[0], os.pardir))
  49. class GdalAlgorithm(QgsProcessingAlgorithm):
  50. def __init__(self):
  51. super().__init__()
  52. # TODO wanger GdalAlgorithm全局参数配置
  53. self.output_values = {}
  54. self.spatialite_db_path = "D:\\temp\\output.sqlite"
  55. self.pgcoon = {
  56. "host": "127.0.0.1",
  57. "schema": "vector",
  58. "port": "5432",
  59. "user": "postgres",
  60. "password": "postgres",
  61. "dbname": "real3d"
  62. }
  63. self.geoservercoon = {
  64. "url": "http://127.0.0.1:28085/geoserver",
  65. "username": "admin",
  66. "password": "geoserver",
  67. "defaultworkspace": "demo",
  68. "cachestart": "0",
  69. "cacheend": "15"
  70. }
  71. def icon(self):
  72. return QIcon(os.path.join(pluginPath, 'images', 'dbms', 'tool.png'))
  73. # return QgsApplication.getThemeIcon("/providerGdal.svg")
  74. def tags(self):
  75. return ['ogr', 'gdal', self.commandName()]
  76. def svgIconPath(self):
  77. return os.path.join(pluginPath, 'images', 'dbms', 'tool.png')
  78. # return QgsApplication.iconPath("providerGdal.svg")
  79. def createInstance(self, config={}):
  80. return self.__class__()
  81. def createCustomParametersWidget(self, parent):
  82. return GdalAlgorithmDialog(self, parent=parent)
  83. def getConsoleCommands(self, parameters, context, feedback, executing=True):
  84. return None
  85. def getOgrCompatibleSource(self, parameter_name, parameters, context, feedback, executing):
  86. """
  87. Interprets a parameter as an OGR compatible source and layer name
  88. :param executing:
  89. """
  90. if not executing and parameter_name in parameters and isinstance(parameters[parameter_name],
  91. QgsProcessingFeatureSourceDefinition):
  92. # if not executing, then we throw away all 'selected features only' settings
  93. # since these have no meaning for command line gdal use, and we don't want to force
  94. # an export of selected features only to a temporary file just to show the command!
  95. parameters = {parameter_name: parameters[parameter_name].source}
  96. input_layer = self.parameterAsVectorLayer(parameters, parameter_name, context)
  97. ogr_data_path = None
  98. ogr_layer_name = None
  99. if input_layer is None or input_layer.dataProvider().name() == 'memory':
  100. if executing:
  101. # parameter is not a vector layer - try to convert to a source compatible with OGR
  102. # and extract selection if required
  103. ogr_data_path = self.parameterAsCompatibleSourceLayerPath(parameters, parameter_name, context,
  104. QgsVectorFileWriter.supportedFormatExtensions(),
  105. QgsVectorFileWriter.supportedFormatExtensions()[
  106. 0],
  107. feedback=feedback)
  108. ogr_layer_name = GdalUtils.ogrLayerName(ogr_data_path)
  109. else:
  110. # not executing - don't waste time converting incompatible sources, just return dummy strings
  111. # for the command preview (since the source isn't compatible with OGR, it has no meaning anyway and can't
  112. # be run directly in the command line)
  113. ogr_data_path = 'path_to_data_file'
  114. ogr_layer_name = 'layer_name'
  115. elif input_layer.dataProvider().name() == 'ogr':
  116. if executing and (
  117. isinstance(parameters[parameter_name], QgsProcessingFeatureSourceDefinition) and parameters[
  118. parameter_name].selectedFeaturesOnly) \
  119. or input_layer.subsetString():
  120. # parameter is a vector layer, with OGR data provider
  121. # so extract selection if required
  122. ogr_data_path = self.parameterAsCompatibleSourceLayerPath(parameters, parameter_name, context,
  123. QgsVectorFileWriter.supportedFormatExtensions(),
  124. feedback=feedback)
  125. parts = QgsProviderRegistry.instance().decodeUri('ogr', ogr_data_path)
  126. ogr_data_path = parts['path']
  127. if 'layerName' in parts and parts['layerName']:
  128. ogr_layer_name = parts['layerName']
  129. else:
  130. ogr_layer_name = GdalUtils.ogrLayerName(ogr_data_path)
  131. else:
  132. # either not using the selection, or
  133. # not executing - don't worry about 'selected features only' handling. It has no meaning
  134. # for the command line preview since it has no meaning outside of a QGIS session!
  135. ogr_data_path = GdalUtils.ogrConnectionStringAndFormatFromLayer(input_layer)[0]
  136. ogr_layer_name = GdalUtils.ogrLayerName(input_layer.dataProvider().dataSourceUri())
  137. elif input_layer.dataProvider().name().lower() == 'wfs':
  138. uri = QgsDataSourceUri(input_layer.source())
  139. baseUrl = uri.param('url').split('?')[0]
  140. ogr_data_path = f"WFS:{baseUrl}"
  141. ogr_layer_name = uri.param('typename')
  142. else:
  143. # vector layer, but not OGR - get OGR compatible path
  144. # TODO - handle "selected features only" mode!!
  145. ogr_data_path = GdalUtils.ogrConnectionStringFromLayer(input_layer)
  146. ogr_layer_name = GdalUtils.ogrLayerName(input_layer.dataProvider().dataSourceUri())
  147. return ogr_data_path, ogr_layer_name
  148. def setOutputValue(self, name, value):
  149. self.output_values[name] = value
  150. def processAlgorithm(self, parameters, context, feedback):
  151. # TODO wanger 拓扑检查
  152. if parameters.get("INPUTVECTOR") is not None:
  153. res = self.topologycheck(parameters, context, feedback, executing=True)
  154. return res
  155. # TODO wanger 生成许可文件
  156. if parameters.get("LICENSEHOST") is not None:
  157. self.generateLicense(parameters)
  158. return {
  159. "许可文件路径": parameters.get("OUTPUT")
  160. }
  161. # TODO wanger 上传图斑文件数据包
  162. if parameters.get("SPOTFILE") is not None:
  163. filepath = parameters.get("SPOTFILE")
  164. print(filepath)
  165. json_obj = spotfileUpload(filepath=filepath)
  166. status = int(json_obj["statuscode"])
  167. if status == 200:
  168. return {
  169. "状态": "上传成功!"
  170. }
  171. else:
  172. return {
  173. "状态": json_obj["message"]
  174. }
  175. # TODO wanger 下载图斑文件数据包
  176. if parameters.get("SPOTFILEDOWNLOAD") is not None:
  177. fileindex = parameters.get("SPOTFILEDOWNLOAD")
  178. print("spotfilelist")
  179. print(self.spotfilelist)
  180. fileparams = self.spotfilelist[fileindex]
  181. print(fileparams)
  182. filestr = downloadspotfile(filename=f'{fileparams["name"]}.{fileparams["filetype"]}',
  183. dir=parameters.get("SPOTFILEOUT"))
  184. return {
  185. "状态": filestr
  186. }
  187. # TODO wanger 删除图斑文件数据包
  188. if parameters.get("SPOTFILEDELETE") is not None:
  189. fileindex = parameters.get("SPOTFILEDELETE")
  190. print("spotfilelist")
  191. print(self.spotfilelist)
  192. fileparams = self.spotfilelist[fileindex]
  193. print(fileparams)
  194. filestr = deletespotfile(id=fileparams["id"])
  195. return {
  196. "状态": "删除成功"
  197. }
  198. # TODO wanger GeoServer服务发布
  199. if parameters.get("Publish_Service") is not None:
  200. zymlbsm = getLastPrint()
  201. if zymlbsm == None or zymlbsm == '':
  202. return {
  203. "Error": "资源目录未选择!"
  204. }
  205. print("zymlbsm====" + zymlbsm)
  206. layer_group_join = ""
  207. if parameters.get("LAYER_GROUP_JOIN") is not None:
  208. layer_group_join = self.groups[parameters.get("LAYER_GROUP_JOIN")]
  209. commands = self.getConsoleCommands(parameters, context, feedback, executing=True)
  210. geoSer = GeoService()
  211. result = None
  212. if parameters.get("INPUTRASTER") != NULL and parameters.get("INPUTRASTER") != "":
  213. # 获取输入栅格图层
  214. raster_layer = self.parameterAsRasterLayer(parameters, self.INPUTRASTER, context)
  215. file = raster_layer.source()
  216. result = geoSer.publishGeoService(parameters, context, feedback, commands, zymlbsm, layer_group_join,
  217. file)
  218. else:
  219. result = geoSer.publishGeoService(parameters, context, feedback, commands, zymlbsm, layer_group_join,
  220. None)
  221. return result
  222. # === 获取gdal命令参数执行并输出log开始 ===
  223. commands = self.getConsoleCommands(parameters, context, feedback, executing=True)
  224. # 增量更新
  225. if parameters.get("ALLOWOVERLAP") is not None and len(commands) == 0:
  226. res = self.updateVector(parameters, context, feedback, executing=True)
  227. return res
  228. # 版本回退
  229. if parameters.get("RESTORETABLE") is not None:
  230. res = self.restoreVector(parameters, context, feedback, executing=True)
  231. return res
  232. command = commands[0]
  233. if command.__contains__(" "):
  234. GdalUtils.runGdal([command], feedback)
  235. commands.remove(command)
  236. GdalUtils.runGdal(commands, feedback)
  237. else:
  238. GdalUtils.runGdal(commands, feedback)
  239. print(commands)
  240. results = {}
  241. for o in self.outputDefinitions():
  242. if o.name() in parameters:
  243. results[o.name()] = parameters[o.name()]
  244. for k, v in self.output_values.items():
  245. results[k] = v
  246. # === 获取gdal命令参数执行并输出log结束 ===
  247. # TODO wanger 元数据入库
  248. if parameters.get("Metadata_storage") is not None and parameters.get("Metadata_storage") == True:
  249. # 所属行政区划
  250. ssxzqh = getLastPrint()
  251. print("ssxzqh====" + ssxzqh)
  252. # 获取附件列表
  253. fileliststr = getFileListPrint()
  254. pgconn = PostgreSQL(schema='base')
  255. ogrLayer = ""
  256. if parameters.get("SOURCE_TYPE") == "vector":
  257. ogrLayer, layername = self.getOgrCompatibleSource(self.INPUT, parameters, context, feedback, None)
  258. elif parameters.get("SOURCE_TYPE") == "raster":
  259. raster_layer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
  260. ogrLayer = raster_layer.source()
  261. print(ogrLayer)
  262. pgconn.metadataStorage(parameters, ssxzqh, fileliststr, self.ywlxs[parameters.get("VECTOR_YWLX")],
  263. self.depts[parameters.get("VECTOR_GLBM")], ogrLayer,
  264. self.zymls[parameters.get("VECTOR_ZYML")])
  265. pgconn.close()
  266. return results
  267. def commandName(self):
  268. parameters = {
  269. param.name(): "1"
  270. for param in self.parameterDefinitions()
  271. }
  272. context = QgsProcessingContext()
  273. feedback = QgsProcessingFeedback()
  274. name = self.getConsoleCommands(parameters, context, feedback, executing=False)[0]
  275. if name.endswith(".py"):
  276. name = name[:-3]
  277. return name
  278. # 将VectorLayer导入到SpatiaLite数据库
  279. def importLayerToSpatiaLite(self, layer, table_name):
  280. # TODO 构造连接到Spatialite数据库的URI
  281. uri = QgsDataSourceUri()
  282. uri.setDatabase(self.spatialite_db_path)
  283. # TODO 将vectorlayer写入Spatialite 数据库
  284. options = QgsVectorFileWriter.SaveVectorOptions()
  285. options.driverName = "SQLite"
  286. options.layerName = table_name
  287. options.fileEncoding = "UTF-8"
  288. options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer
  289. # TODO 将QgsVectorLayer导入到spatialite并指定表名
  290. result = QgsVectorFileWriter.writeAsVectorFormatV2(layer, self.spatialite_db_path,
  291. QgsCoordinateTransformContext(), options)
  292. return result
  293. # 将VectorLayer导出到文件
  294. def vectorLayerExport(self, layer, path, type):
  295. options = QgsVectorFileWriter.SaveVectorOptions()
  296. options.driverName = type # Output format
  297. # options.includeGeometry = True # Include geometry
  298. context2 = QgsCoordinateTransformContext()
  299. error = QgsVectorFileWriter.writeAsVectorFormatV3(layer, path, context2, options)
  300. if error[0] == QgsVectorFileWriter.NoError:
  301. print(f"Exported {path} successfully!")
  302. else:
  303. print(f"Failed to export to {path}: {error}")
  304. # 将VectorLayer导出到矢量文件
  305. def vectorLayerExportToVector(self, layer, path, type="ESRI Shapefile"):
  306. # TODO 导出矢量文件参数配置
  307. export_options = QgsVectorFileWriter.SaveVectorOptions()
  308. export_options.driverName = type
  309. export_options.fileEncoding = "UTF-8"
  310. result = QgsVectorFileWriter.writeAsVectorFormatV2(layer, path,
  311. QgsCoordinateTransformContext(), export_options)
  312. if result[0] != QgsVectorFileWriter.NoError:
  313. print(f"Failed to export processed layer to SHP file.")
  314. # 拓扑检查成功,没有错误项
  315. def topologySuccessWithNone(self):
  316. return {
  317. "状态": "拓扑检查成功",
  318. "结论": "符合"
  319. }
  320. #拓扑检查成功
  321. def topologySuccess(self, count, reportpath):
  322. return {
  323. "状态": "拓扑检查成功",
  324. "结论": "不符合" if count > 0 else "符合",
  325. "错误项": f"{count}条记录",
  326. "报告输出位置": reportpath
  327. }
  328. def tr(self, string, context=''):
  329. if context == '':
  330. context = self.__class__.__name__
  331. return QCoreApplication.translate(context, string)