Example #1
0
    def __init__(self, iface, ts_datasources):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        super().__init__()
        # Save reference to the QGIS interface
        self.iface = iface

        self.ts_datasources = ts_datasources
        # TODO: unsure if this is the right place for initializing this model
        self.downloadable_results = models.DownloadableResultModel()

        # TODO: fix this fugly shizzle
        self.download_directory = None
        self.username = None
        self.password = None

        # download administration
        self.network_manager = QgsNetworkAccessManager(self)

        self.icon_path = ":/plugins/ThreeDiToolbox/icons/icon_add_datasource.png"
        self.menu_text = u"Select 3Di results"

        self.is_active = False
        self.dialog = None
        self.ts_datasources.model_schematisation_change.connect(
            self.on_state_changed)
        self.ts_datasources.results_change.connect(self.on_state_changed)
Example #2
0
    def __init__(self, provider=None, retry_timeout=60):
        """
        :param provider: A openrouteservice provider from config.yml
        :type provider: dict

        :param retry_timeout: Timeout across multiple retriable requests, in
            seconds.
        :type retry_timeout: int
        """
        QObject.__init__(self)

        self.key = provider['key']
        self.base_url = provider['base_url']

        # self.session = requests.Session()
        self.nam = QgsNetworkAccessManager()

        self.retry_timeout = timedelta(seconds=retry_timeout)
        self.headers = {
            "User-Agent": _USER_AGENT,
            'Content-type': 'application/json',
        }

        # Save some references to retrieve in client instances
        self.url = None
        self.warnings = None
        self.response_time = 0
        self.status_code = None
Example #3
0
    def __init__(self):
        self.nam = QgsNetworkAccessManager()

        # has public access methods
        self._status_code = 0
        self._error_string = ""

        # completely private
        self._content = dict()
Example #4
0
def startNetwork(args):
    if all(
        (args.proxyHost, args.proxyPort, args.proxyUser, args.proxyPassword)):
        proxy = QNetworkProxy(QNetworkProxy.HttpProxy, args.proxyHost,
                              args.proxyPort, args.proxyUser,
                              args.proxyPassword)
    else:
        proxy = QNetworkProxy(QNetworkProxy.NoProxy)
    manager = QgsNetworkAccessManager().instance()
    manager.setFallbackProxyAndExcludes(proxy, [], [])
Example #5
0
    def __init__(self, parent=None):
        QWebPage.__init__(self, parent)
        self._manager = None

        # Set proxy in webpage
        proxy = getProxy()

        if proxy is not None:
            self._manager = QgsNetworkAccessManager()
            self._manager.setProxy(proxy)
            self.setNetworkAccessManager(self._manager)
Example #6
0
    def run(self):
        """Do the work."""
        nam = QgsNetworkAccessManager()

        # Don't raise any error during processing, relay error reporting to self.finished()
        try:
            for i, bbox in enumerate(self.grid):
                if self.isCanceled():
                    return False

                # Get the filepath and create the output directory (if necessary)
                x, y = (
                    bbox.boundingBox().xMinimum(),
                    bbox.boundingBox().yMinimum(),
                )
                hemisphere = "S" if y < 0 else "N"
                dir_name = "%s%02d" % (hemisphere, abs(y))
                directory = self.output_dir.joinpath(dir_name)
                directory.mkdir(exist_ok=True)
                tile_name = "%s%02d%s%03d.hgt" % (
                    hemisphere,
                    abs(y),
                    "W" if x < 0 else "E",
                    abs(x),
                )
                filepath = self.output_dir.joinpath(dir_name, tile_name)
                self.tiles.append(filepath)
                if filepath.is_file():
                    QgsMessageLog.logMessage(
                        message=f"Already downloaded tile {tile_name}",
                        level=Qgis.Info,
                    )
                    continue

                # get the new tile if it didn't exist
                url = QUrl(
                    f"http://s3.amazonaws.com/elevation-tiles-prod/skadi/{dir_name}/{tile_name}.gz"
                )
                request = QNetworkRequest(url)
                reply: QgsNetworkReplyContent = nam.blockingGet(request)
                # turn the reply into a file object and write the decompressed file to disk
                with gzip.GzipFile(
                    fileobj=BytesIO(reply.content()), mode="rb"
                ) as gz:
                    with open(filepath, "wb") as f:
                        f.write(gz.read())

                self.setProgress((i / len(self.grid)) * 100)

            return True
        except Exception as e:
            self.exception = e
            return False
Example #7
0
    def __init__(self, path_work=None, url_base=None, parent=None):
        self.masplug_path = None

        if url_base is None:
            self.url_base = ''
        else:
            self.url_base = url_base
        self.parent = parent
        if parent is None:
            self.dbg = True
        else:
            self.dbg = self.parent.DEBUG

        if path_work is None:
            self.masplug_path = ''
        else:
            self.masplug_path = path_work
        self.file_install = None
        self.url = None
        self.manager = QgsNetworkAccessManager()
        self.manager = self.manager.instance()
Example #8
0
    def result(self, result):
        # See if OK was pressed
        if result:
            project = QgsProject.instance()
            # First get all the values of the GUI items
            crs_input = self.dlg.crs_input.crs()
            crs_out = QgsCoordinateReferenceSystem(
                'EPSG:4326')  # we need this to be WGS84 for Nominatim
            lineedit_text = self.dlg.lineedit_xy.value()

            # Protect the free text field for coordinates from generic user failure
            try:
                lineedit_yx = [
                    float(coord.strip()) for coord in lineedit_text.split(',')
                ]
            except:
                QMessageBox.critical(
                    self.iface.mainWindow(), 'QuickAPI error',
                    "Did you really specify a coordinate in comma-separated Lat/Long?\nExiting..."
                )
                return

            # Create a Point and transform if necessary
            point = QgsPointXY(*reversed(lineedit_yx))
            if crs_input.authid() != 'EPSG:4326':
                xform = QgsCoordinateTransform(crs_input, crs_out, project)
                point_transform = xform.transform(point)
                point = point_transform

            # Set up the GET Request to Nominatim
            query = QUrlQuery()
            query.addQueryItem('lat', str(point.y()))
            query.addQueryItem('lon', str(point.x()))
            query.addQueryItem('format', 'json')

            url = QUrl('https://nominatim.openstreetmap.org/reverse')
            url.setQuery(query)

            request = QNetworkRequest(url)
            request.setHeader(QNetworkRequest.UserAgentHeader,
                              '*****@*****.**')

            nam = QgsNetworkAccessManager()
            response: QgsNetworkReplyContent = nam.blockingGet(request)

            # Only process if HTTP status code is 200
            status_code = response.attribute(
                QNetworkRequest.HttpStatusCodeAttribute)
            if status_code == 200:
                # Get the content of the response and process it
                response_json = json.loads(bytes(response.content()))
                if response_json.get('error'):
                    QMessageBox.critical(
                        self.iface.mainWindow(), "Quick API error",
                        "The request was not processed succesfully!\n\n"
                        "Message:\n"
                        "{}".format(response_json['error']))
                    return

                x = float(response_json['lon'])
                y = float(response_json['lat'])
                address = response_json['display_name']
                license = response_json['licence']

                # Create the output memory layer
                layer_out = QgsVectorLayer(
                    "Point?crs=EPSG:4326&field=address:string&field=license:string",
                    "Nominatim Reverse Geocoding", "memory")

                # Create the output feature (only one here)
                point_out = QgsPointXY(x, y)
                feature = QgsFeature()
                feature.setGeometry(QgsGeometry.fromPointXY(point_out))
                feature.setAttributes([address, license])

                # Add feature to layer and layer to map
                layer_out.dataProvider().addFeature(feature)
                layer_out.updateExtents()
                project.addMapLayer(layer_out)

                # build bbox for auto-zoom feature
                bbox = [float(coord) for coord in response_json['boundingbox']]
                min_y, max_y, min_x, max_x = bbox
                bbox_geom = QgsGeometry.fromRect(
                    QgsRectangle(min_x, min_y, max_x, max_y))

                # Transform bbox if map canvas has a different CRS
                if project.crs().authid() != 'EPSG:4326':
                    xform = QgsCoordinateTransform(crs_out, project.crs(),
                                                   project)
                    bbox_geom.transform(xform)

                self.iface.mapCanvas().zoomToFeatureExtent(
                    QgsRectangle.fromWkt(bbox_geom.asWkt()))
Example #9
0
    def __init__(self, parent, iface, chunks, playlistUrl, mimeType, encoding):
        super(Streaming, self).__init__()

        self.DEBUG = True

        # Variables from other classes
        self.parent = parent  # For GUI access
        self.iface = iface
        self.chunks = chunks
        self.playlistUrl = playlistUrl
        self.mimeType = mimeType
        self.encoding = encoding

        # Internal variables
        self.__endTag = "#PLAYLIST-END"
        self.__exceptionTag = "#EXCEPTION"
        self.__exceptionUrl = ""
        self.__exceptionFound = False
        self.__playlistFinished = False  # Did the end tag appeared?
        self.__bytesInlastReply = 0  # To compare last and current reply sizes
        self.__loadedChunks = 0  # For keeping track of # of loaded (to local vars) chunks
        self.__deliveredChunks = 0  # For keeping track of # of loaded (to the map) chunks
        self.__bFirstChunk = True
        self.__features = {}  # {0:[f0,f1,f2], 1:[f0,f1]}
        self.__bGeomMulti = False  # Is the geometry multi{point|line|polygon}
        self.__geometryType = ""  # Values: "Point","LineString","Polygon","Unknown", "NoGeometry"
        self.__tmpGeometry = {
        }  # For visualization purposes {chunkId1: rb1, chunkId2: rb2 }
        self.__memoryLayer = None  # The whole merged data

        # For rasters only
        self.__legend = self.iface.legendInterface()
        self.__groupIndex = 0
        self.__chunksDir = None
        self.__virtualFile = ""  # Virtual raster file path
        if isMimeTypeRaster(self.mimeType, True) != None:
            self.__chunksDir = tempfile.mkdtemp(prefix="tmpChunks")

        # Other objects
        self.timer = QTimer()
        self.timer.setInterval(1 * 1000)  # 1 second
        self.QNAM4Playlist = QgsNetworkAccessManager()
        self.QNAM4Chunks = QgsNetworkAccessManager()
        self.QNAM4Exception = QgsNetworkAccessManager()

        # SIGNAL/SLOT connections
        self.playlistHandled.connect(self.fetchChunks)
        self.urlReady.connect(self.fetchResult)
        self.dataReady.connect(self.loadData)
        self.timer.timeout.connect(
            partial(self.fetchPlaylist, self.playlistUrl))

        self.QNAM4Playlist.finished.connect(self.handlePlaylist)
        self.QNAM4Chunks.finished.connect(self.handleChunk)
        self.QNAM4Exception.finished.connect(self.handleException)
        #self.QNAM4Playlist = QgsNetworkAccessManager.instance()
        #theReply2.error.connect(self.handleErrors)

        # GUI
        self.parent.progressBar.setRange(0, 0)
        self.parent.lblProcess.setText("Reading output playlist...")
Example #10
0
 def __init__(self, server):
     self._nam = QgsNetworkAccessManager()
     self._server = server
     self._token = None
     self._replies = []