Profile information returned by the companion app service
        public MainWindow(bool fromVA = false)
        {
            InitializeComponent();

            this.fromVA = fromVA;

            // Start the EDDI instance
            EDDI.Instance.Start();

            // Configure the EDDI tab
            versionText.Text = Constants.EDDI_VERSION;

            //// Need to set up the correct information in the hero text depending on from where we were started
            if (fromVA)
            {
                heroText.Text = "Any changes made here will take effect automatically in VoiceAttack.  You can close this window when you have finished.";
            }
            else
            {
                heroText.Text = "If you are using VoiceAttack then please close this window before you start VoiceAttack for your changes to take effect.  You can access this window from VoiceAttack with the \"Configure EDDI\" command.";
            }

            EDDIConfiguration eddiConfiguration = EDDIConfiguration.FromFile();
            eddiHomeSystemText.Text = eddiConfiguration.HomeSystem;
            eddiHomeStationText.Text = eddiConfiguration.HomeStation;
            eddiInsuranceDecimal.Text = eddiConfiguration.Insurance.ToString(CultureInfo.InvariantCulture);
            eddiVerboseLogging.IsChecked = eddiConfiguration.Debug;

            Logging.Verbose = eddiConfiguration.Debug;

            // Configure the Companion App tab
            CompanionAppCredentials companionAppCredentials = CompanionAppCredentials.FromFile();
            companionAppEmailText.Text = companionAppCredentials.email;
            // See if the credentials work
            try
            {
                profile = CompanionAppService.Instance.Profile();
                if (profile == null)
                {
                    setUpCompanionAppComplete("Your connection to the companion app is good but experiencing temporary issues.  Your information should be available soon");
                }
                else
                {
                    setUpCompanionAppComplete("Your connection to the companion app is operational, Commander " + profile.Cmdr.name);
                }
            }
            catch (Exception)
            {
                if (CompanionAppService.Instance.CurrentState == CompanionAppService.State.NEEDS_LOGIN)
                {
                    // Fall back to stage 1
                    setUpCompanionAppStage1();
                }
                else if (CompanionAppService.Instance.CurrentState == CompanionAppService.State.NEEDS_CONFIRMATION)
                {
                    // Fall back to stage 2
                    setUpCompanionAppStage2();
                }
            }

            if (profile != null)
            {
                setShipyardFromConfiguration();
            }

            // Configure the Text-to-speech tab
            SpeechServiceConfiguration speechServiceConfiguration = SpeechServiceConfiguration.FromFile();
            List<string> speechOptions = new List<string>();
            speechOptions.Add("Windows TTS default");
            try
            {
                using (SpeechSynthesizer synth = new SpeechSynthesizer())
                {
                    foreach (InstalledVoice voice in synth.GetInstalledVoices())
                    {
                        if (voice.Enabled && (!voice.VoiceInfo.Name.Contains("Microsoft Server Speech Text to Speech Voice")))
                        {
                            speechOptions.Add(voice.VoiceInfo.Name);
                        }
                    }
                }

                ttsVoiceDropDown.ItemsSource = speechOptions;
                ttsVoiceDropDown.Text = speechServiceConfiguration.StandardVoice == null ? "Windows TTS default" : speechServiceConfiguration.StandardVoice;
            }
            catch (Exception e)
            {
                Logging.Warn("" + Thread.CurrentThread.ManagedThreadId + ": Caught exception " + e);
            }
            ttsVolumeSlider.Value = speechServiceConfiguration.Volume;
            ttsRateSlider.Value = speechServiceConfiguration.Rate;
            ttsEffectsLevelSlider.Value = speechServiceConfiguration.EffectsLevel;
            ttsDistortCheckbox.IsChecked = speechServiceConfiguration.DistortOnDamage;
            disableSsmlCheckbox.IsChecked = speechServiceConfiguration.DisableSsml;

            ttsTestShipDropDown.ItemsSource = ShipDefinitions.ShipModels;
            ttsTestShipDropDown.Text = "Adder";

            foreach (EDDIMonitor monitor in EDDI.Instance.monitors)
            {
                Logging.Debug("Adding configuration tab for " + monitor.MonitorName());

                PluginSkeleton skeleton = new PluginSkeleton(monitor.MonitorName());
                skeleton.plugindescription.Text = monitor.MonitorDescription();

                bool enabled;
                if (eddiConfiguration.Plugins.TryGetValue(monitor.MonitorName(), out enabled))
                {
                    skeleton.pluginenabled.IsChecked = enabled;
                }
                else
                {
                    // Default to enabled
                    skeleton.pluginenabled.IsChecked = true;
                    eddiConfiguration.ToFile();
                }

                // Add monitor-specific configuration items
                UserControl monitorConfiguration = monitor.ConfigurationTabItem();
                if (monitorConfiguration != null)
                {
                    monitorConfiguration.Margin = new Thickness(10);
                    skeleton.panel.Children.Add(monitorConfiguration);
                }

                TabItem item = new TabItem { Header = monitor.MonitorName() };
                item.Content = skeleton;
                tabControl.Items.Add(item);
            }

            foreach (EDDIResponder responder in EDDI.Instance.responders)
            {
                Logging.Debug("Adding configuration tab for " + responder.ResponderName());

                PluginSkeleton skeleton = new PluginSkeleton(responder.ResponderName());
                skeleton.plugindescription.Text = responder.ResponderDescription();

                bool enabled;
                if (eddiConfiguration.Plugins.TryGetValue(responder.ResponderName(), out enabled))
                {
                    skeleton.pluginenabled.IsChecked = enabled;
                }
                else
                {
                    // Default to enabled
                    skeleton.pluginenabled.IsChecked = true;
                    eddiConfiguration.ToFile();
                }

                // Add responder-specific configuration items
                UserControl monitorConfiguration = responder.ConfigurationTabItem();
                if (monitorConfiguration != null)
                {
                    monitorConfiguration.Margin = new Thickness(10);
                    skeleton.panel.Children.Add(monitorConfiguration);
                }

                TabItem item = new TabItem { Header = responder.ResponderName() };
                item.Content = skeleton;
                tabControl.Items.Add(item);
            }

            EDDI.Instance.Start();
        }
 // Handle changes to the companion app tab
 private void companionAppNextClicked(object sender, RoutedEventArgs e)
 {
     // See if the user is entering their email address and password
     if (companionAppEmailText.Visibility == Visibility.Visible)
     {
         // Stage 1 of authentication - login
         CompanionAppService.Instance.Credentials.email = companionAppEmailText.Text.Trim();
         CompanionAppService.Instance.Credentials.password = companionAppPasswordText.Password.Trim();
         try
         {
             // It is possible that we have valid cookies at this point so don't log in, but we did
             // need the credentials
             if (CompanionAppService.Instance.CurrentState == CompanionAppService.State.NEEDS_LOGIN)
             {
                 CompanionAppService.Instance.Login();
             }
             if (CompanionAppService.Instance.CurrentState == CompanionAppService.State.NEEDS_CONFIRMATION)
             {
                 setUpCompanionAppStage2();
             }
             else if (CompanionAppService.Instance.CurrentState == CompanionAppService.State.READY)
             {
                 if (profile == null)
                 {
                     profile = CompanionAppService.Instance.Profile();
                 }
                 if (profile == null)
                 {
                     setUpCompanionAppComplete("Your connection to the companion app is good but experiencing temporary issues.  Your information should be available soon");
                 }
                 else
                 {
                     setUpCompanionAppComplete("Your connection to the companion app is operational, Commander " + profile.Cmdr.name);
                     setShipyardFromConfiguration();
                 }
             }
         }
         catch (EliteDangerousCompanionAppAuthenticationException ex)
         {
             companionAppText.Text = ex.Message;
         }
         catch (EliteDangerousCompanionAppErrorException ex)
         {
             companionAppText.Text = ex.Message;
         }
         catch (Exception ex)
         {
             companionAppText.Text = "Unexpected problem\r\nPlease report this at http://github.com/CmdrMcDonald/EliteDangerousDataProvider/issues\r\n" + ex;
         }
     }
     else if (companionAppCodeText.Visibility == Visibility.Visible)
     {
         // Stage 2 of authentication - confirmation
         string code = companionAppCodeText.Text.Trim();
         try
         {
             CompanionAppService.Instance.Confirm(code);
             // All done - see if it works
             profile = CompanionAppService.Instance.Profile();
             if (profile != null)
             {
                 setUpCompanionAppComplete("Your connection to the companion app is operational, Commander " + profile.Cmdr.name);
                 setShipyardFromConfiguration();
             }
         }
         catch (EliteDangerousCompanionAppAuthenticationException ex)
         {
             setUpCompanionAppStage1(ex.Message);
         }
         catch (EliteDangerousCompanionAppErrorException ex)
         {
             setUpCompanionAppStage1(ex.Message);
         }
         catch (Exception ex)
         {
             setUpCompanionAppStage1("Unexpected problem\r\nPlease report this at http://github.com/CmdrMcDonald/EliteDangerousDataProvider/issues\r\n" + ex);
         }
     }
 }
        public static List<Ship> ShipyardFromProfile(dynamic json, ref Profile profile)
        {
            Logging.Debug("Entered");

            Ship currentShip = profile.Ship;

            List<Ship> StoredShips = new List<Ship>();

            foreach (dynamic shipJson in json["ships"])
            {
                if (shipJson != null)
                {
                    // Take underlying value if present
                    JObject shipObj = shipJson.Value == null ? shipJson : shipJson.Value;
                    if (shipObj != null)
                    {
                        if ((int)shipObj["id"] != currentShip.LocalId)
                        {
                            Ship ship = ShipFromProfile(shipObj);

                            if (shipObj["starsystem"] != null)
                            {
                                // If we have a starsystem it means that the ship is stored
                                ship.starsystem = (string)shipObj["starsystem"]["name"];
                                ship.station = (string)shipObj["station"]["name"];

                                StoredShips.Add(ship);
                            }
                        }
                    }
                }
            }

            Logging.Debug("Leaving");
            return StoredShips;
        }
        /// <summary>Create a profile given the results from a /profile call</summary>
        public static Profile ProfileFromJson(JObject json)
        {
            Logging.Debug("Entered");
            Profile Profile = new Profile();

            if (json["commander"] != null)
            {
                Commander Commander = new Commander();
                Commander.name = (string)json["commander"]["name"];

                Commander.combatrating = CombatRating.FromRank((int)json["commander"]["rank"]["combat"]);
                Commander.traderating = TradeRating.FromRank((int)json["commander"]["rank"]["trade"]);
                Commander.explorationrating = ExplorationRating.FromRank((int)json["commander"]["rank"]["explore"]);
                Commander.empirerating = EmpireRating.FromRank((int)json["commander"]["rank"]["empire"]);
                Commander.federationrating = FederationRating.FromRank((int)json["commander"]["rank"]["federation"]);

                Commander.credits = (long)json["commander"]["credits"];
                Commander.debt = (long)json["commander"]["debt"];
                Profile.Cmdr = Commander;

                string systemName = json["lastSystem"] == null ? null : (string)json["lastSystem"]["name"];
                if (systemName != null)
                {
                    Profile.CurrentStarSystem = StarSystemSqLiteRepository.Instance.GetOrCreateStarSystem(systemName);
                }

                Profile.Ship = ShipFromProfile(json["ship"]);

                Profile.Shipyard = ShipyardFromProfile(json, ref Profile);

                AugmentShipInfo(Profile.Ship, Profile.Shipyard);

                if (json["lastStarport"] != null)
                {
                    Profile.LastStation =  Profile.CurrentStarSystem.stations.Find(s => s.name == (string)json["lastStarport"]["name"]);
                    if (Profile.LastStation == null)
                    {
                        // Don't have a station so make one up
                        Profile.LastStation = new Station();
                        Profile.LastStation.name = (string)json["lastStarport"]["name"];
                    }

                    Profile.LastStation.systemname = Profile.CurrentStarSystem.name;
                    Profile.LastStation.outfitting = OutfittingFromProfile(json);
                    Profile.LastStation.commodities = CommoditiesFromProfile(json);
                    Profile.LastStation.shipyard = ShipyardFromProfile(json);
                }
            }

            Logging.Debug("Leaving");
            return Profile;
        }
        public Profile Profile()
        {
            Logging.Debug("Entered");
            if (CurrentState != State.READY)
            {
                // Shouldn't be here
                Logging.Debug("Service in incorrect state to provide profile (" + CurrentState + ")");
                Logging.Debug("Leaving");
                throw new EliteDangerousCompanionAppIllegalStateException("Service in incorrect state to provide profile (" + CurrentState + ")");
            }
            if (cachedProfileExpires > DateTime.Now)
            {
                // return the cached version
                Logging.Debug("Returning cached profile");
                Logging.Debug("Leaving");
                return cachedProfile;
            }

            string data = obtainProfile();

            if (data == null || data == "Profile unavailable")
            {
                // Happens if there is a problem with the API.  Logging in again might clear this...
                relogin();
                data = obtainProfile();
            }

            try
            {
                cachedProfile = ProfileFromJson(data);
            }
            catch (JsonException ex)
            {
                Logging.Error("Failed to parse companion profile", ex);
                cachedProfile = null;
            }

            if (cachedProfile != null)
            {
                cachedProfileExpires = DateTime.Now.AddSeconds(30);
                Logging.Debug("Profile is " + JsonConvert.SerializeObject(cachedProfile));
            }

            Logging.Debug("Leaving");
            return cachedProfile;
        }
Пример #6
0
        /// <summary>Create a profile given the results from a /profile call</summary>
        public static Profile ProfileFromJson(JObject json, DateTime timestamp)
        {
            Profile Profile = new Profile
            {
                json      = json,
                timestamp = timestamp
            };

            if (json["commander"] != null)
            {
                FrontierApiCommander Commander = new FrontierApiCommander
                {
                    // Caution: The "id" property here may not match the FID returned from the player journal
                    name              = (string)json["commander"]["name"],
                    combatrating      = CombatRating.FromRank((int)json["commander"]["rank"]["combat"]),
                    traderating       = TradeRating.FromRank((int)json["commander"]["rank"]["trade"]),
                    explorationrating = ExplorationRating.FromRank((int)json["commander"]["rank"]["explore"]),
                    cqcrating         = CQCRating.FromRank((int)json["commander"]["rank"]["cqc"]),
                    empirerating      = EmpireRating.FromRank((int)json["commander"]["rank"]["empire"]),
                    federationrating  = FederationRating.FromRank((int)json["commander"]["rank"]["federation"]),
                    crimerating       = (int)json["commander"]["rank"]["crime"],
                    servicerating     = (int)json["commander"]["rank"]["service"],
                    powerrating       = (int)json["commander"]["rank"]["power"],

                    credits = (long)json["commander"]["credits"],
                    debt    = (long)json["commander"]["debt"]
                };
                Profile.Cmdr   = Commander;
                Profile.docked = (bool)json["commander"]["docked"];
                Profile.alive  = (bool)json["commander"]["alive"];

                if (json["commander"]["capabilities"] != null)
                {
                    var contexts = new ProfileContexts
                    {
                        allowCobraMkIV = (bool)json["commander"]["capabilities"]["AllowCobraMkIV"],
                        inHorizons     = (bool)json["commander"]["capabilities"]["Horizons"]
                    };
                    Profile.contexts = contexts;
                }

                string systemName = json["lastSystem"] == null ? null : (string)json["lastSystem"]["name"];
                if (systemName != null)
                {
                    Profile.CurrentStarSystem = new ProfileStarSystem
                    {
                        // Caution: The "id" property here may not match the systemAddress
                        systemName = systemName,
                        // Caution: The "faction" property here may return the edName for the faction rather than the invariant name
                    };
                }

                if (json["lastStarport"] != null)
                {
                    Profile.LastStation = new ProfileStation
                    {
                        name     = (string)json["lastStarport"]["name"],
                        marketId = (long?)json["lastStarport"]["id"]
                    };
                    if ((bool)json["commander"]["docked"])
                    {
                        Profile.LastStation.systemname = Profile.CurrentStarSystem.systemName;
                    }
                }
            }

            return(Profile);
        }