Пример #1
0
 def __getReply(self, params):
     url = QUrl('http://ws.audioscrobbler.com/2.0/')
     url.addQueryItem('api_key', self.__last_fm_key)
     for key, value in params.iteritems():
         url.addQueryItem(key, value)
     request = QNetworkRequest(url)
     return self.__networkManager.get(request)
Пример #2
0
    def query(self, query):
        """
        Perform a nominatim query

        @param query: Query to execute
        @type query: str

        @raise NetWorkErrorException

        @return: the result of the query
        @rtype: str
        """

        url_query = QUrl(self.__url)

        query = QUrl.toPercentEncoding(query)
        url_query.addEncodedQueryItem('q', query)
        url_query.addQueryItem('info', 'QgisQuickOSMPlugin')

        request = QNetworkRequest(url_query)
        request.setRawHeader("User-Agent", "QuickOSM")
        self.network_reply = self.network.get(request)
        self.loop = QEventLoop()
        self.network.finished.connect(self._end_of_request)
        self.loop.exec_()

        if self.network_reply.error() == QNetworkReply.NoError:
            return json.loads(self.data)
        else:
            raise NetWorkErrorException(suffix="Nominatim API")
Пример #3
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)

        # self.title.setText( name() + version() )
        # self.description.setText( description() )

        text = self.txt.toHtml()
        text = text.replace("$PLUGIN_NAME$", name())
        text = text.replace("$PLUGIN_VERSION$", version())

        subject = "Help: %s" % name()
        body = """\n\n
--------
Plugin name: %s
Plugin version: %s
Python version: %s
Platform: %s - %s
--------
""" % (name(), version(), platform.python_version(), platform.system(), platform.version())

        mail = QUrl("mailto:[email protected]")
        mail.addQueryItem("subject", subject)
        mail.addQueryItem("body", body)

        text = text.replace("$MAIL_SUBJECT$", unicode(mail.encodedQueryItemValue("subject")))
        text = text.replace("$MAIL_BODY$", unicode(mail.encodedQueryItemValue("body")))

        self.txt.setHtml(text)
Пример #4
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)

        # self.title.setText( name() + version() )
        # self.description.setText( description() )

        text = self.txt.toHtml()
        text = text.replace("$PLUGIN_NAME$", name())
        text = text.replace("$PLUGIN_VERSION$", version())

        subject = "Help: %s" % name()
        body = """\n\n
--------
Plugin name: %s
Plugin version: %s
Python version: %s
Platform: %s - %s
--------
""" % (name(), version(), platform.python_version(), platform.system(),
        platform.version())

        mail = QUrl("mailto:[email protected]")
        mail.addQueryItem("subject", subject)
        mail.addQueryItem("body", body)

        text = text.replace("$MAIL_SUBJECT$",
                            unicode(mail.encodedQueryItemValue("subject")))
        text = text.replace("$MAIL_BODY$",
                            unicode(mail.encodedQueryItemValue("body")))

        self.txt.setHtml(text)
Пример #5
0
 def exchange_authorization_code(self, authorization_code, scopes,
                                 callback):
     log.debug(
         "OAuth: exchanging authorization_code %s for an access_token",
         authorization_code)
     host, port = config.setting['server_host'], config.setting[
         'server_port']
     path = "/oauth2/token"
     url = QUrl()
     url.addQueryItem("grant_type", "authorization_code")
     url.addQueryItem("code", authorization_code)
     url.addQueryItem("client_id", MUSICBRAINZ_OAUTH_CLIENT_ID)
     url.addQueryItem("client_secret", MUSICBRAINZ_OAUTH_CLIENT_SECRET)
     url.addQueryItem("redirect_uri", "urn:ietf:wg:oauth:2.0:oob")
     data = str(url.encodedQuery())
     self.xmlws.post(host,
                     port,
                     path,
                     data,
                     partial(self.on_exchange_authorization_code_finished,
                             scopes, callback),
                     xml=False,
                     mblogin=True,
                     priority=True,
                     important=True)
Пример #6
0
    def query(self, query):
        """
        Perform a nominatim query

        @param query: Query to execute
        @type query: str

        @raise NetWorkErrorException

        @return: the result of the query
        @rtype: str
        """

        url_query = QUrl(self.__url)

        query = QUrl.toPercentEncoding(query)
        url_query.addEncodedQueryItem('q', query)
        url_query.addQueryItem('info', 'QgisQuickOSMPlugin')
        url_query.setPort(80)

        proxy = get_proxy()
        if proxy:
            self.network.setProxy(proxy)

        request = QNetworkRequest(url_query)
        request.setRawHeader("User-Agent", "QuickOSM")
        self.network_reply = self.network.get(request)
        self.loop = QEventLoop()
        self.network.finished.connect(self._end_of_request)
        self.loop.exec_()

        if self.network_reply.error() == QNetworkReply.NoError:
            return json.loads(self.data)
        else:
            raise NetWorkErrorException(suffix="Nominatim API")
Пример #7
0
 def load_account_page(self, account, tab=None, task=None):
     self.tab = tab
     self.task = task
     self.account = account
     url = QUrl(account.server.settings_url)
     for name, value in self.query_items:
         url.addQueryItem(name, value)
     self.load(url)
Пример #8
0
def email(subject, body):
    """Opens the e-mail composer with the given subject and body, with version information added to it."""
    subject = "[{0} {1}] {2}".format(appinfo.appname, appinfo.version, subject)
    body = "{0}\n\n{1}\n\n".format(debuginfo.version_info_string(' -- '), body)
    url = QUrl("mailto:" + appinfo.maintainer_email)
    url.addQueryItem("subject", subject)
    url.addQueryItem("body", body)
    helpers.openUrl(url, "email")
Пример #9
0
def email(subject, body):
    """Opens the e-mail composer with the given subject and body, with version information added to it."""
    subject = "[{0} {1}] {2}".format(appinfo.appname, appinfo.version, subject)
    body = "{0}\n\n{1}\n\n".format(debuginfo.version_info_string(' -- '), body)
    url = QUrl("mailto:" + appinfo.maintainer_email)
    url.addQueryItem("subject", subject)
    url.addQueryItem("body", body)
    helpers.openUrl(url, "email")
Пример #10
0
 def load_account_page(self, account, tab=None, task=None):
     self.tab = tab
     self.task = task
     self.account = account
     url = QUrl(account.server.settings_url)
     for name, value in self.query_items:
         url.addQueryItem(name, value)
     self.load(url)
Пример #11
0
    def _sendRequest(self, url, params):
        if self.asynchonous:
            url = QUrl(url)
            for key, value in params.iteritems():
                url.addQueryItem(key, value)
            request = QNetworkRequest(url)
            self.reply = self.manager.get(request)

        else:
            response = urllib2.urlopen(self.url + '?' + urllib.urlencode(params))
            data = json.load(response)
            self.loadData(data)
Пример #12
0
    def query(self, query):
        """
        Make a query to the overpass

        @param query:Query to execute
        @type query:str

        @raise OverpassBadRequestException,NetWorkErrorException,
        OverpassTimeoutException

        @return: the result of the query
        @rtype: str
        """

        url_query = QUrl(self.__url + 'interpreter')

        # The output format can be forced (JSON or XML)
        if self.__output:
            query = re.sub(
                r'output="[a-z]*"', 'output="' + self.__output + '"', query)
            query = re.sub(
                r'\[out:[a-z]*', '[out:' + self.__output, query)

        # noinspection PyCallByClass
        encoded_query = QUrl.toPercentEncoding(query)
        url_query.addEncodedQueryItem('data', encoded_query)
        url_query.addQueryItem('info', 'QgisQuickOSMPlugin')
        url_query.setPort(80)

        proxy = get_proxy()
        if proxy:
            self.network.setProxy(proxy)

        request = QNetworkRequest(url_query)
        request.setRawHeader("User-Agent", "QuickOSM")
        self.network_reply = self.network.get(request)
        self.loop = QEventLoop()
        self.network.finished.connect(self._end_of_request)
        self.loop.exec_()

        if self.network_reply.error() == QNetworkReply.NoError:
            timeout = '<remark> runtime error: Query timed out in "[a-z]+" ' \
                      'at line [\d]+ after ([\d]+) seconds. </remark>'
            if re.search(timeout, self.data):
                raise OverpassTimeoutException
            else:
                return self.data

        elif self.network_reply.error() == QNetworkReply.UnknownContentError:
            raise OverpassBadRequestException
        else:
            raise NetWorkErrorException(suffix="Overpass API")
Пример #13
0
    def query(self, query):
        """
        Make a query to the overpass

        @param query:Query to execute
        @type query:str

        @raise OverpassBadRequestException,NetWorkErrorException,
        OverpassTimeoutException

        @return: the result of the query
        @rtype: str
        """

        url_query = QUrl(self.__url + 'interpreter')

        # The output format can be forced (JSON or XML)
        if self.__output:
            query = re.sub(r'output="[a-z]*"',
                           'output="' + self.__output + '"', query)
            query = re.sub(r'\[out:[a-z]*', '[out:' + self.__output, query)

        # noinspection PyCallByClass
        encoded_query = QUrl.toPercentEncoding(query)
        url_query.addEncodedQueryItem('data', encoded_query)
        url_query.addQueryItem('info', 'QgisQuickOSMPlugin')
        url_query.setPort(80)

        proxy = get_proxy()
        if proxy:
            self.network.setProxy(proxy)

        request = QNetworkRequest(url_query)
        request.setRawHeader("User-Agent", "QuickOSM")
        self.network_reply = self.network.get(request)
        self.loop = QEventLoop()
        self.network.finished.connect(self._end_of_request)
        self.loop.exec_()

        if self.network_reply.error() == QNetworkReply.NoError:
            timeout = '<remark> runtime error: Query timed out in "[a-z]+" ' \
                      'at line [\d]+ after ([\d]+) seconds. </remark>'
            if re.search(timeout, self.data):
                raise OverpassTimeoutException
            else:
                return self.data

        elif self.network_reply.error() == QNetworkReply.UnknownContentError:
            raise OverpassBadRequestException
        else:
            raise NetWorkErrorException(suffix="Overpass API")
Пример #14
0
 def exchange_authorization_code(self, authorization_code, scopes, callback):
     log.debug("OAuth: exchanging authorization_code %s for an access_token", authorization_code)
     host, port = config.setting['server_host'], config.setting['server_port']
     path = "/oauth2/token"
     url = QUrl()
     url.addQueryItem("grant_type", "authorization_code")
     url.addQueryItem("code", authorization_code)
     url.addQueryItem("client_id", MUSICBRAINZ_OAUTH_CLIENT_ID)
     url.addQueryItem("client_secret", MUSICBRAINZ_OAUTH_CLIENT_SECRET)
     url.addQueryItem("redirect_uri", "urn:ietf:wg:oauth:2.0:oob")
     data = str(url.encodedQuery())
     self.xmlws.post(host, port, path, data,
                     partial(self.on_exchange_authorization_code_finished, scopes, callback),
                     xml=False, mblogin=True, priority=True, important=True)
Пример #15
0
    def _checkUpload(self):

        if self._aborted:
            return

        log.debug('Sending upload status request (%s)', self.upload_id)
        url = QUrl(self.UPLOAD_STATUS.format(id=self.upload_id))
        url.addQueryItem('token', self.auth_token)

        req = QNetworkRequest(url)

        self.reply = self.network_manager.get(req)

        self.reply.finished.connect(self._onUploadStatus)
Пример #16
0
	def __init__(self, url, parent=None):
		super().__init__(parent)
		
		self.access_manager = FullscreenCSSFixer(QUrl('file://' + CSS_PATH))
		self.page().setNetworkAccessManager(self.access_manager)
		
		self.page().mainFrame().initialLayoutCompleted.connect(self.extend_window)
		self.titleChanged.connect(self.setWindowTitle)
		
		if urlparse(url).scheme in ('', 'file'):
			url = p.realpath(url)
		
		qurl = QUrl(VIEWER_PATH)
		qurl.addQueryItem('file', url)  # TODO: fix http urls
		self.load(qurl)
		
		self.page().setLinkDelegationPolicy(self.page().DelegateAllLinks)
		self.linkClicked.connect(self.link_clicked)
Пример #17
0
    def prerun(self, text, options, path, router_success, router_error):
        """Load Google Translate w/ language/text to capture audio."""

        if len(text) > LIMIT:
            raise IOError("Google Translate is limited to %d characters. "
                          "Consider using a different service if you need "
                          "playback for long phrases." % LIMIT)
        elif self._cb:
            raise SocketError("Google Translate does not allow concurrent "
                              "runs. If you need to playback multiple "
                              "phrases at the same time, please consider "
                              "using a different service.")

        if not self._frame:
            self._prerun_setup()

        self._netops += 30

        state = {}  # using a dict to workaround lack of `nonlocal` keyword

        def okay(stream):
            if 'resolved' not in state:
                state['resolved'] = True
                self._cb = None
                router_success(stream)

        def fail(message):
            if 'resolved' not in state:
                state['resolved'] = True
                self._cb = None
                router_error(SocketError(message))

        self._cb = dict(okay=okay, fail=fail)

        url = QUrl('https://translate.google.com/')
        url.addQueryItem('sl', options['voice'])
        url.addQueryItem('q', text)
        self._frame.load(url)

        def timeout():
            fail("Request timed out")

        QTimer.singleShot(15000, timeout)
Пример #18
0
 def decode(self, coord):
   url = QUrl("http://nominatim.openstreetmap.org/reverse")
   url.addQueryItem("format", "json")
   url.addQueryItem("lat", str(coord[0]))
   url.addQueryItem("lon", str(coord[1]))
   url.addQueryItem("zoom", "18")
   url.addQueryItem("addressdetails", "1")
   request = QNetworkRequest(url)
   reply = self.get(request)
   while reply.isRunning() :
     QApplication.processEvents()
   reply.deleteLater()
   self.deleteLater()
   return json.loads(unicode(reply.readAll(), 'UTF-8'))
Пример #19
0
 def refresh_access_token(self, callback):
     refresh_token = config.persist["oauth_refresh_token"]
     log.debug("OAuth: refreshing access_token with a refresh_token %s", refresh_token)
     host, port = config.setting['server_host'], config.setting['server_port']
     path = "/oauth2/token"
     url = QUrl()
     url.addQueryItem("grant_type", "refresh_token")
     url.addQueryItem("refresh_token", refresh_token)
     url.addQueryItem("client_id", MUSICBRAINZ_OAUTH_CLIENT_ID)
     url.addQueryItem("client_secret", MUSICBRAINZ_OAUTH_CLIENT_SECRET)
     data = str(url.encodedQuery())
     self.xmlws.post(host, port, path, data,
                     partial(self.on_refresh_access_token_finished, callback),
                     xml=False, mblogin=True, priority=True, important=True)
Пример #20
0
def _render_header(title, mode, phrase, filters):
    r = []
    r.append(ADV_HEADER)
    r.append('<h1>{0}</h1>'.format(title))
    r.append('<ul class="nav">\n')

    modes = [(name, spec) for (name, spec) in MODE_DICT.items()]
    modes.sort(key=itemgetter(0))

    for (name, spec) in modes:
        href = QUrl('search:///')
        if phrase:
            href.addQueryItem('phrase', phrase)
        if filters:
            href.addQueryItem('filters', filters)
        href.addQueryItem('mode', name)
        if name != mode:
            r.append('<li><a href="{href}">{title}</a></li>\n'.format(
                href=href.toEncoded(), title=spec['title']))
        else:
            r.append('<li><span class="sel">{title}<span></li>\n'.format(
                href=href.toEncoded(), title=spec['title']))

    r.append('</ul>\n')

    return ''.join(r)
Пример #21
0
def _render_header(title, mode, phrase, filters):
    r = []
    r.append(ADV_HEADER)
    r.append('<h1>{0}</h1>'.format(title))
    r.append('<ul class="nav">\n')

    modes = [(name, spec) for (name, spec) in MODE_DICT.items()]
    modes.sort(key=itemgetter(0))

    for (name, spec) in modes:
        href = QUrl('search:///')
        if phrase:
            href.addQueryItem('phrase', phrase)
        if filters:
            href.addQueryItem('filters', filters)
        href.addQueryItem('mode', name)
        if name != mode:
            r.append(
                '<li><a href="{href}">{title}</a></li>\n'.format(
                    href=href.toEncoded(), title=spec['title']))
        else:
            r.append(
                '<li><span class="sel">{title}<span></li>\n'.format(
                    href=href.toEncoded(), title=spec['title']))

    r.append('</ul>\n')

    return ''.join(r)
Пример #22
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)

        config = ConfigParser.ConfigParser()
        config.read(os.path.join(os.path.dirname(__file__), 'metadata.txt'))

        name = config.get('general', 'name')
        description = config.get('general', 'description')
        version = config.get('general', 'version')

        # self.title.setText( name )
        # self.description.setText( description )

        text = self.txt.toHtml()
        text = text.replace("$PLUGIN_NAME$", name)
        text = text.replace("$PLUGIN_VERSION$", version)

        subject = "Help: %s" % name
        body = """\n\n
--------
Plugin name: %s
Plugin version: %s
Python version: %s
Platform: %s - %s
--------
""" % (name, version, platform.python_version(), platform.system(),
        platform.version())

        mail = QUrl("mailto:[email protected]")
        mail.addQueryItem("subject", subject)
        mail.addQueryItem("body", body)

        text = text.replace("$MAIL_SUBJECT$",
                            unicode(mail.encodedQueryItemValue("subject")))
        text = text.replace("$MAIL_BODY$",
                            unicode(mail.encodedQueryItemValue("body")))

        self.txt.setHtml(text)
Пример #23
0
    def _sendRequest(self, url, params, headers={}):
        if self.asynchonous:

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

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

        else:
            response = urllib2.urlopen(self.url + '?' + urllib.urlencode(params))
            data = json.load(response)
            self.loadData(data)
Пример #24
0
 def get_authorization_url(self, scopes):
     host, port = config.setting['server_host'], config.setting['server_port']
     url = QUrl()
     if (host in MUSICBRAINZ_SERVERS and port == 80) or port == 443:
         url.setScheme("https")
     else:
         url.setScheme("http")
         if port != 80:
             url.setPort(port)
     url.setHost(host)
     url.setPath("/oauth2/authorize")
     url.addQueryItem("response_type", "code")
     url.addQueryItem("client_id", MUSICBRAINZ_OAUTH_CLIENT_ID)
     url.addQueryItem("redirect_uri", "urn:ietf:wg:oauth:2.0:oob")
     url.addQueryItem("scope", scopes)
     return str(url.toEncoded())
Пример #25
0
    def _sendRequest(self, url, params, headers={}):
        if self.asynchonous:

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

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

        else:
            response = urllib2.urlopen(self.url + '?' +
                                       urllib.urlencode(params))
            data = json.load(response)
            self.loadData(data)
Пример #26
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)

        config = ConfigParser.ConfigParser()
        config.read(os.path.join(os.path.dirname(__file__), 'metadata.txt'))

        name        = config.get('general', 'name')
        description = config.get('general', 'description')
        version     = config.get('general', 'version')

        # self.title.setText( name )
        # self.description.setText( description )

        text = self.txt.toHtml()
        text = text.replace("$PLUGIN_NAME$", name)
        text = text.replace("$PLUGIN_VERSION$", version)

        subject = "Help: %s" % name
        body = """\n\n
--------
Plugin name: %s
Plugin version: %s
Python version: %s
Platform: %s - %s
--------
""" % (name, version, platform.python_version(), platform.system(), platform.version())

        mail = QUrl("mailto:[email protected]")
        mail.addQueryItem("subject", subject)
        mail.addQueryItem("body", body)

        text = text.replace("$MAIL_SUBJECT$", unicode(mail.encodedQueryItemValue("subject")))
        text = text.replace("$MAIL_BODY$", unicode(mail.encodedQueryItemValue("body")))

        self.txt.setHtml(text)
Пример #27
0
def build_papercdcase_url(artist, album, tracks):
    url = QUrl(PAPERCDCASE_URL)
    # papercdcase.com does not deal well with unicode characters :(
    url.addQueryItem('artist', textencoding.asciipunct(artist))
    url.addQueryItem('title', textencoding.asciipunct(album))
    i = 1
    for track in tracks:
        url.addQueryItem('track' + str(i), textencoding.asciipunct(track))
        i += 1
    return url.toString()
Пример #28
0
 def capabilitiesUrl(url):
     _url = QUrl(url)
     _url.addQueryItem("Service", "SOS")
     _url.addQueryItem("AcceptVersions", "2.0.0")
     _url.addQueryItem("Request", "GetCapabilities")
     return _url
Пример #29
0
 def _urlencode_post_data(self, post_data):
     post_params = QUrl()
     for (key, value) in post_data.items():
         post_params.addQueryItem(key, unicode(value))
     return post_params.encodedQuery()
Пример #30
0
 def capabilitiesUrl(url):
     _url = QUrl (url)
     _url.addQueryItem("Service", "SOS")
     _url.addQueryItem("AcceptVersions", "1.0.0")
     _url.addQueryItem("Request","GetCapabilities")
     return _url
Пример #31
0
        # data[x] = wxResult
        # x += 1
    print json.dumps(data)
    return


if __name__ == '__main__':
    app = QApplication(sys.argv)
    type = 1
    keyword = u"搞笑"
    page = 1
    view = Browser()
    url = QUrl('http://weixin.sogou.com/weixin')
    # 搜索微信文章 test
    if 1 == type:
        url.addQueryItem('type', '1')
        url.addQueryItem('query', keyword)
        url.addQueryItem('page', '1')
    elif 2 == type:
        url.addQueryItem('type', '2')
        url.addQueryItem('query', keyword)
        url.addQueryItem('page', '2')
    # view.searchWxArticle('http://weixin.sogou.com/weixin?type=2&query=%E6%90%9E%E7%AC%91')
    # test 微信号
    # view.searchWxService(url)
    # view.parseWxNumberHome(QUrl('http://mp.weixin.qq.com/profile?src=3&timestamp=1477755435&ver=1&signature=GDDyd1Y3OVTxCrGuGZzQsertKX0LF9yULQwm0kn-rPXRb2dAerVWw06uawCkQqU4etpYmqWLmuKhjfW2QQw1qg=='))
    view.parseWxArticle(
        QUrl(
            'http://mp.weixin.qq.com/s?timestamp=1477759661&src=3&ver=1&signature=ZYVg-oqTE86YJjL2ahRhJae54Yap4I5MAG7B3s*M5h9iG75B8vyjflchYvJgxfkqbmjT4dVJgGXx9Qf6OOefYfi3GeiY9SRRjlgdRf8tmm91MgjfAQmk5*pye-5ZkkOLo*kIEO724rsWk0i1wP1dvDUXNapv*bWZBO1VpHWNKic='
        ))
    # view.page().userAgentForUrl = u'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36'