示例#1
0
    def fetchPrices(priceMap, fetchTimeout, system=None):
        params = {'typeid': {typeID for typeID in priceMap}}
        if system is not None:
            params['usesystem'] = system
        baseurl = 'https://api.evemarketer.com/ec/marketstat'
        network = Network.getInstance()
        data = network.get(url=baseurl,
                           type=network.PRICES,
                           params=params,
                           timeout=fetchTimeout)
        xml = minidom.parseString(data.text)
        types = xml.getElementsByTagName('marketstat').item(
            0).getElementsByTagName('type')
        # Cycle through all types we've got from request
        for type_ in types:
            # Get data out of each typeID details tree
            typeID = int(type_.getAttribute('id'))
            sell = type_.getElementsByTagName('sell').item(0)
            # If price data wasn't there, skip the item
            try:
                percprice = float(
                    sell.getElementsByTagName('percentile').item(
                        0).firstChild.data)
            except (TypeError, ValueError):
                pyfalog.warning('Failed to get price for: {0}', type_)
                continue

            # Price is 0 if evemarketer has info on this item, but it is not available
            # for current scope limit. If we provided scope limit - make sure to skip
            # such items to check globally, and do not skip if requested globally
            if percprice == 0 and system is not None:
                continue
            priceMap[typeID].update(PriceStatus.fetchSuccess, percprice)
            del priceMap[typeID]
示例#2
0
    def __init__(self, types, system, priceMap):
        data = []
        baseurl = "https://eve-central.com/api/marketstat"
        data.append(("usesystem", system))  # Use Jita for market

        for typeID in types:  # Add all typeID arguments
            data.append(("typeid", typeID))

        network = Network.getInstance()
        data = network.request(baseurl, network.PRICES, data)
        xml = minidom.parse(data)
        types = xml.getElementsByTagName("marketstat").item(0).getElementsByTagName("type")
        # Cycle through all types we've got from request
        for type_ in types:
            # Get data out of each typeID details tree
            typeID = int(type_.getAttribute("id"))
            sell = type_.getElementsByTagName("sell").item(0)
            # If price data wasn't there, set price to zero
            try:
                percprice = float(sell.getElementsByTagName("percentile").item(0).firstChild.data)
            except (TypeError, ValueError):
                pyfalog.warning("Failed to get price for: {0}", type_)
                percprice = 0

            # Fill price data
            priceobj = priceMap[typeID]
            priceobj.price = percprice
            priceobj.time = time.time() + VALIDITY
            priceobj.failed = None

            # delete price from working dict
            del priceMap[typeID]
示例#3
0
    def fetchPrices(priceMap, fetchTimeout, system=None):
        params = {"type_ids": ','.join(str(typeID) for typeID in priceMap)}
        if system is not None:
            params["system_id"] = system
        baseurl = "https://eve-marketdata.com/api/item_prices.xml"
        network = Network.getInstance()
        data = network.request(baseurl, network.PRICES, params=params, timeout=fetchTimeout)
        xml = minidom.parseString(data.text)
        types = xml.getElementsByTagName("eve").item(0).getElementsByTagName("price")

        # Cycle through all types we've got from request
        for type_ in types:
            # Get data out of each typeID details tree
            typeID = int(type_.getAttribute("id"))

            try:
                price = float(type_.firstChild.data)
            except (TypeError, ValueError):
                pyfalog.warning("Failed to get price for: {0}", type_)
                continue

            # eve-marketdata returns 0 if price data doesn't even exist for the item
            if price == 0:
                continue
            priceMap[typeID].update(PriceStatus.fetchSuccess, price)
            del priceMap[typeID]
示例#4
0
    def fetchPrices(priceMap, fetchTimeout, system=None):
        params = {"typeid": {typeID for typeID in priceMap}}
        if system is not None:
            params["usesystem"] = system
        baseurl = "https://api.evemarketer.com/ec/marketstat"
        network = Network.getInstance()
        data = network.request(baseurl, network.PRICES, params=params, timeout=fetchTimeout)
        xml = minidom.parseString(data.text)
        types = xml.getElementsByTagName("marketstat").item(0).getElementsByTagName("type")
        # Cycle through all types we've got from request
        for type_ in types:
            # Get data out of each typeID details tree
            typeID = int(type_.getAttribute("id"))
            sell = type_.getElementsByTagName("sell").item(0)
            # If price data wasn't there, set price to zero
            try:
                percprice = float(sell.getElementsByTagName("percentile").item(0).firstChild.data)
            except (TypeError, ValueError):
                pyfalog.warning("Failed to get price for: {0}", type_)
                continue

            # Price is 0 if evemarketer has info on this item, but it is not available
            # for current scope limit. If we provided scope limit - make sure to skip
            # such items to check globally, and do not skip if requested globally
            if percprice == 0 and system is not None:
                continue

            priceMap[typeID].update(PriceStatus.fetchSuccess, percprice)
            del priceMap[typeID]
示例#5
0
 def fetchPrices(priceMap, fetchTimeout, system=None):
     if system not in systemAliases:
         return
     jsonData = {
         'market_name': systemAliases[system],
         'items': [{'type_id': typeID} for typeID in priceMap]}
     baseurl = 'https://evepraisal.com/appraisal/structured.json'
     network = Network.getInstance()
     resp = network.post(baseurl, network.PRICES, jsonData=jsonData, timeout=fetchTimeout)
     data = resp.json()
     try:
         itemsData = data['appraisal']['items']
     except (KeyError, TypeError):
         return
     # Cycle through all types we've got from request
     for itemData in itemsData:
         try:
             typeID = int(itemData['typeID'])
             price = itemData['prices']['sell']['min']
             orderCount = itemData['prices']['sell']['order_count']
         except (KeyError, TypeError):
             continue
         # evepraisal returns 0 if price data doesn't even exist for the item
         if price == 0:
             continue
         # evepraisal seems to provide price for some items despite having no orders up
         if orderCount < 1:
             continue
         priceMap[typeID].update(PriceStatus.fetchSuccess, price)
         del priceMap[typeID]
示例#6
0
    def fetchPrices(priceMap, fetchTimeout, system=None):
        params = {'type_ids': ','.join(str(typeID) for typeID in priceMap)}
        if system is not None:
            params['system_id'] = system
        baseurl = 'https://eve-marketdata.com/api/item_prices.xml'
        network = Network.getInstance()
        data = network.get(url=baseurl,
                           type=network.PRICES,
                           params=params,
                           timeout=fetchTimeout)
        xml = minidom.parseString(data.text)
        types = xml.getElementsByTagName('eve').item(0).getElementsByTagName(
            'price')

        # Cycle through all types we've got from request
        for type_ in types:
            # Get data out of each typeID details tree
            typeID = int(type_.getAttribute('id'))

            try:
                price = float(type_.firstChild.data)
            except (TypeError, ValueError):
                pyfalog.warning('Failed to get price for: {0}', type_)
                continue

            # eve-marketdata returns 0 if price data doesn't even exist for the item
            if price == 0:
                continue
            priceMap[typeID].update(PriceStatus.fetchSuccess, price)
            del priceMap[typeID]
示例#7
0
 def __init__(self, callback):
     threading.Thread.__init__(self)
     self.name = "CheckUpdate"
     self.callback = callback
     self.settings = UpdateSettings.getInstance()
     self.network = Network.getInstance()
     self.running = True
示例#8
0
    def run(self):
        network = Network.getInstance()

        try:
            response = network.request(
                'https://api.github.com/repos/pyfa-org/Pyfa/releases',
                network.UPDATE)
            jsonResponse = json.loads(response.read())
            jsonResponse.sort(key=lambda x: calendar.timegm(
                dateutil.parser.parse(x['published_at']).utctimetuple()),
                              reverse=True)

            for release in jsonResponse:
                # Suppress pre releases
                if release['prerelease'] and self.settings.get('prerelease'):
                    continue

                # Handle use-case of updating to suppressed version
                if self.settings.get('version') == 'v' + config.version:
                    self.settings.set('version', None)

                # Suppress version
                if release['tag_name'] == self.settings.get('version'):
                    break

                # Set the release version that we will be comparing with.
                if release['prerelease']:
                    rVersion = release['tag_name'].replace(
                        'singularity-', '', 1)
                else:
                    rVersion = release['tag_name'].replace('v', '', 1)

                if config.tag is 'git' and \
                        not release['prerelease'] and \
                        self.versiontuple(rVersion) >= self.versiontuple(config.version):
                    wx.CallAfter(self.callback,
                                 release)  # git (dev/Singularity) -> Stable
                elif config.expansionName is not "Singularity":
                    if release['prerelease']:
                        wx.CallAfter(self.callback,
                                     release)  # Stable -> Singularity
                    elif self.versiontuple(rVersion) > self.versiontuple(
                            config.version):
                        wx.CallAfter(self.callback,
                                     release)  # Stable -> Stable
                else:
                    if release[
                            'prerelease'] and rVersion > config.expansionVersion:
                        wx.CallAfter(self.callback,
                                     release)  # Singularity -> Singularity
                break
        except Exception as e:
            pyfalog.error("Caught exception in run")
            pyfalog.error(e)
            pass
示例#9
0
文件: update.py 项目: copyliu/Pyfa
    def run(self):
        network = Network.getInstance()

        try:
            response = network.request('https://api.github.com/repos/pyfa-org/Pyfa/releases', network.UPDATE)
            jsonResponse = json.loads(response.read())
            jsonResponse.sort(
                key=lambda x: calendar.timegm(dateutil.parser.parse(x['published_at']).utctimetuple()),
                reverse=True
            )

            for release in jsonResponse[:5]:
                try:
                    # Suppress pre releases
                    if release['prerelease'] and self.settings.get('prerelease'):
                        continue

                    # Handle use-case of updating to suppressed version
                    if self.settings.get('version') == 'v' + config.version:
                        self.settings.set('version', None)

                    # Suppress version
                    if release['tag_name'] == self.settings.get('version'):
                        break

                    # Set the release version that we will be comparing with.
                    if release['prerelease']:
                        rVersion = release['tag_name'].replace('singularity-', '', 1)
                    else:
                        rVersion = release['tag_name'].replace('v', '', 1)

                    if config.tag is 'git' and \
                            not release['prerelease'] and \
                            self.versiontuple(rVersion) >= self.versiontuple(config.version):
                        wx.CallAfter(self.callback, release)  # git (dev/Singularity) -> Stable
                        break
                    elif config.expansionName is not "Singularity":
                        if release['prerelease']:
                            wx.CallAfter(self.callback, release)  # Stable -> Singularity
                            break
                        elif self.versiontuple(rVersion) > self.versiontuple(config.version):
                            wx.CallAfter(self.callback, release)  # Stable -> Stable
                            break
                    else:
                        if release['prerelease'] and rVersion > config.expansionVersion:
                            wx.CallAfter(self.callback, release)  # Singularity -> Singularity
                            break
                except Exception as e:
                    # if we break at version checking, try the next version
                    pyfalog.error(e)
                    continue
        except Exception as e:
            pyfalog.error("Caught exception in run")
            pyfalog.error(e)
            pass
示例#10
0
    def __init__(self, types, system, priceMap):
        data = []
        baseurl = "https://eve-central.com/api/marketstat"
        data.append(("usesystem", system))  # Use Jita for market

        for typeID in types:  # Add all typeID arguments
            data.append(("typeid", typeID))

        # Attempt to send request and process it
        try:
            network = Network.getInstance()
            data = network.request(baseurl, network.PRICES, data)
            xml = minidom.parse(data)
            types = xml.getElementsByTagName("marketstat").item(
                0).getElementsByTagName("type")
            # Cycle through all types we've got from request
            for type_ in types:
                # Get data out of each typeID details tree
                typeID = int(type_.getAttribute("id"))
                sell = type_.getElementsByTagName("sell").item(0)
                # If price data wasn't there, set price to zero
                try:
                    percprice = float(
                        sell.getElementsByTagName("percentile").item(
                            0).firstChild.data)
                except (TypeError, ValueError):
                    pyfalog.warning("Failed to get price for: {0}", type_)
                    percprice = 0

                # Fill price data
                priceobj = priceMap[typeID]
                priceobj.price = percprice
                priceobj.time = time.time() + VALIDITY
                priceobj.failed = None

                # delete price from working dict
                del priceMap[typeID]

        # If getting or processing data returned any errors
        except TimeoutError:
            # Timeout error deserves special treatment
            pyfalog.warning("Price fetch timout")
            for typeID in priceMap.keys():
                priceobj = priceMap[typeID]
                priceobj.time = time.time() + TIMEOUT
                priceobj.failed = True

                del priceMap[typeID]
        except:
            # all other errors will pass and continue onward to the REREQUEST delay
            pyfalog.warning("Caught exception in fetchPrices")
            pass
        pass
示例#11
0
    def run(self):
        network = Network.getInstance()

        try:
            try:
                response = network.get(
                    url=
                    'https://www.pyfa.io/update_check?pyfa_version={}&client_hash={}'
                    .format(config.version, config.getClientSecret()),
                    type=network.UPDATE,
                    timeout=5)
            except (KeyboardInterrupt, SystemExit):
                raise
            except Exception as e:
                response = network.get(
                    url='https://api.github.com/repos/pyfa-org/Pyfa/releases',
                    type=network.UPDATE,
                    timeout=5)

            jsonResponse = response.json()
            jsonResponse.sort(key=lambda x: calendar.timegm(
                dateutil.parser.parse(x['published_at']).utctimetuple()),
                              reverse=True)

            for release in jsonResponse[:5]:
                rVersion = Version(release['tag_name'])
                cVersion = Version(config.version)

                # Suppress pre releases if we're not already on a pre-release (if we are, we want to know about new ones)
                if not cVersion.is_prerelease and rVersion.is_prerelease and self.settings.get(
                        'prerelease'):
                    continue

                # Handle use-case of updating to suppressed version
                if self.settings.get('version') == 'v' + config.version:
                    self.settings.set('version', None)

                # Suppress version
                if release['tag_name'] == self.settings.get('version'):
                    break

                if rVersion > cVersion:
                    wx.CallAfter(self.callback, release, rVersion)
                    break

        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception as e:
            pyfalog.error("Caught exception in run")
            pyfalog.error(e)
            pass
示例#12
0
文件: eveapi.py 项目: w9jds/Pyfa
    def __call__(self, path, **kw):
        # convert list type arguments to something the API likes
        for k, v in kw.iteritems():
            if isinstance(v, _listtypes):
                kw[k] = ','.join(map(str, list(v)))

        cache = self._root._handler

        # now send the request
        path += ".xml.aspx"

        if cache:
            response = cache.retrieve(self._host, path, kw)
        else:
            response = None

        if response is None:
            network = Network.getInstance()

            req = self._scheme + '://' + self._host + path

            response = network.request(req, network.EVE, kw)

            if cache:
                store = True
                response = response.read()
            else:
                store = False
        else:
            store = False

        retrieve_fallback = cache and getattr(cache, "retrieve_fallback",
                                              False)
        if retrieve_fallback:
            # implementor is handling fallbacks...
            try:
                return _ParseXML(
                    response, True, store and (lambda obj: cache.store(
                        self._host, path, kw, response, obj)))
            except Error as e:
                response = retrieve_fallback(self._host, path, kw, reason=e)
                if response is not None:
                    return response
                raise
        else:
            # implementor is not handling fallbacks...
            return _ParseXML(
                response, True, store and
                (lambda obj: cache.store(self._host, path, kw, response, obj)))
示例#13
0
    def __call__(self, path, **kw):
        # convert list type arguments to something the API likes
        for k, v in kw.iteritems():
            if isinstance(v, _listtypes):
                kw[k] = ','.join(map(str, list(v)))

        cache = self._root._handler

        # now send the request
        path += ".xml.aspx"

        if cache:
            response = cache.retrieve(self._host, path, kw)
        else:
            response = None

        if response is None:
            network = Network.getInstance()

            req = self._scheme + '://' + self._host + path

            response = network.request(req, network.EVE, kw)

            if cache:
                store = True
                response = response.read()
            else:
                store = False
        else:
            store = False

        retrieve_fallback = cache and getattr(cache, "retrieve_fallback", False)
        if retrieve_fallback:
            # implementor is handling fallbacks...
            try:
                return _ParseXML(response, True,
                                 store and (lambda obj: cache.store(self._host, path, kw, response, obj)))
            except Error as e:
                response = retrieve_fallback(self._host, path, kw, reason=e)
                if response is not None:
                    return response
                raise
        else:
            # implementor is not handling fallbacks...
            return _ParseXML(response, True, store and (lambda obj: cache.store(self._host, path, kw, response, obj)))
示例#14
0
文件: update.py 项目: blitzmann/Pyfa
    def run(self):
        network = Network.getInstance()

        try:
            try:
                response = network.request('https://www.pyfa.io/update_check?pyfa_version={}&client_hash={}'.format(
                    config.version, config.getClientSecret()), network.UPDATE)
            except Exception as e:
                response = network.request('https://api.github.com/repos/pyfa-org/Pyfa/releases', network.UPDATE)

            jsonResponse = response.json()
            jsonResponse.sort(
                key=lambda x: calendar.timegm(dateutil.parser.parse(x['published_at']).utctimetuple()),
                reverse=True
            )

            for release in jsonResponse[:5]:
                rVersion = Version(release['tag_name'])
                cVersion = Version(config.version)

                # Suppress pre releases if we're not already on a pre-release (if we are, we want to know about new ones)
                if not cVersion.is_prerelease and rVersion.is_prerelease and self.settings.get('prerelease'):
                    continue

                # Handle use-case of updating to suppressed version
                if self.settings.get('version') == 'v' + config.version:
                    self.settings.set('version', None)

                # Suppress version
                if release['tag_name'] == self.settings.get('version'):
                    break

                if rVersion > cVersion:
                    wx.CallAfter(self.callback, release, rVersion)
                    break

        except Exception as e:
            pyfalog.error("Caught exception in run")
            pyfalog.error(e)
            pass
示例#15
0
文件: fuzzwork.py 项目: zjx1994/Pyfa
 def fetchPrices(priceMap, fetchTimeout, system=None):
     params = {'types': ','.join(str(typeID) for typeID in priceMap)}
     for k, v in locations.get(system, {}).items():
         params[k] = v
     baseurl = 'https://market.fuzzwork.co.uk/aggregates/'
     network = Network.getInstance()
     resp = network.get(url=baseurl, type=network.PRICES, params=params, timeout=fetchTimeout)
     data = resp.json()
     # Cycle through all types we've got from request
     for typeID, typeData in data.items():
         try:
             typeID = int(typeID)
             price = float(typeData['sell']['percentile'])
         except (KeyError, TypeError):
             continue
         # Fuzzworks returns 0 when there's no data for item
         if price == 0:
             continue
         if typeID not in priceMap:
             continue
         priceMap[typeID].update(PriceStatus.fetchSuccess, price)
         del priceMap[typeID]
示例#16
0
    def __init__(self, types, system, priceMap):
        data = {}
        baseurl = "https://eve-marketdata.com/api/item_prices.xml"
        data["system_id"] = system  # Use Jita for market
        data["type_ids"] = ','.join(str(x) for x in types)

        network = Network.getInstance()
        data = network.request(baseurl, network.PRICES, params=data)
        xml = minidom.parseString(data.text)
        types = xml.getElementsByTagName("eve").item(0).getElementsByTagName(
            "price")

        # Cycle through all types we've got from request
        for type_ in types:
            # Get data out of each typeID details tree
            typeID = int(type_.getAttribute("id"))

            try:
                price = float(type_.firstChild.data)
            except (TypeError, ValueError):
                pyfalog.warning("Failed to get price for: {0}", type_)

            # Fill price data
            priceobj = priceMap[typeID]

            # eve-marketdata returns 0 if price data doesn't even exist for the item. In this case, don't reset the
            # cached price, and set the price timeout to TIMEOUT (every 15 minutes currently). Se GH issue #1334
            if price != 0:
                priceobj.price = price
                priceobj.time = time.time() + VALIDITY
            else:
                priceobj.time = time.time() + TIMEOUT

            priceobj.failed = None

            # delete price from working dict
            del priceMap[typeID]
示例#17
0
    def __init__(self, types, system, priceMap):
        data = {}
        baseurl = "https://eve-marketdata.com/api/item_prices.xml"
        data["system_id"] = system  # Use Jita for market
        data["type_ids"] = ','.join(str(x) for x in types)

        network = Network.getInstance()
        data = network.request(baseurl, network.PRICES, params=data)
        xml = minidom.parseString(data.text)
        types = xml.getElementsByTagName("eve").item(0).getElementsByTagName("price")

        # Cycle through all types we've got from request
        for type_ in types:
            # Get data out of each typeID details tree
            typeID = int(type_.getAttribute("id"))

            try:
                price = float(type_.firstChild.data)
            except (TypeError, ValueError):
                pyfalog.warning("Failed to get price for: {0}", type_)

            # Fill price data
            priceobj = priceMap[typeID]

            # eve-marketdata returns 0 if price data doesn't even exist for the item. In this case, don't reset the
            # cached price, and set the price timeout to TIMEOUT (every 15 minutes currently). Se GH issue #1334
            if price != 0:
                priceobj.price = price
                priceobj.time = time.time() + VALIDITY
            else:
                priceobj.time = time.time() + TIMEOUT

            priceobj.failed = None

            # delete price from working dict
            del priceMap[typeID]
示例#18
0
    def __init__(self, types, system, priceMap):
        data = {}
        baseurl = "https://api.evemarketer.com/ec/marketstat"

        data["usesystem"] = system  # Use Jita for market
        data["typeid"] = set()
        for typeID in types:  # Add all typeID arguments
            data["typeid"].add(typeID)

        network = Network.getInstance()
        data = network.request(baseurl, network.PRICES, params=data)
        xml = minidom.parseString(data.text)
        types = xml.getElementsByTagName("marketstat").item(
            0).getElementsByTagName("type")
        # Cycle through all types we've got from request
        for type_ in types:
            # Get data out of each typeID details tree
            typeID = int(type_.getAttribute("id"))
            sell = type_.getElementsByTagName("sell").item(0)
            # If price data wasn't there, set price to zero
            try:
                percprice = float(
                    sell.getElementsByTagName("percentile").item(
                        0).firstChild.data)
            except (TypeError, ValueError):
                pyfalog.warning("Failed to get price for: {0}", type_)
                percprice = 0

            # Fill price data
            priceobj = priceMap[typeID]
            priceobj.price = percprice
            priceobj.time = time.time() + VALIDITY
            priceobj.status = PriceStatus.success

            # delete price from working dict
            del priceMap[typeID]
示例#19
0
 def fetchPrices(priceMap, fetchTimeout, system=None, serenity=False):
     params = {'typeid': {typeID for typeID in priceMap}}
     if system is not None:
         params['usesystem'] = system
     baseurl = 'https://www.ceve-market.org/api/marketstat' if serenity else 'https://www.ceve-market.org/tqapi/marketstat'
     network = Network.getInstance()
     data = network.get(url=baseurl, type=network.PRICES, params=params, timeout=fetchTimeout)
     xml = minidom.parseString(data.text)
     types = xml.getElementsByTagName('marketstat').item(0).getElementsByTagName('type')
     # Cycle through all types we've got from request
     for type_ in types:
         # Get data out of each typeID details tree
         typeID = int(type_.getAttribute('id'))
         sell = type_.getElementsByTagName('sell').item(0)
         # If price data wasn't there, skip the item
         try:
             percprice = float(sell.getElementsByTagName('percentile').item(0).firstChild.data)
         except (TypeError, ValueError):
             pyfalog.warning('Failed to get price for: {0}', type_)
             continue
         if percprice == 0 and system is not None:
             continue
         priceMap[typeID].update(PriceStatus.fetchSuccess, percprice)
         del priceMap[typeID]
示例#20
0
文件: price.py 项目: nikander100/Pyfa
    def fetchPrices(cls, prices):
        """Fetch all prices passed to this method"""

        # Dictionary for our price objects
        priceMap = {}
        # Check all provided price objects, and add invalid ones to dictionary
        for price in prices:
            if not price.isValid:
                priceMap[price.typeID] = price

        if len(priceMap) == 0:
            return

        # Set of items which are still to be requested from this service
        toRequest = set()

        # Compose list of items we're going to request
        for typeID in priceMap:
            # Get item object
            item = db.getItem(typeID)
            # We're not going to request items only with market group, as eve-central
            # doesn't provide any data for items not on the market
            if item is not None and item.marketGroupID:
                toRequest.add(typeID)

        # Do not waste our time if all items are not on the market
        if len(toRequest) == 0:
            return

        # This will store POST data for eve-central
        data = []

        sFit = Fit.getInstance()
        # Base request URL
        baseurl = "https://eve-central.com/api/marketstat"
        data.append(("usesystem", cls.systemsList[sFit.serviceFittingOptions["priceSystem"]]))  # Use Jita for market

        for typeID in toRequest:  # Add all typeID arguments
            data.append(("typeid", typeID))

        # Attempt to send request and process it
        try:
            network = Network.getInstance()
            data = network.request(baseurl, network.PRICES, data)
            xml = minidom.parse(data)
            types = xml.getElementsByTagName("marketstat").item(0).getElementsByTagName("type")
            # Cycle through all types we've got from request
            for type_ in types:
                # Get data out of each typeID details tree
                typeID = int(type_.getAttribute("id"))
                sell = type_.getElementsByTagName("sell").item(0)
                # If price data wasn't there, set price to zero
                try:
                    percprice = float(sell.getElementsByTagName("percentile").item(0).firstChild.data)
                except (TypeError, ValueError):
                    pyfalog.warning("Failed to get price for: {0}", type_)
                    percprice = 0

                # Fill price data
                priceobj = priceMap[typeID]
                priceobj.price = percprice
                priceobj.time = time.time() + VALIDITY
                priceobj.failed = None

                # delete price from working dict
                del priceMap[typeID]

        # If getting or processing data returned any errors
        except TimeoutError:
            # Timeout error deserves special treatment
            pyfalog.warning("Price fetch timout")
            for typeID in priceMap.keys():
                priceobj = priceMap[typeID]
                priceobj.time = time.time() + TIMEOUT
                priceobj.failed = True
                del priceMap[typeID]
        except:
            # all other errors will pass and continue onward to the REREQUEST delay
            pyfalog.warning("Caught exception in fetchPrices")
            pass

        # if we get to this point, then we've got an error. Set to REREQUEST delay
        for typeID in priceMap.keys():
            priceobj = priceMap[typeID]
            priceobj.time = time.time() + REREQUEST
            priceobj.failed = True
示例#21
0
    def fetchPrices(cls, prices):
        """Fetch all prices passed to this method"""

        # Dictionary for our price objects
        priceMap = {}
        # Check all provided price objects, and add invalid ones to dictionary
        for price in prices:
            if not price.isValid:
                priceMap[price.typeID] = price

        if len(priceMap) == 0:
            return

        # Set of items which are still to be requested from this service
        toRequest = set()

        # Compose list of items we're going to request
        for typeID in priceMap:
            # Get item object
            item = db.getItem(typeID)
            # We're not going to request items only with market group, as eve-central
            # doesn't provide any data for items not on the market
            if item is not None and item.marketGroupID:
                toRequest.add(typeID)

        # Do not waste our time if all items are not on the market
        if len(toRequest) == 0:
            return

        # This will store POST data for eve-central
        data = []

        sFit = Fit.getInstance()
        # Base request URL
        baseurl = "https://eve-central.com/api/marketstat"
        data.append(("usesystem", cls.systemsList[sFit.serviceFittingOptions["priceSystem"]]))  # Use Jita for market

        for typeID in toRequest:  # Add all typeID arguments
            data.append(("typeid", typeID))

        # Attempt to send request and process it
        try:
            network = Network.getInstance()
            data = network.request(baseurl, network.PRICES, data)
            xml = minidom.parse(data)
            types = xml.getElementsByTagName("marketstat").item(0).getElementsByTagName("type")
            # Cycle through all types we've got from request
            for type_ in types:
                # Get data out of each typeID details tree
                typeID = int(type_.getAttribute("id"))
                sell = type_.getElementsByTagName("sell").item(0)
                # If price data wasn't there, set price to zero
                try:
                    percprice = float(sell.getElementsByTagName("percentile").item(0).firstChild.data)
                except (TypeError, ValueError):
                    pyfalog.warning("Failed to get price for: {0}", type_)
                    percprice = 0

                # Fill price data
                priceobj = priceMap[typeID]
                priceobj.price = percprice
                priceobj.time = time.time() + VALIDITY
                priceobj.failed = None

                # delete price from working dict
                del priceMap[typeID]

        # If getting or processing data returned any errors
        except TimeoutError:
            # Timeout error deserves special treatment
            pyfalog.warning("Price fetch timout")
            for typeID in priceMap.keys():
                priceobj = priceMap[typeID]
                priceobj.time = time.time() + TIMEOUT
                priceobj.failed = True

                del priceMap[typeID]
        except:
            # all other errors will pass and continue onward to the REREQUEST delay
            pyfalog.warning("Caught exception in fetchPrices")
            pass

        # if we get to this point, then we've got an error. Set to REREQUEST delay
        for typeID in priceMap.keys():
            priceobj = priceMap[typeID]
            priceobj.time = time.time() + REREQUEST
            priceobj.failed = True
示例#22
0
 def __init__(self, callback):
     threading.Thread.__init__(self)
     self.name = "CheckUpdate"
     self.callback = callback
     self.settings = UpdateSettings.getInstance()
     self.network = Network.getInstance()
示例#23
0
    def populatePanel(self, panel):

        self.mainFrame = gui.mainFrame.MainFrame.getInstance()
        self.settings = NetworkSettings.getInstance()
        self.network = Network.getInstance()
        self.dirtySettings = False

        mainSizer = wx.BoxSizer(wx.VERTICAL)

        self.stTitle = wx.StaticText(panel, wx.ID_ANY, self.title, wx.DefaultPosition, wx.DefaultSize, 0)
        self.stTitle.Wrap(-1)
        self.stTitle.SetFont(wx.Font(12, 70, 90, 90, False, wx.EmptyString))

        mainSizer.Add(self.stTitle, 0, wx.ALL, 5)

        self.m_staticline1 = wx.StaticLine(panel, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.LI_HORIZONTAL)
        mainSizer.Add(self.m_staticline1, 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 5)

        self.cbEnableNetwork = wx.CheckBox(panel, wx.ID_ANY, "Enable Network", wx.DefaultPosition, wx.DefaultSize, 0)
        mainSizer.Add(self.cbEnableNetwork, 0, wx.ALL | wx.EXPAND, 5)

        subSizer = wx.BoxSizer(wx.VERTICAL)
        self.cbEve = wx.CheckBox(panel, wx.ID_ANY, "EVE Servers (API && CREST import)", wx.DefaultPosition,
                                 wx.DefaultSize, 0)
        subSizer.Add(self.cbEve, 0, wx.ALL | wx.EXPAND, 5)

        self.cbPricing = wx.CheckBox(panel, wx.ID_ANY, "Pricing updates", wx.DefaultPosition, wx.DefaultSize, 0)
        subSizer.Add(self.cbPricing, 0, wx.ALL | wx.EXPAND, 5)

        self.cbPyfaUpdate = wx.CheckBox(panel, wx.ID_ANY, "Pyfa Update checks", wx.DefaultPosition, wx.DefaultSize, 0)
        subSizer.Add(self.cbPyfaUpdate, 0, wx.ALL | wx.EXPAND, 5)

        mainSizer.Add(subSizer, 0, wx.LEFT | wx.EXPAND, 30)

        proxyTitle = wx.StaticText(panel, wx.ID_ANY, "Proxy settings", wx.DefaultPosition, wx.DefaultSize, 0)
        proxyTitle.Wrap(-1)
        proxyTitle.SetFont(wx.Font(12, 70, 90, 90, False, wx.EmptyString))

        mainSizer.Add(proxyTitle, 0, wx.ALL, 5)
        mainSizer.Add(wx.StaticLine(panel, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.LI_HORIZONTAL), 0,
                      wx.EXPAND, 5)

        self.cbEnableNetwork.SetValue(self.settings.isEnabled(self.network.ENABLED))
        self.cbEve.SetValue(self.settings.isEnabled(self.network.EVE))
        self.cbPricing.SetValue(self.settings.isEnabled(self.network.PRICES))
        self.cbPyfaUpdate.SetValue(self.settings.isEnabled(self.network.UPDATE))

        self.cbEnableNetwork.Bind(wx.EVT_CHECKBOX, self.OnCBEnableChange)
        self.cbEve.Bind(wx.EVT_CHECKBOX, self.OnCBEveChange)
        self.cbPricing.Bind(wx.EVT_CHECKBOX, self.OnCBPricingChange)
        self.cbPyfaUpdate.Bind(wx.EVT_CHECKBOX, self.OnCBUpdateChange)

        self.toggleNetworks(self.cbEnableNetwork.GetValue())

        # ---------------
        # Proxy
        # ---------------

        self.nMode = self.settings.getMode()
        self.nAddr = self.settings.getAddress()
        self.nPort = self.settings.getPort()
        self.nType = self.settings.getType()
        self.nAuth = self.settings.getProxyAuthDetails()  # tuple of (login, password)
        if self.nAuth is None:
            self.nAuth = ("", "")  # we don't want None here, it should be a tuple

        ptypeSizer = wx.BoxSizer(wx.HORIZONTAL)

        self.stPType = wx.StaticText(panel, wx.ID_ANY, "Mode:", wx.DefaultPosition, wx.DefaultSize, 0)
        self.stPType.Wrap(-1)
        ptypeSizer.Add(self.stPType, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.chProxyTypeChoices = ["No proxy", "Auto-detected proxy settings", "Manual proxy settings"]
        self.chProxyType = wx.Choice(panel, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, self.chProxyTypeChoices, 0)

        self.chProxyType.SetSelection(self.nMode)

        ptypeSizer.Add(self.chProxyType, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        mainSizer.Add(ptypeSizer, 0, wx.EXPAND, 5)

        fgAddrSizer = wx.FlexGridSizer(2, 2, 0, 0)
        fgAddrSizer.AddGrowableCol(1)
        fgAddrSizer.SetFlexibleDirection(wx.BOTH)
        fgAddrSizer.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)

        self.stPSetAddr = wx.StaticText(panel, wx.ID_ANY, "Addr:", wx.DefaultPosition, wx.DefaultSize, 0)
        self.stPSetAddr.Wrap(-1)
        fgAddrSizer.Add(self.stPSetAddr, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.editProxySettingsAddr = wx.TextCtrl(panel, wx.ID_ANY, self.nAddr, wx.DefaultPosition, wx.DefaultSize, 0)

        fgAddrSizer.Add(self.editProxySettingsAddr, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5)

        self.stPSetPort = wx.StaticText(panel, wx.ID_ANY, "Port:", wx.DefaultPosition, wx.DefaultSize, 0)
        self.stPSetPort.Wrap(-1)

        fgAddrSizer.Add(self.stPSetPort, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.editProxySettingsPort = wx.TextCtrl(panel, wx.ID_ANY, self.nPort, wx.DefaultPosition, wx.DefaultSize, 0)

        fgAddrSizer.Add(self.editProxySettingsPort, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5)

        mainSizer.Add(fgAddrSizer, 0, wx.EXPAND, 5)

        # proxy auth information: login and pass
        self.stPSetLogin = wx.StaticText(panel, wx.ID_ANY, "Username:"******"Password:"******"Auto-detected: ", wx.DefaultPosition, wx.DefaultSize,
                                               0)
        self.stPSAutoDetected.Wrap(-1)
        mainSizer.Add(self.stPSAutoDetected, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
        btnSizer.AddStretchSpacer()

        self.btnApply = wx.Button(panel, wx.ID_ANY, "Apply Proxy Settings", wx.DefaultPosition, wx.DefaultSize, 0)

        btnSizer.Add(self.btnApply, 0, wx.ALL, 5)

        mainSizer.Add(btnSizer, 0, wx.EXPAND, 5)

        proxy = self.settings.autodetect()

        if proxy is not None:
            addr, port = proxy
            txt = addr + ":" + str(port)
        else:
            txt = "None"

        self.stPSAutoDetected.SetLabel("Auto-detected: " + txt)
        self.stPSAutoDetected.Disable()

        self.chProxyType.Bind(wx.EVT_CHOICE, self.OnCHProxyTypeSelect)
        self.editProxySettingsAddr.Bind(wx.EVT_TEXT, self.OnEditPSAddrText)
        self.editProxySettingsPort.Bind(wx.EVT_TEXT, self.OnEditPSPortText)
        self.editProxySettingsLogin.Bind(wx.EVT_TEXT, self.OnEditPSLoginText)
        self.editProxySettingsPassword.Bind(wx.EVT_TEXT, self.OnEditPSPasswordText)

        self.btnApply.Bind(wx.EVT_BUTTON, self.OnBtnApply)

        self.UpdateApplyButtonState()

        if self.nMode is not NetworkSettings.PROXY_MODE_MANUAL:  # == 2
            self.ToggleProxySettings(False)
        else:
            self.ToggleProxySettings(True)

        panel.SetSizer(mainSizer)
        panel.Layout()
示例#24
0
    def populatePanel(self, panel):

        self.mainFrame = gui.mainFrame.MainFrame.getInstance()
        self.settings = NetworkSettings.getInstance()
        self.network = Network.getInstance()
        self.dirtySettings = False

        mainSizer = wx.BoxSizer(wx.VERTICAL)

        self.stTitle = wx.StaticText(panel, wx.ID_ANY, self.title,
                                     wx.DefaultPosition, wx.DefaultSize, 0)
        self.stTitle.Wrap(-1)
        self.stTitle.SetFont(wx.Font(12, 70, 90, 90, False, wx.EmptyString))
        mainSizer.Add(self.stTitle, 0, wx.EXPAND | wx.ALL, 5)

        self.m_staticline1 = wx.StaticLine(panel, wx.ID_ANY,
                                           wx.DefaultPosition, wx.DefaultSize,
                                           wx.LI_HORIZONTAL)
        mainSizer.Add(self.m_staticline1, 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 5)

        self.cbEnableNetwork = wx.CheckBox(panel, wx.ID_ANY, "Enable Network",
                                           wx.DefaultPosition, wx.DefaultSize,
                                           0)
        mainSizer.Add(self.cbEnableNetwork, 0, wx.ALL | wx.EXPAND, 5)

        subSizer = wx.BoxSizer(wx.VERTICAL)
        self.cbEve = wx.CheckBox(panel, wx.ID_ANY,
                                 "EVE Servers (API && CREST import)",
                                 wx.DefaultPosition, wx.DefaultSize, 0)
        subSizer.Add(self.cbEve, 0, wx.ALL | wx.EXPAND, 5)

        self.cbPricing = wx.CheckBox(panel, wx.ID_ANY, "Pricing updates",
                                     wx.DefaultPosition, wx.DefaultSize, 0)
        subSizer.Add(self.cbPricing, 0, wx.ALL | wx.EXPAND, 5)

        self.cbPyfaUpdate = wx.CheckBox(panel, wx.ID_ANY, "Pyfa Update checks",
                                        wx.DefaultPosition, wx.DefaultSize, 0)
        subSizer.Add(self.cbPyfaUpdate, 0, wx.ALL | wx.EXPAND, 5)

        mainSizer.Add(subSizer, 0, wx.LEFT | wx.EXPAND, 30)

        proxyTitle = wx.StaticText(panel, wx.ID_ANY, "Proxy settings",
                                   wx.DefaultPosition, wx.DefaultSize, 0)
        proxyTitle.Wrap(-1)
        proxyTitle.SetFont(wx.Font(12, 70, 90, 90, False, wx.EmptyString))

        mainSizer.Add(proxyTitle, 0, wx.ALL, 5)
        mainSizer.Add(
            wx.StaticLine(panel, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize,
                          wx.LI_HORIZONTAL), 0, wx.EXPAND, 5)

        self.cbEnableNetwork.SetValue(
            self.settings.isEnabled(self.network.ENABLED))
        self.cbEve.SetValue(self.settings.isEnabled(self.network.EVE))
        self.cbPricing.SetValue(self.settings.isEnabled(self.network.PRICES))
        self.cbPyfaUpdate.SetValue(self.settings.isEnabled(
            self.network.UPDATE))

        self.cbEnableNetwork.Bind(wx.EVT_CHECKBOX, self.OnCBEnableChange)
        self.cbEve.Bind(wx.EVT_CHECKBOX, self.OnCBEveChange)
        self.cbPricing.Bind(wx.EVT_CHECKBOX, self.OnCBPricingChange)
        self.cbPyfaUpdate.Bind(wx.EVT_CHECKBOX, self.OnCBUpdateChange)

        self.toggleNetworks(self.cbEnableNetwork.GetValue())

        # ---------------
        # Proxy
        # ---------------

        self.nMode = self.settings.getMode()
        self.nAddr = self.settings.getAddress()
        self.nPort = self.settings.getPort()
        self.nType = self.settings.getType()
        self.nAuth = self.settings.getProxyAuthDetails(
        )  # tuple of (login, password)
        if self.nAuth is None:
            self.nAuth = ("", ""
                          )  # we don't want None here, it should be a tuple

        ptypeSizer = wx.BoxSizer(wx.HORIZONTAL)

        self.stPType = wx.StaticText(panel, wx.ID_ANY, "Mode:",
                                     wx.DefaultPosition, wx.DefaultSize, 0)
        self.stPType.Wrap(-1)
        ptypeSizer.Add(self.stPType, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.chProxyTypeChoices = [
            "No proxy", "Auto-detected proxy settings", "Manual proxy settings"
        ]
        self.chProxyType = wx.Choice(panel, wx.ID_ANY, wx.DefaultPosition,
                                     wx.DefaultSize, self.chProxyTypeChoices,
                                     0)

        self.chProxyType.SetSelection(self.nMode)

        ptypeSizer.Add(self.chProxyType, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL,
                       5)

        mainSizer.Add(ptypeSizer, 0, wx.EXPAND, 5)

        fgAddrSizer = wx.FlexGridSizer(2, 2, 0, 0)
        fgAddrSizer.AddGrowableCol(1)
        fgAddrSizer.SetFlexibleDirection(wx.BOTH)
        fgAddrSizer.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)

        self.stPSetAddr = wx.StaticText(panel, wx.ID_ANY, "Addr:",
                                        wx.DefaultPosition, wx.DefaultSize, 0)
        self.stPSetAddr.Wrap(-1)
        fgAddrSizer.Add(self.stPSetAddr, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL,
                        5)

        self.editProxySettingsAddr = wx.TextCtrl(panel, wx.ID_ANY, self.nAddr,
                                                 wx.DefaultPosition,
                                                 wx.DefaultSize, 0)

        fgAddrSizer.Add(self.editProxySettingsAddr, 0,
                        wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5)

        self.stPSetPort = wx.StaticText(panel, wx.ID_ANY, "Port:",
                                        wx.DefaultPosition, wx.DefaultSize, 0)
        self.stPSetPort.Wrap(-1)

        fgAddrSizer.Add(self.stPSetPort, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL,
                        5)

        self.editProxySettingsPort = wx.TextCtrl(panel, wx.ID_ANY, self.nPort,
                                                 wx.DefaultPosition,
                                                 wx.DefaultSize, 0)

        fgAddrSizer.Add(self.editProxySettingsPort, 0,
                        wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5)

        mainSizer.Add(fgAddrSizer, 0, wx.EXPAND, 5)

        # proxy auth information: login and pass
        self.stPSetLogin = wx.StaticText(panel, wx.ID_ANY, "Username:"******"Password:"******"Auto-detected: ",
                                              wx.DefaultPosition,
                                              wx.DefaultSize, 0)
        self.stPSAutoDetected.Wrap(-1)
        mainSizer.Add(self.stPSAutoDetected, 0,
                      wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
        btnSizer.AddStretchSpacer()

        self.btnApply = wx.Button(panel, wx.ID_ANY, "Apply Proxy Settings",
                                  wx.DefaultPosition, wx.DefaultSize, 0)

        btnSizer.Add(self.btnApply, 0, wx.ALL, 5)

        mainSizer.Add(btnSizer, 0, wx.EXPAND, 5)

        proxy = self.settings.autodetect()

        if proxy is not None:
            addr, port = proxy
            txt = addr + ":" + str(port)
        else:
            txt = "None"

        self.stPSAutoDetected.SetLabel("Auto-detected: " + txt)
        self.stPSAutoDetected.Disable()

        self.chProxyType.Bind(wx.EVT_CHOICE, self.OnCHProxyTypeSelect)
        self.editProxySettingsAddr.Bind(wx.EVT_TEXT, self.OnEditPSAddrText)
        self.editProxySettingsPort.Bind(wx.EVT_TEXT, self.OnEditPSPortText)
        self.editProxySettingsLogin.Bind(wx.EVT_TEXT, self.OnEditPSLoginText)
        self.editProxySettingsPassword.Bind(wx.EVT_TEXT,
                                            self.OnEditPSPasswordText)

        self.btnApply.Bind(wx.EVT_BUTTON, self.OnBtnApply)

        self.UpdateApplyButtonState()

        if self.nMode is not NetworkSettings.PROXY_MODE_MANUAL:  # == 2
            self.ToggleProxySettings(False)
        else:
            self.ToggleProxySettings(True)

        panel.SetSizer(mainSizer)
        panel.Layout()