def update_fade_status(self, widget):        
     if widget.get_active():
         config.set("player", "crossfade", "true")
         self.fade_spin.set_sensitive(True)
     else:    
         config.set("player", "crossfade", "false")
         self.fade_spin.set_sensitive(False)
Esempio n. 2
0
def credentials(cmdr: str) -> Optional[Tuple[str, str]]:
    """
    Get credentials for the given commander, if they exist.

    :param cmdr: The commander to get credentials for
    :return: The credentials, or None
    """
    # Credentials for cmdr
    if not cmdr:
        return None

    cmdrs = config.get('edsm_cmdrs')
    if not cmdrs:
        # Migrate from <= 2.25
        cmdrs = [cmdr]
        config.set('edsm_cmdrs', cmdrs)

    if cmdr in cmdrs and config.get('edsm_usernames') and config.get(
            'edsm_apikeys'):
        idx = cmdrs.index(cmdr)
        return (config.get('edsm_usernames')[idx],
                config.get('edsm_apikeys')[idx])

    else:
        return None
 def on_tab_box_switch_tab(self, widget, item):    
     try:
         config.set("listmanager", "source", item.title)
         config.write()
     except: pass    
     
     Dispatcher.emit("switch-browser", item, True)
Esempio n. 4
0
 def save(self):
     """
     Save the saved distance to config
     :return:
     """
     config.set(CFG_DISTANCE,
                str(self.saved_distance + self.trip_distance()))
Esempio n. 5
0
 def __on_playing(self, bin, uri):
     """ Signal emitted by fadebin when a new stream previously queue start """
     if uri == self.song.get("uri"):
         self.loginfo("signal playing-stream receive by %s", uri)
         config.set("player", "play", "true")
         self.emit("played")
         self.__emit_signal_new_song()
Esempio n. 6
0
def prefs_changed(cmdr, is_beta):
	"""
	Save settings.
	"""
	config.set('disable_presence', this.disablePresence.get())
	config.set('show_ship_name', this.showShipName.get())
	update_presence()
Esempio n. 7
0
    def send(self, cmdr, msg):
        if config.getint('anonymous'):
            uploaderID = config.get('uploaderID')
            if not uploaderID:
                uploaderID = uuid.uuid4().hex
                config.set('uploaderID', uploaderID)
        else:
            uploaderID = cmdr.encode('utf-8')

        msg = OrderedDict([
            ('$schemaRef', msg['$schemaRef']),
            ('header',     OrderedDict([
                ('softwareName',    '%s [%s]' % (applongname, sys.platform=='darwin' and "Mac OS" or system())),
                ('softwareVersion', appversion),
                ('uploaderID',      uploaderID),
            ])),
            ('message',    msg['message']),
        ])

        r = self.session.post(self.UPLOAD, data=json.dumps(msg), timeout=self.TIMEOUT)
        if __debug__ and r.status_code != requests.codes.ok:
            print 'Status\t%s'  % r.status_code
            print 'URL\t%s'  % r.url
            print 'Headers\t%s' % r.headers
            print ('Content:\n%s' % r.text).encode('utf-8')
        r.raise_for_status()
Esempio n. 8
0
def writelog(timestamp, system, edsmlookupfn):

    try:
        # Look up the system before adding it to the log, since adding it to the log has the side-effect of creating it
        edsmlookupfn()

        r = requests.get(
            'http://www.edsm.net/api-logs-v1/set-log?commanderName=%s&apiKey=%s&systemName=%s&dateVisited=%s&fromSoftware=%s&fromSoftwareVersion=%s'
            % (urllib.quote(config.get('edsm_cmdrname')),
               urllib.quote(config.get('edsm_apikey')), urllib.quote(system),
               urllib.quote(
                   time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(timestamp))),
               urllib.quote(applongname), urllib.quote(appversion)),
            timeout=EDSM._TIMEOUT)
        r.raise_for_status()
        reply = r.json()
        (msgnum, msg) = reply['msgnum'], reply['msg']
    except:
        if __debug__: print_exc()
        raise Exception(_("Error: Can't connect to EDSM"))

    # Message numbers: 1xx = OK, 2xx = fatal error, 3xx = error (but not generated in practice), 4xx = ignorable errors
    if msgnum // 100 not in (1, 4):
        raise Exception(_('Error: EDSM {MSG}').format(MSG=msg))

    if not config.getint('edsm_historical'):
        config.set('edsm_historical', 1)
        thread = threading.Thread(target=export_historical, name='EDSM export')
        thread.daemon = True
        thread.start()
Esempio n. 9
0
def prefs_changed(cmdr, is_beta):
    config.set('output', (config.getint('output') &
                          (config.OUT_MKT_TD | config.OUT_MKT_CSV
                           | config.OUT_SHIP | config.OUT_MKT_MANUAL)) +
               (this.eddn_station.get() and config.OUT_MKT_EDDN) +
               (this.eddn_system.get() and config.OUT_SYS_EDDN) +
               (this.eddn_delay.get() and config.OUT_SYS_DELAY))
Esempio n. 10
0
    def use_refresh_token(self):
        refresh_token = config.get('token')

        data = dict(
            client_id=CLIENT_ID,
            client_secret=CLIENT_SECRET,
            refresh_token=refresh_token,
            grant_type="refresh_token"
        )

        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }

        response = requests.post(FRONTIER_AUTH_SERVER, data=data, headers=headers)
        if 200 != response.status_code:
            raise VerificationRequired

        response = response.json()
        self.access_token = response.get('access_token')
        refresh_token = response.get('refresh_token')

        config.set('token', refresh_token)
        self.state = CompanionOAuth2.STATE_OK
Esempio n. 11
0
    def on_auth_callback(self, code, state):
        if(CompanionOAuth2.STATE_AUTH == self.state):
            data = dict(
                client_id=CLIENT_ID,
                client_secret=CLIENT_SECRET,
                code=code,
                redirect_uri=REDIRECT_URI,
                state=state,
                grant_type="authorization_code"
            )

            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': 'application/json'
            }

            r = requests.post(FRONTIER_AUTH_SERVER, data=data, headers=headers)
            response = r.json()
            self.access_token = response.get('access_token')
            refresh_token = response.get('refresh_token')

            config.set('token', refresh_token)

            self.state = CompanionOAuth2.STATE_OK
            if self.cb: self.cb()

            self.cb = None

            return r.content
        else:
            return 'Internal state not correct'
Esempio n. 12
0
 def save_current_playlist(self, *args):    
     index = 0
     player_source = Player.get_source()
     for i, item in enumerate(self.category_list.get_items()):
         if item.song_view == player_source:
             index = i
     config.set("playlist","current_index", str(index))
Esempio n. 13
0
def fetch_show_all():
    this.show_all_cfg = tk.IntVar(value=config.get_int("ugc_show_all"))
    this.show_all = this.show_all_cfg.get()
    config.set("ugc_show_all", this.show_all)
    this.show_all_cfg = tk.IntVar(value=config.get_int("ugc_show_all"))
    fetch_show_all_bgs()
    return ()
Esempio n. 14
0
 def on_preferences_closed(self, cmdr: str, is_beta: bool) -> None:
     if self.load_list:
         logger.info(f"Saving {len(self.load_list)} items to preferences.")
         config.set('auto_loader_list', '\n'.join(self.load_list))
     elif self.raw_list.get():
         logger.info("List empty, deleting config entry.")
         config.delete('auto_loader_list')
Esempio n. 15
0
 def run(self):
     config.set("lyrics", "status", "true")
     self.play_time_source()
     if self.__lyrics_mode == LRC_WINDOW_MODE:
         self.show_scroll_lyrics()
     else:
         self.show_desktop_lyrics()
 def change_lyrics_save_dir(self, widget):
     local_dir = WinDir(False).run()
     if local_dir:
         config.set("lyrics", "save_lrc_path", local_dir)
         self.dir_entry.set_editable(True)        
         self.dir_entry.set_text(os.path.expanduser(local_dir))
         self.dir_entry.set_editable(False)
Esempio n. 17
0
def prefs_changed(cmdr, is_beta):
    """
    Save settings.
    """
    config.set('RouteHelperPlugin_RouteFileLocationSetting', this.route_file_location_setting.get())   # Store new value in config
    if this.current_system and this.current_system in this.systems:
        copy_next_system(this.current_system)
Esempio n. 18
0
def prefs_changed():
    this.distances = list()
    for (system, x, y, z) in this.settingUiEntries:
        systemText = system.get()
        xText = x.get()
        yText = y.get()
        zText = z.get()
        if systemText and xText and yText and zText:
            try:
                d = dict()
                d["system"] = systemText.strip()
                d["x"] = Locale.numberFromString(xText.strip())
                d["y"] = Locale.numberFromString(yText.strip())
                d["z"] = Locale.numberFromString(zText.strip())
                this.distances.append(d)
            except:  # error while parsing the numbers
                sys.stderr.write(
                    "DistanceCalc: Error while parsing the coordinates for {0}"
                    .format(systemText.strip()))
                continue
    config.set("DistanceCalc", json.dumps(this.distances))

    settings = this.travelledTotalOption.get() | (
        this.travelledSessionOption.get() << 1) | (
            this.travelledSessionSelected.get() << 2)
    config.set("DistanceCalc_options", settings)

    updateUi()
    updateDistances()
Esempio n. 19
0
def writelog(timestamp, system, edsmlookupfn):

    try:
        # Look up the system before adding it to the log, since adding it to the log has the side-effect of creating it
        edsmlookupfn()

        r = requests.get(
            "http://www.edsm.net/api-logs-v1/set-log?commanderName=%s&apiKey=%s&systemName=%s&dateVisited=%s&fromSoftware=%s&fromSoftwareVersion=%s"
            % (
                urllib.quote(config.get("edsm_cmdrname")),
                urllib.quote(config.get("edsm_apikey")),
                urllib.quote(system),
                urllib.quote(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(timestamp))),
                urllib.quote(applongname),
                urllib.quote(appversion),
            ),
            timeout=EDSM._TIMEOUT,
        )
        r.raise_for_status()
        reply = r.json()
        (msgnum, msg) = reply["msgnum"], reply["msg"]
    except:
        if __debug__:
            print_exc()
        raise Exception(_("Error: Can't connect to EDSM"))

    # Message numbers: 1xx = OK, 2xx = fatal error, 3xx = error (but not generated in practice), 4xx = ignorable errors
    if msgnum // 100 not in (1, 4):
        raise Exception(_("Error: EDSM {MSG}").format(MSG=msg))

    if not config.getint("edsm_historical"):
        config.set("edsm_historical", 1)
        thread = threading.Thread(target=export_historical, name="EDSM export")
        thread.daemon = True
        thread.start()
Esempio n. 20
0
    def send(self, cmdr, msg):
        if config.getint('anonymous'):
            uploaderID = config.get('uploaderID')
            if not uploaderID:
                uploaderID = uuid.uuid4().hex
                config.set('uploaderID', uploaderID)
        else:
            uploaderID = cmdr.encode('utf-8')

        msg['header'] = {
            'softwareName':
            '%s [%s]' %
            (applongname, platform == 'darwin' and "Mac OS" or system()),
            'softwareVersion':
            appversion,
            'uploaderID':
            uploaderID,
        }
        if not msg['message'].get(
                'timestamp'):  # already present in journal messages
            msg['message']['timestamp'] = time.strftime(
                '%Y-%m-%dT%H:%M:%SZ',
                time.gmtime(config.getint('querytime') or int(time.time())))

        r = self.session.post(self.UPLOAD,
                              data=json.dumps(msg),
                              timeout=timeout)
        if __debug__ and r.status_code != requests.codes.ok:
            print 'Status\t%s' % r.status_code
            print 'URL\t%s' % r.url
            print 'Headers\t%s' % r.headers
            print('Content:\n%s' % r.text).encode('utf-8')
        r.raise_for_status()
Esempio n. 21
0
 def save(self):
     """
     Save the saved earnings to config
     :return:
     """
     config.set(CFG_EARNINGS,
                str(self.saved_earnings + self.trip_earnings()))
 def update_preview_line_number(self, widget, label, allocated_data, index):    
     if allocated_data == 1:
         switch_tab(self.line_align_hbox, self.single_align_combo_box)
     else:    
         switch_tab(self.line_align_hbox, self.double_align_combo_box)
         
     config.set("lyrics", "line_count", str(allocated_data))
Esempio n. 23
0
def prefs_changed():
    # bits are as follows:
    # 0-3 radius # not used anymore
    # 4-5 interval, not used anymore
    # 6: copy to clipboard
    # 7: overwrite enabled status
    # 8: EDSM body check, value inverted
    settings = (this.clipboard.get() << 5) | (this.overwrite.get() << 6) | (
        (not this.edsmBodyCheck.get()) << 7)
    config.set(this.CONFIG_MAIN, settings)
    this.enabled = checkTransmissionOptions()
    this.rseData.radiusExponent = RseData.DEFAULT_RADIUS_EXPONENT

    oldFlags = this.rseData.ignoredProjectsFlags
    for k, v in this.ignoredProjectsCheckboxes.items():
        if not v.get():  # inverted, user wants to ignore this project
            this.rseData.ignoredProjectsFlags = this.rseData.ignoredProjectsFlags | k
        else:
            this.rseData.ignoredProjectsFlags = this.rseData.ignoredProjectsFlags & (
                0xFFFFFFFF - k)  # DWord = 32 bit

    if oldFlags != this.rseData.ignoredProjectsFlags:
        this.rseData.radius = RseData.DEFAULT_RADIUS_EXPONENT  # reset radius just in case
        if this.currentSystem:
            this.rseData.systemList = list(
            )  # clear list in case there is no system nearby
            this.queue.put(
                BackgroundTask.JumpedSystemTask(this.rseData,
                                                this.currentSystem))

    config.set(this.CONFIG_IGNORED_PROJECTS, this.rseData.ignoredProjectsFlags)

    updateUiUnconfirmedSystem()
    updateUiEdsmBodyCount()
Esempio n. 24
0
def prefs_changed(cmdr, is_beta):
    this.distances = list()
    for settingsUiElement in this.settingsUiElements:
        systemText = settingsUiElement.systemEntry.get()
        xText = settingsUiElement.xEntry.get()
        yText = settingsUiElement.yEntry.get()
        zText = settingsUiElement.zEntry.get()
        if systemText and xText and yText and zText:
            try:
                d = dict()
                d["system"] = systemText.strip()
                d["x"] = Locale.numberFromString(xText.strip())
                d["y"] = Locale.numberFromString(yText.strip())
                d["z"] = Locale.numberFromString(zText.strip())
                this.distances.append(d)
            except Exception as e:  # error while parsing the numbers
                print(e)
                sys.stderr.write(
                    "DistanceCalc: Error while parsing the coordinates for {0}"
                    .format(systemText.strip()))
                continue
    config.set("DistanceCalc", json.dumps(this.distances))

    settings = this.travelledTotalOption.get() | (
        this.travelledSessionOption.get() << 1) | (
            this.travelledSessionSelected.get() << 2)
    config.set("DistanceCalc_options", settings)

    updateMainUi()
    updateDistances()
Esempio n. 25
0
 def on_font_set(self, widget):
     print "on font set cb"
     print widget.get_font_name()
     self.font_info = widget.get_font_name()
     
     config.set("OSD","font", self.font_info)        
     config.write()
Esempio n. 26
0
 def show_output_folder_select_dialog(self):
     folder = self.output_folder_select_dialog.getExistingDirectory(
         self, 'Choose folder')
     if folder:
         self.output_folder_label.setText(folder)
         self.output_folder_label.setToolTip(folder)
         config.set('output_folder', folder)
Esempio n. 27
0
 def set_dock_mode(self, value):
     if config.getboolean("lyrics", "dock_mode"):
         config.set("lyrics", "dock_mode", "false")
         self.set_type_hint(gtk.WINDOW_TYPE_HINT_NORMAL)
     else:    
         config.set("lyrics", "dock_mode", "true")
         self.set_type_hint(gtk.WINDOW_TYPE_HINT_DOCK)
Esempio n. 28
0
 def save_current_playlist(self, *args):
     index = 0
     player_source = Player.get_source()
     for i, item in enumerate(self.category_list.get_items()):
         if item.song_view == player_source:
             index = i
     config.set("playlist","current_index", str(index))
Esempio n. 29
0
def plugin_start():
    """
    Start up our EDMC Plugin
    :return:
    """
    global _overlay
    global SERVER
    _overlay = edmcoverlay.Overlay()
    time.sleep(2)
    notify("ED:HITS Plugin Loaded")

    if not SERVER.get():
        SERVER.set(DEFAULT_SERVER)
        config.set(PREFNAME_SERVER, DEFAULT_SERVER)
    if not OVERLAY_MESSAGE_DURATION.get():
        OVERLAY_MESSAGE_DURATION.set(str(DEFAULT_OVERLAY_MESSAGE_DURATION))
        config.set(PREFNAME_OVERLAY_DURATION,
                   str(DEFAULT_OVERLAY_MESSAGE_DURATION))
    try:
        check_update()
    except:
        notify("Could not connect to server {}".format(SERVER.get()))

    try:
        OVERLAY_HITS_MODE.get()
    except:
        OVERLAY_HITS_MODE.set("on")
Esempio n. 30
0
 def setUp(self):
     # Run a local sound server
     config.set('Network', 'ServerIP', '127.0.0.1')
     config.set('Network', 'ServerPort', '4004')
     self.server = server.Server()
     threading.Thread(target=self.server.serve, daemon=True).start()
     sleep(1)  # Wait for server to start (shh it's fine)
Esempio n. 31
0
 def on_tab_box_switch_tab(self, widget, item):    
     try:
         config.set("listmanager", "source", item.title)
         config.write()
     except: pass    
     
     Dispatcher.emit("switch-browser", item, True)
 def run(self):
     config.set("lyrics", "status", "true")                    
     self.play_time_source()
     if self.__lyrics_mode == LRC_WINDOW_MODE:
         self.show_scroll_lyrics()
     else:    
         self.show_desktop_lyrics()
Esempio n. 33
0
def prefs_changed(cmdr: str, is_beta: bool) -> None:
    xpos = xpos_var.get()
    ypos = ypos_var.get()
    width = width_var.get()
    height = height_var.get()
    change = False
    for name, val in [("xpos", xpos), ("ypos", ypos), ("width", width),
                      ("height", height)]:
        try:
            assert int(val) >= 0
        except (ValueError, AssertionError):
            logger.warning("Bad config value for %s: %r", name, val)
        else:
            try:
                old_val = int(config.get(f"edmcoverlay2_{name}"))
            except (TypeError, ValueError):
                pass
            else:
                if val != old_val:
                    change = True
            config.set(f"edmcoverlay2_{name}", val)
    if change and overlay_process is not None:
        logger.info("Settings changes detected, restarting overlay")
        stop_overlay()
        start_overlay()
Esempio n. 34
0
def prefs_changed(cmdr, is_beta):
    """
    Save settings.
    """
    config.set('disable_presence', this.disablePresence.get())
    config.set('edmcdrpc__disable_auto_update', this.disable_auto_update.get())
    update_presence()
Esempio n. 35
0
 def pause(self):
     '''pause'''
     if self.song is None :
         return 
     self.bin.xfade_pause()
     config.set("player", "play", "false")
     self.emit("paused")
Esempio n. 36
0
    def stop(self):    
        self.stop_after_this_track = False
        self.update_skipcount()

        self.bin.xfade_close()
        config.set("player", "play", "false")
        self.emit("stopped")
Esempio n. 37
0
 def __on_error(self, bin, uri):   
     self.logdebug("gst error received for %s", uri)
     
     if self.skip_error_song_flag:
         self.skip_error_song_flag = False
         return 
     
     self.bin.xfade_close()
     config.set("player", "play", "false")
     self.emit("paused")
     
     if self.song:
         if getattr(self.__source, 'add_invaild_song', None):
             self.__source.add_invaild_song(self.song)
     
     if not self.song:
         self.emit("init-status")
         self.song = None
         return 
     
     if self.song.get_type() != "local":
         return
     
     if self.song.get_type() in [ "cdda", "webcast"]:
         self.emit("init-status")
         self.song = None
         return 
     if uri == self.song.get("uri") and not self.__next_already_called:
         self.logdebug("request new song: error and play-end not emit")
         self.emit("play-end")
         self.next(True)
         
     self.__next_already_called = False    
 def onexit(self, event=None):
     flightlog.close()
     if platform!='darwin' or self.w.winfo_rooty()>0:	# http://core.tcl.tk/tk/tktview/c84f660833546b1b84e7
         config.set('geometry', '+{1}+{2}'.format(*self.w.geometry().split('+')))
     config.close()
     self.session.close()
     self.w.destroy()
Esempio n. 39
0
    def send(self, cmdr, msg):
        if config.getint('anonymous'):
            uploaderID = config.get('uploaderID')
            if not uploaderID:
                uploaderID = uuid.uuid4().hex
                config.set('uploaderID', uploaderID)
        else:
            uploaderID = cmdr.encode('utf-8')

        msg = OrderedDict([
            ('$schemaRef', msg['$schemaRef']),
            ('header',
             OrderedDict([
                 ('softwareName', '%s [%s]' %
                  (applongname, sys.platform == 'darwin' and "Mac OS"
                   or system())),
                 ('softwareVersion', appversion),
                 ('uploaderID', uploaderID),
             ])),
            ('message', msg['message']),
        ])

        r = self.session.post(self.UPLOAD,
                              data=json.dumps(msg),
                              timeout=self.TIMEOUT)
        if __debug__ and r.status_code != requests.codes.ok:
            print 'Status\t%s' % r.status_code
            print 'URL\t%s' % r.url
            print 'Headers\t%s' % r.headers
            print('Content:\n%s' % r.text).encode('utf-8')
        r.raise_for_status()
Esempio n. 40
0
    def change_view(self, widget):

        if not widget.get_active():
            config.set("setting", "window_mode", "simple")
            self.window.unmaximize()
            self.browser_align.hide_all()
            self.browser_align.set_no_show_all(True)
            self.window.set_default_size(SIMPLE_DEFAULT_WIDTH,
                                         SIMPLE_DEFAULT_HEIGHT)
            self.window.set_geometry_hints(
                None,
                SIMPLE_DEFAULT_WIDTH,
                SIMPLE_DEFAULT_HEIGHT,
                SIMPLE_DEFAULT_WIDTH,
                SIMPLE_DEFAULT_HEIGHT,  # (310, 700)
                -1,
                -1,
                -1,
                -1,
                -1,
                -1)
            self.window.resize(SIMPLE_DEFAULT_WIDTH, SIMPLE_DEFAULT_HEIGHT)
            self.window.queue_draw()
        else:
            config.set("setting", "window_mode", "full")
            self.browser_align.set_no_show_all(False)
            self.browser_align.show_all()
            self.window.set_default_size(FULL_DEFAULT_WIDTH,
                                         FULL_DEFAULT_HEIGHT)
            self.window.set_geometry_hints(None, FULL_DEFAULT_WIDTH,
                                           FULL_DEFAULT_HEIGHT,
                                           FULL_DEFAULT_WIDTH,
                                           FULL_DEFAULT_HEIGHT, -1, -1, -1, -1,
                                           -1, -1)
            self.window.resize(FULL_DEFAULT_WIDTH, FULL_DEFAULT_HEIGHT)
Esempio n. 41
0
    def authorize(self, payload):
        # Handle OAuth authorization code callback. Returns access token if successful, otherwise raises CredentialsError
        if not '?' in payload:
            print 'Auth\tMalformed response "%s"' % payload.encode('utf-8')
            raise CredentialsError()	# Not well formed

        data = urlparse.parse_qs(payload[payload.index('?')+1:])
        if not self.state or not data.get('state') or data['state'][0] != self.state:
            print 'Auth\tUnexpected response "%s"' % payload.encode('utf-8')
            raise CredentialsError()	# Unexpected reply

        if not data.get('code'):
            print 'Auth\tNegative response "%s"' % payload.encode('utf-8')
            if data.get('error_description'):
                raise CredentialsError('Error: %s' % data['error_description'][0])
            elif data.get('error'):
                raise CredentialsError('Error: %s' % data['error'][0])
            elif data.get('message'):
                raise CredentialsError('Error: %s' % data['message'][0])
            else:
                raise CredentialsError()

        try:
            r = None
            data = {
                'grant_type': 'authorization_code',
                'client_id': CLIENT_ID,
                'code_verifier': self.verifier,
                'code': data['code'][0],
                'redirect_uri': protocolhandler.redirect,
            }
            r = self.session.post(SERVER_AUTH + URL_TOKEN, data=data, timeout=auth_timeout)
            data = r.json()
            if r.status_code == requests.codes.ok:
                print 'Auth\tNew token for %s' % self.cmdr.encode('utf-8')
                cmdrs = config.get('cmdrs')
                idx = cmdrs.index(self.cmdr)
                tokens = config.get('fdev_apikeys') or []
                tokens = tokens + [''] * (len(cmdrs) - len(tokens))
                tokens[idx] = data.get('refresh_token', '')
                config.set('fdev_apikeys', tokens)
                config.save()	# Save settings now for use by command-line app
                return data.get('access_token')
        except:
            print 'Auth\tCan\'t get token for %s' % self.cmdr.encode('utf-8')
            print_exc()
            if r: self.dump(r)
            raise CredentialsError()

        print 'Auth\tCan\'t get token for %s' % self.cmdr.encode('utf-8')
        self.dump(r)
        if data.get('error_description'):
            raise CredentialsError('Error: %s' % data['error_description'])
        elif data.get('error'):
            raise CredentialsError('Error: %s' % data['error'])
        elif data.get('message'):
            raise CredentialsError('Error: %s' % data['message'])
        else:
            raise CredentialsError()
Esempio n. 42
0
 def __on_playing(self, bin, uri):
     '''Signal emitted by fadebin when a new stream previously queued start'''
     if not self.song: return 
     if uri == self.song.get("uri"):
         self.logdebug("signal playing-stream receive by %s", uri)
         config.set("player", "play", "true")
         self.emit("played")
         self.__emit_signal_new_song()
Esempio n. 43
0
def journal_entry(cmdr, is_beta, system, station, entry, state):
    """
    Look for SRV destruction and record it so we can add it to the navigation
    locations
    """
    if not is_beta and entry['event'] == 'SRVDestroyed' and this._location:
        config.set("Kumay3305.crash_location", json.dumps(this._location))
        this.waypoints.update_crash_location(this._location)
Esempio n. 44
0
def prefs_changed(cmdr, is_beta):
    """
   Save settings.
   """
    config.set('MyPluginSetting',
               this.mysetting.getint())  # Store new value in config

    this = sys.modules[__name__]  # For holding module globals
Esempio n. 45
0
 def __on_config_changed(self, dispatcher, section, option, value):
     if section == "plugins" and option.find("globalkey_") == 0 and option.find("_last") == -1:
         self.__try_unbind(config.get(section, option + "_last", value))
         
         if value:            
             self.__bind(config.get(section, option, value), option)
             
         config.set(section, option + "_last", value)
Esempio n. 46
0
 def test_soft_eol(self):
     self.assertFalse(abnf.parse('JOIN #a\r', abnf.message))
     self.assertFalse(abnf.parse('JOIN #a\n', abnf.message))
     config.set('parser', 'soft_eol', 'true')
     self._test(abnf.message, {
         'JOIN #a\r': ['', 'JOIN', '#a'],
         'JOIN #a\n': ['', 'JOIN', '#a']
     })
Esempio n. 47
0
 def __volume_changed(self, widget, value, status):
     val = value / 100.0
     if status == -1:
         config.set("player", "volume", "0.0")
         Player.volume = 0.0
     else:    
         config.set("player","volume","%f" % val)
         Player.volume = val
Esempio n. 48
0
 def hide_to_tray(self):
     event = self.window.get_state()
     if config.get("setting", "window_mode") == "full":
         if event & gtk.gdk.WINDOW_STATE_MAXIMIZED == gtk.gdk.WINDOW_STATE_MAXIMIZED:
             config.set("window", "state", "maximized")
         else:
             config.set("window", "state", "normal")
     self.window.hide_all()
Esempio n. 49
0
def _putfirst(setting, config_idx, new_value=None):
    assert config_idx >= 0 or new_value is not None, (setting, config_idx,
                                                      new_value)
    values = config.get(setting)
    values.insert(0, new_value if config_idx < 0 else values.pop(config_idx))
    if new_value is not None:
        values[0] = new_value
    config.set(setting, values)
Esempio n. 50
0
 def hide_to_tray(self):
     event = self.window.get_state()
     if config.get("setting", "window_mode") == "full":
         if event & gtk.gdk.WINDOW_STATE_MAXIMIZED == gtk.gdk.WINDOW_STATE_MAXIMIZED:
             config.set("window", "state", "maximized")
         else:
             config.set("window", "state", "normal")
     self.window.hide_all()
 def onexit(self, event=None):
     hotkeymgr.unregister()
     flightlog.close()
     if platform != "darwin" or self.w.winfo_rooty() > 0:  # http://core.tcl.tk/tk/tktview/c84f660833546b1b84e7
         config.set("geometry", "+{1}+{2}".format(*self.w.geometry().split("+")))
     config.close()
     self.updater.close()
     self.session.close()
     self.w.destroy()
Esempio n. 52
0
 def invalidate(cmdr):
     print 'Auth\tInvalidated token for %s' % cmdr.encode('utf-8')
     cmdrs = config.get('cmdrs')
     idx = cmdrs.index(cmdr)
     tokens = config.get('fdev_apikeys') or []
     tokens = tokens + [''] * (len(cmdrs) - len(tokens))
     tokens[idx] = ''
     config.set('fdev_apikeys', tokens)
     config.save()	# Save settings now for use by command-line app
Esempio n. 53
0
 def test_regr01(self):
     """
     Regression in 119da40fc8a2ddfb885d6687b7dddd90144d2995
     Problem: Fails to parse \r\n terminated messages when soft_eol is on
     """
     config.set('parser', 'soft_eol', 'true')
     self.assertEqual(
         ['', 'JOIN', '#a'],
         abnf.parse('JOIN #a\r\n', abnf.message))
 def change_enbale_status(self, widget):    
     if widget.get_active():
         config.set("globalkey", "enable", "true")
         for each_entry in self.control_entrys:
             each_entry.set_sensitive(True)
     else:    
         config.set("globalkey", "enable", "false")
         for each_entry in self.control_entrys:
             each_entry.set_sensitive(False)
Esempio n. 55
0
 def set_locked(self, locked=True):    
     if locked:
         config.set("lyrics", "locked", "true")
         self.set_input_shape_mask(True)
         self.emit("hide-bg")
         self.queue_draw()
     else:    
         config.set("lyrics", "locked", "false")
         self.set_input_shape_mask(False)
Esempio n. 56
0
 def set_karaoke_mode(self):
     if not self.get_karaoke_mode():
         config.set("lyrics", "karaoke_mode", "true")
     else:    
         config.set("lyrics", "karaoke_mode", "false")
         self.line_percentage = [0.0, 0.0]
         for i in range(self.get_line_count()):
             self.update_lyric_surface(i)
         self.queue_draw()    
Esempio n. 57
0
 def change_app_mode(self, mode):        
     config.set("setting", "app_mode", mode)        
     if mode == "normal":
         self.mini_window.hide_to_tray()
         self.show_from_tray()
         self.simple_header_bar.sync_volume()
     else:    
         self.hide_to_tray()
         self.mini_window.show_from_tray()
         self.mini_window.sync_volume()
Esempio n. 58
0
def updateBTimer():
    global lastUpdate
    now = time()
    delta = now - lastUpdate
    lastUpdate = now
    try:
        saved = float(config.get("DEFAULT", "btimer", True))
    except NoOptionError:
        saved = 0
    config.set("DEFAULT", "btimer", delta + saved)
Esempio n. 59
0
 def apply(self):
     credentials = (config.get('username'), config.get('password'))
     config.set('username', self.username.get().strip())
     config.set('password', self.password.get().strip())
     config.set('output', (self.out_eddn.get() and config.OUT_EDDN or 0) + (self.out_bpc.get() and config.OUT_BPC or 0) + (self.out_td.get() and config.OUT_TD or 0) + (self.out_csv.get() and config.OUT_CSV or 0) + (self.out_ship.get() and config.OUT_SHIP or 0) + (self.out_log.get() and config.OUT_LOG or 0) + (self.out_stat.get() and config.OUT_STAT or 0))
     config.set('outdir', self.outdir.get().strip())
     config.set('anonymous', self.out_anon.get())
     self.destroy()
     if credentials != (config.get('username'), config.get('password')) and self.callback:
         self.callback()