FreeCAD
693 строки · 29.6 Кб
1# SPDX-License-Identifier: LGPL-2.1-or-later
2# ***************************************************************************
3# * *
4# * Copyright (c) 2022-2023 FreeCAD Project Association *
5# * *
6# * This file is part of FreeCAD. *
7# * *
8# * FreeCAD is free software: you can redistribute it and/or modify it *
9# * under the terms of the GNU Lesser General Public License as *
10# * published by the Free Software Foundation, either version 2.1 of the *
11# * License, or (at your option) any later version. *
12# * *
13# * FreeCAD is distributed in the hope that it will be useful, but *
14# * WITHOUT ANY WARRANTY; without even the implied warranty of *
15# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
16# * Lesser General Public License for more details. *
17# * *
18# * You should have received a copy of the GNU Lesser General Public *
19# * License along with FreeCAD. If not, see *
20# * <https://www.gnu.org/licenses/>. *
21# * *
22# ***************************************************************************
23
24"""
25#############################################################################
26#
27# ABOUT NETWORK MANAGER
28#
29# A wrapper around QNetworkAccessManager providing proxy-handling
30# capabilities, and simplified access to submitting requests from any
31# application thread.
32#
33#
34# USAGE
35#
36# Once imported, this file provides access to a global object called
37# AM_NETWORK_MANAGER. This is a QObject running on the main thread, but
38# designed to be interacted with from any other application thread. It
39# provides two principal methods: submit_unmonitored_get() and
40# submit_monitored_get(). Use the unmonitored version for small amounts of
41# data (suitable for caching in RAM, and without a need to show a progress
42# bar during download), and the monitored version for larger amounts of data.
43# Both functions take a URL, and return an integer index. That index allows
44# tracking of the completed request by attaching to the signals completed(),
45# progress_made(), and progress_complete(). All three provide, as the first
46# argument to the signal, the index of the request the signal refers to.
47# Code attached to those signals should filter them to look for the indices
48# of the requests they care about. Requests may complete in any order.
49#
50# A secondary blocking interface is also provided, for very short network
51# accesses: the blocking_get() function blocks until the network transmission
52# is complete, directly returning a QByteArray object with the received data.
53# Do not run on the main GUI thread!
54"""
55
56import threading57import os58import queue59import itertools60import tempfile61import sys62from typing import Dict, List, Optional63
64try:65import FreeCAD66
67if FreeCAD.GuiUp:68import FreeCADGui69
70HAVE_FREECAD = True71translate = FreeCAD.Qt.translate72except ImportError:73# For standalone testing support working without the FreeCAD import74HAVE_FREECAD = False75
76from PySide import QtCore77
78if FreeCAD.GuiUp:79from PySide import QtWidgets80
81
82# This is the global instance of the NetworkManager that outside code
83# should access
84AM_NETWORK_MANAGER = None85
86HAVE_QTNETWORK = True87try:88from PySide import QtNetwork89except ImportError:90if HAVE_FREECAD:91FreeCAD.Console.PrintError(92translate(93"AddonsInstaller",94'Could not import QtNetwork -- it does not appear to be installed on your system. Your provider may have a package for this dependency (often called "python3-pyside2.qtnetwork")',95)96+ "\n"97)98else:99print("Could not import QtNetwork, unable to test this file.")100sys.exit(1)101HAVE_QTNETWORK = False102
103if HAVE_QTNETWORK:104
105# Added in Qt 5.15106if hasattr(QtNetwork.QNetworkRequest, "DefaultTransferTimeoutConstant"):107default_timeout = QtNetwork.QNetworkRequest.DefaultTransferTimeoutConstant108else:109default_timeout = 30000110
111class QueueItem:112"""A container for information about an item in the network queue."""113
114def __init__(self, index: int, request: QtNetwork.QNetworkRequest, track_progress: bool):115self.index = index116self.request = request117self.original_url = request.url()118self.track_progress = track_progress119
120class NetworkManager(QtCore.QObject):121"""A single global instance of NetworkManager is instantiated and stored as122AM_NETWORK_MANAGER. Outside threads should send GET requests to this class by
123calling the submit_unmonitored_request() or submit_monitored_request() function,
124as needed. See the documentation of those functions for details."""
125
126# Connect to complete for requests with no progress monitoring (e.g. small amounts of data)127completed = QtCore.Signal(128int, int, QtCore.QByteArray129) # Index, http response code, received data (if any)130
131# Connect to progress_made and progress_complete for large amounts of data, which get buffered into a temp file132# That temp file should be deleted when your code is done with it133progress_made = QtCore.Signal(int, int, int) # Index, bytes read, total bytes (may be None)134
135progress_complete = QtCore.Signal(136int, int, os.PathLike137) # Index, http response code, filename138
139__request_queued = QtCore.Signal()140
141def __init__(self):142super().__init__()143
144self.counting_iterator = itertools.count()145self.queue = queue.Queue()146self.__last_started_index = 0147self.__abort_when_found: List[int] = []148self.replies: Dict[int, QtNetwork.QNetworkReply] = {}149self.file_buffers = {}150
151# We support an arbitrary number of threads using synchronous GET calls:152self.synchronous_lock = threading.Lock()153self.synchronous_complete: Dict[int, bool] = {}154self.synchronous_result_data: Dict[int, QtCore.QByteArray] = {}155
156# Make sure we exit nicely on quit157if QtCore.QCoreApplication.instance() is not None:158QtCore.QCoreApplication.instance().aboutToQuit.connect(self.__aboutToQuit)159
160# Create the QNAM on this thread:161self.QNAM = QtNetwork.QNetworkAccessManager()162self.QNAM.proxyAuthenticationRequired.connect(self.__authenticate_proxy)163self.QNAM.authenticationRequired.connect(self.__authenticate_resource)164
165qnam_cache = QtCore.QStandardPaths.writableLocation(QtCore.QStandardPaths.CacheLocation)166os.makedirs(qnam_cache, exist_ok=True)167self.diskCache = QtNetwork.QNetworkDiskCache()168self.diskCache.setCacheDirectory(qnam_cache)169self.QNAM.setCache(self.diskCache)170
171self.monitored_connections: List[int] = []172self._setup_proxy()173
174# A helper connection for our blocking interface175self.completed.connect(self.__synchronous_process_completion)176
177# Set up our worker connection178self.__request_queued.connect(self.__setup_network_request)179
180def _setup_proxy(self):181"""Set up the proxy based on user preferences or prompts on command line"""182
183# Set up the proxy, if necessary:184if HAVE_FREECAD:185(186noProxyCheck,187systemProxyCheck,188userProxyCheck,189proxy_string,190) = self._setup_proxy_freecad()191else:192(193noProxyCheck,194systemProxyCheck,195userProxyCheck,196proxy_string,197) = self._setup_proxy_standalone()198
199if noProxyCheck:200pass201elif systemProxyCheck:202query = QtNetwork.QNetworkProxyQuery(203QtCore.QUrl("https://github.com/FreeCAD/FreeCAD")204)205proxy = QtNetwork.QNetworkProxyFactory.systemProxyForQuery(query)206if proxy and proxy[0]:207self.QNAM.setProxy(proxy[0]) # This may still be QNetworkProxy.NoProxy208elif userProxyCheck:209host, _, port_string = proxy_string.rpartition(":")210try:211port = 0 if not port_string else int(port_string)212except ValueError:213FreeCAD.Console.PrintError(214translate(215"AddonsInstaller",216"Failed to convert the specified proxy port '{}' to a port number",217).format(port_string)218+ "\n"219)220port = 0221# For now assume an HttpProxy, but eventually this should be a parameter222proxy = QtNetwork.QNetworkProxy(QtNetwork.QNetworkProxy.HttpProxy, host, port)223self.QNAM.setProxy(proxy)224
225def _setup_proxy_freecad(self):226"""If we are running within FreeCAD, this uses the config data to set up the proxy"""227noProxyCheck = True228systemProxyCheck = False229userProxyCheck = False230proxy_string = ""231pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons")232noProxyCheck = pref.GetBool("NoProxyCheck", noProxyCheck)233systemProxyCheck = pref.GetBool("SystemProxyCheck", systemProxyCheck)234userProxyCheck = pref.GetBool("UserProxyCheck", userProxyCheck)235proxy_string = pref.GetString("ProxyUrl", "")236
237# Add some error checking to the proxy setup, since for historical reasons they238# are independent booleans, rather than an enumeration:239option_count = [noProxyCheck, systemProxyCheck, userProxyCheck].count(True)240if option_count != 1:241FreeCAD.Console.PrintWarning(242translate(243"AddonsInstaller",244"Parameter error: mutually exclusive proxy options set. Resetting to default.",245)246+ "\n"247)248noProxyCheck = True249systemProxyCheck = False250userProxyCheck = False251pref.SetBool("NoProxyCheck", noProxyCheck)252pref.SetBool("SystemProxyCheck", systemProxyCheck)253pref.SetBool("UserProxyCheck", userProxyCheck)254
255if userProxyCheck and not proxy_string:256FreeCAD.Console.PrintWarning(257translate(258"AddonsInstaller",259"Parameter error: user proxy indicated, but no proxy provided. Resetting to default.",260)261+ "\n"262)263noProxyCheck = True264userProxyCheck = False265pref.SetBool("NoProxyCheck", noProxyCheck)266pref.SetBool("UserProxyCheck", userProxyCheck)267return noProxyCheck, systemProxyCheck, userProxyCheck, proxy_string268
269def _setup_proxy_standalone(self):270"""If we are NOT running inside FreeCAD, prompt the user for proxy information"""271noProxyCheck = True272systemProxyCheck = False273userProxyCheck = False274proxy_string = ""275print("Please select a proxy type:")276print("1) No proxy")277print("2) Use system proxy settings")278print("3) Custom proxy settings")279result = input("Choice: ")280if result == "1":281pass282elif result == "2":283noProxyCheck = False284systemProxyCheck = True285elif result == "3":286noProxyCheck = False287userProxyCheck = True288proxy_string = input("Enter your proxy server (host:port): ")289else:290print(f"Got {result}, expected 1, 2, or 3.")291app.quit()292return noProxyCheck, systemProxyCheck, userProxyCheck, proxy_string293
294def __aboutToQuit(self):295"""Called when the application is about to quit. Not currently used."""296
297def __setup_network_request(self):298"""Get the next request off the queue and launch it."""299try:300item = self.queue.get_nowait()301if item:302if item.index in self.__abort_when_found:303self.__abort_when_found.remove(item.index)304return # Do not do anything with this item, it's been aborted...305if item.track_progress:306self.monitored_connections.append(item.index)307self.__launch_request(item.index, item.request)308except queue.Empty:309pass310
311def __launch_request(self, index: int, request: QtNetwork.QNetworkRequest) -> None:312"""Given a network request, ask the QNetworkAccessManager to begin processing it."""313reply = self.QNAM.get(request)314self.replies[index] = reply315
316self.__last_started_index = index317reply.finished.connect(self.__reply_finished)318reply.redirected.connect(self.__follow_redirect)319reply.sslErrors.connect(self.__on_ssl_error)320if index in self.monitored_connections:321reply.readyRead.connect(self.__ready_to_read)322reply.downloadProgress.connect(self.__download_progress)323
324def submit_unmonitored_get(325self,326url: str,327timeout_ms: int = default_timeout,328) -> int:329"""Adds this request to the queue, and returns an index that can be used by calling code330in conjunction with the completed() signal to handle the results of the call. All data is
331kept in memory, and the completed() call includes a direct handle to the bytes returned. It
332is not called until the data transfer has finished and the connection is closed."""
333
334current_index = next(self.counting_iterator) # A thread-safe counter335# Use a queue because we can only put things on the QNAM from the main event loop thread336self.queue.put(337QueueItem(338current_index, self.__create_get_request(url, timeout_ms), track_progress=False339)340)341self.__request_queued.emit()342return current_index343
344def submit_monitored_get(345self,346url: str,347timeout_ms: int = default_timeout,348) -> int:349"""Adds this request to the queue, and returns an index that can be used by calling code350in conjunction with the progress_made() and progress_completed() signals to handle the
351results of the call. All data is cached to disk, and progress is reported periodically
352as the underlying QNetworkReply reports its progress. The progress_completed() signal
353contains a path to a temporary file with the stored data. Calling code should delete this
354file when done with it (or move it into its final place, etc.)."""
355
356current_index = next(self.counting_iterator) # A thread-safe counter357# Use a queue because we can only put things on the QNAM from the main event loop thread358self.queue.put(359QueueItem(360current_index, self.__create_get_request(url, timeout_ms), track_progress=True361)362)363self.__request_queued.emit()364return current_index365
366def blocking_get(367self,368url: str,369timeout_ms: int = default_timeout,370) -> Optional[QtCore.QByteArray]:371"""Submits a GET request to the QNetworkAccessManager and block until it is complete"""372
373current_index = next(self.counting_iterator) # A thread-safe counter374with self.synchronous_lock:375self.synchronous_complete[current_index] = False376
377self.queue.put(378QueueItem(379current_index, self.__create_get_request(url, timeout_ms), track_progress=False380)381)382self.__request_queued.emit()383while True:384if QtCore.QThread.currentThread().isInterruptionRequested():385return None386QtCore.QCoreApplication.processEvents()387with self.synchronous_lock:388if self.synchronous_complete[current_index]:389break390
391with self.synchronous_lock:392self.synchronous_complete.pop(current_index)393if current_index in self.synchronous_result_data:394return self.synchronous_result_data.pop(current_index)395return None396
397def __synchronous_process_completion(398self, index: int, code: int, data: QtCore.QByteArray399) -> None:400"""Check the return status of a completed process, and handle its returned data (if401any)."""
402with self.synchronous_lock:403if index in self.synchronous_complete:404if code == 200:405self.synchronous_result_data[index] = data406else:407FreeCAD.Console.PrintWarning(408translate(409"AddonsInstaller",410"Addon Manager: Unexpected {} response from server",411).format(code)412+ "\n"413)414self.synchronous_complete[index] = True415
416@staticmethod417def __create_get_request(url: str, timeout_ms: int) -> QtNetwork.QNetworkRequest:418"""Construct a network request to a given URL"""419request = QtNetwork.QNetworkRequest(QtCore.QUrl(url))420request.setAttribute(421QtNetwork.QNetworkRequest.RedirectPolicyAttribute,422QtNetwork.QNetworkRequest.UserVerifiedRedirectPolicy,423)424request.setAttribute(QtNetwork.QNetworkRequest.CacheSaveControlAttribute, True)425request.setAttribute(426QtNetwork.QNetworkRequest.CacheLoadControlAttribute,427QtNetwork.QNetworkRequest.PreferNetwork,428)429if hasattr(request, "setTransferTimeout"):430# Added in Qt 5.15431request.setTransferTimeout(timeout_ms)432return request433
434def abort_all(self):435"""Abort ALL network calls in progress, including clearing the queue"""436for reply in self.replies.values():437if reply.abort().isRunning():438reply.abort()439while True:440try:441self.queue.get()442self.queue.task_done()443except queue.Empty:444break445
446def abort(self, index: int):447"""Abort a specific request"""448if index in self.replies and self.replies[index].isRunning():449self.replies[index].abort()450elif index < self.__last_started_index:451# It's still in the queue. Mark it for later destruction.452self.__abort_when_found.append(index)453
454def __authenticate_proxy(455self,456reply: QtNetwork.QNetworkProxy,457authenticator: QtNetwork.QAuthenticator,458):459"""If proxy authentication is required, attempt to authenticate. If the GUI is running this displays460a window asking for credentials. If the GUI is not running, it prompts on the command line.
461"""
462if HAVE_FREECAD and FreeCAD.GuiUp:463proxy_authentication = FreeCADGui.PySideUic.loadUi(464os.path.join(os.path.dirname(__file__), "proxy_authentication.ui")465)466proxy_authentication.setWindowFlag(QtCore.Qt.WindowStaysOnTopHint, True)467# Show the right labels, etc.468proxy_authentication.labelProxyAddress.setText(f"{reply.hostName()}:{reply.port()}")469if authenticator.realm():470proxy_authentication.labelProxyRealm.setText(authenticator.realm())471else:472proxy_authentication.labelProxyRealm.hide()473proxy_authentication.labelRealmCaption.hide()474result = proxy_authentication.exec()475if result == QtWidgets.QDialogButtonBox.Ok:476authenticator.setUser(proxy_authentication.lineEditUsername.text())477authenticator.setPassword(proxy_authentication.lineEditPassword.text())478else:479username = input("Proxy username: ")480import getpass481
482password = getpass.getpass()483authenticator.setUser(username)484authenticator.setPassword(password)485
486def __authenticate_resource(487self,488_reply: QtNetwork.QNetworkReply,489_authenticator: QtNetwork.QAuthenticator,490):491"""Unused."""492
493def __follow_redirect(self, url):494"""Used with the QNetworkAccessManager to follow redirects."""495sender = self.sender()496current_index = -1497timeout_ms = default_timeout498# TODO: Figure out what the actual timeout value should be from the original request499if sender:500for index, reply in self.replies.items():501if reply == sender:502current_index = index503break504
505if current_index != -1:506self.__launch_request(current_index, self.__create_get_request(url, timeout_ms))507
508def __on_ssl_error(self, reply: str, errors: List[str] = None):509"""Called when an SSL error occurs: prints the error information."""510if HAVE_FREECAD:511FreeCAD.Console.PrintWarning(512translate("AddonsInstaller", "Error with encrypted connection") + "\n:"513)514FreeCAD.Console.PrintWarning(reply)515if errors is not None:516for error in errors:517FreeCAD.Console.PrintWarning(error)518else:519print("Error with encrypted connection")520if errors is not None:521for error in errors:522print(error)523
524def __download_progress(self, bytesReceived: int, bytesTotal: int) -> None:525"""Monitors download progress and emits a progress_made signal"""526sender = self.sender()527if not sender:528return529for index, reply in self.replies.items():530if reply == sender:531self.progress_made.emit(index, bytesReceived, bytesTotal)532return533
534def __ready_to_read(self) -> None:535"""Called when data is available, this reads that data."""536sender = self.sender()537if not sender:538return539
540for index, reply in self.replies.items():541if reply == sender:542self.__data_incoming(index, reply)543return544
545def __data_incoming(self, index: int, reply: QtNetwork.QNetworkReply) -> None:546"""Read incoming data and attach it to a data object"""547if not index in self.replies:548# We already finished this reply, this is a vestigial signal549return550buffer = reply.readAll()551if not index in self.file_buffers:552f = tempfile.NamedTemporaryFile("wb", delete=False)553self.file_buffers[index] = f554else:555f = self.file_buffers[index]556try:557f.write(buffer.data())558except OSError as e:559if HAVE_FREECAD:560FreeCAD.Console.PrintError(f"Network Manager internal error: {str(e)}")561else:562print(f"Network Manager internal error: {str(e)}")563
564def __reply_finished(self) -> None:565"""Called when a reply has been completed: this makes sure the data has been read and566any notifications have been called."""
567reply = self.sender()568if not reply:569# This can happen during a cancellation operation: silently do nothing570return571
572index = None573for key, value in self.replies.items():574if reply == value:575index = key576break577if index is None:578return579
580response_code = reply.attribute(QtNetwork.QNetworkRequest.HttpStatusCodeAttribute)581if response_code == 301 or response_code == 302: # This is a redirect, bail out582return583if reply.error() != QtNetwork.QNetworkReply.NetworkError.OperationCanceledError:584# It this was not a timeout, make sure we mark the queue task done585self.queue.task_done()586if reply.error() == QtNetwork.QNetworkReply.NetworkError.NoError:587if index in self.monitored_connections:588# Make sure to read any remaining data589self.__data_incoming(index, reply)590self.monitored_connections.remove(index)591f = self.file_buffers[index]592f.close()593self.progress_complete.emit(index, response_code, f.name)594else:595data = reply.readAll()596self.completed.emit(index, response_code, data)597else:598if index in self.monitored_connections:599self.progress_complete.emit(index, response_code, "")600else:601self.completed.emit(index, response_code, None)602self.replies.pop(index)603
604else: # HAVE_QTNETWORK is false:605
606class NetworkManager(QtCore.QObject):607"""A dummy class to enable an offline mode when the QtNetwork package is not yet installed"""608
609completed = QtCore.Signal(610int, int, bytes611) # Emitted as soon as the request is made, with a connection failed error612progress_made = QtCore.Signal(int, int, int) # Never emitted, no progress is made here613progress_complete = QtCore.Signal(614int, int, os.PathLike615) # Emitted as soon as the request is made, with a connection failed error616
617def __init__(self):618super().__init__()619self.monitored_queue = queue.Queue()620self.unmonitored_queue = queue.Queue()621
622def submit_unmonitored_request(self, _) -> int:623"""Returns a fake index that can be used for testing -- nothing is actually queued"""624current_index = next(itertools.count())625self.unmonitored_queue.put(current_index)626return current_index627
628def submit_monitored_request(self, _) -> int:629"""Returns a fake index that can be used for testing -- nothing is actually queued"""630current_index = next(itertools.count())631self.monitored_queue.put(current_index)632return current_index633
634def blocking_get(self, _: str) -> QtCore.QByteArray:635"""No operation - returns None immediately"""636return None637
638def abort_all(639self,640):641"""There is nothing to abort in this case"""642
643def abort(self, _):644"""There is nothing to abort in this case"""645
646
647def InitializeNetworkManager():648"""Called once at the beginning of program execution to create the appropriate manager object"""649global AM_NETWORK_MANAGER650if AM_NETWORK_MANAGER is None:651AM_NETWORK_MANAGER = NetworkManager()652
653
654if __name__ == "__main__":655app = QtCore.QCoreApplication()656
657InitializeNetworkManager()658
659count = 0660
661# For testing, create several network requests and send them off in quick succession:662# (Choose small downloads, no need for significant data)663urls = [664"https://api.github.com/zen",665"http://climate.ok.gov/index.php/climate/rainfall_table/local_data",666"https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/AIANNHA/MapServer",667]668
669def handle_completion(index: int, code: int, data):670"""Attached to the completion signal, prints diagnostic information about the network access"""671global count672if code == 200:673print(f"For request {index+1}, response was {data.size()} bytes.", flush=True)674else:675print(676f"For request {index+1}, request failed with HTTP result code {code}",677flush=True,678)679
680count += 1681if count >= len(urls):682print("Shutting down...", flush=True)683AM_NETWORK_MANAGER.requestInterruption()684AM_NETWORK_MANAGER.wait(5000)685app.quit()686
687AM_NETWORK_MANAGER.completed.connect(handle_completion)688for test_url in urls:689AM_NETWORK_MANAGER.submit_unmonitored_get(test_url)690
691app.exec_()692
693print("Done with all requests.")694