示例#1
0
文件: rest.py 项目: tanonl/openuds
 def get(self):
     request = QNetworkRequest(self.url)
     request.setRawHeader(
         b'User-Agent',
         osDetector.getOs().encode('utf-8') + b" - UDS Connector " +
         VERSION.encode('utf-8'))
     self._manager.get(request)
示例#2
0
 def _makeRequestByType(self, type: str) -> None:
     Logger.log("i", "Marketplace: Requesting %s metadata from server.",
                type)
     request = QNetworkRequest(self._request_urls[type])
     request.setRawHeader(*self._request_header)
     if self._network_manager:
         self._network_manager.get(request)
示例#3
0
 def _makeRequestByType(self, request_type: str) -> None:
     Logger.log("i", "Requesting %s metadata from server.", request_type)
     request = QNetworkRequest(self._request_urls[request_type])
     for header_name, header_value in self._request_headers:
         request.setRawHeader(header_name, header_value)
     if self._network_manager:
         self._network_manager.get(request)
 def _createRequest(self, url: str, basic_auth_username: str = "", basic_auth_password: str = "") -> QNetworkRequest:
     request = QNetworkRequest(url)
     request.setRawHeader("User-Agent".encode(), self._user_agent)
     if basic_auth_username and basic_auth_password:
         data = base64.b64encode(("%s:%s" % (basic_auth_username, basic_auth_password)).encode()).decode("utf-8")
         request.setRawHeader("Authorization".encode(), ("Basic %s" % data).encode())
     return request
示例#5
0
 def _get(self, url):
     """设置图片或者请求网络图片
     :param url:
     """
     if not url:
         self.onError('')
         return
     if url.startswith('http') and not self.loadingTimer.isActive():
         url = QUrl(url)
         request = QNetworkRequest(url)
         request.setHeader(QNetworkRequest.UserAgentHeader, b'CAvatar')
         request.setRawHeader(b'Author', b'Irony')
         request.setAttribute(QNetworkRequest.FollowRedirectsAttribute,
                              True)
         if qApp._network.cache():
             request.setAttribute(QNetworkRequest.CacheLoadControlAttribute,
                                  QNetworkRequest.PreferNetwork)
             request.setAttribute(QNetworkRequest.CacheSaveControlAttribute,
                                  True)
         reply = qApp._network.get(request)
         self.pradius = 0
         self.loadingTimer.start(50)  # 显示进度动画
         reply.finished.connect(self.onFinished)
         reply.error.connect(self.onError)
         return
     self.pradius = 0
     if os.path.exists(url) and os.path.isfile(url):
         self._pixmap = QPixmap(url)
         self._resizePixmap()
     else:
         self.onError('')
示例#6
0
 def _makeRequestByType(self, request_type: str) -> None:
     Logger.log("d", "Requesting %s metadata from server.", request_type)
     request = QNetworkRequest(self._request_urls[request_type])
     for header_name, header_value in self._request_headers:
         request.setRawHeader(header_name, header_value)
     if self._network_manager:
         self._network_manager.get(request)
示例#7
0
def pack_request(request, ssl_config):
    """Create a QNetworkRequest
    """
    if not isinstance(request.url, bytes):
        # No great exception to raise here
        return None

    from . ssl_config import SSLConfig as QtSSLConfig
    assert isinstance(ssl_config, QtSSLConfig)

    # PyQt5 specifically wants text.
    if not isinstance(request.url, str):
        url = request.url.decode("utf-8")
    else:
        url = request.url
    q_url = QUrl(url)
    q_request = QNetworkRequest(q_url)

    # Set headers on the request.
    # We use setRawHeader to avoid looking up header-name constants.
    for header_name, header_value in request.headers.pairs():
        q_request.setRawHeader(header_name, header_value)

    # Set SSL configuration (SSLConfig hides many details).
    q_request.setSslConfiguration(ssl_config._q_ssl_config)

    return q_request
示例#8
0
    def saveServer(self, image):
        name = 'tmp.png'
        url = 'https://joxi-server.herokuapp.com/save'

        # save file on disk
        image.save(f"./{name}")

        with open(f"./{name}", 'rb') as img:
            files = {
                'image': (name, img, 'multipart/form-data', {
                    'Expires': '0'
                })
            }

            with requests.Session() as s:
                # create pyqt QNetworkRequest from requests module
                r = s.post(url, files=files)
                request = r.request
                request.prepare(method="POST", url=url)

                request_qt = QNetworkRequest(QUrl(url))

                for header, value in request.headers.items():
                    request_qt.setRawHeader(bytes(header, encoding="utf-8"),
                                            bytes(value, encoding="utf-8"))

                # set handlers
                self.manager = QNetworkAccessManager()
                self.manager.finished.connect(self.saveServerFinished)
                self.manager.post(request_qt, request.body)
    def confirm_modify_message(self, content):
        """ 确定修改内容 """
        def modify_finished():
            f_reply = self.sender()
            if f_reply.error():
                p_info = InformationPopup("修改失败了!\n只能修改自己发送的短信通", popup)
                p_info.exec_()
            else:
                p_info = InformationPopup("修改成功!", popup)
                p_info.exec_()
                popup.close()
                self.content_label.setText(
                    popup.text_edit.toHtml())  # 设置修改后的内容

        popup = self.sender()
        # 发送修改的网络请求
        network_manager = getattr(qApp, "_network")
        url = SERVER_API + "short-message/{}/".format(self.msg_id)
        user_token = get_user_token()
        request = QNetworkRequest(QUrl(url))
        request.setRawHeader("Authorization".encode("utf-8"),
                             user_token.encode("utf-8"))
        body_data = {"message_content": content[5:]}
        reply = network_manager.put(request,
                                    json.dumps(body_data).encode("utf-8"))
        reply.finished.connect(modify_finished)
 def _createRequest(self, url: str, basic_auth_username: str = "", basic_auth_password: str = "") -> QNetworkRequest:
     request = QNetworkRequest(url)
     request.setRawHeader("User-Agent".encode(), self._user_agent)
     if basic_auth_username and basic_auth_password:
         data = base64.b64encode(("%s:%s" % (basic_auth_username, basic_auth_password)).encode()).decode("utf-8")
         request.setRawHeader("Authorization".encode(), ("Basic %s" % data).encode())
     return request
示例#11
0
 def modify_client_information(self):
     """ 修改客户端的基本信息 """
     sender_button = self.sender()
     current_row = getattr(sender_button, "row_index")
     client_id = self.client_table.item(current_row, 0).text()
     client_name = self.client_table.item(current_row, 2).text().strip()
     client_uuid = self.client_table.item(current_row, 3).text()
     is_manager = 1 if self.client_table.item(current_row,
                                              4).checkState() else 0
     is_active = 1 if self.client_table.item(current_row,
                                             5).checkState() else 0
     body_data = {
         "client_id": client_id,
         "client_name": client_name,
         "is_manager": is_manager,
         "is_active": is_active,
         "client_uuid": client_uuid
     }
     url = SERVER_API + 'client/{}/'.format(client_id)
     request = QNetworkRequest(QUrl(url))
     user_token = get_user_token()
     request.setRawHeader("Authorization".encode("utf-8"),
                          user_token.encode("utf-8"))
     network_manger = getattr(qApp, "_network")
     reply = network_manger.put(request,
                                json.dumps(body_data).encode("utf-8"))
     reply.finished.connect(self.modify_client_reply)
 def create_new_advertisement(self):
     """ 确认创建新的广告 """
     ad_params = self.get_new_advertisement_params()
     if not all([ad_params["image"], ad_params["title"]]):
         p = InformationPopup("标题和图片不能为空!", self)
         p.exec_()
         return
     self.create_button.setEnabled(False)
     image_file = QFile(ad_params["image"])
     image_file.open(QFile.ReadOnly)
     file_dict = {"image": image_file}
     if ad_params["filepath"]:
         pdf_file = QFile(ad_params["filepath"])
         pdf_file.open(QFile.ReadOnly)
         file_dict["pdf_file"] = pdf_file
     text_dict = ad_params.copy()
     multipart_data = generate_multipart_data(text_dict, file_dict)
     # close后便无法生成multipartData
     # image_file.close()
     # if pdf_file:
     #     pdf_file.close()
     url = SERVER_API + 'advertisement/'
     request = QNetworkRequest(QUrl(url))
     request.setRawHeader("Authorization".encode("utf-8"),
                          get_user_token().encode("utf-8"))
     network_manager = getattr(qApp, "_network")
     reply = network_manager.post(request, multipart_data)
     reply.finished.connect(self.create_advertisement_reply)
     multipart_data.setParent(reply)
示例#13
0
 def modify_user_information(self):
     """ 修改用户的基础信息 """
     current_row = getattr(self.sender(), "row_index")
     role = self.user_list_widget.show_user_table.cellWidget(
         current_row, 5).currentData()
     is_active = 1 if self.user_list_widget.show_user_table.item(
         current_row, 6).checkState() else 0
     body_data = {
         "modify_id":
         self.user_list_widget.show_user_table.item(current_row, 0).text(),
         "user_code":
         self.user_list_widget.show_user_table.item(current_row, 3).text(),
         "username":
         self.user_list_widget.show_user_table.item(current_row, 1).text(),
         "phone":
         self.user_list_widget.show_user_table.item(current_row, 2).text(),
         "email":
         self.user_list_widget.show_user_table.item(current_row, 4).text(),
         "role":
         role,
         "is_active":
         is_active,
         "note":
         self.user_list_widget.show_user_table.item(current_row, 10).text()
     }
     user_token = get_user_token()
     network_manager = getattr(qApp, "_network")
     url = SERVER_API + "user/info/"
     request = QNetworkRequest(QUrl(url))
     request.setRawHeader("Authorization".encode("utf-8"),
                          user_token.encode('utf-8'))
     reply = network_manager.put(request,
                                 json.dumps(body_data).encode('utf-8'))
     reply.finished.connect(self.modify_information_reply)
    def add_request(self, request):
        if len(self.requests_in_flight) > self.max_in_flight:
            self.evict_timed_out_requests()

        self.requests_in_flight[id(request)] = request
        log = [request, 0]
        performed_requests.append(log)

        # qt_request is managed by QNetworkAccessManager, so we don't have to
        qt_request = QNetworkRequest(QUrl(request.url))
        qt_request.setPriority(request.priority)
        qt_request.setHeader(QNetworkRequest.ContentTypeHeader,
                             "application/x-www-form-urlencoded")
        qt_request.setRawHeader(b'X-Api-Key', self.key)

        buf = QBuffer()
        if request.raw_data:
            buf.setData(request.raw_data)
        buf.open(QIODevice.ReadOnly)

        request.reply = self.sendCustomRequest(qt_request,
                                               request.method.encode("utf8"),
                                               buf)
        buf.setParent(request.reply)

        connect(request.reply.finished, lambda: request.on_finished(request))
示例#15
0
    def send_local_report(self, body_data):
        """ 上传本地报告文件 """
        def create_report_reply():
            if reply.error():
                message = "创建报告失败!"
            else:
                message = "创建报告成功!"
                self.local_file_edit.clear()
                self.clear_relative_variety()
            reply.deleteLater()
            p = InformationPopup(message, self)
            p.exec_()

        # 文件信息
        file = QFile(self.local_file_path)
        file.open(QFile.ReadOnly)
        file_dict = {"report_file": file}
        # 其他信息
        text_dict = body_data.copy()
        multipart_data = generate_multipart_data(text_dict, file_dict)
        url = SERVER_API + 'report-file/'
        request = QNetworkRequest(QUrl(url))
        request.setRawHeader("Authorization".encode("utf-8"),
                             get_user_token().encode("utf-8"))
        network_manager = getattr(qApp, "_network")
        reply = network_manager.post(request, multipart_data)
        reply.finished.connect(create_report_reply)
        multipart_data.setParent(reply)
示例#16
0
 def _createEmptyRequest(self, path: str, content_type: Optional[str] = "application/json") -> QNetworkRequest:
     request = QNetworkRequest(QUrl(path))
     if content_type:
         request.setHeader(QNetworkRequest.ContentTypeHeader, content_type)
     access_token = self._account.accessToken
     if access_token:
         request.setRawHeader(b"Authorization", "Bearer {}".format(access_token).encode())
     return request
示例#17
0
 def reconnect(self, url):
     self.disconnect()
     request = QNetworkRequest(url)
     request.setRawHeader(b"Accept", b"text/event-stream")
     self._reply = self._manager.get(request)
     self._reply.readyRead.connect(self.processReadyRead)
     self._reply.finished.connect(self.processFinished)
     self.status = self.Status.Connecting
示例#18
0
 def _createEmptyRequest(self, path: str, content_type: Optional[str] = "application/json") -> QNetworkRequest:
     request = QNetworkRequest(QUrl(path))
     if content_type:
         request.setHeader(QNetworkRequest.ContentTypeHeader, content_type)
     access_token = self._account.accessToken
     if access_token:
         request.setRawHeader(b"Authorization", "Bearer {}".format(access_token).encode())
     return request
 def getPrinterList(self, base_url):        
     self._instance_responded = False
     url = QUrl("http://" + base_url + "/printer/info")
     Logger.log("d", "getPrinterList:" + url.toString())
     settings_request = QNetworkRequest(url)        
     settings_request.setRawHeader("User-Agent".encode(), self._user_agent)
     self._printerlist_reply=self._network_manager.get(settings_request)
     return self._printers
示例#20
0
 def download(self):
     row = self.tableWidget.selectionModel().currentIndex().row()
     URL = self.tableWidget.video_list[row][1]
     page_url = self.tableWidget.video_list[row][2]
     request = QNetworkRequest(URL)
     request.setRawHeader(b'Referer', page_url.encode('utf-8'))
     self.downloadRequested.emit(request)
     self.accept()  # quit dialog
 def downloadFile(self, index=0):
     self.file = QtCore.QFile(self.download_list[index][0], self)
     if self.file.exists():
         self.file.resize(0)
     req = QNetworkRequest(
         QtCore.QUrl.fromUserInput(self.download_list[index][1]))
     req.setRawHeader(b'User-Agent', self.useragent)
     self.startDownload(req)
示例#22
0
 def _get_variety_sheets(self, variety_en):
     """ 获取当前品种下的数据表 """
     network_manager = getattr(qApp, "_network")
     user_token = get_user_token()
     url = SERVER_API + "variety/{}/sheet/".format(variety_en)
     request = QNetworkRequest(QUrl(url))
     request.setRawHeader("Authorization".encode("utf-8"), user_token.encode("utf-8"))
     reply = network_manager.get(request)
     reply.finished.connect(self.variety_sheets_reply)
 def _setAuth(self, request: QNetworkRequest) -> None:
     # FIXME: Waiting for Thingiverse app approval
     # token = PreferencesHelper.getSettingValue(Settings.THINGIVERSE_API_TOKEN_KEY)
     # if not token or token == "":
     #     # If the user was not signed in we use a default token for the public endpoints.
     #     token = Settings.THINGIVERSE_API_TOKEN
     request.setRawHeader(
         b"Authorization",
         "Bearer {}".format(Settings.THINGIVERSE_API_TOKEN).encode())
示例#24
0
 def _setAuth(self, request: QNetworkRequest) -> None:
     token = PreferencesHelper.getSettingValue(
         Settings.MYMINIFACTORY_API_TOKEN_KEY)
     if not token or token == "":
         # If the user was not signed in we use a default token for the public endpoints.
         # We'll use the 'old way' of injecting the API key in the request
         return self._injectApiToken(request)
     request.setRawHeader(b"Authorization",
                          "Bearer {}".format(token).encode())
 def confirm_delete_short_message(self):
     network_manager = getattr(qApp, "_network")
     url = SERVER_API + 'short-message/{}/'.format(self.msg_id)
     user_token = get_user_token()
     request = QNetworkRequest(QUrl(url))
     request.setRawHeader("Authorization".encode("utf-8"),
                          user_token.encode("utf-8"))
     reply = network_manager.deleteResource(request)
     reply.finished.connect(self.delete_message_reply)
示例#26
0
    def repository_clicked(self):
        selection_model = self.repository_lv.selectionModel()
        if selection_model is not None and selection_model.hasSelection():
            selected = selection_model.currentIndex()
            selected_info = self.repo_soundpacks[selected.row()]

            self.viewname_le.setText(selected_info['viewname'])
            self.name_le.setText(selected_info['name'])

            if selected_info['type'] == 'direct_download':
                self.path_label.setText(_('Url:'))
                self.path_le.setText(selected_info['url'])
                self.homepage_tb.setText('<a href="{url}">{url}</a>'.format(
                    url=html.escape(selected_info['homepage'])))
                if 'size' not in selected_info:
                    if not (self.current_repo_info is not None
                            and self.http_reply is not None
                            and self.http_reply.isRunning()
                            and self.current_repo_info is selected_info):
                        if (self.http_reply is not None
                                and self.http_reply.isRunning()):
                            self.http_reply_aborted = True
                            self.http_reply.abort()

                        self.http_reply_aborted = False
                        self.size_le.setText(_('Getting remote size'))
                        self.current_repo_info = selected_info

                        request = QNetworkRequest(QUrl(selected_info['url']))
                        request.setRawHeader(b'User-Agent',
                                             cons.FAKE_USER_AGENT)

                        self.http_reply = self.qnam.head(request)
                        self.http_reply.finished.connect(
                            self.size_query_finished)
                else:
                    self.size_le.setText(sizeof_fmt(selected_info['size']))
            elif selected_info['type'] == 'browser_download':
                self.path_label.setText(_('Url:'))
                self.path_le.setText(selected_info['url'])
                self.homepage_tb.setText('<a href="{url}">{url}</a>'.format(
                    url=html.escape(selected_info['homepage'])))
                if 'size' in selected_info:
                    self.size_le.setText(sizeof_fmt(selected_info['size']))
                else:
                    self.size_le.setText(_('Unknown'))

        if (self.soundpacks_dir is not None
                and os.path.isdir(self.soundpacks_dir)
                and not self.tab_disabled):
            self.install_new_button.setEnabled(True)
        self.disable_existing_button.setEnabled(False)
        self.delete_existing_button.setEnabled(False)

        installed_selection = self.installed_lv.selectionModel()
        if installed_selection is not None:
            installed_selection.clearSelection()
示例#27
0
 def reconnect(self, url):
     print("Reconnecting")
     if self._reply is not None:
         self._reply.abort()
         self._reply = None
     request = QNetworkRequest(url)
     request.setRawHeader(b"Accept", b"text/event-stream")
     self._reply = self._manager.get(request)
     self._reply.readyRead.connect(self.processReadyRead)
     self._reply.finished.connect(self.processFinished)
示例#28
0
 def _get_user_variety(self):
     """ 获取用户有权限的品种 """
     network_manager = getattr(qApp, "_network")
     user_token = get_user_token()
     url = SERVER_API + "user/variety-authenticate/"
     request = QNetworkRequest(QUrl(url))
     request.setRawHeader("Authorization".encode("utf-8"),
                          user_token.encode("utf-8"))
     reply = network_manager.get(request)
     reply.finished.connect(self.user_variety_reply)
示例#29
0
def fetch_raw(
    url: str,
    encoding: str = ENCODING,
    authcfg_id: str = "",
    params: Optional[Dict[str, str]] = None,
) -> Tuple[bytes, str]:
    """
    Fetch resource from the internet. Similar to requests.get(url) but is
    recommended way of handling requests in QGIS plugin
    :param url: address of the web resource
    :param encoding: Encoding which will be used to decode the bytes
    :param authcfg_id: authcfg id from QGIS settings, defaults to ''
    :param params: Dictionary to send in the query string
    :return: bytes of the content and default name of the file or empty string
    """
    if params:
        url += "?" + urlencode(params)
    LOGGER.debug(url)
    req = QNetworkRequest(QUrl(url))
    # http://osgeo-org.1560.x6.nabble.com/QGIS-Developer-Do-we-have-a-User-Agent-string-for-QGIS-td5360740.html
    user_agent = QSettings().value("/qgis/networkAndProxy/userAgent",
                                   "Mozilla/5.0")
    user_agent += " " if len(user_agent) else ""
    # noinspection PyUnresolvedReferences
    user_agent += f"QGIS/{Qgis.QGIS_VERSION_INT}"
    user_agent += f" {plugin_name()}"
    # https://www.riverbankcomputing.com/pipermail/pyqt/2016-May/037514.html
    req.setRawHeader(b"User-Agent", bytes(user_agent, encoding))
    request_blocking = QgsBlockingNetworkRequest()
    if authcfg_id:
        request_blocking.setAuthCfg(authcfg_id)
    _ = request_blocking.get(req)
    reply: QgsNetworkReplyContent = request_blocking.reply()
    reply_error = reply.error()
    if reply_error != QNetworkReply.NoError:
        # Error content will be empty in older QGIS versions:
        # https://github.com/qgis/QGIS/issues/42442
        message = (bytes(reply.content()).decode("utf-8") if len(
            bytes(reply.content())) else None)
        # bar_msg will just show a generic Qt error string.
        raise QgsPluginNetworkException(
            message=message,
            error=reply_error,
            bar_msg=bar_msg(reply.errorString()),
        )

    # https://stackoverflow.com/a/39103880/10068922
    default_name = ""
    if reply.hasRawHeader(CONTENT_DISPOSITION_BYTE_HEADER):
        header: QByteArray = reply.rawHeader(CONTENT_DISPOSITION_BYTE_HEADER)
        default_name = bytes(header).decode(encoding).split("filename=")[1]
        if default_name[0] in ['"', "'"]:
            default_name = default_name[1:-1]

    return bytes(reply.content()), default_name
示例#30
0
    def _createRequest(self, http_method: str, url: str,
                       headers_dict: Optional[Dict[str, str]] = None,
                       data: Optional[Union[bytes, bytearray]] = None,
                       callback: Optional[Callable[["QNetworkReply"], None]] = None,
                       error_callback: Optional[Callable[["QNetworkReply", "QNetworkReply.NetworkError"], None]] = None,
                       download_progress_callback: Optional[Callable[[int, int], None]] = None,
                       upload_progress_callback: Optional[Callable[[int, int], None]] = None,
                       timeout: Optional[float] = None,
                       scope: Optional[HttpRequestScope] = None ) -> "HttpRequestData":
        # Sanity checks
        if timeout is not None and timeout <= 0:
            raise ValueError("Timeout must be a positive number if provided, but [%s] was given" % timeout)

        request = QNetworkRequest(QUrl(url))

        # Make sure that Qt handles redirects
        if hasattr(QNetworkRequest, "FollowRedirectsAttribute"):
            # Patch for Qt 5.6-5.8
            request.setAttribute(QNetworkRequest.FollowRedirectsAttribute, True)
        if hasattr(QNetworkRequest, "RedirectPolicyAttribute"):
            # Patch for Qt 5.9+
            request.setAttribute(QNetworkRequest.RedirectPolicyAttribute, True)

        # Set headers
        if headers_dict is not None:
            for key, value in headers_dict.items():
                request.setRawHeader(key.encode("utf-8"), value.encode("utf-8"))

        if scope is not None:
            scope.request_hook(request)

        # Generate a unique request ID
        request_id = uuid.uuid4().hex

        # Create the request data
        request_data = HttpRequestData(request_id,
                                       http_method = http_method,
                                       request = request,
                                       data = data,
                                       manager_timeout_callback = self._onRequestTimeout,
                                       callback = callback,
                                       error_callback = error_callback,
                                       download_progress_callback = download_progress_callback,
                                       upload_progress_callback = upload_progress_callback,
                                       timeout = timeout)

        with self._request_lock:
            self._request_queue.append(request_data)

            # Schedule a call to process pending requests in the queue
            if not self._process_requests_scheduled:
                self.callLater(0, self._processNextRequestsInQueue)
                self._process_requests_scheduled = True

        return request_data
 def _createEmptyRequest(self, url: str, content_type: str = "application/json") -> QNetworkRequest:
     """
     Create a new network request with the needed HTTP headers.
     :param url: The full URL to do the request on.
     :return: The QNetworkRequest.
     """
     request = QNetworkRequest(QUrl().fromUserInput(url))
     request.setHeader(QNetworkRequest.ContentTypeHeader, content_type)
     request.setAttribute(QNetworkRequest.RedirectPolicyAttribute, True)  # file downloads reply with a 302 first
     request.setRawHeader(b"Authorization", "Bearer {}".format(self._token).encode())
     return request
 def resumeDownload(self):
     self.file = QtCore.QFile(self.filepath, self)
     request = QNetworkRequest(QtCore.QUrl(self.url))
     if self.support_resume:
         self.loadedsize = self.file.size()
         if str(self.loadedsize) == self.totalsize: return
         request.setRawHeader(
             b'Range', 'bytes={}-'.format(self.loadedsize).encode('ascii'))
     else:
         self.file.resize(0)
         self.loadedsize = 0
     self.download = self.nam.get(request)
示例#33
0
 def get(self):
     request = QNetworkRequest(self.url)
     # Ensure loads certifi certificates
     sslCfg = request.sslConfiguration()
     sslCfg.addCaCertificates(certifi.where())
     request.setSslConfiguration(sslCfg)
     request.setRawHeader(
         b'User-Agent',
         os_detector.getOs().encode('utf-8') + b" - UDS Connector " +
         VERSION.encode('utf-8'),
     )
     self._manager.get(request)
示例#34
0
 def _getRequest(self, url):
     request = QNetworkRequest(QUrl(url))
     # key
     request.setRawHeader(b"Key", b"")
     # request.setRawHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
     # request.setRawHeader("Accept-Encoding", "gzip, deflate, sdch")
     # request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.8")
     # header
     request.setHeader(QNetworkRequest.ContentTypeHeader, "application/octet-stream")
     # user agent
     request.setHeader(QNetworkRequest.UserAgentHeader, "Blog/Mzone 1.0")
     return request
示例#35
0
    def _load_content(self, content_type, content):
        """
        This method is for displaying some content of
        such types: local web pages, remote web pages,
        local pdf`s, local videos.

        It should be called like in the following example
        to work correctly:
        self._load_content('local_video', 'some_video.mp4')
        """
        self._main_browser_reset_zoom()  # reset zoom
        if content_type == 'local_url':
            source = config['flask_server_home'] + \
                config['flask_server_local_page_client'] + \
                content  # simply get the file from flask-server by its relative path-id
            # specify type of currently opened file for zoom and scroll methods
            self._cur_filetype = "webpage"
        elif content_type == 'external_url':
            self._cur_filetype = "webpage"
            # no needs required as, link should be given in
            # 'http://yoursite.com/yourpage'
            source = content
        elif content_type == 'local_pdf':
            # to render PDF`s we use PDF.js, so we open its page and send it a
            # path for the target file.
            source = config['flask_server_home'] + \
                config['flask_server_local_page_client'] + \
                content
            self._cur_filetype = "pdf"
        elif content_type == 'local_video':
            # in case of opening local videos we need to modify the path to the video in the source code of
            # the videoplayer, so don`t die after reading this code. It works just in the same style as other
            # filetypes, but in a very weird way.
            source = config['flask_server_home'] + \
                config['flask_server_video_addr_client'] + content
            logger.info('Opening video at {}'.format(source))
            self._cur_filetype = "video"
        # Set a custom user agent to avoid message about deprecated version of
        # browser

        self._main_browser.page().userAgentForUrl = self._custom_ua

        logger.info('Loading data on address: {}'.format(source))

        # Create a request to be able to set user-agent data. Without
        # it, it`s impossible to customize request data.
        request = QNetworkRequest()
        request.setUrl(QUrl(source))
        request.setRawHeader("USER-AGENT", config['output_user_agent'])

        # and finally load the result
        self._main_browser.load(request)
示例#36
0
 def __tabContextMenuClone(self):
     """
     Private method to clone the selected tab.
     """
     idx = self.__tabContextMenuIndex
     if idx < 0:
         idx = self.currentIndex()
     if idx < 0 or idx > self.count():
         return
     
     req = QNetworkRequest(self.widget(idx).url())
     req.setRawHeader(b"X-Eric6-UserLoadAction", b"1")
     self.newBrowser(None, (req, QNetworkAccessManager.GetOperation, b""))
示例#37
0
def junk(app):
    userapi = "https://api.gitter.im/v1/user"
    roomapi = "https://api.gitter.im/v1/rooms/{}/rooms"
    streamapi = 'https://stream.gitter.im/v1/rooms/{}/chatMessages'
    
    userurl = QUrl(userapi)
    #roomsurl = QUrl(roomapi.format(user_id))
    #encoded = QUrl(streamapi.format(encoded_id))
    req = QNetworkRequest(userurl)
    req.setRawHeader("Accept", "application/json")
    req.setRawHeader("Authorization", 'Bearer '+token)
    resp = app.net.get(req)
    resp.readyRead.connect(lambda : viewresp(resp))
示例#38
0
文件: daemon.py 项目: hydrargyrum/eye
	def _doGet(self, path):
		url = urlunsplit(('http', self.addr, path, '', ''))
		sig = self._sign(b'GET', path.encode('utf-8'), b'')
		headers = {
			HMAC_HEADER: b64encode(sig)
		}

		request = QNetworkRequest(QUrl(url))
		for hname in headers:
			request.setRawHeader(hname, headers[hname])

		reply = self.network.get(request)
		return reply
示例#39
0
文件: daemon.py 项目: hydrargyrum/eye
	def _doPost(self, path, **params):
		url = urlunsplit(('http', self.addr, path, '', ''))
		body = json.dumps(params)
		sig = self._sign(b'POST', path.encode('utf-8'), body.encode('utf-8'))
		headers = {
			HMAC_HEADER: b64encode(sig),
			'Content-Type': 'application/json'
		}

		request = QNetworkRequest(QUrl(url))
		for hname in headers:
			request.setRawHeader(hname, headers[hname])
		reply = self.network.post(request, body)
		return reply
示例#40
0
 def __lineEditReturnPressed(self):
     """
     Private slot to handle the entering of an URL.
     """
     edit = self.sender()
     url = self.__guessUrlFromPath(edit.text())
     request = QNetworkRequest(url)
     request.setRawHeader(b"X-Eric6-UserLoadAction", b"1")
     if e5App().keyboardModifiers() == Qt.AltModifier:
         self.newBrowser(
             None, (request, QNetworkAccessManager.GetOperation, b""))
     else:
         self.currentBrowser().setSource(
             None, (request, QNetworkAccessManager.GetOperation, b""))
         self.currentBrowser().setFocus()
示例#41
0
    def request_obj(self, url, headers=None, body=None):
        """ Return a QNetworkRequest object """
        request = QNetworkRequest()
        request.setUrl(to_qurl(url))
        request.setOriginatingObject(self.web_page.mainFrame())

        if headers is not None:
            self.web_page.skip_custom_headers = True
            self._set_request_headers(request, headers)

        if body and not request.hasRawHeader(b"content-type"):
            # there is POST body but no content-type
            # QT will set this header, but it will complain so better to do this here
            request.setRawHeader(b"content-type", b"application/x-www-form-urlencoded")

        return request
示例#42
0
class DownloadManager(QNetworkAccessManager):
    def __init__(self, parent=None):
        super().__init__(parent)


    def addUrl(self, url):
        print(url)
        self.request = QNetworkRequest(QUrl(url))
        self.request.setRawHeader(b"User-Agent", b"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1")

        self.reply = self.get(self.request)

        self.reply.downloadProgress.connect(self.setProgress)

        return self.request

    def setProgress(self, a, s):
        print(a, s)
def downloadBinPackage(packageUrl, destinationFileName):
    request = QNetworkRequest(QUrl(packageUrl))
    request.setRawHeader(b'Accept-Encoding', b'gzip,deflate')

    reply = QgsNetworkAccessManager.instance().get(request)
    evloop = QEventLoop()
    reply.finished.connect(evloop.quit)
    evloop.exec_(QEventLoop.ExcludeUserInputEvents)
    content_type = reply.rawHeader(b'Content-Type')
    if content_type == b'application/zip':
        if os.path.isfile(destinationFileName):
            os.unlink(destinationFileName)

        destinationFile = open(destinationFileName, 'wb')
        destinationFile.write(bytearray(reply.readAll()))
        destinationFile.close()
    else:
        ret_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
        raise IOError("{} {}".format(ret_code, packageUrl))
示例#44
0
    def download(self):
        grab = None
        for x in range(self._tilesRect.width()):
            for y in range(self._tilesRect.height()):
                tp = Point(self._tilesRect.topLeft() + QPoint(x, y))
                if tp not in self._tilePixmaps:
                    grab = QPoint(tp)
                    break

        if grab is None:
            self._url = QUrl()
            return

        path = 'http://tile.openstreetmap.org/%d/%d/%d.png' % (self.zoom, grab.x(), grab.y())
        self._url = QUrl(path)
        request = QNetworkRequest()
        request.setUrl(self._url)
        request.setRawHeader(b'User-Agent', b'Nokia (PyQt) Graphics Dojo 1.0')
        request.setAttribute(QNetworkRequest.User, grab)
        self._manager.get(request)
示例#45
0
    def _sendRequest(self, url, params, headers={}):
        if self.asynchonous:

            if self.reply is not None:
                self.reply.finished.disconnect(self.reply_finished)
                self.reply.abort()
                self.reply = None

            url = QUrl(url)
            q = QUrlQuery(url)
            for key, value in params.items():
                q.addQueryItem(key, value)
            url.setQuery(q)
            QgsLogger.debug('Request: {}'.format(url.toEncoded()))
            request = QNetworkRequest(url)
            for key, value in headers.items():
                request.setRawHeader(key, value)
            self.reply = QgsNetworkAccessManager.instance().get(request)
            self.reply.finished.connect(self.reply_finished)

        else:
            response = urlopen(self.url + '?' + urllib.urlencode(params))
            data = json.load(response)
            self.load_data(data)
示例#46
0
文件: Toolbox.py 项目: CPS-3/Cura
 def _makeRequestByType(self, type: str) -> None:
     Logger.log("i", "Toolbox: Requesting %s metadata from server.", type)
     request = QNetworkRequest(self._request_urls[type])
     request.setRawHeader(*self._request_header)
     self._network_manager.get(request)
示例#47
0
class SearchThread(QThread):
    domain = 'kyfw.12306.cn' #请求域名(真实连接地址)
    host='kyfw.12306.cn' #请求的域名(host)
    http = requests.session()
    stopSignal=False
    threadId=1
    leftTicketUrl="leftTicket/query"
    requests.packages.urllib3.disable_warnings()

    searchThreadCallback= pyqtSignal(list)

    def __init__(self,from_station,to_station,train_date,threadId,leftTicketUrl,interval=2,domain=''):
        super(SearchThread,self).__init__()
        if domain!='':
            self.domain=domain

        self.threadId=threadId
        self.from_station=from_station
        self.to_station=to_station
        self.train_date=train_date
        self.interval=interval
        self.leftTicketUrl=leftTicketUrl


    def run(self):
        time.sleep(self.threadId)

        userAgent="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36"
        headers={'Referer':'https://kyfw.12306.cn/otn/leftTicket/init',"host":self.host\
            ,'Cache-Control':'no-cache','Pragma':"no-cache","User-Agent":userAgent,"X-Requested-With":"XMLHttpRequest"}

        t=str(random.random())

        dataUrl='?leftTicketDTO.train_date='+self.train_date\
            +"&leftTicketDTO.from_station="+self.stationCode[self.from_station]+"&leftTicketDTO.to_station="+\
            self.stationCode[self.to_station]+"&purpose_codes=ADULT"

        logUrl='https://' + self.domain + '/otn/leftTicket/log'+dataUrl
        url='https://' + self.domain + '/otn/'+self.leftTicketUrl+dataUrl


        self.http.get(logUrl,verify=False,headers=headers)
        jc_fromStation=xxtea.unicodeStr(self.from_station+","+self.stationCode[self.from_station])
        jc_toStation=xxtea.unicodeStr(self.to_station+","+self.stationCode[self.to_station])
        self.http.cookies.set("_jc_save_fromStation",jc_fromStation)
        self.http.cookies.set("_jc_save_toStation",jc_toStation)
        self.http.cookies.set('_jc_save_fromDate',self.train_date)
        self.http.cookies.set('_jc_save_toDate',"2014-01-01")
        self.http.cookies.set('_jc_save_wfdc_flag','dc')

        ret=self.http.get(url,verify=False,headers=headers)
        ticketInfo=ret.json()

        if ticketInfo['status']!=True :
            print(ticketInfo)

        cookies=self.http.cookies.get_dict()
        cookieStr=";".join('%s=%s' % (key, value) for (key, value) in cookies.items())

        self.http.get(logUrl,verify=False,headers=headers)
        self.req=QNetworkRequest()
        self.req.setUrl(QUrl(url))
        self.req.setRawHeader("Referer","https://kyfw.12306.cn/otn/leftTicket/init")
        self.req.setRawHeader("host",self.host)
        self.req.setRawHeader("Cache-Control","no-cache")
        self.req.setRawHeader("Pragma","no-cache")
        self.req.setRawHeader("User-Agent",userAgent)
        self.req.setRawHeader("Cookie",cookieStr)

        while not self.stopSignal:
            mutex.acquire(1)
            self.search_ticket(self.from_station,self.to_station,self.train_date)
            mutex.release(1)
            time.sleep(self.interval)


    def search_ticket(self, fromStation, toStation, date):
        try:
            self.netWorkManager=QNetworkAccessManager()
            self.reply=self.netWorkManager.get(self.req)
            self.reply.ignoreSslErrors()
            self.reply.finished.connect(self.search_finished)
            self.exec()

        except Exception as e:
            print("ip:"+self.domain+"查询发生错误:"+e.__str__())
            return False



    def search_finished(self):
        try:
            ret=self.reply.readAll()
            ret=str(ret,'utf8')
            ticketInfo=json.loads(ret)
            self.reply=None
            self.netWorkManager=None
            self.exit()
            if ticketInfo['status']!=True or ticketInfo['messages']!=[] :
                print(self.domain)
                print(ticketInfo)
                return False

            if len(ticketInfo['data'])<=0:
                return False

            data=ticketInfo['data']
            ret=None
            ticketInfo=None

            self.searchThreadCallback.emit(data)
        except Exception as e:
            print(e.__str__())

    def load_station_code(self,stationCode):
        self.stationCode = stationCode
        return True

    def stop(self):
        self.stopSignal=True
class OctoPrintOutputDevice(PrinterOutputDevice):
    def __init__(self, key, address, properties):
        super().__init__(key)
        self._address = address
        self._key = key
        self._properties = properties  # Properties dict as provided by zero conf

        self._gcode = None

        ##  Todo: Hardcoded value now; we should probably read this from the machine definition and octoprint.
        self._num_extruders = 1

        self._hotend_temperatures = [0] * self._num_extruders
        self._target_hotend_temperatures = [0] * self._num_extruders

        self._api_version = "1"
        self._api_prefix = "/api/"
        self._api_header = "X-Api-Key"
        self._api_key = None

        self.setName(key)
        self.setShortDescription(i18n_catalog.i18nc("@action:button", "Print with OctoPrint"))
        self.setDescription(i18n_catalog.i18nc("@properties:tooltip", "Print with OctoPrint"))
        self.setIconName("print")

        #   QNetwork manager needs to be created in advance. If we don't it can happen that it doesn't correctly
        #   hook itself into the event loop, which results in events never being fired / done.
        self._manager = QNetworkAccessManager()
        self._manager.finished.connect(self._onFinished)

        ##  Hack to ensure that the qt networking stuff isn't garbage collected (unless we want it to)
        self._printer_request = None
        self._printer_reply = None

        self._print_job_request = None
        self._print_job_reply = None

        self._image_request = None
        self._image_reply = None

        self._post_request = None
        self._post_reply = None
        self._post_multi_part = None
        self._post_part = None

        self._job_request = None
        self._job_reply = None

        self._progress_message = None
        self._error_message = None

        self._update_timer = QTimer()
        self._update_timer.setInterval(2000)  # TODO; Add preference for update interval
        self._update_timer.setSingleShot(False)
        self._update_timer.timeout.connect(self._update)

        self._camera_timer = QTimer()
        self._camera_timer.setInterval(500)  # Todo: Add preference for camera update interval
        self._camera_timer.setSingleShot(False)
        self._camera_timer.timeout.connect(self._update_camera)

        self._camera_image_id = 0

        self._camera_image = QImage()

    def getProperties(self):
        return self._properties

    ##  Get the unique key of this machine
    #   \return key String containing the key of the machine.
    @pyqtSlot(result = str)
    def getKey(self):
        return self._key

    ##  Set the API key of this OctoPrint instance
    def setApiKey(self, api_key):
        self._api_key = api_key

    ##  Name of the printer (as returned from the zeroConf properties)
    @pyqtProperty(str, constant = True)
    def name(self):
        return self._key

    ##  Version (as returned from the zeroConf properties)
    @pyqtProperty(str, constant=True)
    def octoprintVersion(self):
        return self._properties.get(b"version", b"").decode("utf-8")

    ## IPadress of this printer
    @pyqtProperty(str, constant=True)
    def ipAddress(self):
        return self._address

    def _update_camera(self):
        ## Request new image
        url = QUrl("http://" + self._address + ":8080/?action=snapshot")
        self._image_request = QNetworkRequest(url)
        self._image_reply = self._manager.get(self._image_request)

    def _update(self):
        ## Request 'general' printer data
        url = QUrl("http://" + self._address + self._api_prefix + "printer")
        self._printer_request = QNetworkRequest(url)
        self._printer_request.setRawHeader(self._api_header.encode(), self._api_key.encode())
        self._printer_reply = self._manager.get(self._printer_request)

        ## Request print_job data
        url = QUrl("http://" + self._address + self._api_prefix + "job")
        self._job_request = QNetworkRequest(url)
        self._job_request.setRawHeader(self._api_header.encode(), self._api_key.encode())
        self._job_reply = self._manager.get(self._job_request)

    def close(self):
        self.setConnectionState(ConnectionState.closed)
        self._update_timer.stop()
        self._camera_timer.stop()

    def requestWrite(self, node, file_name = None, filter_by_machine = False):
        self._gcode = getattr(Application.getInstance().getController().getScene(), "gcode_list")

        self.startPrint()

    def isConnected(self):
        return self._connection_state != ConnectionState.closed and self._connection_state != ConnectionState.error

    ##  Start requesting data from printer
    def connect(self):
        self.setConnectionState(ConnectionState.connecting)
        self._update()  # Manually trigger the first update, as we don't want to wait a few secs before it starts.
        self._update_camera()
        Logger.log("d", "Connection with printer %s with ip %s started", self._key, self._address)
        self._update_timer.start()
        self._camera_timer.start()

    newImage = pyqtSignal()

    @pyqtProperty(QUrl, notify = newImage)
    def cameraImage(self):
        self._camera_image_id += 1
        temp = "image://camera/" + str(self._camera_image_id)
        return QUrl(temp, QUrl.TolerantMode)

    def getCameraImage(self):
        return self._camera_image

    def _setJobState(self, job_state):
        url = QUrl("http://" + self._address + self._api_prefix + "job")
        self._job_request = QNetworkRequest(url)
        self._job_request.setRawHeader(self._api_header.encode(), self._api_key.encode())
        self._job_request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
        if job_state == "abort":
            command = "cancel"
        elif job_state == "print":
            if self.jobState == "paused":
                command = "pause"
            else:
                command = "start"
        elif job_state == "pause":
            command = "pause"
        data = "{\"command\": \"%s\"}" % command
        self._job_reply = self._manager.post(self._job_request, data.encode())
        Logger.log("d", "Sent command to OctoPrint instance: %s", data)

    def startPrint(self):
        if self.jobState != "ready" and self.jobState != "":
            self._error_message = Message(i18n_catalog.i18nc("@info:status", "Printer is printing. Unable to start a new job."))
            self._error_message.show()
            return
        try:
            self._progress_message = Message(i18n_catalog.i18nc("@info:status", "Sending data to printer"), 0, False, -1)
            self._progress_message.show()

            ## Mash the data into single string
            single_string_file_data = ""
            for line in self._gcode:
                single_string_file_data += line

            ##  TODO: Use correct file name (we use placeholder now)
            file_name = "%s.gcode" % Application.getInstance().getPrintInformation().jobName

            ##  Create multi_part request
            self._post_multi_part = QHttpMultiPart(QHttpMultiPart.FormDataType)

            ##  Create parts (to be placed inside multipart)
            self._post_part = QHttpPart()
            self._post_part.setHeader(QNetworkRequest.ContentDispositionHeader, "form-data; name=\"select\"")
            self._post_part.setBody(b"true")
            self._post_multi_part.append(self._post_part)

            self._post_part = QHttpPart()
            self._post_part.setHeader(QNetworkRequest.ContentDispositionHeader, "form-data; name=\"print\"")
            self._post_part.setBody(b"true")
            self._post_multi_part.append(self._post_part)

            self._post_part = QHttpPart()
            self._post_part.setHeader(QNetworkRequest.ContentDispositionHeader, "form-data; name=\"file\"; filename=\"%s\"" % file_name)
            self._post_part.setBody(single_string_file_data.encode())
            self._post_multi_part.append(self._post_part)

            url = QUrl("http://" + self._address + self._api_prefix + "files/local")

            ##  Create the QT request
            self._post_request = QNetworkRequest(url)
            self._post_request.setRawHeader(self._api_header.encode(), self._api_key.encode())

            ##  Post request + data
            self._post_reply = self._manager.post(self._post_request, self._post_multi_part)
            self._post_reply.uploadProgress.connect(self._onUploadProgress)

            self._gcode = None

        except IOError:
            self._progress_message.hide()
            self._error_message = Message(i18n_catalog.i18nc("@info:status", "Unable to send data to printer. Is another job still active?"))
            self._error_message.show()
        except Exception as e:
            self._progress_message.hide()
            Logger.log("e", "An exception occurred in network connection: %s" % str(e))

    ##  Handler for all requests that have finished.
    def _onFinished(self, reply):
        http_status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
        if reply.operation() == QNetworkAccessManager.GetOperation:
            if "printer" in reply.url().toString():  # Status update from /printer.
                if http_status_code == 200:
                    if self._connection_state == ConnectionState.connecting:
                        self.setConnectionState(ConnectionState.connected)
                    json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))

                    # Check for hotend temperatures
                    for index in range(0, self._num_extruders):
                        temperature = json_data["temperature"]["tool%d" % index]["actual"]
                        self._setHotendTemperature(index, temperature)

                    bed_temperature = json_data["temperature"]["bed"]["actual"]
                    self._setBedTemperature(bed_temperature)

                    printer_state = "offline"
                    if json_data["state"]["flags"]["error"]:
                        printer_state = "error"
                    elif json_data["state"]["flags"]["paused"]:
                        printer_state = "paused"
                    elif json_data["state"]["flags"]["printing"]:
                        printer_state = "printing"
                    elif json_data["state"]["flags"]["ready"]:
                        printer_state = "ready"
                    self._updateJobState(printer_state)
                else:
                    pass  # TODO: Handle errors

            elif "job" in reply.url().toString():  # Status update from /job:
                if http_status_code == 200:
                    json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))

                    progress = json_data["progress"]["completion"]
                    if progress:
                        self.setProgress(progress)

                    if json_data["progress"]["printTime"]:
                        self.setTimeElapsed(json_data["progress"]["printTime"])
                        if json_data["progress"]["printTimeLeft"]:
                            self.setTimeTotal(json_data["progress"]["printTime"] + json_data["progress"]["printTimeLeft"])
                        elif json_data["job"]["estimatedPrintTime"]:
                            self.setTimeTotal(json_data["job"]["estimatedPrintTime"])
                        elif progress > 0:
                            self.setTimeTotal(json_data["progress"]["printTime"] / (progress / 100))
                        else:
                            self.setTimeTotal(0)
                    else:
                        self.setTimeElapsed(0)
                        self.setTimeTotal(0)
                    self.setJobName(json_data["job"]["file"]["name"])
                else:
                    pass  # TODO: Handle errors

            elif "snapshot" in reply.url().toString():  # Update from camera:
                if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) == 200:
                    self._camera_image.loadFromData(reply.readAll())
                    self.newImage.emit()
                else:
                    pass  # TODO: Handle errors

        elif reply.operation() == QNetworkAccessManager.PostOperation:
            if "files" in reply.url().toString():  # Result from /files command:
                if http_status_code == 201:
                    Logger.log("d", "Resource created on OctoPrint instance: %s", reply.header(QNetworkRequest.LocationHeader).toString())
                else:
                    pass  # TODO: Handle errors

                reply.uploadProgress.disconnect(self._onUploadProgress)
                self._progress_message.hide()

            elif "job" in reply.url().toString():  # Result from /job command:
                if http_status_code == 204:
                    Logger.log("d", "Octoprint command accepted")
                else:
                    pass  # TODO: Handle errors

        else:
            Logger.log("d", "OctoPrintOutputDevice got an unhandled operation %s", reply.operation())

    def _onUploadProgress(self, bytes_sent, bytes_total):
        if bytes_total > 0:
            self._progress_message.setProgress(bytes_sent / bytes_total * 100)
        else:
            self._progress_message.setProgress(0)
示例#49
0
class E5XmlRpcClient(QObject):
    """
    Class implementing a xmlrpc client for Qt.
    """
    def __init__(self, url, parent=None):
        """
        Constructor
        
        @param url xmlrpc handler URL (string or QUrl)
        @param parent parent object (QObject)
        """
        super(E5XmlRpcClient, self).__init__(parent)
        
        # attributes for the network objects
        self.__networkManager = QNetworkAccessManager(self)
        self.__networkManager.proxyAuthenticationRequired.connect(
            proxyAuthenticationRequired)
        self.__networkManager.finished.connect(self.__replyFinished)
        if SSL_AVAILABLE:
            self.__sslErrorHandler = E5SslErrorHandler(self)
            self.__networkManager.sslErrors.connect(self.__sslErrors)
        
        self.__callmap = {}
        
        self.__request = QNetworkRequest(QUrl(url))
        self.__request.setRawHeader(b"User-Agent", b"E5XmlRpcClient/1.0")
        self.__request.setHeader(QNetworkRequest.ContentTypeHeader, "text/xml")
    
    def setUrl(self, url):
        """
        Public slot to set the xmlrpc handler URL.
        
        @param url xmlrpc handler URL (string or QUrl)
        """
        url = QUrl(url)
        if url.isValid():
            self.__request.setUrl(url)
    
    def call(self, method, args, responseCallback, errorCallback):
        """
        Public method to call the remote server.
        
        @param method name of the remote method to be called (string)
        @param args tuple of method arguments (tuple)
        @param responseCallback method to be called with the returned
            result as a tuple (function)
        @param errorCallback method to be called in case of an error
            with error code and error string (function)
        """
        assert isinstance(args, tuple), \
            "argument must be tuple or Fault instance"
        
        data = xmlrpc.dumps(args, method).encode("utf-8")
        reply = self.__networkManager.post(
            self.__request, QByteArray(data))
        self.__callmap[reply] = (responseCallback, errorCallback)
    
    def abort(self):
        """
        Public method to abort all calls.
        """
        for reply in list(self.__callmap):
            if reply.isRunning():
                reply.abort()
    
    def __sslErrors(self, reply, errors):
        """
        Private slot to handle SSL errors.
        
        @param reply reference to the reply object (QNetworkReply)
        @param errors list of SSL errors (list of QSslError)
        """
        ignored = self.__sslErrorHandler.sslErrorsReply(reply, errors)[0]
        if ignored == E5SslErrorHandler.NotIgnored and reply in self.__callmap:
            self.__callmap[reply][1](xmlrpc.TRANSPORT_ERROR, self.tr(
                "SSL Error"))
    
    def __replyFinished(self, reply):
        """
        Private slot handling the receipt of a reply.
        
        @param reply reference to the finished reply (QNetworkReply)
        """
        if reply not in self.__callmap:
            return
        
        if reply.error() != QNetworkReply.NoError:
            self.__callmap[reply][1](xmlrpc.TRANSPORT_ERROR,
                                     reply.errorString())
        else:
            data = bytes(reply.readAll()).decode("utf-8")
            try:
                data = xmlrpc.loads(data)[0]
                self.__callmap[reply][0](data)
            except xmlrpc.Fault as fault:
                self.__callmap[reply][1](fault.faultCode, fault.faultString)
        
        reply.deleteLater()
        del self.__callmap[reply]
示例#50
0
文件: browser.py 项目: blropb/qt-test
class Browser(QObject):

    comment_postdata_example = {
            'ft_ent_identifier': '735272899920440', # ИД сообщения
            'comment_text': 'Cool))', # Текст коментария
            'source': '22',
            'client_id': '1429632677205%3A3425397009',
            'reply_fbid': '',
            'parent_comment_id': '',
            'rootid': 'u_ps_0_0_k',
            'clp': '',
            'attached_sticker_fbid': '0',
            'attached_photo_fbid': '0',
            'feed_context': '%7B%22fbfeed_context%22%3Atrue%2C%22location_type%22%3A36%2C%22is_starred%22%3Afalse%2C%22is_pinned_post%22%3Afalse%2C%22can_moderate_timeline_story%22%3Afalse%2C%22profile_id%22%3A308106089303792%2C%22outer_object_element_id%22%3A%22u_ps_0_0_0%22%2C%22object_element_id%22%3A%22u_ps_0_0_0%22%2C%22is_ad_preview%22%3Afalse%2C%22is_editable%22%3Afalse%7D',
            'ft[tn]': '[]',
            'ft[top_level_post_id]': '750869418360788',
            'ft[fbfeed_location]': '36',
            'nctr[_mod]': 'pagelet_timeline_main_column',
            'av': '100009110845526',
            '__user': '******',
            '__a': '1',
            '__dyn': '', #пустой
            '__req': 'c',
            'fb_dtsg': 'AQEkxiOYhtrJ', # инпут в теле документа
            'ttstamp': '26581716611911872109105876676',
            '__rev': '1713404',
        }

    def __init__(self, parent):
        super().__init__(parent)
        self.set_url('http://google.ru')
        conn = QNetworkAccessManager()
        self.conn = conn
        self.r = QNetworkRequest()
        self.r.attribute(QNetworkRequest.CookieSaveControlAttribute, QVariant(True))
        # self.r.setHeader(QNetworkRequest.ContentTypeHeader, "application/x-www-form-urlencoded")
        # self.r.setRawHeader("Referer", "http://www.facebook.com/")
        # self.r.setRawHeader("Host", "www.facebook.com")
        self.cj = QNetworkCookieJar()
        conn.setCookieJar(self.cj)
        conn.createRequest = self._create_request
        self.wv = WebView()
        self.wv.show()
        self.wv.page().setNetworkAccessManager(conn)
        # self.wv.auth()
        self.loop = QEventLoop()
        pass

    def _create_request(self, operation, request, data):
        # print(data)
        reply = QNetworkAccessManager.createRequest(self.conn,
                                                    operation,
                                                    request,
                                                    data)
        self.conn.new_reply = reply
        self.wv_reply = reply
        return reply

    def set_url(self, url):
        if isinstance(url, QByteArray):
            self.url = QUrl().fromEncoded(url)
        else:
            self.url = QUrl(url)

    def send_request(self, post=None, data={}):
        loop = QEventLoop()
        self.r.setUrl(self.url)
        if post:
            encoded_data = self._urlencode_post_data(data)
            pprint(encoded_data)
            self.reply_post = self.conn.post(self.r, encoded_data)
            self.reply_post.downloadProgress.connect(self.prepare_responce)

        else:
            self.reply = self.conn.get(self.r)
            self.reply.finished.connect(self.prepare_responce)
        # return \
        loop.exec()

    def prepare_responce(self):
        # self.check_redirect()
        self.responce = self.reply_post.readAll()#.data().decode('utf-8')
        pprint(self.responce)
        sys.exit()

    def check_redirect(self):
        print(self.url)
        a = self.reply.rawHeader('Location')

        if len(a) > 0:
            self.set_url(a)
            self.send_request()
        else:
            self.loop.exit()

    def test(self):
        self.wv.auth('https://www.facebook.com/freelanceuidesignerdeveloper')
        self.wv.authentication.connect(self.webview_login)

    def _urlencode_post_data(self, post_data):
        post_params = []
        for (key, value) in post_data.items():
            print(key, value)
            post_params.append(key+'='+value)
        return '&'.join(post_params)

    def webview_login(self):
        text_page = self.wv.page().mainFrame().toHtml()
        data = {
            'ft_ent_identifier': '735272899920440',
            'comment_text': 'amazing',
            'source': '22',
            'client_id': '1429632677205%3A3425397009',
            'reply_fbid': '',
            'parent_comment_id': '',
            'rootid': 'u_ps_0_0_o',
            'clp': '',
            'attached_sticker_fbid': '0',
            'attached_photo_fbid': '0',
            'feed_context': '%7B%22fbfeed_context%22%3Atrue%2C%22location_type%22%3A36%2C%22is_starred%22%3Afalse%2C%22is_pinned_post%22%3Afalse%2C%22can_moderate_timeline_story%22%3Afalse%2C%22profile_id%22%3A308106089303792%2C%22outer_object_element_id%22%3A%22u_ps_0_0_0%22%2C%22object_element_id%22%3A%22u_ps_0_0_0%22%2C%22is_ad_preview%22%3Afalse%2C%22is_editable%22%3Afalse%7D',
            'ft[tn]': '[]',
            'ft[top_level_post_id]': '',
            'ft[fbfeed_location]': '36',
            'nctr[_mod]': 'pagelet_timeline_main_column',
            'av': '100009110845526',
            '__user': '******',
            '__a': '1',
            '__dyn': '', #пустой
            '__req': 'c',
            'fb_dtsg': 'AQEkxiOYhtrJ', # инпут в теле документа
            'ttstamp': '26581716611911872109105876676',
            '__rev': '1713404',
        }
        dtsg_index = text_page.find('"token":"AQ')
        data['fb_dtsg'] = text_page[dtsg_index+9:dtsg_index+21]
        data['ttstamp'] = self.ttstamp_gen(data['fb_dtsg'])
        data['ft_ent_identifier'] = '849713745045784' # self.get_post_id(post_object)
        data['comment_text'] = random_number.choice(config.comments_list)
        pprint(data['comment_text'])


        # data['av'] = data['__user'] = from_user
        # self.applyMetaData()
        self.url = QUrl('https://www.facebook.com/ajax/ufi/add_comment.php')
        self.send_request(True, data)
        sys.exit()


    def applyMetaData(self):
        print('applyMetaData')
        raw_header = {
            'Host': 'www.facebook.com',
            'User-Agent': ' Mozilla/5.0 (X11; Linux x86_64; rv:37.0) Gecko/20100101 Firefox/37.0',
            'Accept': ' text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language': ' en-US,en;q=0.5',
            'Content-Type': ' application/x-www-form-urlencoded; charset=UTF-8',
            'Referer': ' https://www.facebook.com/SoftProposal?fref=nf',
        }
        for (key, header) in raw_header.items():
            self.r.setRawHeader(key, header)

    @staticmethod
    def ttstamp_gen(fb_dtsg):
        u = ''
        for v in fb_dtsg:
            u += str(ord(v))
        return '2'+u
    @staticmethod
    def get_post_id(post):
        if post.object_id:
            return post.object_id
        else:
            str = post.id.split('_')
            if len(str) > 1:
                return str[0]
            else:
                post.id
示例#51
0
class PluginBrowser(QObject, Extension):
    def __init__(self, parent = None):
        super().__init__(parent)
        self.addMenuItem(i18n_catalog.i18n("Browse plugins"), self.browsePlugins)
        self._api_version = 1
        self._api_url = "http://software.ultimaker.com/cura/v%s/" % self._api_version

        self._plugin_list_request = None
        self._download_plugin_request = None

        self._download_plugin_reply = None

        self._network_manager = None

        self._plugins_metadata = []
        self._plugins_model = None

        self._qml_component = None
        self._qml_context = None
        self._dialog = None
        self._download_progress = 0

        self._is_downloading = False

        self._request_header = [b"User-Agent", str.encode("%s - %s" % (Application.getInstance().getApplicationName(), Application.getInstance().getVersion()))]

        # Installed plugins are really installed after reboot. In order to prevent the user from downloading the
        # same file over and over again, we keep track of the upgraded plugins.
        self._newly_installed_plugin_ids = []


    pluginsMetadataChanged = pyqtSignal()
    onDownloadProgressChanged = pyqtSignal()
    onIsDownloadingChanged = pyqtSignal()

    @pyqtProperty(bool, notify = onIsDownloadingChanged)
    def isDownloading(self):
        return self._is_downloading

    def browsePlugins(self):
        self._createNetworkManager()
        self.requestPluginList()

        if not self._dialog:
            self._createDialog()
        self._dialog.show()

    def requestPluginList(self):
        url = QUrl(self._api_url + "plugins")
        self._plugin_list_request = QNetworkRequest(url)
        self._plugin_list_request.setRawHeader(*self._request_header)
        self._network_manager.get(self._plugin_list_request)

    def _createDialog(self):
        Logger.log("d", "PluginBrowser")

        path = QUrl.fromLocalFile(os.path.join(PluginRegistry.getInstance().getPluginPath(self.getPluginId()), "PluginBrowser.qml"))
        self._qml_component = QQmlComponent(Application.getInstance()._engine, path)

        # We need access to engine (although technically we can't)
        self._qml_context = QQmlContext(Application.getInstance()._engine.rootContext())
        self._qml_context.setContextProperty("manager", self)
        self._dialog = self._qml_component.create(self._qml_context)
        if self._dialog is None:
            Logger.log("e", "QQmlComponent status %s", self._qml_component.status())
            Logger.log("e", "QQmlComponent errorString %s", self._qml_component.errorString())

    def setIsDownloading(self, is_downloading):
        if self._is_downloading != is_downloading:
            self._is_downloading = is_downloading
            self.onIsDownloadingChanged.emit()

    def _onDownloadPluginProgress(self, bytes_sent, bytes_total):
        if bytes_total > 0:
            new_progress = bytes_sent / bytes_total * 100
            if new_progress > self._download_progress:
                self._download_progress = new_progress
                self.onDownloadProgressChanged.emit()
            self._download_progress = new_progress
            if new_progress == 100.0:
                self.setIsDownloading(False)
                self._download_plugin_reply.downloadProgress.disconnect(self._onDownloadPluginProgress)
                self._temp_plugin_file = tempfile.NamedTemporaryFile(suffix = ".curaplugin")
                self._temp_plugin_file.write(self._download_plugin_reply.readAll())

                result = PluginRegistry.getInstance().installPlugin("file://" + self._temp_plugin_file.name)

                self._newly_installed_plugin_ids.append(result["id"])
                self.pluginsMetadataChanged.emit()

                Application.getInstance().messageBox(i18n_catalog.i18nc("@window:title", "Plugin browser"), result["message"])

                self._temp_plugin_file.close()  # Plugin was installed, delete temp file

    @pyqtProperty(int, notify = onDownloadProgressChanged)
    def downloadProgress(self):
        return self._download_progress

    @pyqtSlot(str)
    def downloadAndInstallPlugin(self, url):
        Logger.log("i", "Attempting to download & install plugin from %s", url)
        url = QUrl(url)
        self._download_plugin_request = QNetworkRequest(url)
        self._download_plugin_request.setRawHeader(*self._request_header)
        self._download_plugin_reply = self._network_manager.get(self._download_plugin_request)
        self._download_progress = 0
        self.setIsDownloading(True)
        self.onDownloadProgressChanged.emit()
        self._download_plugin_reply.downloadProgress.connect(self._onDownloadPluginProgress)

    @pyqtProperty(QObject, notify=pluginsMetadataChanged)
    def pluginsModel(self):
        if self._plugins_model is None:
            self._plugins_model = ListModel()
            self._plugins_model.addRoleName(Qt.UserRole + 1, "name")
            self._plugins_model.addRoleName(Qt.UserRole + 2, "version")
            self._plugins_model.addRoleName(Qt.UserRole + 3, "short_description")
            self._plugins_model.addRoleName(Qt.UserRole + 4, "author")
            self._plugins_model.addRoleName(Qt.UserRole + 5, "already_installed")
            self._plugins_model.addRoleName(Qt.UserRole + 6, "file_location")
            self._plugins_model.addRoleName(Qt.UserRole + 7, "can_upgrade")
        else:
            self._plugins_model.clear()
        items = []
        for metadata in self._plugins_metadata:
            items.append({
                "name": metadata["label"],
                "version": metadata["version"],
                "short_description": metadata["short_description"],
                "author": metadata["author"],
                "already_installed": self._checkAlreadyInstalled(metadata["id"]),
                "file_location": metadata["file_location"],
                "can_upgrade": self._checkCanUpgrade(metadata["id"], metadata["version"])
            })
        self._plugins_model.setItems(items)
        return self._plugins_model

    def _checkCanUpgrade(self, id, version):
        plugin_registry = PluginRegistry.getInstance()
        metadata = plugin_registry.getMetaData(id)
        if metadata != {}:
            if id in self._newly_installed_plugin_ids:
                return False  # We already updated this plugin.
            current_version = Version(metadata["plugin"]["version"])
            new_version = Version(version)
            if new_version > current_version:
                return True
        return False

    def _checkAlreadyInstalled(self, id):
        plugin_registry = PluginRegistry.getInstance()
        metadata = plugin_registry.getMetaData(id)
        if metadata != {}:
            return True
        else:
            if id in self._newly_installed_plugin_ids:
                return True  # We already installed this plugin, but the registry just doesn't know it yet.
            return False

    def _onRequestFinished(self, reply):
        reply_url = reply.url().toString()
        if reply.operation() == QNetworkAccessManager.GetOperation:
            if reply_url == self._api_url + "plugins":
                try:
                    json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))
                    self._plugins_metadata = json_data
                    self.pluginsMetadataChanged.emit()
                except json.decoder.JSONDecodeError:
                    Logger.log("w", "Received an invalid print job state message: Not valid JSON.")
                    return
        else:
            # Ignore any operation that is not a get operation
            pass

    def _createNetworkManager(self):
        if self._network_manager:
            self._network_manager.finished.disconnect(self._onRequestFinished)

        self._network_manager = QNetworkAccessManager()
        self._network_manager.finished.connect(self._onRequestFinished)
示例#52
0
def makeRequest(url, token):
    logger.debug("makeRequest: %s", url)
    req = QNetworkRequest(url)
    req.setRawHeader(b"Accept", b"application/json")
    req.setRawHeader(b"Authorization", b'Bearer ' + bytes(token))
    return req
示例#53
0
 def createRequest(self, op, request, outgoingData=None):
     """
     Public method to create a request.
     
     @param op the operation to be performed
         (QNetworkAccessManager.Operation)
     @param request reference to the request object (QNetworkRequest)
     @param outgoingData reference to an IODevice containing data to be sent
         (QIODevice)
     @return reference to the created reply object (QNetworkReply)
     """
     scheme = request.url().scheme()
     if scheme == "https" and \
             (not SSL_AVAILABLE or not QSslSocket.supportsSsl()):
         from .NetworkProtocolUnknownErrorReply import \
             NetworkProtocolUnknownErrorReply
         return NetworkProtocolUnknownErrorReply(scheme, self)
     
     import Helpviewer.HelpWindow
     
     if op == QNetworkAccessManager.PostOperation and \
             outgoingData is not None:
         outgoingDataByteArray = outgoingData.peek(1024 * 1024)
         Helpviewer.HelpWindow.HelpWindow.passwordManager().post(
             request, outgoingDataByteArray)
     
     reply = None
     if scheme in self.__schemeHandlers:
         reply = self.__schemeHandlers[scheme]\
                     .createRequest(op, request, outgoingData)
     if reply is not None:
         return reply
     
     # give GreaseMonkey the chance to create a request
     reply = Helpviewer.HelpWindow.HelpWindow.greaseMonkeyManager()\
         .createRequest(op, request, outgoingData)
     if reply is not None:
         return reply
     
     req = QNetworkRequest(request)
     if req.rawHeader(b"X-Eric6-UserLoadAction") == QByteArray(b"1"):
         req.setRawHeader(b"X-Eric6-UserLoadAction", QByteArray())
         req.setAttribute(QNetworkRequest.User + 200, "")
     else:
         req.setAttribute(
             QNetworkRequest.User + 200, req.rawHeader(b"Referer"))
     
     if hasattr(QNetworkRequest, 'HttpPipeliningAllowedAttribute'):
         req.setAttribute(
             QNetworkRequest.HttpPipeliningAllowedAttribute, True)
     if not self.__acceptLanguage.isEmpty():
         req.setRawHeader(b"Accept-Language", self.__acceptLanguage)
     
     # AdBlock code
     if op == QNetworkAccessManager.GetOperation:
         if self.__adblockNetwork is None:
             self.__adblockNetwork = \
                 Helpviewer.HelpWindow.HelpWindow.adBlockManager().network()
         reply = self.__adblockNetwork.block(req)
         if reply is not None:
             reply.setParent(self)
             return reply
     
     # set cache policy
     if op == QNetworkAccessManager.GetOperation:
         urlHost = req.url().host()
         for host in Preferences.getHelp("NoCacheHosts"):
             if host in urlHost:
                 req.setAttribute(
                     QNetworkRequest.CacheLoadControlAttribute,
                     QNetworkRequest.AlwaysNetwork)
                 break
         else:
             req.setAttribute(
                 QNetworkRequest.CacheLoadControlAttribute,
                 Preferences.getHelp("CachePolicy"))
     else:
         req.setAttribute(
             QNetworkRequest.CacheLoadControlAttribute,
             QNetworkRequest.AlwaysNetwork)
     
     # Do Not Track feature
     if self.__doNotTrack:
         req.setRawHeader(b"DNT", b"1")
         req.setRawHeader(b"X-Do-Not-Track", b"1")
     
     # Send referer header?
     if not self.__sendReferer and \
        req.url().host() not in Preferences.getHelp("SendRefererWhitelist"):
         req.setRawHeader(b"Referer", b"")
     
     reply = QNetworkAccessManager.createRequest(
         self, op, req, outgoingData)
     self.requestCreated.emit(op, req, reply)
     
     return reply
示例#54
0
文件: Toolbox.py 项目: CPS-3/Cura
class Toolbox(QObject, Extension):
    def __init__(self, parent=None) -> None:
        super().__init__(parent)

        self._application = Application.getInstance()
        self._package_manager = None
        self._plugin_registry = Application.getInstance().getPluginRegistry()
        self._packages_version = self._plugin_registry.APIVersion
        self._api_version = 1
        self._api_url = "https://api-staging.ultimaker.com/cura-packages/v{api_version}/cura/v{package_version}".format( api_version = self._api_version, package_version = self._packages_version)

        # Network:
        self._get_packages_request = None
        self._get_showcase_request = None
        self._download_request = None
        self._download_reply = None
        self._download_progress = 0
        self._is_downloading = False
        self._network_manager = None
        self._request_header = [
            b"User-Agent",
            str.encode(
                "%s/%s (%s %s)" % (
                    Application.getInstance().getApplicationName(),
                    Application.getInstance().getVersion(),
                    platform.system(),
                    platform.machine(),
                )
            )
        ]
        self._request_urls = {
            "authors":            QUrl("{base_url}/authors".format(base_url = self._api_url)),
            "packages":           QUrl("{base_url}/packages".format(base_url = self._api_url)),
            "plugins_showcase":   QUrl("{base_url}/showcase".format(base_url = self._api_url)),
            "materials_showcase": QUrl("{base_url}/showcase".format(base_url = self._api_url))
        }

        # Data:
        self._metadata = {
            "authors": [],
            "packages": [],
            "plugins_showcase": [],
            "plugins_installed": [],
            "materials_showcase": [],
            "materials_installed": []
        }

        # Models:
        self._models = {
            "authors": AuthorsModel(self),
            "packages": PackagesModel(self),
            "plugins_showcase": PackagesModel(self),
            "plugins_available": PackagesModel(self),
            "plugins_installed": PackagesModel(self),
            "materials_showcase": AuthorsModel(self),
            "materials_available": PackagesModel(self),
            "materials_installed": PackagesModel(self)
        }

        # These properties are for keeping track of the UI state:
        # ----------------------------------------------------------------------
        # View category defines which filter to use, and therefore effectively
        # which category is currently being displayed. For example, possible
        # values include "plugin" or "material", but also "installed".
        self._view_category = "plugin"

        # View page defines which type of page layout to use. For example,
        # possible values include "overview", "detail" or "author".
        self._view_page = "loading"

        # Active package refers to which package is currently being downloaded,
        # installed, or otherwise modified.
        self._active_package = None

        self._dialog = None
        self._restart_required = False

        # variables for the license agreement dialog
        self._license_dialog_plugin_name = ""
        self._license_dialog_license_content = ""
        self._license_dialog_plugin_file_location = ""
        self._restart_dialog_message = ""

        Application.getInstance().initializationFinished.connect(self._onAppInitialized)



    # Signals:
    # --------------------------------------------------------------------------
    # Downloading changes
    activePackageChanged = pyqtSignal()
    onDownloadProgressChanged = pyqtSignal()
    onIsDownloadingChanged = pyqtSignal()
    restartRequiredChanged = pyqtSignal()
    installChanged = pyqtSignal()
    enabledChanged = pyqtSignal()

    # UI changes
    viewChanged = pyqtSignal()
    detailViewChanged = pyqtSignal()
    filterChanged = pyqtSignal()
    metadataChanged = pyqtSignal()
    showLicenseDialog = pyqtSignal()

    @pyqtSlot(result = str)
    def getLicenseDialogPluginName(self) -> str:
        return self._license_dialog_plugin_name

    @pyqtSlot(result = str)
    def getLicenseDialogPluginFileLocation(self) -> str:
        return self._license_dialog_plugin_file_location

    @pyqtSlot(result = str)
    def getLicenseDialogLicenseContent(self) -> str:
        return self._license_dialog_license_content

    def openLicenseDialog(self, plugin_name: str, license_content: str, plugin_file_location: str) -> None:
        self._license_dialog_plugin_name = plugin_name
        self._license_dialog_license_content = license_content
        self._license_dialog_plugin_file_location = plugin_file_location
        self.showLicenseDialog.emit()

    # This is a plugin, so most of the components required are not ready when
    # this is initialized. Therefore, we wait until the application is ready.
    def _onAppInitialized(self) -> None:
        self._package_manager = Application.getInstance().getCuraPackageManager()

    @pyqtSlot()
    def browsePackages(self) -> None:
        # Create the network manager:
        # This was formerly its own function but really had no reason to be as
        # it was never called more than once ever.
        if self._network_manager:
            self._network_manager.finished.disconnect(self._onRequestFinished)
            self._network_manager.networkAccessibleChanged.disconnect(self._onNetworkAccessibleChanged)
        self._network_manager = QNetworkAccessManager()
        self._network_manager.finished.connect(self._onRequestFinished)
        self._network_manager.networkAccessibleChanged.connect(self._onNetworkAccessibleChanged)

        # Make remote requests:
        self._makeRequestByType("packages")
        self._makeRequestByType("authors")
        self._makeRequestByType("plugins_showcase")
        self._makeRequestByType("materials_showcase")

        # Gather installed packages:
        self._updateInstalledModels()

        if not self._dialog:
            self._dialog = self._createDialog("Toolbox.qml")
        self._dialog.show()

        # Apply enabled/disabled state to installed plugins
        self.enabledChanged.emit()

    def _createDialog(self, qml_name: str) -> Optional[QObject]:
        Logger.log("d", "Toolbox: Creating dialog [%s].", qml_name)
        path = os.path.join(PluginRegistry.getInstance().getPluginPath(self.getPluginId()), "resources", "qml", qml_name)
        dialog = Application.getInstance().createQmlComponent(path, {"toolbox": self})
        return dialog

    @pyqtSlot()
    def _updateInstalledModels(self) -> None:
        all_packages = self._package_manager.getAllInstalledPackagesInfo()
        if "plugin" in all_packages:
            self._metadata["plugins_installed"] = all_packages["plugin"]
            self._models["plugins_installed"].setMetadata(self._metadata["plugins_installed"])
            self.metadataChanged.emit()
        if "material" in all_packages:
            self._metadata["materials_installed"] = all_packages["material"]
            self._models["materials_installed"].setMetadata(self._metadata["materials_installed"])
            self.metadataChanged.emit()

    @pyqtSlot(str)
    def install(self, file_path: str) -> None:
        self._package_manager.installPackage(file_path)
        self.installChanged.emit()
        self._updateInstalledModels()
        self.metadataChanged.emit()
        self._restart_required = True
        self.restartRequiredChanged.emit()

    @pyqtSlot(str)
    def uninstall(self, plugin_id: str) -> None:
        self._package_manager.removePackage(plugin_id)
        self.installChanged.emit()
        self._updateInstalledModels()
        self.metadataChanged.emit()
        self._restart_required = True
        self.restartRequiredChanged.emit()

    @pyqtSlot(str)
    def enable(self, plugin_id: str) -> None:
        self._plugin_registry.enablePlugin(plugin_id)
        self.enabledChanged.emit()
        Logger.log("i", "%s was set as 'active'.", plugin_id)
        self._restart_required = True
        self.restartRequiredChanged.emit()

    @pyqtSlot(str)
    def disable(self, plugin_id: str) -> None:
        self._plugin_registry.disablePlugin(plugin_id)
        self.enabledChanged.emit()
        Logger.log("i", "%s was set as 'deactive'.", plugin_id)
        self._restart_required = True
        self.restartRequiredChanged.emit()

    @pyqtProperty(bool, notify = metadataChanged)
    def dataReady(self) -> bool:
        return self._packages_model is not None

    @pyqtProperty(bool, notify = restartRequiredChanged)
    def restartRequired(self) -> bool:
        return self._restart_required

    @pyqtSlot()
    def restart(self):
        self._package_manager._removeAllScheduledPackages()
        CuraApplication.getInstance().windowClosed()

    # Checks
    # --------------------------------------------------------------------------
    @pyqtSlot(str, result = bool)
    def canUpdate(self, package_id: str) -> bool:
        local_package = self._package_manager.getInstalledPackageInfo(package_id)
        if local_package is None:
            return False

        remote_package = None
        for package in self._metadata["packages"]:
            if package["package_id"] == package_id:
                remote_package = package
        if remote_package is None:
            return False

        local_version = local_package["package_version"]
        remote_version = remote_package["package_version"]
        return Version(remote_version) > Version(local_version)

    @pyqtSlot(str, result = bool)
    def isInstalled(self, package_id: str) -> bool:
        return self._package_manager.isPackageInstalled(package_id)

    @pyqtSlot(str, result = bool)
    def isEnabled(self, package_id: str) -> bool:
        if package_id in self._plugin_registry.getActivePlugins():
            return True
        return False

    def loadingComplete(self) -> bool:
        populated = 0
        for list in self._metadata.items():
            if len(list) > 0:
                populated += 1
        if populated == len(self._metadata.items()):
            return True
        return False

    # Make API Calls
    # --------------------------------------------------------------------------
    def _makeRequestByType(self, type: str) -> None:
        Logger.log("i", "Toolbox: Requesting %s metadata from server.", type)
        request = QNetworkRequest(self._request_urls[type])
        request.setRawHeader(*self._request_header)
        self._network_manager.get(request)

    @pyqtSlot(str)
    def startDownload(self, url: str) -> None:
        Logger.log("i", "Toolbox: Attempting to download & install package from %s.", url)
        url = QUrl(url)
        self._download_request = QNetworkRequest(url)
        if hasattr(QNetworkRequest, "FollowRedirectsAttribute"):
            # Patch for Qt 5.6-5.8
            self._download_request.setAttribute(QNetworkRequest.FollowRedirectsAttribute, True)
        if hasattr(QNetworkRequest, "RedirectPolicyAttribute"):
            # Patch for Qt 5.9+
            self._download_request.setAttribute(QNetworkRequest.RedirectPolicyAttribute, True)
        self._download_request.setRawHeader(*self._request_header)
        self._download_reply = self._network_manager.get(self._download_request)
        self.setDownloadProgress(0)
        self.setIsDownloading(True)
        self._download_reply.downloadProgress.connect(self._onDownloadProgress)

    @pyqtSlot()
    def cancelDownload(self) -> None:
        Logger.log("i", "Toolbox: User cancelled the download of a plugin.")
        self.resetDownload()

    def resetDownload(self) -> None:
        if self._download_reply:
            self._download_reply.abort()
            self._download_reply.downloadProgress.disconnect(self._onDownloadProgress)
        self._download_reply = None
        self._download_request = None
        self.setDownloadProgress(0)
        self.setIsDownloading(False)

    # Handlers for Network Events
    # --------------------------------------------------------------------------
    def _onNetworkAccessibleChanged(self, accessible: int) -> None:
        if accessible == 0:
            self.resetDownload()

    def _onRequestFinished(self, reply: QNetworkReply) -> None:

        if reply.error() == QNetworkReply.TimeoutError:
            Logger.log("w", "Got a timeout.")
            self.setViewPage("errored")
            self.resetDownload()
            return

        if reply.error() == QNetworkReply.HostNotFoundError:
            Logger.log("w", "Unable to reach server.")
            self.setViewPage("errored")
            self.resetDownload()
            return

        if reply.operation() == QNetworkAccessManager.GetOperation:
            for type, url in self._request_urls.items():
                if reply.url() == url:
                    try:
                        json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))

                        # Check for errors:
                        if "errors" in json_data:
                            for error in json_data["errors"]:
                                Logger.log("e", "%s", error["title"])
                            return

                        # Create model and apply metadata:
                        if not self._models[type]:
                            Logger.log("e", "Could not find the %s model.", type)
                            break

                        # HACK: Eventually get rid of the code from here...
                        if type is "plugins_showcase" or type is "materials_showcase":
                            self._metadata["plugins_showcase"] = json_data["data"]["plugin"]["packages"]
                            self._models["plugins_showcase"].setMetadata(self._metadata["plugins_showcase"])
                            self._metadata["materials_showcase"] = json_data["data"]["material"]["authors"]
                            self._models["materials_showcase"].setMetadata(self._metadata["materials_showcase"])
                        else:
                            # ...until here.
                            # This hack arises for multiple reasons but the main
                            # one is because there are not separate API calls
                            # for different kinds of showcases.
                            self._metadata[type] = json_data["data"]
                            self._models[type].setMetadata(self._metadata[type])

                        # Do some auto filtering
                        # TODO: Make multiple API calls in the future to handle this
                        if type is "packages":
                            self._models[type].setFilter({"type": "plugin"})
                        if type is "authors":
                            self._models[type].setFilter({"package_types": "material"})

                        self.metadataChanged.emit()

                        if self.loadingComplete() is True:
                            self.setViewPage("overview")

                        return
                    except json.decoder.JSONDecodeError:
                        Logger.log("w", "Toolbox: Received invalid JSON for %s.", type)
                        break

        else:
            # Ignore any operation that is not a get operation
            pass

    def _onDownloadProgress(self, bytes_sent: int, bytes_total: int) -> None:
        if bytes_total > 0:
            new_progress = bytes_sent / bytes_total * 100
            self.setDownloadProgress(new_progress)
            if bytes_sent == bytes_total:
                self.setIsDownloading(False)
                self._download_reply.downloadProgress.disconnect(self._onDownloadProgress)
                # Must not delete the temporary file on Windows
                self._temp_plugin_file = tempfile.NamedTemporaryFile(mode = "w+b", suffix = ".curapackage", delete = False)
                file_path = self._temp_plugin_file.name
                # Write first and close, otherwise on Windows, it cannot read the file
                self._temp_plugin_file.write(self._download_reply.readAll())
                self._temp_plugin_file.close()
                self._onDownloadComplete(file_path)

    def _onDownloadComplete(self, file_path: str):
        Logger.log("i", "Toolbox: Download complete.")
        package_info = self._package_manager.getPackageInfo(file_path)
        if not package_info:
            Logger.log("w", "Toolbox: Package file [%s] was not a valid CuraPackage.", file_path)
            return

        license_content = self._package_manager.getPackageLicense(file_path)
        if license_content is not None:
            self.openLicenseDialog(package_info["package_id"], license_content, file_path)
            return

        self.install(file_path)
        return

    # Getter & Setters for Properties:
    # --------------------------------------------------------------------------
    def setDownloadProgress(self, progress: Union[int, float]) -> None:
        if progress != self._download_progress:
            self._download_progress = progress
            self.onDownloadProgressChanged.emit()

    @pyqtProperty(int, fset = setDownloadProgress, notify = onDownloadProgressChanged)
    def downloadProgress(self) -> int:
        return self._download_progress

    def setIsDownloading(self, is_downloading: bool) -> None:
        if self._is_downloading != is_downloading:
            self._is_downloading = is_downloading
            self.onIsDownloadingChanged.emit()

    @pyqtProperty(bool, fset = setIsDownloading, notify = onIsDownloadingChanged)
    def isDownloading(self) -> bool:
        return self._is_downloading

    def setActivePackage(self, package: Dict[str, Any]) -> None:
        self._active_package = package
        self.activePackageChanged.emit()

    @pyqtProperty(QObject, fset = setActivePackage, notify = activePackageChanged)
    def activePackage(self) -> Optional[Dict[str, Any]]:
        return self._active_package

    def setViewCategory(self, category: str = "plugin") -> None:
        self._view_category = category
        self.viewChanged.emit()

    @pyqtProperty(str, fset = setViewCategory, notify = viewChanged)
    def viewCategory(self) -> str:
        return self._view_category

    def setViewPage(self, page: str = "overview") -> None:
        self._view_page = page
        self.viewChanged.emit()

    @pyqtProperty(str, fset = setViewPage, notify = viewChanged)
    def viewPage(self) -> str:
        return self._view_page



    # Expose Models:
    # --------------------------------------------------------------------------
    @pyqtProperty(QObject, notify = metadataChanged)
    def authorsModel(self) -> AuthorsModel:
        return self._models["authors"]

    @pyqtProperty(QObject, notify = metadataChanged)
    def packagesModel(self) -> PackagesModel:
        return self._models["packages"]

    @pyqtProperty(QObject, notify = metadataChanged)
    def pluginsShowcaseModel(self) -> PackagesModel:
        return self._models["plugins_showcase"]

    @pyqtProperty(QObject, notify = metadataChanged)
    def pluginsInstalledModel(self) -> PackagesModel:
        return self._models["plugins_installed"]

    @pyqtProperty(QObject, notify = metadataChanged)
    def materialsShowcaseModel(self) -> PackagesModel:
        return self._models["materials_showcase"]

    @pyqtProperty(QObject, notify = metadataChanged)
    def materialsInstalledModel(self) -> PackagesModel:
        return self._models["materials_installed"]



    # Filter Models:
    # --------------------------------------------------------------------------
    @pyqtSlot(str, str, str)
    def filterModelByProp(self, modelType: str, filterType: str, parameter: str):
        if not self._models[modelType]:
            Logger.log("w", "Toolbox: Couldn't filter %s model because it doesn't exist.", modelType)
            return
        self._models[modelType].setFilter({ filterType: parameter })
        self.filterChanged.emit()

    @pyqtSlot()
    def removeFilters(self, modelType: str):
        if not self._models[modelType]:
            Logger.log("w", "Toolbox: Couldn't remove filters on %s model because it doesn't exist.", modelType)
            return
        self._models[modelType].setFilter({})
        self.filterChanged.emit()
示例#55
-1
 def send(params):
     url = self.formatUrl(endpoint, params)
     request = QNetworkRequest(url)
     headers['User-Agent'] = 'Divi QGIS Plugin/%s' % PLUGIN_VERSION
     QgsMessageLog.logMessage(str(headers), 'DIVI')
     for key, value in headers.items():
         request.setRawHeader(key.encode('utf-8'), value.encode('utf-8'))
     if method == 'delete':
         reply = manager.sendCustomRequest(request, 'DELETE'.encode('utf-8'), data)
     else:
         if not data:
             reply = getattr(manager, method)(request)
         elif isinstance(data, QHttpMultiPart) == True:
             reply = getattr(manager, method)(request, data)
         elif isinstance(data, str) == True:
             reply = getattr(manager, method)(request, data.encode('utf-8'))
     loop = QEventLoop()
     reply.uploadProgress.connect(self.uploadProgress)
     reply.downloadProgress.connect(self.downloadProgress)
     reply.metaDataChanged.connect(self.metaDataChanged)
     #reply.error.connect(self._error)
     reply.finished.connect(loop.exit)
     self.abort_sig.connect( reply.abort )
     loop.exec_()
     self.abort_sig.disconnect( reply.abort )
     return reply