public static async Task <bool> InitializeSession()
        {
            try
            {
                TwitchNewAPI.Users.UserModel twitchChannelNew = await ChannelSession.TwitchUserConnection.GetNewAPICurrentUser();

                TwitchV5API.Channel.ChannelModel twitchChannelv5 = await ChannelSession.TwitchUserConnection.GetCurrentV5APIChannel();

                if (twitchChannelNew != null && twitchChannelv5 != null)
                {
                    try
                    {
                        ChannelSession.TwitchUserNewAPI   = twitchChannelNew;
                        ChannelSession.TwitchChannelV5    = twitchChannelv5;
                        ChannelSession.TwitchStreamNewAPI = await ChannelSession.TwitchUserConnection.GetStream(ChannelSession.TwitchUserNewAPI);

                        ChannelSession.TwitchStreamV5 = await ChannelSession.TwitchUserConnection.GetV5LiveStream(ChannelSession.TwitchChannelV5);

                        if (ChannelSession.Settings == null)
                        {
                            IEnumerable <SettingsV3Model> currentSettings = await ChannelSession.Services.Settings.GetAllSettings();

                            if (currentSettings.Any(s => !string.IsNullOrEmpty(s.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].ChannelID) && string.Equals(s.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].ChannelID, twitchChannelNew.id)))
                            {
                                GlobalEvents.ShowMessageBox(string.Format(Resources.TwitchAccountExists, twitchChannelNew.login));
                                return(false);
                            }

                            ChannelSession.Settings = await ChannelSession.Services.Settings.Create(twitchChannelNew.display_name);
                        }
                        else if (ChannelSession.Settings.StreamingPlatformAuthentications.ContainsKey(StreamingPlatformTypeEnum.Twitch) &&
                                 !string.IsNullOrEmpty(ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].UserID) &&
                                 !string.Equals(ChannelSession.TwitchUserNewAPI.id, ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].UserID))
                        {
                            Logger.Log(LogLevel.Error, $"Signed in account does not match settings account: {ChannelSession.TwitchUserNewAPI.login} - {ChannelSession.TwitchUserNewAPI.id} - {ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].UserID}");
                            GlobalEvents.ShowMessageBox(Resources.TwitchAccountMismatch);
                            ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].UserOAuthToken = null;
                            return(false);
                        }

                        await ChannelSession.Services.Settings.Initialize(ChannelSession.Settings);

                        ChannelSession.Settings.Name = ChannelSession.TwitchUserNewAPI.display_name;

                        ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].UserID    = ChannelSession.TwitchUserNewAPI.id;
                        ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].ChannelID = ChannelSession.TwitchUserNewAPI.id;
                        if (ChannelSession.TwitchBotNewAPI != null)
                        {
                            ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].BotID = ChannelSession.TwitchBotNewAPI.id;
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Log(ex);
                        Logger.Log(LogLevel.Error, "Initialize Settings - " + JSONSerializerHelper.SerializeToString(ex));
                        await DialogHelper.ShowMessage(Resources.FailedToInitializeSettings +
                                                       Environment.NewLine + Environment.NewLine + Resources.ErrorDetailsHeader + " " + ex.Message);

                        return(false);
                    }

                    try
                    {
                        await ChannelSession.Services.Telemetry.Connect();

                        ChannelSession.Services.Telemetry.SetUserID(ChannelSession.Settings.TelemetryUserID);

                        TwitchChatService  twitchChatService  = new TwitchChatService();
                        TwitchEventService twitchEventService = new TwitchEventService();

                        List <Task <Result> > twitchPlatformServiceTasks = new List <Task <Result> >();
                        twitchPlatformServiceTasks.Add(twitchChatService.ConnectUser());
                        twitchPlatformServiceTasks.Add(twitchEventService.Connect());

                        await Task.WhenAll(twitchPlatformServiceTasks);

                        if (twitchPlatformServiceTasks.Any(c => !c.Result.Success))
                        {
                            string errors = string.Join(Environment.NewLine, twitchPlatformServiceTasks.Where(c => !c.Result.Success).Select(c => c.Result.Message));
                            GlobalEvents.ShowMessageBox(Resources.TwitchFailed + Environment.NewLine + Environment.NewLine + errors);
                            return(false);
                        }

                        await ChannelSession.Services.Chat.Initialize(twitchChatService);

                        await ChannelSession.Services.Events.Initialize(twitchEventService);
                    }
                    catch (Exception ex)
                    {
                        Logger.Log(ex);
                        Logger.Log(LogLevel.Error, "Twitch Services - " + JSONSerializerHelper.SerializeToString(ex));
                        await DialogHelper.ShowMessage(Resources.FailedToConnectToTwitch +
                                                       Environment.NewLine + Environment.NewLine + Resources.ErrorDetailsHeader + " " + ex.Message);

                        return(false);
                    }

                    Result result = await ChannelSession.InitializeBotInternal();

                    if (!result.Success)
                    {
                        await DialogHelper.ShowMessage(Resources.FailedToInitializeBotAccount);

                        return(false);
                    }

                    try
                    {
                        // Connect External Services
                        Dictionary <IExternalService, OAuthTokenModel> externalServiceToConnect = new Dictionary <IExternalService, OAuthTokenModel>();
                        if (ChannelSession.Settings.StreamlabsOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.Streamlabs] = ChannelSession.Settings.StreamlabsOAuthToken;
                        }
                        if (ChannelSession.Settings.StreamElementsOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.StreamElements] = ChannelSession.Settings.StreamElementsOAuthToken;
                        }
                        if (ChannelSession.Settings.RainMakerOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.Rainmaker] = ChannelSession.Settings.RainMakerOAuthToken;
                        }
                        if (ChannelSession.Settings.TipeeeStreamOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.TipeeeStream] = ChannelSession.Settings.TipeeeStreamOAuthToken;
                        }
                        if (ChannelSession.Settings.TreatStreamOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.TreatStream] = ChannelSession.Settings.TreatStreamOAuthToken;
                        }
                        if (ChannelSession.Settings.StreamlootsOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.Streamloots] = ChannelSession.Settings.StreamlootsOAuthToken;
                        }
                        if (ChannelSession.Settings.TiltifyOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.Tiltify] = ChannelSession.Settings.TiltifyOAuthToken;
                        }
                        if (ChannelSession.Settings.JustGivingOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.JustGiving] = ChannelSession.Settings.JustGivingOAuthToken;
                        }
                        if (ChannelSession.Settings.IFTTTOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.IFTTT] = ChannelSession.Settings.IFTTTOAuthToken;
                        }
                        if (ChannelSession.Settings.ExtraLifeTeamID > 0)
                        {
                            externalServiceToConnect[ChannelSession.Services.ExtraLife] = new OAuthTokenModel();
                        }
                        if (ChannelSession.Settings.PatreonOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.Patreon] = ChannelSession.Settings.PatreonOAuthToken;
                        }
                        if (ChannelSession.Settings.DiscordOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.Discord] = ChannelSession.Settings.DiscordOAuthToken;
                        }
                        if (ChannelSession.Settings.TwitterOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.Twitter] = ChannelSession.Settings.TwitterOAuthToken;
                        }
                        if (ChannelSession.Settings.PixelChatOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.PixelChat] = ChannelSession.Settings.PixelChatOAuthToken;
                        }
                        if (ChannelSession.Settings.VTubeStudioOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.VTubeStudio] = ChannelSession.Settings.VTubeStudioOAuthToken;
                        }
                        if (ChannelSession.Settings.EnableVoicemodStudio)
                        {
                            externalServiceToConnect[ChannelSession.Services.Voicemod] = null;
                        }
                        if (ChannelSession.Services.OBSStudio.IsEnabled)
                        {
                            externalServiceToConnect[ChannelSession.Services.OBSStudio] = null;
                        }
                        if (ChannelSession.Services.StreamlabsOBS.IsEnabled)
                        {
                            externalServiceToConnect[ChannelSession.Services.StreamlabsOBS] = null;
                        }
                        if (ChannelSession.Services.XSplit.IsEnabled)
                        {
                            externalServiceToConnect[ChannelSession.Services.XSplit] = null;
                        }
                        if (!string.IsNullOrEmpty(ChannelSession.Settings.OvrStreamServerIP))
                        {
                            externalServiceToConnect[ChannelSession.Services.OvrStream] = null;
                        }
                        if (ChannelSession.Settings.EnableOverlay)
                        {
                            externalServiceToConnect[ChannelSession.Services.Overlay] = null;
                        }
                        if (ChannelSession.Settings.EnableDeveloperAPI)
                        {
                            externalServiceToConnect[ChannelSession.Services.DeveloperAPI] = null;
                        }

                        if (externalServiceToConnect.Count > 0)
                        {
                            Dictionary <IExternalService, Task <Result> > externalServiceTasks = new Dictionary <IExternalService, Task <Result> >();
                            foreach (var kvp in externalServiceToConnect)
                            {
                                Logger.Log(LogLevel.Debug, "Trying automatic OAuth service connection: " + kvp.Key.Name);

                                try
                                {
                                    if (kvp.Key is IOAuthExternalService && kvp.Value != null)
                                    {
                                        externalServiceTasks[kvp.Key] = ((IOAuthExternalService)kvp.Key).Connect(kvp.Value);
                                    }
                                    else
                                    {
                                        externalServiceTasks[kvp.Key] = kvp.Key.Connect();
                                    }
                                }
                                catch (Exception sex)
                                {
                                    Logger.Log(LogLevel.Error, "Error in external service initial connection: " + kvp.Key.Name);
                                    Logger.Log(sex);
                                }
                            }

                            try
                            {
                                await Task.WhenAll(externalServiceTasks.Values);
                            }
                            catch (Exception sex)
                            {
                                Logger.Log(LogLevel.Error, "Error in batch external service connection");
                                Logger.Log(sex);
                            }

                            List <IExternalService> failedServices = new List <IExternalService>();
                            foreach (var kvp in externalServiceTasks)
                            {
                                try
                                {
                                    if (kvp.Value.Result != null && !kvp.Value.Result.Success && kvp.Key is IOAuthExternalService)
                                    {
                                        Logger.Log(LogLevel.Debug, "Automatic OAuth token connection failed, trying manual connection: " + kvp.Key.Name);
                                        result = await kvp.Key.Connect();

                                        if (!result.Success)
                                        {
                                            failedServices.Add(kvp.Key);
                                        }
                                    }
                                }
                                catch (Exception sex)
                                {
                                    Logger.Log(LogLevel.Error, "Error in external service failed re-connection: " + kvp.Key.Name);
                                    Logger.Log(sex);
                                    failedServices.Add(kvp.Key);
                                }
                            }

                            if (failedServices.Count > 0)
                            {
                                Logger.Log(LogLevel.Debug, "Connection failed for services: " + string.Join(", ", failedServices.Select(s => s.Name)));

                                StringBuilder message = new StringBuilder();
                                message.AppendLine("The following services could not be connected:");
                                message.AppendLine();
                                foreach (IExternalService service in failedServices)
                                {
                                    message.AppendLine(" - " + service.Name);
                                }
                                message.AppendLine();
                                message.Append("We will attempt to re-connect with the service when possible. If this continues, please go to the Services page to reconnect them manually.");
                                await DialogHelper.ShowMessage(message.ToString());
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Log(ex);
                        Logger.Log(LogLevel.Error, "External Services - " + JSONSerializerHelper.SerializeToString(ex));
                        await DialogHelper.ShowMessage(Resources.FailedToInitializeExternalServices +
                                                       Environment.NewLine + Environment.NewLine + Resources.ErrorDetailsHeader + " " + ex.Message);

                        return(false);
                    }

                    try
                    {
                        ChannelSession.Services.WebhookService.BackgroundConnect();

                        foreach (CurrencyModel currency in ChannelSession.Settings.Currency.Values)
                        {
                            if (currency.ShouldBeReset())
                            {
                                await currency.Reset();
                            }
                        }

                        if (ChannelSession.Settings.ModerationResetStrikesOnLaunch)
                        {
                            foreach (UserDataModel userData in ChannelSession.Settings.UserData.Values)
                            {
                                if (userData.ModerationStrikes > 0)
                                {
                                    userData.ModerationStrikes = 0;
                                    ChannelSession.Settings.UserData.ManualValueChanged(userData.ID);
                                }
                            }
                        }

                        await ChannelSession.Services.Command.Initialize();

                        await ChannelSession.Services.Timers.Initialize();

                        await ChannelSession.Services.Moderation.Initialize();

                        IEnumerable <TwitchV5API.Users.UserModel> channelEditors = await ChannelSession.TwitchUserConnection.GetV5APIChannelEditors(ChannelSession.TwitchChannelV5);

                        if (channelEditors != null)
                        {
                            foreach (TwitchV5API.Users.UserModel channelEditor in channelEditors)
                            {
                                ChannelSession.TwitchChannelEditorsV5.Add(channelEditor.id);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Log(ex);
                        Logger.Log(LogLevel.Error, "Streamer Services - " + JSONSerializerHelper.SerializeToString(ex));
                        await DialogHelper.ShowMessage(Resources.FailedToInitializeStreamerBasedServices +
                                                       Environment.NewLine + Environment.NewLine + Resources.ErrorDetailsHeader + " " + ex.Message);

                        return(false);
                    }

                    try
                    {
                        ChannelSession.Services.Statistics.Initialize();

                        ChannelSession.Services.InputService.HotKeyPressed += InputService_HotKeyPressed;

                        foreach (RedemptionStoreProductModel product in ChannelSession.Settings.RedemptionStoreProducts.Values)
                        {
                            product.ReplenishAmount();
                        }

                        foreach (RedemptionStorePurchaseModel purchase in ChannelSession.Settings.RedemptionStorePurchases.ToList())
                        {
                            if (purchase.State != RedemptionStorePurchaseRedemptionState.ManualRedeemNeeded)
                            {
                                ChannelSession.Settings.RedemptionStorePurchases.Remove(purchase);
                            }
                        }

                        ChannelSession.Services.Telemetry.TrackLogin(ChannelSession.Settings.TelemetryUserID, ChannelSession.TwitchUserNewAPI?.broadcaster_type);

                        await ChannelSession.SaveSettings();

                        await ChannelSession.Services.Settings.SaveLocalBackup(ChannelSession.Settings);

                        if (!await ChannelSession.Services.Settings.PerformAutomaticBackupIfApplicable(ChannelSession.Settings))
                        {
                            await DialogHelper.ShowMessage(Resources.AutomaticBackupFailedToCreate);
                        }

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                        AsyncRunner.RunAsyncBackground(SessionBackgroundTask, sessionBackgroundCancellationTokenSource.Token, 60000);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                    }
                    catch (Exception ex)
                    {
                        Logger.Log(ex);
                        Logger.Log(LogLevel.Error, "Finalize Initialization - " + JSONSerializerHelper.SerializeToString(ex));
                        await DialogHelper.ShowMessage(Resources.FailedToFinalizeInitialization +
                                                       Environment.NewLine + Environment.NewLine + Resources.ErrorDetailsHeader + " " + ex.Message);

                        return(false);
                    }

                    return(true);
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                Logger.Log(LogLevel.Error, "Channel Information - " + JSONSerializerHelper.SerializeToString(ex));
                await DialogHelper.ShowMessage(Resources.FailedToGetChannelInformation +
                                               Environment.NewLine + Environment.NewLine + Resources.ErrorDetailsHeader + " " + ex.Message);
            }
            return(false);
        }
Beispiel #2
0
        public static async Task <bool> InitializeSession()
        {
            try
            {
                TwitchNewAPI.Users.UserModel twitchChannelNew = await ChannelSession.TwitchUserConnection.GetNewAPICurrentUser();

                TwitchV5API.Channel.ChannelModel twitchChannelv5 = await ChannelSession.TwitchUserConnection.GetCurrentV5APIChannel();

                if (twitchChannelNew != null && twitchChannelv5 != null)
                {
                    try
                    {
                        ChannelSession.TwitchUserNewAPI   = twitchChannelNew;
                        ChannelSession.TwitchChannelV5    = twitchChannelv5;
                        ChannelSession.TwitchStreamNewAPI = await ChannelSession.TwitchUserConnection.GetStream(ChannelSession.TwitchUserNewAPI);

                        ChannelSession.TwitchStreamV5 = await ChannelSession.TwitchUserConnection.GetV5LiveStream(ChannelSession.TwitchChannelV5);

                        IEnumerable <TwitchV5API.Users.UserModel> channelEditors = await ChannelSession.TwitchUserConnection.GetV5APIChannelEditors(ChannelSession.TwitchChannelV5);

                        if (channelEditors != null)
                        {
                            foreach (TwitchV5API.Users.UserModel channelEditor in channelEditors)
                            {
                                ChannelSession.TwitchChannelEditorsV5.Add(channelEditor.id);
                            }
                        }

                        if (ChannelSession.Settings == null)
                        {
                            IEnumerable <SettingsV3Model> currentSettings = await ChannelSession.Services.Settings.GetAllSettings();

                            if (currentSettings.Any(s => !string.IsNullOrEmpty(s.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].ChannelID) && string.Equals(s.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].ChannelID, twitchChannelNew.id)))
                            {
                                GlobalEvents.ShowMessageBox($"There already exists settings for the account {twitchChannelNew.login}. Please sign in with a different account or re-launch Mix It Up to select those settings from the drop-down.");
                                return(false);
                            }

                            ChannelSession.Settings = await ChannelSession.Services.Settings.Create(twitchChannelNew.display_name);
                        }
                        await ChannelSession.Services.Settings.Initialize(ChannelSession.Settings);

                        if (!string.IsNullOrEmpty(ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].UserID) && !string.Equals(ChannelSession.TwitchUserNewAPI.id, ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].UserID))
                        {
                            Logger.Log(LogLevel.Error, $"Signed in account does not match settings account: {ChannelSession.TwitchUserNewAPI.login} - {ChannelSession.TwitchUserNewAPI.id} - {ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].UserID}");
                            GlobalEvents.ShowMessageBox("The account you are logged in as on Twitch does not match the account for this settings. Please log in as the correct account on Twitch.");
                            ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].UserOAuthToken.accessToken  = string.Empty;
                            ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].UserOAuthToken.refreshToken = string.Empty;
                            ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].UserOAuthToken.expiresIn    = 0;
                            return(false);
                        }

                        ChannelSession.Settings.Name = ChannelSession.TwitchUserNewAPI.display_name;

                        ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].UserID    = ChannelSession.TwitchUserNewAPI.id;
                        ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].ChannelID = ChannelSession.TwitchUserNewAPI.id;
                        if (ChannelSession.TwitchBotNewAPI != null)
                        {
                            ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].BotID = ChannelSession.TwitchBotNewAPI.id;
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Log(ex);
                        Logger.Log(LogLevel.Error, "Initialize Settings - " + JSONSerializerHelper.SerializeToString(ex));
                        await DialogHelper.ShowMessage("Failed to initialize settings. If this continues, please visit the Mix It Up Discord for assistance." +
                                                       Environment.NewLine + Environment.NewLine + "Error Details: " + ex.Message);

                        return(false);
                    }

                    try
                    {
                        await ChannelSession.Services.Telemetry.Connect();

                        ChannelSession.Services.Telemetry.SetUserID(ChannelSession.Settings.TelemetryUserID);

                        TwitchChatService  twitchChatService  = new TwitchChatService();
                        TwitchEventService twitchEventService = new TwitchEventService();

                        List <Task <Result> > twitchPlatformServiceTasks = new List <Task <Result> >();
                        twitchPlatformServiceTasks.Add(twitchChatService.ConnectUser());
                        twitchPlatformServiceTasks.Add(twitchEventService.Connect());

                        await Task.WhenAll(twitchPlatformServiceTasks);

                        if (twitchPlatformServiceTasks.Any(c => !c.Result.Success))
                        {
                            string errors = string.Join(Environment.NewLine, twitchPlatformServiceTasks.Where(c => !c.Result.Success).Select(c => c.Result.Message));
                            GlobalEvents.ShowMessageBox("Failed to connect to Twitch services:" + Environment.NewLine + Environment.NewLine + errors);
                            return(false);
                        }

                        await ChannelSession.Services.Chat.Initialize(twitchChatService);

                        await ChannelSession.Services.Events.Initialize(twitchEventService);
                    }
                    catch (Exception ex)
                    {
                        Logger.Log(ex);
                        Logger.Log(LogLevel.Error, "Twitch Services - " + JSONSerializerHelper.SerializeToString(ex));
                        await DialogHelper.ShowMessage("Failed to connect to Twitch services. If this continues, please visit the Mix It Up Discord for assistance." +
                                                       Environment.NewLine + Environment.NewLine + "Error Details: " + ex.Message);

                        return(false);
                    }

                    Result result = await ChannelSession.InitializeBotInternal();

                    if (!result.Success)
                    {
                        await DialogHelper.ShowMessage("Failed to initialize Bot account");

                        return(false);
                    }

                    try
                    {
                        // Connect External Services
                        Dictionary <IExternalService, OAuthTokenModel> externalServiceToConnect = new Dictionary <IExternalService, OAuthTokenModel>();
                        if (ChannelSession.Settings.StreamlabsOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.Streamlabs] = ChannelSession.Settings.StreamlabsOAuthToken;
                        }
                        if (ChannelSession.Settings.StreamElementsOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.StreamElements] = ChannelSession.Settings.StreamElementsOAuthToken;
                        }
                        if (ChannelSession.Settings.StreamJarOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.StreamJar] = ChannelSession.Settings.StreamJarOAuthToken;
                        }
                        if (ChannelSession.Settings.TipeeeStreamOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.TipeeeStream] = ChannelSession.Settings.TipeeeStreamOAuthToken;
                        }
                        if (ChannelSession.Settings.TreatStreamOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.TreatStream] = ChannelSession.Settings.TreatStreamOAuthToken;
                        }
                        if (ChannelSession.Settings.StreamlootsOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.Streamloots] = ChannelSession.Settings.StreamlootsOAuthToken;
                        }
                        if (ChannelSession.Settings.TiltifyOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.Tiltify] = ChannelSession.Settings.TiltifyOAuthToken;
                        }
                        if (ChannelSession.Settings.JustGivingOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.JustGiving] = ChannelSession.Settings.JustGivingOAuthToken;
                        }
                        if (ChannelSession.Settings.IFTTTOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.IFTTT] = ChannelSession.Settings.IFTTTOAuthToken;
                        }
                        if (ChannelSession.Settings.ExtraLifeTeamID > 0)
                        {
                            externalServiceToConnect[ChannelSession.Services.ExtraLife] = new OAuthTokenModel();
                        }
                        if (ChannelSession.Settings.PatreonOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.Patreon] = ChannelSession.Settings.PatreonOAuthToken;
                        }
                        if (ChannelSession.Settings.DiscordOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.Discord] = ChannelSession.Settings.DiscordOAuthToken;
                        }
                        if (ChannelSession.Settings.TwitterOAuthToken != null)
                        {
                            externalServiceToConnect[ChannelSession.Services.Twitter] = ChannelSession.Settings.TwitterOAuthToken;
                        }
                        if (ChannelSession.Services.OBSStudio.IsEnabled)
                        {
                            externalServiceToConnect[ChannelSession.Services.OBSStudio] = null;
                        }
                        if (ChannelSession.Services.StreamlabsOBS.IsEnabled)
                        {
                            externalServiceToConnect[ChannelSession.Services.StreamlabsOBS] = null;
                        }
                        if (ChannelSession.Services.XSplit.IsEnabled)
                        {
                            externalServiceToConnect[ChannelSession.Services.XSplit] = null;
                        }
                        if (!string.IsNullOrEmpty(ChannelSession.Settings.OvrStreamServerIP))
                        {
                            externalServiceToConnect[ChannelSession.Services.OvrStream] = null;
                        }
                        if (ChannelSession.Settings.EnableOverlay)
                        {
                            externalServiceToConnect[ChannelSession.Services.Overlay] = null;
                        }
                        if (ChannelSession.Settings.EnableDeveloperAPI)
                        {
                            externalServiceToConnect[ChannelSession.Services.DeveloperAPI] = null;
                        }

                        if (externalServiceToConnect.Count > 0)
                        {
                            Dictionary <IExternalService, Task <Result> > externalServiceTasks = new Dictionary <IExternalService, Task <Result> >();
                            foreach (var kvp in externalServiceToConnect)
                            {
                                Logger.Log(LogLevel.Debug, "Trying automatic OAuth service connection: " + kvp.Key.Name);

                                try
                                {
                                    if (kvp.Key is IOAuthExternalService && kvp.Value != null)
                                    {
                                        externalServiceTasks[kvp.Key] = ((IOAuthExternalService)kvp.Key).Connect(kvp.Value);
                                    }
                                    else
                                    {
                                        externalServiceTasks[kvp.Key] = kvp.Key.Connect();
                                    }
                                }
                                catch (Exception sex)
                                {
                                    Logger.Log(LogLevel.Error, "Error in external service initial connection: " + kvp.Key.Name);
                                    Logger.Log(sex);
                                }
                            }

                            try
                            {
                                await Task.WhenAll(externalServiceTasks.Values);
                            }
                            catch (Exception sex)
                            {
                                Logger.Log(LogLevel.Error, "Error in batch external service connection");
                                Logger.Log(sex);
                            }

                            List <IExternalService> failedServices = new List <IExternalService>();
                            foreach (var kvp in externalServiceTasks)
                            {
                                try
                                {
                                    if (kvp.Value.Result != null && !kvp.Value.Result.Success && kvp.Key is IOAuthExternalService)
                                    {
                                        Logger.Log(LogLevel.Debug, "Automatic OAuth token connection failed, trying manual connection: " + kvp.Key.Name);
                                        result = await kvp.Key.Connect();

                                        if (!result.Success)
                                        {
                                            failedServices.Add(kvp.Key);
                                        }
                                    }
                                }
                                catch (Exception sex)
                                {
                                    Logger.Log(LogLevel.Error, "Error in external service failed re-connection: " + kvp.Key.Name);
                                    Logger.Log(sex);
                                    failedServices.Add(kvp.Key);
                                }
                            }

                            if (failedServices.Count > 0)
                            {
                                Logger.Log(LogLevel.Debug, "Connection failed for services: " + string.Join(", ", failedServices.Select(s => s.Name)));

                                StringBuilder message = new StringBuilder();
                                message.AppendLine("The following services could not be connected:");
                                message.AppendLine();
                                foreach (IExternalService service in failedServices)
                                {
                                    message.AppendLine(" - " + service.Name);
                                }
                                message.AppendLine();
                                message.Append("Please go to the Services page to reconnect them manually.");
                                await DialogHelper.ShowMessage(message.ToString());
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Log(ex);
                        Logger.Log(LogLevel.Error, "External Services - " + JSONSerializerHelper.SerializeToString(ex));
                        await DialogHelper.ShowMessage("Failed to initialize external services. If this continues, please visit the Mix It Up Discord for assistance." +
                                                       Environment.NewLine + Environment.NewLine + "Error Details: " + ex.Message);

                        return(false);
                    }

                    try
                    {
                        //if (ChannelSession.Settings.RemoteHostConnection != null)
                        //{
                        //    await ChannelSession.Services.RemoteService.InitializeConnection(ChannelSession.Settings.RemoteHostConnection);
                        //}

                        foreach (CurrencyModel currency in ChannelSession.Settings.Currency.Values)
                        {
                            if (currency.ShouldBeReset())
                            {
                                await currency.Reset();
                            }
                        }

                        if (ChannelSession.Settings.ModerationResetStrikesOnLaunch)
                        {
                            foreach (UserDataModel userData in ChannelSession.Settings.UserData.Values)
                            {
                                if (userData.ModerationStrikes > 0)
                                {
                                    userData.ModerationStrikes = 0;
                                    ChannelSession.Settings.UserData.ManualValueChanged(userData.ID);
                                }
                            }
                        }

                        ChannelSession.PreMadeChatCommands.Clear();
                        foreach (PreMadeChatCommandModelBase command in ReflectionHelper.CreateInstancesOfImplementingType <PreMadeChatCommandModelBase>())
                        {
                            ChannelSession.PreMadeChatCommands.Add(command);
                        }

                        foreach (PreMadeChatCommandSettingsModel commandSetting in ChannelSession.Settings.PreMadeChatCommandSettings)
                        {
                            PreMadeChatCommandModelBase command = ChannelSession.PreMadeChatCommands.FirstOrDefault(c => c.Name.Equals(commandSetting.Name));
                            if (command != null)
                            {
                                command.UpdateFromSettings(commandSetting);
                            }
                        }
                        ChannelSession.Services.Chat.RebuildCommandTriggers();

                        await ChannelSession.Services.Timers.Initialize();

                        await ChannelSession.Services.Moderation.Initialize();
                    }
                    catch (Exception ex)
                    {
                        Logger.Log(ex);
                        Logger.Log(LogLevel.Error, "Streamer Services - " + JSONSerializerHelper.SerializeToString(ex));
                        await DialogHelper.ShowMessage("Failed to initialize streamer-based services. If this continues, please visit the Mix It Up Discord for assistance." +
                                                       Environment.NewLine + Environment.NewLine + "Error Details: " + ex.Message);

                        return(false);
                    }

                    try
                    {
                        ChannelSession.Services.Statistics.Initialize();

                        ChannelSession.Services.InputService.HotKeyPressed += InputService_HotKeyPressed;

                        foreach (RedemptionStoreProductModel product in ChannelSession.Settings.RedemptionStoreProducts.Values)
                        {
                            product.ReplenishAmount();
                        }

                        foreach (RedemptionStorePurchaseModel purchase in ChannelSession.Settings.RedemptionStorePurchases.ToList())
                        {
                            if (purchase.State != RedemptionStorePurchaseRedemptionState.ManualRedeemNeeded)
                            {
                                ChannelSession.Settings.RedemptionStorePurchases.Remove(purchase);
                            }
                        }

                        ChannelSession.Services.Telemetry.TrackLogin(ChannelSession.Settings.TelemetryUserID, ChannelSession.TwitchUserNewAPI?.broadcaster_type);

                        await ChannelSession.SaveSettings();

                        await ChannelSession.Services.Settings.SaveLocalBackup(ChannelSession.Settings);

                        await ChannelSession.Services.Settings.PerformAutomaticBackupIfApplicable(ChannelSession.Settings);

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                        AsyncRunner.RunAsyncBackground(SessionBackgroundTask, sessionBackgroundCancellationTokenSource.Token, 60000);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                    }
                    catch (Exception ex)
                    {
                        Logger.Log(ex);
                        Logger.Log(LogLevel.Error, "Finalize Initialization - " + JSONSerializerHelper.SerializeToString(ex));
                        await DialogHelper.ShowMessage("Failed to finalize initialization. If this continues, please visit the Mix It Up Discord for assistance." +
                                                       Environment.NewLine + Environment.NewLine + "Error Details: " + ex.Message);

                        return(false);
                    }

                    return(true);
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                Logger.Log(LogLevel.Error, "Channel Information - " + JSONSerializerHelper.SerializeToString(ex));
                await DialogHelper.ShowMessage("Failed to get channel information. If this continues, please visit the Mix It Up Discord for assistance." +
                                               Environment.NewLine + Environment.NewLine + "Error Details: " + ex.Message);
            }
            return(false);
        }