def getandsend(self, event=None, retrying=False):

        play_sound = event and event.type == '35' and not config.getint(
            'hotkey_mute')

        if not retrying:
            if time(
            ) < self.holdofftime:  # Was invoked by key while in cooldown
                self.status['text'] = ''
                if play_sound and (self.holdofftime -
                                   time()) < companion.holdoff * 0.75:
                    hotkeymgr.play_bad(
                    )  # Don't play sound in first few seconds to prevent repeats
                return
            elif play_sound:
                hotkeymgr.play_good()
            self.cmdr['text'] = self.system['text'] = self.station['text'] = ''
            self.system['image'] = ''
            self.status['text'] = _('Fetching data...')
            self.button['state'] = tk.DISABLED
            self.edit_menu.entryconfigure(_('Copy'), state=tk.DISABLED)
            self.w.update_idletasks()

        try:
            querytime = int(time())
            data = self.session.query()
            config.set('querytime', querytime)

            # Validation
            if not data.get('commander') or not data['commander'].get(
                    'name', '').strip():
                self.status['text'] = _("Who are you?!")  # Shouldn't happen
            elif not data.get('lastSystem') or not data['lastSystem'].get(
                    'name', '').strip() or not data.get(
                        'lastStarport') or not data['lastStarport'].get(
                            'name', '').strip():
                self.status['text'] = _("Where are you?!")  # Shouldn't happen
            elif not data.get('ship') or not data['ship'].get(
                    'modules') or not data['ship'].get('name', '').strip():
                self.status['text'] = _(
                    "What are you flying?!")  # Shouldn't happen

            else:
                if __debug__:  # Recording
                    with open(
                            '%s%s.%s.json' %
                        (data['lastSystem']['name'],
                         data['commander'].get('docked')
                         and '.' + data['lastStarport']['name'] or '',
                         strftime('%Y-%m-%dT%H.%M.%S', localtime())),
                            'wt') as h:
                        h.write(
                            json.dumps(data,
                                       ensure_ascii=False,
                                       indent=2,
                                       sort_keys=True).encode('utf-8'))

                self.cmdr['text'] = data.get('commander') and data.get(
                    'commander').get('name') or ''
                self.system['text'] = data.get('lastSystem') and data.get(
                    'lastSystem').get('name') or ''
                self.station['text'] = data.get('commander') and data.get(
                    'commander').get('docked') and data.get(
                        'lastStarport') and data.get('lastStarport').get(
                            'name') or (EDDB.system(self.system['text'])
                                        and self.STATION_UNDOCKED or '')
                self.status['text'] = ''
                self.edit_menu.entryconfigure(_('Copy'), state=tk.NORMAL)
                self.view_menu.entryconfigure(_('Status'), state=tk.NORMAL)

                # stuff we can do when not docked
                if config.getint('output') & config.OUT_SHIP_EDS:
                    loadout.export(data)
                if config.getint('output') & config.OUT_SHIP_CORIOLIS:
                    coriolis.export(data)
                if config.getint('output') & config.OUT_LOG_FILE:
                    flightlog.export(data)
                if config.getint('output') & config.OUT_LOG_EDSM:
                    # Catch any EDSM errors here so that they don't prevent station update
                    try:
                        self.status['text'] = _('Sending data to EDSM...')
                        self.w.update_idletasks()
                        edsm.export(data, lambda: self.edsm.lookup(
                            self.system['text'],
                            EDDB.system(self.system['text']))
                                    )  # Do EDSM lookup during EDSM export
                        self.status['text'] = ''
                    except Exception as e:
                        if __debug__: print_exc()
                        self.status['text'] = unicode(e)
                else:
                    self.edsm.link(self.system['text'])
                self.edsmpoll()

                if not (config.getint('output') &
                        (config.OUT_CSV | config.OUT_TD | config.OUT_BPC
                         | config.OUT_EDDN)):
                    # no station data requested - we're done
                    pass

                elif not data['commander'].get('docked'):
                    # signal as error because the user might actually be docked but the server hosting the Companion API hasn't caught up
                    if not self.status['text']:
                        self.status['text'] = _(
                            "You're not docked at a station!")

                else:
                    # Finally - the data looks sane and we're docked at a station
                    (station_id, has_market, has_outfitting,
                     has_shipyard) = EDDB.station(self.system['text'],
                                                  self.station['text'])

                    # No EDDN output at known station?
                    if (config.getint('output')
                            & config.OUT_EDDN) and station_id and not (
                                has_market or has_outfitting or has_shipyard):
                        if not self.status['text']:
                            self.status['text'] = _(
                                "Station doesn't have anything!")

                    # No EDDN output at unknown station?
                    elif (
                            config.getint('output') & config.OUT_EDDN
                    ) and not station_id and not (
                            data['lastStarport'].get('commodities')
                            or data['lastStarport'].get('modules')
                    ):  # Ignore usually spurious shipyard at unknown stations
                        if not self.status['text']:
                            self.status['text'] = _(
                                "Station doesn't have anything!")

                    # No market output at known station?
                    elif not (config.getint('output') & config.OUT_EDDN
                              ) and station_id and not has_market:
                        if not self.status['text']:
                            self.status['text'] = _(
                                "Station doesn't have a market!")

                    # No market output at unknown station?
                    elif not (config.getint('output') &
                              config.OUT_EDDN) and not station_id and not data[
                                  'lastStarport'].get('commodities'):
                        if not self.status['text']:
                            self.status['text'] = _(
                                "Station doesn't have a market!")

                    else:
                        if data['lastStarport'].get('commodities'):
                            # Fixup anomalies in the commodity data
                            self.session.fixup(
                                data['lastStarport']['commodities'])

                            if config.getint('output') & config.OUT_CSV:
                                bpc.export(data, True)
                            if config.getint('output') & config.OUT_TD:
                                td.export(data)
                            if config.getint('output') & config.OUT_BPC:
                                bpc.export(data, False)

                        elif has_market and (
                                config.getint('output') &
                            (config.OUT_CSV | config.OUT_TD | config.OUT_BPC
                             | config.OUT_EDDN)):
                            # Overwrite any previous error message
                            self.status['text'] = _(
                                "Error: Can't get market data!")

                        if config.getint('output') & config.OUT_EDDN:
                            old_status = self.status['text']
                            if not old_status:
                                self.status['text'] = _(
                                    'Sending data to EDDN...')
                            self.w.update_idletasks()
                            eddn.export_commodities(data)
                            if has_outfitting or not station_id:
                                # Only send if eddb says that the station provides outfitting, or unknown station
                                eddn.export_outfitting(data)
                            elif __debug__ and data['lastStarport'].get(
                                    'modules'):
                                print 'Spurious outfitting!'
                            if has_shipyard:
                                # Only send if eddb says that the station has a shipyard -
                                # https://github.com/Marginal/EDMarketConnector/issues/16
                                if data['lastStarport'].get('ships'):
                                    eddn.export_shipyard(data)
                                else:
                                    # API is flakey about shipyard info - silently retry if missing (<1s is usually sufficient - 5s for margin).
                                    self.w.after(int(SERVER_RETRY * 1000),
                                                 self.retry_for_shipyard)
                            elif __debug__ and data['lastStarport'].get(
                                    'ships'):
                                print 'Spurious shipyard!'
                            if not old_status:
                                self.status['text'] = ''

        except companion.VerificationRequired:
            return prefs.AuthenticationDialog(self.w, self.verify)

        # Companion API problem
        except companion.ServerError as e:
            if retrying:
                self.status['text'] = unicode(e)
            else:
                # Retry once if Companion server is unresponsive
                self.w.after(int(SERVER_RETRY * 1000),
                             lambda: self.getandsend(event, True))
                return  # early exit to avoid starting cooldown count

        except requests.exceptions.ConnectionError as e:
            if __debug__: print_exc()
            self.status['text'] = _("Error: Can't connect to EDDN")

        except requests.exceptions.Timeout as e:
            if __debug__: print_exc()
            self.status['text'] = _("Error: Connection to EDDN timed out")

        except Exception as e:
            if __debug__: print_exc()
            self.status['text'] = unicode(e)

        if not self.status['text']:  # no errors
            self.status['text'] = strftime(
                _('Last updated at {HH}:{MM}:{SS}').format(
                    HH='%H', MM='%M', SS='%S').encode('utf-8'),
                localtime(querytime)).decode('utf-8')
        elif play_sound:
            hotkeymgr.play_bad()

        self.holdofftime = querytime + companion.holdoff
        self.cooldown()
    def getandsend(self, event=None, retrying=False):

        play_sound = event and event.type=='35' and not config.getint('hotkey_mute')

        if not retrying:
            if time() < self.holdofftime:	# Was invoked by key while in cooldown
                self.status['text'] = ''
                if play_sound and (self.holdofftime-time()) < companion.holdoff*0.75:
                    hotkeymgr.play_bad()	# Don't play sound in first few seconds to prevent repeats
                return
            elif play_sound:
                hotkeymgr.play_good()
            self.cmdr['text'] = self.system['text'] = self.station['text'] = ''
            self.system['image'] = ''
            self.status['text'] = _('Fetching data...')
            self.button['state'] = tk.DISABLED
            self.edit_menu.entryconfigure(_('Copy'), state=tk.DISABLED)
            self.w.update_idletasks()

        try:
            querytime = int(time())
            data = self.session.query()
            config.set('querytime', querytime)

            # Validation
            if not data.get('commander') or not data['commander'].get('name','').strip():
                self.status['text'] = _("Who are you?!")		# Shouldn't happen
            elif not data.get('lastSystem') or not data['lastSystem'].get('name','').strip() or not data.get('lastStarport') or not data['lastStarport'].get('name','').strip():
                self.status['text'] = _("Where are you?!")		# Shouldn't happen
            elif not data.get('ship') or not data['ship'].get('modules') or not data['ship'].get('name','').strip():
                self.status['text'] = _("What are you flying?!")	# Shouldn't happen

            else:
                if __debug__:	# Recording
                    with open('%s%s.%s.json' % (data['lastSystem']['name'], data['commander'].get('docked') and '.'+data['lastStarport']['name'] or '', strftime('%Y-%m-%dT%H.%M.%S', localtime())), 'wt') as h:
                        h.write(json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True).encode('utf-8'))

                self.cmdr['text'] = data.get('commander') and data.get('commander').get('name') or ''
                self.system['text'] = data.get('lastSystem') and data.get('lastSystem').get('name') or ''
                self.station['text'] = data.get('commander') and data.get('commander').get('docked') and data.get('lastStarport') and data.get('lastStarport').get('name') or (EDDB.system(self.system['text']) and self.STATION_UNDOCKED or '')
                self.status['text'] = ''
                self.edit_menu.entryconfigure(_('Copy'), state=tk.NORMAL)
                self.view_menu.entryconfigure(_('Status'), state=tk.NORMAL)

                # stuff we can do when not docked
                if config.getint('output') & config.OUT_SHIP_EDS:
                    loadout.export(data)
                if config.getint('output') & config.OUT_SHIP_CORIOLIS:
                    coriolis.export(data)
                if config.getint('output') & config.OUT_LOG_FILE:
                    flightlog.export(data)
                if config.getint('output') & config.OUT_LOG_EDSM:
                    # Catch any EDSM errors here so that they don't prevent station update
                    try:
                        self.status['text'] = _('Sending data to EDSM...')
                        self.w.update_idletasks()
                        edsm.export(data, lambda:self.edsm.lookup(self.system['text'], EDDB.system(self.system['text'])))	# Do EDSM lookup during EDSM export
                        self.status['text'] = ''
                    except Exception as e:
                        if __debug__: print_exc()
                        self.status['text'] = unicode(e)
                else:
                    self.edsm.link(self.system['text'])
                self.edsmpoll()

                if not (config.getint('output') & (config.OUT_CSV|config.OUT_TD|config.OUT_BPC|config.OUT_EDDN)):
                    # no station data requested - we're done
                    pass

                elif not data['commander'].get('docked'):
                    # signal as error because the user might actually be docked but the server hosting the Companion API hasn't caught up
                    if not self.status['text']:
                        self.status['text'] = _("You're not docked at a station!")

                else:
                    # Finally - the data looks sane and we're docked at a station
                    (station_id, has_market, has_outfitting, has_shipyard) = EDDB.station(self.system['text'], self.station['text'])


                    # No EDDN output at known station?
                    if (config.getint('output') & config.OUT_EDDN) and station_id and not (has_market or has_outfitting or has_shipyard):
                        if not self.status['text']:
                            self.status['text'] = _("Station doesn't have anything!")

                    # No EDDN output at unknown station?
                    elif (config.getint('output') & config.OUT_EDDN) and not station_id and not (data['lastStarport'].get('commodities') or data['lastStarport'].get('modules')):	# Ignore usually spurious shipyard at unknown stations
                        if not self.status['text']:
                            self.status['text'] = _("Station doesn't have anything!")

                    # No market output at known station?
                    elif not (config.getint('output') & config.OUT_EDDN) and station_id and not has_market:
                        if not self.status['text']:
                            self.status['text'] = _("Station doesn't have a market!")

                    # No market output at unknown station?
                    elif not (config.getint('output') & config.OUT_EDDN) and not station_id and not data['lastStarport'].get('commodities'):
                        if not self.status['text']:
                            self.status['text'] = _("Station doesn't have a market!")

                    else:
                        if data['lastStarport'].get('commodities'):
                            # Fixup anomalies in the commodity data
                            self.session.fixup(data['lastStarport']['commodities'])

                            if config.getint('output') & config.OUT_CSV:
                                bpc.export(data, True)
                            if config.getint('output') & config.OUT_TD:
                                td.export(data)
                            if config.getint('output') & config.OUT_BPC:
                                bpc.export(data, False)

                        elif has_market and (config.getint('output') & (config.OUT_CSV|config.OUT_TD|config.OUT_BPC|config.OUT_EDDN)):
                            # Overwrite any previous error message
                            self.status['text'] = _("Error: Can't get market data!")

                        if config.getint('output') & config.OUT_EDDN:
                            old_status = self.status['text']
                            if not old_status:
                                self.status['text'] = _('Sending data to EDDN...')
                            self.w.update_idletasks()
                            eddn.export_commodities(data)
                            if has_outfitting or not station_id:
                                # Only send if eddb says that the station provides outfitting, or unknown station
                                eddn.export_outfitting(data)
                            elif __debug__ and data['lastStarport'].get('modules'):
                                print 'Spurious outfitting!'
                            if has_shipyard:
                                # Only send if eddb says that the station has a shipyard -
                                # https://github.com/Marginal/EDMarketConnector/issues/16
                                if data['lastStarport'].get('ships'):
                                    eddn.export_shipyard(data)
                                else:
                                    # API is flakey about shipyard info - silently retry if missing (<1s is usually sufficient - 5s for margin).
                                    self.w.after(int(SERVER_RETRY * 1000), self.retry_for_shipyard)
                            elif __debug__ and data['lastStarport'].get('ships'):
                                print 'Spurious shipyard!'
                            if not old_status:
                                self.status['text'] = ''

        except companion.VerificationRequired:
            return prefs.AuthenticationDialog(self.w, self.verify)

        # Companion API problem
        except companion.ServerError as e:
            if retrying:
                self.status['text'] = unicode(e)
            else:
                # Retry once if Companion server is unresponsive
                self.w.after(int(SERVER_RETRY * 1000), lambda:self.getandsend(event, True))
                return	# early exit to avoid starting cooldown count

        except requests.exceptions.ConnectionError as e:
            if __debug__: print_exc()
            self.status['text'] = _("Error: Can't connect to EDDN")

        except requests.exceptions.Timeout as e:
            if __debug__: print_exc()
            self.status['text'] = _("Error: Connection to EDDN timed out")

        except Exception as e:
            if __debug__: print_exc()
            self.status['text'] = unicode(e)

        if not self.status['text']:	# no errors
            self.status['text'] = strftime(_('Last updated at {HH}:{MM}:{SS}').format(HH='%H', MM='%M', SS='%S').encode('utf-8'), localtime(querytime)).decode('utf-8')
        elif play_sound:
            hotkeymgr.play_bad()

        self.holdofftime = querytime + companion.holdoff
        self.cooldown()
Ejemplo n.º 3
0
    def getandsend(self, event=None):
        if time() < self.holdofftime: return	# Was invoked by Return key while in cooldown

        self.cmdr['text'] = self.system['text'] = self.station['text'] = ''
        self.status['text'] = 'Fetching market data...'
        self.button['state'] = tk.DISABLED
        self.w.update_idletasks()

        try:
            querytime = int(time())

            data = self.session.query()

            self.cmdr['text'] = data.get('commander') and data.get('commander').get('name') or ''
            self.system['text'] = data.get('lastSystem') and data.get('lastSystem').get('name') or ''
            self.station['text'] = data.get('commander') and data.get('commander').get('docked') and data.get('lastStarport') and data.get('lastStarport').get('name') or '-'

            config.set('querytime', querytime)
            self.holdofftime = querytime + companion.holdoff

            # Validation
            if not data.get('commander') or not data['commander'].get('name','').strip():
                self.status['text'] = "Who are you?!"		# Shouldn't happen
            elif not data.get('lastSystem') or not data['lastSystem'].get('name','').strip() or not data.get('lastStarport') or not data['lastStarport'].get('name','').strip():
                self.status['text'] = "Where are you?!"		# Shouldn't happen
            elif not data.get('ship') or not data['ship'].get('modules') or not data['ship'].get('name','').strip():
                self.status['text'] = "What are you flying?!"	# Shouldn't happen
            else:
                # stuff we can do when not docked
                if config.getint('output') & config.OUT_LOG:
                    flightlog.export(data)
                if config.getint('output') & config.OUT_SHIP:
                    loadout.export(data)

                if not (config.getint('output') & (config.OUT_CSV|config.OUT_TD|config.OUT_BPC|config.OUT_EDDN)):
                    # no further output requested
                    self.status['text'] = strftime('Last updated at %H:%M:%S', localtime(querytime))

                elif not data['commander'].get('docked'):
                    self.status['text'] = "You're not docked at a station!"
                elif not data['lastStarport'].get('commodities'):
                    self.status['text'] = "Station doesn't have a market!"
                else:
                    if config.getint('output') & config.OUT_CSV:
                        bpc.export(data, True)
                    if config.getint('output') & config.OUT_TD:
                        td.export(data)
                    if config.getint('output') & config.OUT_BPC:
                        bpc.export(data, False)
                    if config.getint('output') & config.OUT_EDDN:
                        self.status['text'] = 'Sending data to EDDN...'
                        self.w.update_idletasks()
                        eddn.export(data)
                    self.status['text'] = strftime('Last updated at %H:%M:%S', localtime(querytime))

        except companion.VerificationRequired:
            return prefs.AuthenticationDialog(self.w, self.verify)

        except companion.ServerError as e:
            self.status['text'] = str(e)

        except Exception as e:
            if __debug__: print_exc()
            self.status['text'] = str(e)

        self.cooldown()
Ejemplo n.º 4
0
    def getandsend(self, event=None, retrying=False):

        if not retrying:
            if time() < self.holdofftime: return	# Was invoked by Return key while in cooldown
            self.cmdr['text'] = self.system['text'] = self.station['text'] = ''
            self.status['text'] = 'Fetching station data...'
            self.button['state'] = tk.DISABLED
            self.w.update_idletasks()

        try:
            querytime = int(time())

            data = self.session.query()

            self.cmdr['text'] = data.get('commander') and data.get('commander').get('name') or ''
            self.system['text'] = data.get('lastSystem') and data.get('lastSystem').get('name') or ''
            self.station['text'] = data.get('commander') and data.get('commander').get('docked') and data.get('lastStarport') and data.get('lastStarport').get('name') or '-'

            config.set('querytime', querytime)
            self.holdofftime = querytime + companion.holdoff

            # Validation
            if not data.get('commander') or not data['commander'].get('name','').strip():
                self.status['text'] = "Who are you?!"		# Shouldn't happen
            elif not data.get('lastSystem') or not data['lastSystem'].get('name','').strip() or not data.get('lastStarport') or not data['lastStarport'].get('name','').strip():
                self.status['text'] = "Where are you?!"		# Shouldn't happen
            elif not data.get('ship') or not data['ship'].get('modules') or not data['ship'].get('name','').strip():
                self.status['text'] = "What are you flying?!"	# Shouldn't happen
            elif (config.getint('output') & config.OUT_EDDN) and not data['lastStarport'].get('ships') and not retrying:
                # API is flakey about shipyard info - retry if missing (<1s is usually sufficient - 2.5s for margin).
                self.w.after(2500, lambda:self.getandsend(retrying=True))
                return
            else:
                if __debug__ and retrying: print data['lastStarport'].get('ships') and 'Retry for shipyard - Success' or 'Retry for shipyard - Fail'

                # stuff we can do when not docked
                if __debug__:	# Recording
                    with open('%s%s.%s.json' % (data['lastSystem']['name'], data['commander'].get('docked') and '.'+data['lastStarport']['name'] or '', strftime('%Y-%m-%dT%H.%M.%S', localtime())), 'wt') as h:
                        h.write(json.dumps(data, indent=2, sort_keys=True))
                if config.getint('output') & config.OUT_LOG:
                    flightlog.export(data)
                if config.getint('output') & config.OUT_SHIP:
                    loadout.export(data)

                if not (config.getint('output') & (config.OUT_CSV|config.OUT_TD|config.OUT_BPC|config.OUT_EDDN)):
                    # no further output requested
                    self.status['text'] = strftime('Last updated at %H:%M:%S', localtime(querytime))

                elif not data['commander'].get('docked'):
                    self.status['text'] = "You're not docked at a station!"
                else:
                    if data['lastStarport'].get('commodities'):
                        # Fixup anomalies in the commodity data
                        self.session.fixup(data['lastStarport']['commodities'])

                        if config.getint('output') & config.OUT_CSV:
                            bpc.export(data, True)
                        if config.getint('output') & config.OUT_TD:
                            td.export(data)
                        if config.getint('output') & config.OUT_BPC:
                            bpc.export(data, False)

                    if config.getint('output') & config.OUT_EDDN:
                        if data['lastStarport'].get('commodities') or data['lastStarport'].get('modules') or data['lastStarport'].get('ships'):
                            self.status['text'] = 'Sending data to EDDN...'
                            self.w.update_idletasks()
                            eddn.export(data)
                            self.status['text'] = strftime('Last updated at %H:%M:%S', localtime(querytime))
                        else:
                            self.status['text'] = "Station doesn't have anything!"
                    elif not data['lastStarport'].get('commodities'):
                        self.status['text'] = "Station doesn't have a market!"
                    else:
                        self.status['text'] = strftime('Last updated at %H:%M:%S', localtime(querytime))

        except companion.VerificationRequired:
            return prefs.AuthenticationDialog(self.w, self.verify)

        # Companion API problem
        except companion.ServerError as e:
            self.status['text'] = str(e)

        except requests.exceptions.ConnectionError as e:
            if __debug__: print_exc()
            self.status['text'] = "Error: Can't connect to EDDN"

        except requests.exceptions.Timeout as e:
            if __debug__: print_exc()
            self.status['text'] = "Error: Connection to EDDN timed out"

        except Exception as e:
            if __debug__: print_exc()
            self.status['text'] = str(e)

        self.cooldown()
Ejemplo n.º 5
0
    def send(self, event=None):
        data = self.data
        try:
            if True:  # validation now done in get part
                # stuff we can do when not docked
                if config.getint('output') & config.OUT_SHIP_EDS:
                    loadout.export(data)
                if config.getint('output') & config.OUT_SHIP_CORIOLIS:
                    coriolis.export(data)
                if config.getint('output') & config.OUT_LOG_FILE:
                    flightlog.export(data)
                if config.getint('output') & config.OUT_LOG_EDSM:
                    # Catch any EDSM errors here so that they don't prevent station update
                    try:
                        self.status['text'] = _('Sending data to EDSM...')
                        self.w.update_idletasks()
                        edsm.export(data, lambda: self.edsm.lookup(
                            self.system['text'],
                            EDDB.system(self.system['text']))
                                    )  # Do EDSM lookup during EDSM export
                        self.status['text'] = ''
                    except Exception as e:
                        if __debug__: print_exc()
                        self.status['text'] = unicode(e)
                else:
                    self.edsm.link(self.system['text'])
                self.edsmpoll()

                if not (config.getint('output') &
                        (config.OUT_CSV | config.OUT_TD | config.OUT_BPC
                         | config.OUT_EDDN)):
                    # no station data requested - we're done
                    pass

                elif not data['commander'].get('docked'):
                    # signal as error because the user might actually be docked but the server hosting the Companion API hasn't caught up
                    if not self.status['text']:
                        self.status['text'] = _(
                            "You're not docked at a station!")

                else:
                    # Finally - the data looks sane and we're docked at a station
                    (station_id, has_market, has_outfitting,
                     has_shipyard) = EDDB.station(self.system['text'],
                                                  self.station['text'])

                    # No EDDN output at known station?
                    if (
                            config.getint('output') & config.OUT_EDDN
                    ) and station_id and not has_market and not has_outfitting and not has_shipyard:
                        if not self.status['text']:
                            self.status['text'] = _(
                                "Station doesn't have anything!")

                    # No EDDN output at unknown station?
                    elif (
                            config.getint('output') & config.OUT_EDDN
                    ) and not station_id and not data['lastStarport'].get(
                            'commodities') and not data['lastStarport'].get(
                                'modules') and not data['lastStarport'].get(
                                    'ships'):
                        if not self.status['text']:
                            self.status['text'] = _(
                                "Station doesn't have anything!")

                    # No market output at known station?
                    elif not (config.getint('output') & config.OUT_EDDN
                              ) and station_id and not has_market:
                        if not self.status['text']:
                            self.status['text'] = _(
                                "Station doesn't have a market!")

                    # No market output at unknown station?
                    elif not (config.getint('output') &
                              config.OUT_EDDN) and not station_id and not data[
                                  'lastStarport'].get('commodities'):
                        if not self.status['text']:
                            self.status['text'] = _(
                                "Station doesn't have a market!")

                    else:
                        if data['lastStarport'].get('commodities'):
                            # Fixup anomalies in the commodity data
                            self.session.fixup(
                                data['lastStarport']['commodities'])

                            if config.getint('output') & config.OUT_CSV:
                                bpc.export(data, True)
                            if config.getint('output') & config.OUT_TD:
                                td.export(data)
                            if config.getint('output') & config.OUT_BPC:
                                bpc.export(data, False)

                        elif has_market and (
                                config.getint('output') &
                            (config.OUT_CSV | config.OUT_TD | config.OUT_BPC
                             | config.OUT_EDDN)):
                            # Overwrite any previous error message
                            self.status['text'] = _(
                                "Error: Can't get market data!")

                        if config.getint('output') & config.OUT_EDDN:
                            old_status = self.status['text']
                            if not old_status:
                                self.status['text'] = _(
                                    'Sending data to EDDN...')
                            self.w.update_idletasks()
                            eddn.export_commodities(data)
                            if has_outfitting or not station_id:
                                # Only send if eddb says that the station provides outfitting
                                eddn.export_outfitting(data)
                            elif __debug__ and data['lastStarport'].get(
                                    'modules'):
                                print 'Spurious outfitting!'
                            if has_shipyard or not station_id:
                                # Only send if eddb says that the station has a shipyard -
                                # https://github.com/Marginal/EDMarketConnector/issues/16
                                if data['lastStarport'].get('ships'):
                                    eddn.export_shipyard(data)
                                else:
                                    # API is flakey about shipyard info - silently retry if missing (<1s is usually sufficient - 5s for margin).
                                    self.w.after(int(SERVER_RETRY * 1000),
                                                 self.retry_for_shipyard)
                            elif __debug__ and data['lastStarport'].get(
                                    'ships'):
                                print 'Spurious shipyard!'
                            if not old_status:
                                self.status['text'] = ''

        except requests.exceptions.ConnectionError as e:
            if __debug__: print_exc()
            self.status['text'] = _("Error: Can't connect to EDDN")

        except requests.exceptions.Timeout as e:
            if __debug__: print_exc()
            self.status['text'] = _("Error: Connection to EDDN timed out")

        except Exception as e:
            if __debug__: print_exc()
            self.status['text'] = unicode(e)

        if not self.status['text']:  # no errors
            self.status['text'] = strftime(
                _('Last updated at {HH}:{MM}:{SS}').format(
                    HH='%H', MM='%M', SS='%S').encode('utf-8'),
                localtime(self.querytime)).decode('utf-8')
        elif play_sound:
            hotkeymgr.play_bad()

        self.holdofftime = self.querytime + companion.holdoff
        self.cooldown()
Ejemplo n.º 6
0
    def getandsend(self, event=None, retrying=False):

        if not retrying:
            if time() < self.holdofftime:
                return  # Was invoked by Return key while in cooldown
            self.cmdr['text'] = self.system['text'] = self.station['text'] = ''
            self.status['text'] = 'Fetching station data...'
            self.button['state'] = tk.DISABLED
            self.w.update_idletasks()

        try:
            querytime = int(time())

            data = self.session.query()

            self.cmdr['text'] = data.get('commander') and data.get(
                'commander').get('name') or ''
            self.system['text'] = data.get('lastSystem') and data.get(
                'lastSystem').get('name') or ''
            self.station['text'] = data.get('commander') and data.get(
                'commander').get('docked') and data.get(
                    'lastStarport') and data.get('lastStarport').get(
                        'name') or '-'

            config.set('querytime', querytime)
            self.holdofftime = querytime + companion.holdoff

            # Validation
            if not data.get('commander') or not data['commander'].get(
                    'name', '').strip():
                self.status['text'] = "Who are you?!"  # Shouldn't happen
            elif not data.get('lastSystem') or not data['lastSystem'].get(
                    'name', '').strip() or not data.get(
                        'lastStarport') or not data['lastStarport'].get(
                            'name', '').strip():
                self.status['text'] = "Where are you?!"  # Shouldn't happen
            elif not data.get('ship') or not data['ship'].get(
                    'modules') or not data['ship'].get('name', '').strip():
                self.status[
                    'text'] = "What are you flying?!"  # Shouldn't happen
            elif (config.getint('output') & config.OUT_EDDN
                  ) and not data['lastStarport'].get('ships') and not retrying:
                # API is flakey about shipyard info - retry if missing (<1s is usually sufficient - 2.5s for margin).
                self.w.after(2500, lambda: self.getandsend(retrying=True))
                return
            else:
                if __debug__ and retrying:
                    print data['lastStarport'].get(
                        'ships'
                    ) and 'Retry for shipyard - Success' or 'Retry for shipyard - Fail'

                # stuff we can do when not docked
                if __debug__:  # Recording
                    with open(
                            '%s%s.%s.json' %
                        (data['lastSystem']['name'],
                         data['commander'].get('docked')
                         and '.' + data['lastStarport']['name'] or '',
                         strftime('%Y-%m-%dT%H.%M.%S', localtime())),
                            'wt') as h:
                        h.write(json.dumps(data, indent=2, sort_keys=True))
                if config.getint('output') & config.OUT_LOG:
                    flightlog.export(data)
                if config.getint('output') & config.OUT_SHIP:
                    loadout.export(data)

                if not (config.getint('output') &
                        (config.OUT_CSV | config.OUT_TD | config.OUT_BPC
                         | config.OUT_EDDN)):
                    # no further output requested
                    self.status['text'] = strftime('Last updated at %H:%M:%S',
                                                   localtime(querytime))

                elif not data['commander'].get('docked'):
                    self.status['text'] = "You're not docked at a station!"
                else:
                    if data['lastStarport'].get('commodities'):
                        # Fixup anomalies in the commodity data
                        self.session.fixup(data['lastStarport']['commodities'])

                        if config.getint('output') & config.OUT_CSV:
                            bpc.export(data, True)
                        if config.getint('output') & config.OUT_TD:
                            td.export(data)
                        if config.getint('output') & config.OUT_BPC:
                            bpc.export(data, False)

                    if config.getint('output') & config.OUT_EDDN:
                        if data['lastStarport'].get(
                                'commodities') or data['lastStarport'].get(
                                    'modules') or data['lastStarport'].get(
                                        'ships'):
                            self.status['text'] = 'Sending data to EDDN...'
                            self.w.update_idletasks()
                            eddn.export(data)
                            self.status['text'] = strftime(
                                'Last updated at %H:%M:%S',
                                localtime(querytime))
                        else:
                            self.status[
                                'text'] = "Station doesn't have anything!"
                    elif not data['lastStarport'].get('commodities'):
                        self.status['text'] = "Station doesn't have a market!"
                    else:
                        self.status['text'] = strftime(
                            'Last updated at %H:%M:%S', localtime(querytime))

        except companion.VerificationRequired:
            return prefs.AuthenticationDialog(self.w, self.verify)

        # Companion API problem
        except companion.ServerError as e:
            self.status['text'] = str(e)

        except requests.exceptions.ConnectionError as e:
            if __debug__: print_exc()
            self.status['text'] = "Error: Can't connect to EDDN"

        except requests.exceptions.Timeout as e:
            if __debug__: print_exc()
            self.status['text'] = "Error: Connection to EDDN timed out"

        except Exception as e:
            if __debug__: print_exc()
            self.status['text'] = str(e)

        self.cooldown()