util.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. ###############################################################################
  2. #
  3. # Copyright (C) 2010 NextGIS (http://nextgis.org),
  4. # Alexander Bruy (alexander.bruy@gmail.com),
  5. # Maxim Dubinin (sim@gis-lab.info)
  6. #
  7. # Copyright (C) 2014 Tom Kralidis (tomkralidis@gmail.com)
  8. # Copyright (C) 2014 Angelos Tzotsos (tzotsos@gmail.com)
  9. #
  10. # This source is free software; you can redistribute it and/or modify it under
  11. # the terms of the GNU General Public License as published by the Free
  12. # Software Foundation; either version 2 of the License, or (at your option)
  13. # any later version.
  14. #
  15. # This code is distributed in the hope that it will be useful, but WITHOUT ANY
  16. # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  17. # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  18. # details.
  19. #
  20. # You should have received a copy of the GNU General Public License along
  21. # with this program; if not, write to the Free Software Foundation, Inc.,
  22. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  23. #
  24. ###############################################################################
  25. from gettext import gettext, ngettext
  26. import json
  27. import logging
  28. import warnings
  29. import os
  30. import webbrowser
  31. from xml.dom.minidom import parseString
  32. import xml.etree.ElementTree as etree
  33. with warnings.catch_warnings():
  34. warnings.filterwarnings("ignore", category=DeprecationWarning)
  35. from jinja2 import Environment, FileSystemLoader
  36. from pygments import highlight
  37. from pygments.lexers import JsonLexer, XmlLexer
  38. from pygments.formatters import HtmlFormatter
  39. from qgis.PyQt.QtCore import QUrl, QUrlQuery
  40. from qgis.PyQt.QtWidgets import QMessageBox
  41. from qgis.PyQt.uic import loadUiType
  42. from qgis.core import Qgis, QgsSettings
  43. LOGGER = logging.getLogger('MetaSearch')
  44. class StaticContext:
  45. """base configuration / scaffolding"""
  46. def __init__(self):
  47. """init"""
  48. self.ppath = os.path.dirname(os.path.abspath(__file__))
  49. def get_ui_class(ui_file):
  50. """return class object of a uifile"""
  51. ui_file_full = '{}{}ui{}{}'.format(os.path.dirname(os.path.abspath(__file__)), os.sep, os.sep, ui_file)
  52. return loadUiType(ui_file_full)[0]
  53. def render_template(language, context, data, template):
  54. """Renders HTML display of raw API request/response/content"""
  55. env = Environment(extensions=['jinja2.ext.i18n'],
  56. loader=FileSystemLoader(context.ppath))
  57. env.install_gettext_callables(gettext, ngettext, newstyle=True)
  58. template_file = 'resources/templates/%s' % template
  59. template = env.get_template(template_file)
  60. return template.render(language=language, obj=data)
  61. def get_connections_from_file(parent, filename):
  62. """load connections from connection file"""
  63. error = 0
  64. try:
  65. doc = etree.parse(filename).getroot()
  66. if doc.tag != 'qgsCSWConnections':
  67. error = 1
  68. msg = parent.tr('Invalid Catalog connections XML.')
  69. except etree.ParseError as err:
  70. error = 1
  71. msg = parent.tr('Cannot parse XML file: {0}').format(err)
  72. except OSError as err:
  73. error = 1
  74. msg = parent.tr('Cannot open file: {0}').format(err)
  75. if error == 1:
  76. QMessageBox.information(parent, parent.tr('Loading Connections'), msg)
  77. return
  78. return doc
  79. def prettify_xml(xml):
  80. """convenience function to prettify XML"""
  81. if isinstance(xml, bytes):
  82. xml = xml.decode('utf-8')
  83. if xml.count('\n') > 20: # likely already pretty printed
  84. return xml
  85. # check if it's a GET request
  86. if xml.startswith('http'):
  87. return xml
  88. else:
  89. return parseString(xml).toprettyxml()
  90. def highlight_content(context, content, mimetype):
  91. """render content as highlighted HTML"""
  92. hformat = HtmlFormatter()
  93. css = hformat.get_style_defs('.highlight')
  94. if mimetype == 'json':
  95. body = highlight(json.dumps(content, indent=4), JsonLexer(), hformat)
  96. elif mimetype == 'xml':
  97. body = highlight(prettify_xml(content), XmlLexer(), hformat)
  98. env = Environment(loader=FileSystemLoader(context.ppath))
  99. template_file = 'resources/templates/api_highlight.html'
  100. template = env.get_template(template_file)
  101. return template.render(css=css, body=body)
  102. def get_help_url():
  103. """return QGIS MetaSearch help documentation link"""
  104. locale_name = QgsSettings().value('locale/userLocale')[0:2]
  105. major, minor = Qgis.QGIS_VERSION.split('.')[:2]
  106. if minor == '99': # master
  107. version = 'testing'
  108. else:
  109. version = '.'.join([major, minor])
  110. path = f'{version}/{locale_name}/docs/user_manual/plugins/core_plugins/plugins_metasearch.html' # noqa
  111. return '/'.join(['https://docs.qgis.org', path])
  112. def open_url(url):
  113. """open URL in web browser"""
  114. webbrowser.open(url)
  115. def normalize_text(text):
  116. """tidy up string"""
  117. return text.replace('\n', '')
  118. def serialize_string(input_string):
  119. """apply a serial counter to a string"""
  120. s = input_string.strip().split()
  121. last_token = s[-1]
  122. all_other_tokens_as_string = input_string.replace(last_token, '')
  123. if last_token.isdigit():
  124. value = f'{all_other_tokens_as_string}{int(last_token) + 1}'
  125. else:
  126. value = '%s 1' % input_string
  127. return value
  128. def clean_ows_url(url):
  129. """clean an OWS URL of added basic service parameters"""
  130. url = QUrl(url)
  131. query_string = url.query()
  132. if query_string:
  133. query_string = QUrlQuery(query_string)
  134. query_string.removeQueryItem('service')
  135. query_string.removeQueryItem('SERVICE')
  136. query_string.removeQueryItem('request')
  137. query_string.removeQueryItem('REQUEST')
  138. url.setQuery(query_string)
  139. return url.toString()