示例#1
0
        private void Arrange()
        {
            var random = new Random();

            _localChannelNumber           = (uint)random.Next(0, int.MaxValue);
            _localWindowSize              = (uint)random.Next(2000, 3000);
            _localPacketSize              = (uint)random.Next(1000, 2000);
            _initialSessionSemaphoreCount = random.Next(10, 20);
            _sessionSemaphore             = new SemaphoreLight(_initialSessionSemaphoreCount);
            _channelClosedRegister        = new List <ChannelEventArgs>();
            _channelExceptionRegister     = new List <ExceptionEventArgs>();
            _waitOnConfirmationException  = new SystemException();

            _sessionMock        = new Mock <ISession>(MockBehavior.Strict);
            _connectionInfoMock = new Mock <IConnectionInfo>(MockBehavior.Strict);

            var sequence = new MockSequence();

            _sessionMock.InSequence(sequence).Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object);
            _connectionInfoMock.InSequence(sequence).Setup(p => p.RetryAttempts).Returns(2);
            _sessionMock.Setup(p => p.SessionSemaphore).Returns(_sessionSemaphore);
            _sessionMock.InSequence(sequence)
            .Setup(
                p =>
                p.SendMessage(
                    It.Is <ChannelOpenMessage>(
                        m =>
                        m.LocalChannelNumber == _localChannelNumber &&
                        m.InitialWindowSize == _localWindowSize && m.MaximumPacketSize == _localPacketSize &&
                        m.Info is SessionChannelOpenInfo)));
            _sessionMock.InSequence(sequence)
            .Setup(p => p.WaitOnHandle(It.IsNotNull <WaitHandle>()))
            .Throws(_waitOnConfirmationException);

            _channel            = new ChannelSession(_sessionMock.Object, _localChannelNumber, _localWindowSize, _localPacketSize);
            _channel.Closed    += (sender, args) => _channelClosedRegister.Add(args);
            _channel.Exception += (sender, args) => _channelExceptionRegister.Add(args);
        }
示例#2
0
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!this._isDisposed)
            {
                if (this._channel != null)
                {
                    this._channel.DataReceived -= Channel_DataReceived;
                    this._channel.Closed       -= Channel_Closed;
                    this._channel.Dispose();
                    this._channel = null;
                }

                this._session.ErrorOccured -= Session_ErrorOccured;
                this._session.Disconnected -= Session_Disconnected;

                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing)
                {
                    // Dispose managed resources.
                    if (this._errorOccuredWaitHandle != null)
                    {
                        this._errorOccuredWaitHandle.Dispose();
                        this._errorOccuredWaitHandle = null;
                    }

                    if (this._channelClosedWaitHandle != null)
                    {
                        this._channelClosedWaitHandle.Dispose();
                        this._channelClosedWaitHandle = null;
                    }
                }

                // Note disposing has been done.
                _isDisposed = true;
            }
        }
示例#3
0
        private void Channel_Closed(object sender, ChannelEventArgs e)
        {
            if (this.Stopping != null)
            {
                //  Handle event on different thread
                this.ExecuteThread(() => this.Stopping(this, new EventArgs()));
            }

            if (this._channel.IsOpen)
            {
                this._channel.SendEof();

                this._channel.Close();
            }

            this._channelClosedWaitHandle.Set();

            this._input.Dispose();
            this._input = null;

            this._dataReaderTaskCompleted.WaitOne(this._session.ConnectionInfo.Timeout);
            this._dataReaderTaskCompleted.Dispose();
            this._dataReaderTaskCompleted = null;

            this._channel.DataReceived         -= Channel_DataReceived;
            this._channel.ExtendedDataReceived -= Channel_ExtendedDataReceived;
            this._channel.Closed       -= Channel_Closed;
            this._session.Disconnected -= Session_Disconnected;
            this._session.ErrorOccured -= Session_ErrorOccured;

            if (this.Stopped != null)
            {
                //  Handle event on different thread
                this.ExecuteThread(() => this.Stopped(this, new EventArgs()));
            }

            this._channel = null;
        }
示例#4
0
        private async void ConnectRemoteButton_Click(object sender, RoutedEventArgs e)
        {
            await this.Window.RunAsyncOperation(async() =>
            {
                await ChannelSession.SaveSettings();

                this.remoteService = new RemoteService();

                this.remoteService.OnDisconnectOccurred += RemoteService_OnDisconnectOccurred;
                this.remoteService.OnAuthRequest        += RemoteService_OnAuthRequest;
                this.remoteService.OnNewAccessCode      += RemoteService_OnNewAccessCode;
                this.remoteService.OnBoardRequest       += RemoteService_OnBoardRequest;
                this.remoteService.OnActionRequest      += RemoteService_OnActionRequest;

                await this.remoteService.Connect();

                this.BoardSetupGrid.Visibility      = Visibility.Collapsed;
                this.ConnectToDeviceGrid.Visibility = Visibility.Visible;

                this.AccessCodeTextBlock.Text   = this.remoteService.AccessCode;
                this.RemoteEventsTextBlock.Text = string.Empty;
            });
        }
        public override async Task CustomRun(CommandParametersModel parameters)
        {
            await ChannelSession.RefreshChannel();

            if (ChannelSession.TwitchChannelV5 != null)
            {
                GameInformation details = await XboxGamePreMadeChatCommandModel.GetXboxGameInfo(ChannelSession.TwitchChannelV5.game);

                if (details == null)
                {
                    details = await SteamGamePreMadeChatCommandModel.GetSteamGameInfo(ChannelSession.TwitchChannelV5.game);
                }

                if (details != null)
                {
                    await ChannelSession.Services.Chat.SendMessage(details.ToString());
                }
                else
                {
                    await ChannelSession.Services.Chat.SendMessage("Game: " + ChannelSession.TwitchChannelV5.game);
                }
            }
        }
示例#6
0
        protected override void OnStartup(StartupEventArgs e)
        {
            App.AppSettings = ApplicationSettings.Load();
            this.SwitchTheme(App.AppSettings.ColorScheme, App.AppSettings.ThemeName, App.AppSettings.IsDarkColoring);

            LocalizationHandler.SetCurrentLanguage(App.AppSettings.Language);

            DesktopServicesHandler desktopServicesHandler = new DesktopServicesHandler();

            desktopServicesHandler.Initialize();

            Logger.Initialize(desktopServicesHandler.FileService);
            SerializerHelper.Initialize(desktopServicesHandler.FileService);

            Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException       += CurrentDomain_UnhandledException;

            ChannelSession.Initialize(desktopServicesHandler);

            Logger.Log("Application Version: " + ChannelSession.Services.FileService.GetApplicationVersion());

            base.OnStartup(e);
        }
示例#7
0
        protected override void OnStartup(StartupEventArgs e)
        {
            if (Settings.Default.DarkTheme)
            {
                this.SwitchTheme(isDark: true);
            }

            DesktopServicesHandler desktopServicesHandler = new DesktopServicesHandler();

            desktopServicesHandler.Initialize();

            Logger.Initialize(desktopServicesHandler.FileService);
            SerializerHelper.Initialize(desktopServicesHandler.FileService);

            Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException       += CurrentDomain_UnhandledException;

            ChannelSession.Initialize(desktopServicesHandler);

            Logger.Log("Application Version: " + Assembly.GetEntryAssembly().GetName().Version.ToString());

            base.OnStartup(e);
        }
示例#8
0
        public App()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            try
            {
                // We need to load the language setting VERY early, so this is the minimal code necessary to get this value
                WindowsServicesManager servicesManager = new WindowsServicesManager();
                servicesManager.Initialize();
                ChannelSession.Initialize(servicesManager).Wait();
                var selectedLanguageTask = ApplicationSettingsV2Model.Load();
                selectedLanguageTask.Wait();

                var culture = System.Threading.Thread.CurrentThread.CurrentCulture;
                if (LanguageMaps.TryGetValue(selectedLanguageTask.Result.LanguageOption, out string locale))
                {
                    culture = new System.Globalization.CultureInfo(locale);
                }

                System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
            }
            catch { }
        }
示例#9
0
        private async Task ChannelRefreshBackground()
        {
            await BackgroundTaskWrapper.RunBackgroundTask(this.backgroundThreadCancellationTokenSource, async (tokenSource) =>
            {
                tokenSource.Token.ThrowIfCancellationRequested();

                await ChannelSession.RefreshChannel();
                await Task.Delay(30000);

                tokenSource.Token.ThrowIfCancellationRequested();

                await ChannelSession.RefreshChannel();
                await Task.Delay(30000);

                tokenSource.Token.ThrowIfCancellationRequested();

                List <UserCurrencyViewModel> currenciesToUpdate = new List <UserCurrencyViewModel>();
                foreach (UserCurrencyViewModel currency in ChannelSession.Settings.Currencies.Values)
                {
                    if (currency.IsActive)
                    {
                        currenciesToUpdate.Add(currency);
                    }
                }

                foreach (UserViewModel user in await ChannelSession.ChannelUsers.GetAllWorkableUsers())
                {
                    user.UpdateMinuteUserData(currenciesToUpdate);
                }

                await ChannelSession.SaveSettings();

                tokenSource.Token.ThrowIfCancellationRequested();

                await ChannelSession.SaveSettings();
            });
        }
示例#10
0
        /// <summary>
        /// Starts this shell.
        /// </summary>
        /// <exception cref="SshException">Shell is started.</exception>
        public void Start()
        {
            if (this.IsStarted)
            {
                throw new SshException("Shell is started.");
            }

            if (this.Starting != null)
            {
                this.Starting(this, new EventArgs());
            }

            this._channel = this._session.CreateChannel <ChannelSession>();
            this._channel.DataReceived         += Channel_DataReceived;
            this._channel.ExtendedDataReceived += Channel_ExtendedDataReceived;
            this._channel.Closed       += Channel_Closed;
            this._session.Disconnected += Session_Disconnected;
            this._session.ErrorOccured += Session_ErrorOccured;

            this._channel.Open();
            //  TODO:   Terminal mode is ignored as this functionality will be obsolete
            this._channel.SendPseudoTerminalRequest(this._terminalName, this._columns, this._rows, this._width, this._height);
            this._channel.SendShellRequest();

            this._channelClosedWaitHandle = new AutoResetEvent(false);

            //  Start input stream listener
            this._dataReaderTaskCompleted = new ManualResetEvent(false);
            this.ExecuteThread(_channel.GetReaderAction(_bufferSize, _input, RaiseError, _dataReaderTaskCompleted));

            this.IsStarted = true;

            if (this.Started != null)
            {
                this.Started(this, new EventArgs());
            }
        }
        private async void AddPreMadeGameButton_Click(object sender, RoutedEventArgs e)
        {
            if (this.PreMadeGamesComboBox.SelectedIndex >= 0)
            {
                await this.Window.RunAsyncOperation(async() =>
                {
                    string gameName = (string)this.PreMadeGamesComboBox.SelectedItem;
                    if (ChannelSession.Settings.GameCommands.Any(c => c.Name.Equals(gameName)))
                    {
                        await MessageBoxHelper.ShowMessageDialog("This game already exist in your game list");
                        return;
                    }

                    UserCurrencyViewModel currency = ChannelSession.Settings.Currencies.Values.First();
                    GameCommandBase game           = null;
                    switch (gameName)
                    {
                    case "Spin Wheel": game = new SpinWheelGameCommand(currency); break;

                    case "Heist": game = new HeistGameCommand(currency); break;

                    case "Russian Roulette": game = new RussianRouletteGameCommand(currency); break;

                    case "Charity": game = new CharityGameCommand(currency); break;

                    case "Give": game = new GiveGameCommand(currency); break;
                    }

                    ChannelSession.Settings.GameCommands.Add(game);
                    await ChannelSession.SaveSettings();

                    this.PreMadeGamesComboBox.SelectedIndex = -1;

                    this.RefreshList();
                });
            }
        }
        public override async Task CustomRun(CommandParametersModel parameters)
        {
            if (ChannelSession.Settings.QuotesEnabled)
            {
                if (parameters.Arguments.Count() > 0)
                {
                    StringBuilder quoteBuilder = new StringBuilder();
                    foreach (string arg in parameters.Arguments)
                    {
                        quoteBuilder.Append(arg + " ");
                    }

                    string quoteText = quoteBuilder.ToString();
                    quoteText = quoteText.Trim(new char[] { ' ', '\'', '\"' });

                    UserQuoteModel quote = new UserQuoteModel(UserQuoteViewModel.GetNextQuoteNumber(), quoteText, DateTimeOffset.Now, ChannelSession.TwitchChannelV5?.game);
                    ChannelSession.Settings.Quotes.Add(quote);
                    await ChannelSession.SaveSettings();

                    GlobalEvents.QuoteAdded(quote);

                    if (ChannelSession.Services.Chat != null)
                    {
                        await ChannelSession.Services.Chat.SendMessage("Added " + quote.ToString());
                    }
                }
                else
                {
                    await ChannelSession.Services.Chat.SendMessage("Usage: !addquote <FULL QUOTE TEXT>");
                }
            }
            else
            {
                await ChannelSession.Services.Chat.SendMessage("Quotes must be enabled with Mix It Up for this feature to work");
            }
        }
示例#13
0
        public async Task <Quote> Add([FromBody] AddQuote quote)
        {
            if (quote == null || quote.QuoteText.IsNullOrEmpty())
            {
                var resp = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new ObjectContent <Error>(new Error {
                        Message = $"Unable to create quote, no QuoteText was supplied."
                    }, new JsonMediaTypeFormatter(), "application/json"),
                    ReasonPhrase = "QuoteText not specified"
                };
                throw new HttpResponseException(resp);
            }

            var quoteText = quote.QuoteText.Trim(new char[] { ' ', '\'', '\"' });
            UserQuoteViewModel newQuote = new UserQuoteViewModel(quoteText, DateTimeOffset.Now, ChannelSession.TwitchChannelV5?.game);

            ChannelSession.Settings.Quotes.Add(newQuote);
            await ChannelSession.SaveSettings();

            GlobalEvents.QuoteAdded(newQuote);

            return(QuoteFromUserQuoteViewModel(newQuote));
        }
示例#14
0
        public async Task PerformEvent(EventTrigger trigger)
        {
            if (this.CanPerformEvent(trigger))
            {
                UserViewModel user = trigger.User;
                if (user == null)
                {
                    user = ChannelSession.GetCurrentUser();
                }

                if (this.userEventTracking.ContainsKey(trigger.Type))
                {
                    this.userEventTracking[trigger.Type].Add(user.ID);
                }

                EventCommand command = this.GetEventCommand(trigger.Type);
                if (command != null)
                {
                    Logger.Log(LogLevel.Debug, $"Performing event trigger: {trigger.Type}");

                    await command.Perform(user, platform : trigger.Platform, arguments : trigger.Arguments, extraSpecialIdentifiers : trigger.SpecialIdentifiers);
                }
            }
        }
示例#15
0
        public SetAudienceChatCommand()
            : base("Set Audience", "setaudience", 5, MixerRoleEnum.Mod)
        {
            this.Actions.Add(new CustomAction(async(UserViewModel user, IEnumerable <string> arguments) =>
            {
                if (ChannelSession.Chat != null)
                {
                    if (arguments.Count() == 1)
                    {
                        string rating = arguments.ElementAt(0);
                        rating        = rating.ToLower().Replace(AdultSettings, Adult18PlusSetting);
                        if (rating.Equals(FamilySetting) || rating.Equals(TeenSetting) || rating.Equals(Adult18PlusSetting))
                        {
                            await ChannelSession.Connection.UpdateChannel(ChannelSession.Channel.id, ageRating: rating);
                            await ChannelSession.RefreshChannel();

                            return;
                        }
                    }

                    await ChannelSession.Chat.Whisper(user.UserName, "Usage: !setaudience family|teen|adult");
                }
            }));
        }
        private async void BotLogInButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            bool result = await this.RunAsyncOperation(async() =>
            {
                return(await ChannelSession.ConnectBot((OAuthShortCodeModel shortCode) =>
                {
                    this.BotLoginShortCodeTextBox.Text = shortCode.code;

                    Process.Start("https://mixer.com/oauth/shortcode?approval_prompt=force&code=" + shortCode.code);
                }));
            });

            if (result)
            {
                this.BotLoggedInNameTextBlock.Text = ChannelSession.BotUser.username;
                if (!string.IsNullOrEmpty(ChannelSession.BotUser.avatarUrl))
                {
                    this.BotProfileAvatar.SetImageUrl(ChannelSession.BotUser.avatarUrl);
                }

                this.BotLogInGrid.Visibility    = System.Windows.Visibility.Hidden;
                this.BotLoggedInGrid.Visibility = System.Windows.Visibility.Visible;
            }
        }
示例#17
0
        public async Task Save()
        {
            if (this.IsNew)
            {
                this.StreamPass = new StreamPassModel();
                ChannelSession.Settings.StreamPass[this.StreamPass.ID] = this.StreamPass;
            }

            this.StreamPass.Name = this.Name;
            this.StreamPass.SpecialIdentifier = SpecialIdentifierStringBuilder.ConvertToSpecialIdentifier(this.Name, maxLength: 15);
            this.StreamPass.Permission        = this.Permission;
            this.StreamPass.MaxLevel          = this.MaxLevel;
            this.StreamPass.PointsForLevelUp  = this.PointsForLevelUp;
            this.StreamPass.SubMultiplier     = this.SubMultiplier;

            this.StreamPass.StartDate = this.StartDate;
            this.StreamPass.EndDate   = this.EndDate;

            this.StreamPass.ViewingRateAmount  = this.ViewingRateAmount;
            this.StreamPass.ViewingRateMinutes = this.ViewingRateMinutes;
            this.StreamPass.MinimumActiveRate  = this.MinimumActiveRate;
            this.StreamPass.FollowBonus        = this.FollowBonus;
            this.StreamPass.HostBonus          = this.HostBonus;
            this.StreamPass.SubscribeBonus     = this.SubscribeBonus;
            this.StreamPass.DonationBonus      = this.DonationBonus;
            this.StreamPass.BitsBonus          = this.BitsBonus;

            this.StreamPass.DefaultLevelUpCommand = this.DefaultLevelUpCommand;
            this.StreamPass.CustomLevelUpCommands.Clear();
            foreach (StreamPassCustomLevelUpCommandViewModel customCommand in this.CustomLevelUpCommands)
            {
                this.StreamPass.CustomLevelUpCommands[customCommand.Level] = customCommand.CommandID;
            }

            await ChannelSession.SaveSettings();
        }
示例#18
0
        /// <summary>
        /// Waits for the pending asynchronous command execution to complete.
        /// </summary>
        /// <param name="asyncResult">The reference to the pending asynchronous request to finish.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentException">Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.</exception>
        public string EndExecute(IAsyncResult asyncResult)
        {
            if (this._asyncResult == asyncResult && this._asyncResult != null)
            {
                lock (this._endExecuteLock)
                {
                    if (this._asyncResult != null)
                    {
                        //  Make sure that operation completed if not wait for it to finish
                        this.WaitHandle(this._asyncResult.AsyncWaitHandle);

                        this._channel.Close();

                        this._channel = null;

                        this._asyncResult = null;

                        return(this.Result);
                    }
                }
            }

            throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.");
        }
示例#19
0
        private async void GroupDeleteButton_Click(object sender, RoutedEventArgs e)
        {
            if (this.GroupNameComboBox.SelectedIndex >= 0)
            {
                await this.Window.RunAsyncOperation(async() =>
                {
                    if (this.groups.Count > 1)
                    {
                        if (await MessageBoxHelper.ShowConfirmationDialog("Are you sure you wish to delete this group?"))
                        {
                            RemoteBoardGroupModel group = (RemoteBoardGroupModel)this.GroupNameComboBox.SelectedItem;
                            this.CurrentBoard.Groups.Remove(group);
                            await ChannelSession.SaveSettings();

                            this.RefreshBoardsView();
                        }
                    }
                    else
                    {
                        await MessageBoxHelper.ShowMessageDialog("All boards must have at least 1 group");
                    }
                });
            }
        }
        private async void SaveButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            await this.RunAsyncOperation(async() =>
            {
                if (string.IsNullOrEmpty(this.NameTextBox.Text))
                {
                    await MessageBoxHelper.ShowMessageDialog(string.Format("A {0} name must be specified", this.CurrencyRankIdentifierString));
                    return;
                }

                if (this.NameTextBox.Text.Any(c => char.IsDigit(c)))
                {
                    await MessageBoxHelper.ShowMessageDialog("The name can not contain any number digits in it");
                    return;
                }

                UserCurrencyViewModel dupeCurrency = ChannelSession.Settings.Currencies.Values.FirstOrDefault(c => c.Name.Equals(this.NameTextBox.Text));
                if (dupeCurrency != null && (this.currency == null || !this.currency.ID.Equals(dupeCurrency.ID)))
                {
                    await MessageBoxHelper.ShowMessageDialog("There already exists a currency or rank system with this name");
                    return;
                }

                UserInventoryViewModel dupeInventory = ChannelSession.Settings.Inventories.Values.FirstOrDefault(c => c.Name.Equals(this.NameTextBox.Text));
                if (dupeInventory != null)
                {
                    await MessageBoxHelper.ShowMessageDialog("There already exists an inventory with this name");
                    return;
                }

                string siName = SpecialIdentifierStringBuilder.ConvertToSpecialIdentifier(this.NameTextBox.Text);

                if (siName.Equals("time") || siName.Equals("hours") || siName.Equals("mins") || siName.Equals("sparks") || siName.Equals("embers"))
                {
                    await MessageBoxHelper.ShowMessageDialog("This name is reserved and can not be used");
                    return;
                }

                int maxAmount = int.MaxValue;
                if (!string.IsNullOrEmpty(this.MaxAmountTextBox.Text))
                {
                    if (!int.TryParse(this.MaxAmountTextBox.Text, out maxAmount) || maxAmount <= 0)
                    {
                        await MessageBoxHelper.ShowMessageDialog("The max amount must be greater than 0 or can be left empty for no max amount");
                        return;
                    }
                }

                if (string.IsNullOrEmpty(this.OnlineAmountRateTextBox.Text) || !int.TryParse(this.OnlineAmountRateTextBox.Text, out int onlineAmount) || onlineAmount < 0)
                {
                    await MessageBoxHelper.ShowMessageDialog("The online amount must be 0 or greater");
                    return;
                }

                if (string.IsNullOrEmpty(this.OnlineTimeRateTextBox.Text) || !int.TryParse(this.OnlineTimeRateTextBox.Text, out int onlineTime) || onlineTime < 0)
                {
                    await MessageBoxHelper.ShowMessageDialog("The online minutes must be 0 or greater");
                    return;
                }

                if (string.IsNullOrEmpty(this.OfflineAmountRateTextBox.Text) || !int.TryParse(this.OfflineAmountRateTextBox.Text, out int offlineAmount) || offlineAmount < 0)
                {
                    await MessageBoxHelper.ShowMessageDialog("The offline amount must be 0 or greater");
                    return;
                }

                if (string.IsNullOrEmpty(this.OfflineTimeRateTextBox.Text) || !int.TryParse(this.OfflineTimeRateTextBox.Text, out int offlineTime) || offlineTime < 0)
                {
                    await MessageBoxHelper.ShowMessageDialog("The offline minutes must be 0 or greater");
                    return;
                }

                if (onlineAmount > 0 && onlineTime == 0)
                {
                    await MessageBoxHelper.ShowMessageDialog("The online time can not be 0 if the online amount is greater than 0");
                    return;
                }

                if (offlineAmount > 0 && offlineTime == 0)
                {
                    await MessageBoxHelper.ShowMessageDialog("The offline time can not be 0 if the offline amount is greater than 0");
                    return;
                }

                int subscriberBonus = 0;
                if (string.IsNullOrEmpty(this.SubscriberBonusTextBox.Text) || !int.TryParse(this.SubscriberBonusTextBox.Text, out subscriberBonus) || subscriberBonus < 0)
                {
                    await MessageBoxHelper.ShowMessageDialog("The Subscriber bonus must be 0 or greater");
                    return;
                }

                int modBonus = 0;
                if (string.IsNullOrEmpty(this.ModeratorBonusTextBox.Text) || !int.TryParse(this.ModeratorBonusTextBox.Text, out modBonus) || modBonus < 0)
                {
                    await MessageBoxHelper.ShowMessageDialog("The Moderator bonus must be 0 or greater");
                    return;
                }

                int onFollowBonus = 0;
                if (string.IsNullOrEmpty(this.OnFollowBonusTextBox.Text) || !int.TryParse(this.OnFollowBonusTextBox.Text, out onFollowBonus) || onFollowBonus < 0)
                {
                    await MessageBoxHelper.ShowMessageDialog("The On Follow bonus must be 0 or greater");
                    return;
                }

                int onHostBonus = 0;
                if (string.IsNullOrEmpty(this.OnHostBonusTextBox.Text) || !int.TryParse(this.OnHostBonusTextBox.Text, out onHostBonus) || onHostBonus < 0)
                {
                    await MessageBoxHelper.ShowMessageDialog("The On Host bonus must be 0 or greater");
                    return;
                }

                int onSubscribeBonus = 0;
                if (string.IsNullOrEmpty(this.OnSubscribeBonusTextBox.Text) || !int.TryParse(this.OnSubscribeBonusTextBox.Text, out onSubscribeBonus) || onSubscribeBonus < 0)
                {
                    await MessageBoxHelper.ShowMessageDialog("The On Subscribe bonus must be 0 or greater");
                    return;
                }

                if (this.IsRankToggleButton.IsChecked.GetValueOrDefault())
                {
                    if (this.ranks.Count() < 1)
                    {
                        await MessageBoxHelper.ShowMessageDialog("At least one rank must be created");
                        return;
                    }
                }

                int minActivityRate = 0;
                if (string.IsNullOrEmpty(this.MinimumActivityRateTextBox.Text) || !int.TryParse(this.MinimumActivityRateTextBox.Text, out minActivityRate) || minActivityRate < 0)
                {
                    await MessageBoxHelper.ShowMessageDialog("The Minimum Activity Rate must be 0 or greater");
                    return;
                }

                bool isNew = false;
                if (this.currency == null)
                {
                    isNew         = true;
                    this.currency = new UserCurrencyViewModel();
                    ChannelSession.Settings.Currencies[this.currency.ID] = this.currency;
                }

                CurrencyAcquireRateTypeEnum acquireRate = CurrencyAcquireRateTypeEnum.Custom;
                if (this.OnlineRateComboBox.SelectedIndex >= 0)
                {
                    acquireRate = EnumHelper.GetEnumValueFromString <CurrencyAcquireRateTypeEnum>((string)this.OnlineRateComboBox.SelectedItem);
                }

                this.currency.IsTrackingSparks = false;
                this.currency.IsTrackingEmbers = false;
                if (acquireRate == CurrencyAcquireRateTypeEnum.Sparks)
                {
                    this.currency.IsTrackingSparks = true;
                }
                else if (acquireRate == CurrencyAcquireRateTypeEnum.Embers)
                {
                    this.currency.IsTrackingEmbers = true;
                }

                this.currency.Name      = this.NameTextBox.Text;
                this.currency.MaxAmount = maxAmount;

                this.currency.AcquireAmount          = onlineAmount;
                this.currency.AcquireInterval        = onlineTime;
                this.currency.OfflineAcquireAmount   = offlineAmount;
                this.currency.OfflineAcquireInterval = offlineTime;

                this.currency.SubscriberBonus  = subscriberBonus;
                this.currency.ModeratorBonus   = modBonus;
                this.currency.OnFollowBonus    = onFollowBonus;
                this.currency.OnHostBonus      = onHostBonus;
                this.currency.OnSubscribeBonus = onSubscribeBonus;

                this.currency.MinimumActiveRate = minActivityRate;
                this.currency.ResetInterval     = EnumHelper.GetEnumValueFromString <CurrencyResetRateEnum>((string)this.AutomaticResetComboBox.SelectedItem);

                this.currency.SpecialIdentifier = SpecialIdentifierStringBuilder.ConvertToSpecialIdentifier(this.currency.Name);

                if (this.IsRankToggleButton.IsChecked.GetValueOrDefault())
                {
                    this.currency.Ranks = ranks.ToList();
                    this.currency.RankChangedCommand = this.rankChangedCommand;
                }
                else
                {
                    this.currency.Ranks = new List <UserRankViewModel>();
                    this.currency.RankChangedCommand = null;
                }

                foreach (var otherCurrencies in ChannelSession.Settings.Currencies)
                {
                    if (otherCurrencies.Value.IsRank == this.currency.IsRank)
                    {
                        // Turn off primary for all other currencies/ranks of the same kind
                        otherCurrencies.Value.IsPrimary = false;
                    }
                }
                this.currency.IsPrimary = this.IsPrimaryToggleButton.IsChecked.GetValueOrDefault();

                await ChannelSession.SaveSettings();

                if (isNew)
                {
                    List <NewCurrencyRankCommand> commandsToAdd = new List <NewCurrencyRankCommand>();

                    ChatCommand statusCommand = new ChatCommand("User " + this.currency.Name, this.currency.SpecialIdentifier, new RequirementViewModel(MixerRoleEnum.User, 5));
                    string statusChatText     = string.Empty;
                    if (this.currency.IsRank)
                    {
                        statusChatText = string.Format("@$username is a ${0} with ${1} {2}!", this.currency.UserRankNameSpecialIdentifier, this.currency.UserAmountSpecialIdentifier, this.currency.Name);
                    }
                    else
                    {
                        statusChatText = string.Format("@$username has ${0} {1}!", this.currency.UserAmountSpecialIdentifier, this.currency.Name);
                    }
                    statusCommand.Actions.Add(new ChatAction(statusChatText));
                    commandsToAdd.Add(new NewCurrencyRankCommand(string.Format("!{0} - {1}", statusCommand.Commands.First(), "Shows User's Amount"), statusCommand));

                    if (!this.currency.IsTrackingSparks && !this.currency.IsTrackingEmbers)
                    {
                        ChatCommand addCommand = new ChatCommand("Add " + this.currency.Name, "add" + this.currency.SpecialIdentifier, new RequirementViewModel(MixerRoleEnum.Mod, 5));
                        addCommand.Actions.Add(new CurrencyAction(this.currency, CurrencyActionTypeEnum.AddToSpecificUser, "$arg2text", username: "******"));
                        addCommand.Actions.Add(new ChatAction(string.Format("@$targetusername received $arg2text {0}!", this.currency.Name)));
                        commandsToAdd.Add(new NewCurrencyRankCommand(string.Format("!{0} - {1}", addCommand.Commands.First(), "Adds Amount To Specified User"), addCommand));

                        ChatCommand addAllCommand = new ChatCommand("Add All " + this.currency.Name, "addall" + this.currency.SpecialIdentifier, new RequirementViewModel(MixerRoleEnum.Mod, 5));
                        addAllCommand.Actions.Add(new CurrencyAction(this.currency, CurrencyActionTypeEnum.AddToAllChatUsers, "$arg1text"));
                        addAllCommand.Actions.Add(new ChatAction(string.Format("Everyone got $arg1text {0}!", this.currency.Name)));
                        commandsToAdd.Add(new NewCurrencyRankCommand(string.Format("!{0} - {1}", addAllCommand.Commands.First(), "Adds Amount To All Chat Users"), addAllCommand));

                        if (!this.currency.IsRank)
                        {
                            ChatCommand giveCommand = new ChatCommand("Give " + this.currency.Name, "give" + this.currency.SpecialIdentifier, new RequirementViewModel(MixerRoleEnum.User, 5));
                            giveCommand.Actions.Add(new CurrencyAction(this.currency, CurrencyActionTypeEnum.AddToSpecificUser, "$arg2text", username: "******", deductFromUser: true));
                            giveCommand.Actions.Add(new ChatAction(string.Format("@$username gave @$targetusername $arg2text {0}!", this.currency.Name)));
                            commandsToAdd.Add(new NewCurrencyRankCommand(string.Format("!{0} - {1}", giveCommand.Commands.First(), "Gives Amount To Specified User"), giveCommand));
                        }
                    }

                    NewCurrencyRankCommandsDialogControl dControl = new NewCurrencyRankCommandsDialogControl(this.currency, commandsToAdd);
                    string result = await MessageBoxHelper.ShowCustomDialog(dControl);
                    if (!string.IsNullOrEmpty(result) && result.Equals("True"))
                    {
                        foreach (NewCurrencyRankCommand command in dControl.commands)
                        {
                            if (command.AddCommand)
                            {
                                ChannelSession.Settings.ChatCommands.Add(command.Command);
                            }
                        }
                    }
                }

                this.Close();
            });
        }
示例#21
0
        public CommandEditorWindowViewModelBase(CommandTypeEnum type)
        {
            this.Type = type;

            this.SaveCommand = this.CreateCommand(async(parameter) =>
            {
                CommandModelBase command = await this.ValidateAndBuildCommand();
                if (command != null)
                {
                    if (!command.IsEmbedded)
                    {
                        ChannelSession.Settings.SetCommand(command);
                        await ChannelSession.SaveSettings();
                    }
                    await this.SaveCommandToSettings(command);
                    this.CommandSaved(this, command);
                }
            });

            this.TestCommand = this.CreateCommand(async(parameter) =>
            {
                if (!await this.CheckForResultErrors(await this.ValidateActions()))
                {
                    IEnumerable <ActionModelBase> actions = await this.GetActions();
                    if (actions != null)
                    {
                        await CommandModelBase.RunActions(actions, CommandParametersModel.GetTestParameters(this.GetTestSpecialIdentifiers()));
                    }
                }
            });

            this.ExportCommand = this.CreateCommand(async(parameter) =>
            {
                CommandModelBase command = await this.ValidateAndBuildCommand();
                if (command != null)
                {
                    string fileName = ChannelSession.Services.FileService.ShowSaveFileDialog(this.Name + MixItUpCommandFileExtension);
                    if (!string.IsNullOrEmpty(fileName))
                    {
                        await FileSerializerHelper.SerializeToFile(fileName, command);
                    }
                }
            });

            this.ImportCommand = this.CreateCommand(async(parameter) =>
            {
                try
                {
                    CommandModelBase command = await CommandEditorWindowViewModelBase.ImportCommandFromFile();
                    if (command != null)
                    {
                        // TODO Check if the imported command type matches the currently edited command. If so, import additional information.
                        foreach (ActionModelBase action in command.Actions)
                        {
                            await this.AddAction(action);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Log(ex);
                    await DialogHelper.ShowMessage(MixItUp.Base.Resources.FailedToImportCommand);
                }
            });
        }
        private async void SaveButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            await this.RunAsyncOperation(async() =>
            {
                if (string.IsNullOrEmpty(this.NameTextBox.Text))
                {
                    await MessageBoxHelper.ShowMessageDialog("An inventory name must be specified");
                    return;
                }

                UserInventoryViewModel dupeInventory = ChannelSession.Settings.Inventories.Values.FirstOrDefault(c => c.Name.Equals(this.NameTextBox.Text));
                if (dupeInventory != null && (this.inventory == null || !this.inventory.ID.Equals(dupeInventory.ID)))
                {
                    await MessageBoxHelper.ShowMessageDialog("There already exists an inventory with this name");
                    return;
                }

                UserCurrencyViewModel dupeCurrency = ChannelSession.Settings.Currencies.Values.FirstOrDefault(c => c.Name.Equals(this.NameTextBox.Text));
                if (dupeCurrency != null)
                {
                    await MessageBoxHelper.ShowMessageDialog("There already exists a currency or rank system with this name");
                    return;
                }

                if (string.IsNullOrEmpty(this.DefaultMaxAmountTextBox.Text) || !int.TryParse(this.DefaultMaxAmountTextBox.Text, out int maxAmount) || maxAmount <= 0)
                {
                    await MessageBoxHelper.ShowMessageDialog("The default max amount must be greater than 0");
                    return;
                }

                if (this.items.Count == 0)
                {
                    await MessageBoxHelper.ShowMessageDialog("At least 1 item must be added");
                    return;
                }

                if (this.ShopEnableDisableToggleButton.IsChecked.GetValueOrDefault())
                {
                    if (string.IsNullOrEmpty(this.ShopCommandTextBox.Text))
                    {
                        await MessageBoxHelper.ShowMessageDialog("A command name must be specified for the shop");
                        return;
                    }

                    if (this.ShopCurrencyComboBox.SelectedIndex < 0)
                    {
                        await MessageBoxHelper.ShowMessageDialog("A currency must be specified for the shop");
                        return;
                    }
                }

                if (this.inventory == null)
                {
                    this.inventory = new UserInventoryViewModel();
                    ChannelSession.Settings.Inventories[this.inventory.ID] = this.inventory;
                }

                this.inventory.Name              = this.NameTextBox.Text;
                this.inventory.DefaultMaxAmount  = maxAmount;
                this.inventory.ResetInterval     = EnumHelper.GetEnumValueFromString <CurrencyResetRateEnum>((string)this.AutomaticResetComboBox.SelectedItem);
                this.inventory.SpecialIdentifier = SpecialIdentifierStringBuilder.ConvertToSpecialIdentifier(this.inventory.Name);
                this.inventory.Items             = new Dictionary <string, UserInventoryItemViewModel>(this.items.ToDictionary(i => i.Name, i => i));
                this.inventory.ShopEnabled       = this.ShopEnableDisableToggleButton.IsChecked.GetValueOrDefault();
                this.inventory.ShopCommand       = this.ShopCommandTextBox.Text;
                if (this.ShopCurrencyComboBox.SelectedIndex >= 0)
                {
                    UserCurrencyViewModel currency = (UserCurrencyViewModel)this.ShopCurrencyComboBox.SelectedItem;
                    if (currency != null)
                    {
                        this.inventory.ShopCurrencyID = currency.ID;
                    }
                }
                this.inventory.ItemsBoughtCommand = (CustomCommand)this.ShopItemsBoughtCommandButtonsControl.DataContext;
                this.inventory.ItemsSoldCommand   = (CustomCommand)this.ShopItemsSoldCommandButtonsControl.DataContext;

                await ChannelSession.SaveSettings();

                this.Close();
            });
        }
示例#23
0
        public async Task Initialize()
        {
            if (this.IsStreamer)
            {
                if (!ChannelSession.Services.FileService.FileExists(this.DatabaseFilePath))
                {
                    await ChannelSession.Services.FileService.CopyFile(SettingsV2Model.SettingsTemplateDatabaseFileName, this.DatabaseFilePath);
                }

                foreach (StreamingPlatformTypeEnum platform in StreamingPlatforms.Platforms)
                {
                    this.UsernameLookups[platform] = new Dictionary <string, Guid>();
                }

                await ChannelSession.Services.Database.Read(this.DatabaseFilePath, "SELECT * FROM Users", (Dictionary <string, object> data) =>
                {
                    UserDataModel userData     = JSONSerializerHelper.DeserializeFromString <UserDataModel>((string)data["Data"]);
                    this.UserData[userData.ID] = userData;
                    if (userData.Platform.HasFlag(StreamingPlatformTypeEnum.Twitch))
                    {
                        this.TwitchUserIDLookups[userData.TwitchID] = userData.ID;
                        if (!string.IsNullOrEmpty(userData.TwitchUsername))
                        {
                            this.UsernameLookups[StreamingPlatformTypeEnum.Twitch][userData.TwitchUsername.ToLowerInvariant()] = userData.ID;
                        }
                    }
#pragma warning disable CS0612 // Type or member is obsolete
                    else if (userData.Platform.HasFlag(StreamingPlatformTypeEnum.Mixer))
                    {
                        if (!string.IsNullOrEmpty(userData.MixerUsername))
                        {
                            this.UsernameLookups[StreamingPlatformTypeEnum.Mixer][userData.MixerUsername.ToLowerInvariant()] = userData.ID;
                        }
                    }
#pragma warning restore CS0612 // Type or member is obsolete
                });

                this.UserData.ClearTracking();

                await ChannelSession.Services.Database.Read(this.DatabaseFilePath, "SELECT * FROM Quotes", (Dictionary <string, object> data) =>
                {
                    string json = (string)data["Data"];
                    if (json.Contains("MixItUp.Base.ViewModel.User.UserQuoteViewModel"))
                    {
                        json = json.Replace("MixItUp.Base.ViewModel.User.UserQuoteViewModel", "MixItUp.Base.Model.User.UserQuoteModel");
                        this.Quotes.Add(new UserQuoteViewModel(JSONSerializerHelper.DeserializeFromString <UserQuoteModel>(json)));
                    }
                    else
                    {
                        this.Quotes.Add(new UserQuoteViewModel(JSONSerializerHelper.DeserializeFromString <UserQuoteModel>((string)data["Data"])));
                    }
                });

                this.Quotes.ClearTracking();

                await ChannelSession.Services.Database.Read(this.DatabaseFilePath, "SELECT * FROM Commands", (Dictionary <string, object> data) =>
                {
                    CommandTypeEnum type = (CommandTypeEnum)Convert.ToInt32(data["TypeID"]);
                    if (type == CommandTypeEnum.Chat)
                    {
                        this.ChatCommands.Add(JSONSerializerHelper.DeserializeFromString <ChatCommand>((string)data["Data"]));
                    }
                    else if (type == CommandTypeEnum.Event)
                    {
                        this.EventCommands.Add(JSONSerializerHelper.DeserializeFromString <EventCommand>((string)data["Data"]));
                    }
                    else if (type == CommandTypeEnum.Timer)
                    {
                        this.TimerCommands.Add(JSONSerializerHelper.DeserializeFromString <TimerCommand>((string)data["Data"]));
                    }
                    else if (type == CommandTypeEnum.ActionGroup)
                    {
                        this.ActionGroupCommands.Add(JSONSerializerHelper.DeserializeFromString <ActionGroupCommand>((string)data["Data"]));
                    }
                    else if (type == CommandTypeEnum.Game)
                    {
                        this.GameCommands.Add(JSONSerializerHelper.DeserializeFromString <GameCommandBase>((string)data["Data"]));
                    }
                    else if (type == CommandTypeEnum.TwitchChannelPoints)
                    {
                        this.TwitchChannelPointsCommands.Add(JSONSerializerHelper.DeserializeFromString <TwitchChannelPointsCommand>((string)data["Data"]));
                    }
                    else if (type == CommandTypeEnum.Custom)
                    {
                        CustomCommand command           = JSONSerializerHelper.DeserializeFromString <CustomCommand>((string)data["Data"]);
                        this.CustomCommands[command.ID] = command;
                    }
#pragma warning disable CS0612 // Type or member is obsolete
                    else if (type == CommandTypeEnum.Interactive)
                    {
                        MixPlayCommand command = JSONSerializerHelper.DeserializeFromString <MixPlayCommand>((string)data["Data"]);
                        if (command is MixPlayButtonCommand || command is MixPlayTextBoxCommand)
                        {
                            this.OldMixPlayCommands.Add(command);
                        }
                    }
#pragma warning restore CS0612 // Type or member is obsolete
                });

                this.ChatCommands.ClearTracking();
                this.EventCommands.ClearTracking();
                this.TimerCommands.ClearTracking();
                this.ActionGroupCommands.ClearTracking();
                this.GameCommands.ClearTracking();
                this.TwitchChannelPointsCommands.ClearTracking();
                this.CustomCommands.ClearTracking();

                foreach (CounterModel counter in this.Counters.Values.ToList())
                {
                    if (counter.ResetOnLoad)
                    {
                        await counter.ResetAmount();
                    }
                }
            }

            if (string.IsNullOrEmpty(this.TelemetryUserID))
            {
                if (ChannelSession.IsDebug())
                {
                    this.TelemetryUserID = "MixItUpDebuggingUser";
                }
                else
                {
                    this.TelemetryUserID = Guid.NewGuid().ToString();
                }
            }

            // Mod accounts cannot use this feature, forcefully disable on load
            if (!this.IsStreamer)
            {
                this.TrackWhispererNumber = false;
            }

            this.InitializeMissingData();
        }
示例#24
0
        public override Task LoadTestData()
        {
            UserViewModel user = ChannelSession.GetCurrentUser();

            return(Task.FromResult(0));
        }
示例#25
0
        public UserDataImportWindowViewModel()
        {
            this.Columns.Add(new UserDataImportColumnViewModel(UserDataImportColumnViewModel.TwitchIDColumn));
            this.Columns.Add(new UserDataImportColumnViewModel(UserDataImportColumnViewModel.TwitchUsernameColumn));
            this.Columns.Add(new UserDataImportColumnViewModel(UserDataImportColumnViewModel.MixerUsernameColumn));
            this.Columns.Add(new UserDataImportColumnViewModel(UserDataImportColumnViewModel.LiveViewingHoursColumn));
            this.Columns.Add(new UserDataImportColumnViewModel(UserDataImportColumnViewModel.LiveViewingMinutesColumn));
            this.Columns.Add(new UserDataImportColumnViewModel(UserDataImportColumnViewModel.OfflineViewingHoursColumn));
            this.Columns.Add(new UserDataImportColumnViewModel(UserDataImportColumnViewModel.OfflineViewingMinutesColumn));

            foreach (CurrencyModel currency in ChannelSession.Settings.Currency.Values)
            {
                this.Columns.Add(new UserDataImportColumnViewModel(currency.Name));
            }

            foreach (UserDataImportColumnViewModel column in this.Columns)
            {
                this.columnDictionary[column.Name] = column;
            }

            this.UserDataFileBrowseCommand = this.CreateCommand((parameter) =>
            {
                string filePath = ChannelSession.Services.FileService.ShowOpenFileDialog("Valid Data File Types|*.txt;*.csv;*.xls;*.xlsx");
                if (!string.IsNullOrEmpty(filePath))
                {
                    this.UserDataFilePath = filePath;
                }
                return(Task.FromResult(0));
            });

            this.ImportButtonCommand = this.CreateCommand(async(parameter) =>
            {
                try
                {
                    int usersImported = 0;
                    int failedImports = 0;

                    if (string.IsNullOrEmpty(this.UserDataFilePath) || !File.Exists(this.UserDataFilePath))
                    {
                        await DialogHelper.ShowMessage("A valid data file must be specified");
                        return;
                    }

                    if (!this.Columns[0].ColumnNumber.HasValue && !this.Columns[1].ColumnNumber.HasValue)
                    {
                        await DialogHelper.ShowMessage("Your data file must include at least either" + Environment.NewLine + "the Mixer ID or Username columns.");
                        return;
                    }

                    List <UserDataImportColumnViewModel> importingColumns = new List <UserDataImportColumnViewModel>();
                    foreach (UserDataImportColumnViewModel column in this.Columns.Skip(2))
                    {
                        if (column.ColumnNumber.HasValue && column.ColumnNumber <= 0)
                        {
                            await DialogHelper.ShowMessage("A number 0 or greater must be specified for" + Environment.NewLine + "each column that you want to include.");
                            return;
                        }
                        importingColumns.Add(column);
                    }

                    Dictionary <string, CurrencyModel> nameToCurrencies = new Dictionary <string, CurrencyModel>();
                    foreach (CurrencyModel currency in ChannelSession.Settings.Currency.Values)
                    {
                        nameToCurrencies[currency.Name] = currency;
                    }

                    List <List <string> > lines = new List <List <string> >();

                    string extension = Path.GetExtension(this.UserDataFilePath);
                    if (extension.Equals(".txt") || extension.Equals(".csv"))
                    {
                        string fileContents = await ChannelSession.Services.FileService.ReadFile(this.UserDataFilePath);
                        if (!string.IsNullOrEmpty(fileContents))
                        {
                            foreach (string line in fileContents.Split(new string[] { "\n", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
                            {
                                List <string> splits = new List <string>();
                                foreach (string split in line.Split(new char[] { ' ', '\t', ',', ';' }))
                                {
                                    splits.Add(split);
                                }
                                lines.Add(splits);
                            }
                        }
                        else
                        {
                            await DialogHelper.ShowMessage("We were unable to read data from the file. Please make sure it is not already opened in another program.");
                        }
                    }
                    else if (extension.Equals(".xls") || extension.Equals(".xlsx"))
                    {
                        using (var stream = File.Open(this.UserDataFilePath, FileMode.Open, FileAccess.Read))
                        {
                            using (var reader = ExcelReaderFactory.CreateReader(stream))
                            {
                                var result = reader.AsDataSet();
                                if (result.Tables.Count > 0)
                                {
                                    for (int i = 0; i < result.Tables[0].Rows.Count; i++)
                                    {
                                        List <string> values = new List <string>();
                                        for (int j = 0; j < result.Tables[0].Rows[i].ItemArray.Length; j++)
                                        {
                                            values.Add(result.Tables[0].Rows[i].ItemArray[j].ToString());
                                        }
                                        lines.Add(values);
                                    }
                                }
                            }
                        }
                    }

                    if (lines.Count > 0)
                    {
                        foreach (List <string> line in lines)
                        {
                            try
                            {
                                long twitchID = 0;
                                if (this.columnDictionary[UserDataImportColumnViewModel.TwitchIDColumn].ArrayNumber >= 0)
                                {
                                    long.TryParse(line[this.columnDictionary[UserDataImportColumnViewModel.TwitchIDColumn].ArrayNumber], out twitchID);
                                }

                                string twitchUsername = null;
                                if (this.columnDictionary[UserDataImportColumnViewModel.TwitchUsernameColumn].ArrayNumber >= 0)
                                {
                                    twitchUsername = line[this.columnDictionary[UserDataImportColumnViewModel.TwitchUsernameColumn].ArrayNumber];
                                }

                                string mixerUsername = null;
                                if (this.columnDictionary[UserDataImportColumnViewModel.MixerUsernameColumn].ArrayNumber >= 0)
                                {
                                    mixerUsername = line[this.columnDictionary[UserDataImportColumnViewModel.MixerUsernameColumn].ArrayNumber];
                                }

                                bool newUser       = true;
                                UserDataModel user = null;
                                if (twitchID > 0)
                                {
                                    user = ChannelSession.Settings.GetUserDataByTwitchID(twitchID.ToString());
                                    if (user != null)
                                    {
                                        newUser = false;
                                    }
                                    else
                                    {
                                        Twitch.Base.Models.NewAPI.Users.UserModel twitchUser = await ChannelSession.TwitchUserConnection.GetNewAPIUserByID(twitchID.ToString());
                                        if (twitchUser != null)
                                        {
                                            UserViewModel userViewModel = new UserViewModel(twitchUser);
                                            user = userViewModel.Data;
                                        }
                                    }
                                }
                                else if (!string.IsNullOrEmpty(twitchUsername))
                                {
                                    Twitch.Base.Models.NewAPI.Users.UserModel twitchUser = await ChannelSession.TwitchUserConnection.GetNewAPIUserByLogin(twitchUsername);
                                    if (twitchUser != null)
                                    {
                                        user = ChannelSession.Settings.GetUserDataByTwitchID(twitchUser.id);
                                        if (user != null)
                                        {
                                            newUser = false;
                                        }
                                        else
                                        {
                                            UserViewModel userViewModel = new UserViewModel(twitchUser);
                                            user = userViewModel.Data;
                                        }
                                    }
                                }
                                else if (!string.IsNullOrEmpty(mixerUsername))
                                {
#pragma warning disable CS0612 // Type or member is obsolete
                                    UserDataModel mixerUserData = ChannelSession.Settings.GetUserDataByUsername(StreamingPlatformTypeEnum.Mixer, mixerUsername);
#pragma warning restore CS0612 // Type or member is obsolete
                                    if (mixerUserData != null)
                                    {
                                        newUser = false;
                                    }
                                    else
                                    {
                                        user = new UserDataModel()
                                        {
                                            MixerID       = uint.MaxValue,
                                            MixerUsername = mixerUsername
                                        };
                                    }
                                }

                                if (user != null)
                                {
                                    if (newUser)
                                    {
                                        ChannelSession.Settings.AddUserData(user);
                                    }

                                    int iValue = 0;
                                    if (this.GetIntValueFromLineColumn(UserDataImportColumnViewModel.LiveViewingHoursColumn, line, out iValue))
                                    {
                                        user.ViewingHoursPart = iValue;
                                    }
                                    if (this.GetIntValueFromLineColumn(UserDataImportColumnViewModel.LiveViewingMinutesColumn, line, out iValue))
                                    {
                                        user.ViewingMinutesPart = iValue;
                                    }
                                    if (this.GetIntValueFromLineColumn(UserDataImportColumnViewModel.OfflineViewingHoursColumn, line, out iValue))
                                    {
                                        user.OfflineViewingMinutes = iValue;
                                    }
                                    if (this.GetIntValueFromLineColumn(UserDataImportColumnViewModel.OfflineViewingMinutesColumn, line, out iValue))
                                    {
                                        user.OfflineViewingMinutes = iValue;
                                    }
                                    foreach (var kvp in nameToCurrencies)
                                    {
                                        if (this.GetIntValueFromLineColumn(kvp.Key, line, out iValue))
                                        {
                                            kvp.Value.SetAmount(user, iValue);
                                        }
                                    }

                                    ChannelSession.Settings.UserData.ManualValueChanged(user.ID);

                                    usersImported++;
                                    this.ImportButtonText = string.Format("{0} {1}", usersImported, MixItUp.Base.Resources.Imported);
                                }
                                else
                                {
                                    failedImports++;
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.Log(LogLevel.Error, "User Data Import Failure - " + line);
                                Logger.Log(ex);
                                failedImports++;
                            }
                        }
                    }

                    await ChannelSession.SaveSettings();

                    if (failedImports > 0)
                    {
                        await DialogHelper.ShowMessage($"{usersImported} users were imported successfully, but {failedImports} users were not able to be imported. This could be due to invalid data or failure to find their information on the platform. Please contact support for further help with this if needed");
                    }
                    else
                    {
                        await DialogHelper.ShowMessage($"{usersImported} users were imported successfully");
                    }
                }
                catch (Exception ex)
                {
                    Logger.Log(ex);
                    await DialogHelper.ShowMessage("We were unable to read data from the file. Please make sure it is not already opened in another program. If this continues, please reach out to support.");
                }
                this.ImportButtonText = MixItUp.Base.Resources.ImportData;
            });
        }
示例#26
0
        private async void PlayButton_Click(object sender, RoutedEventArgs e)
        {
            this.PlayButton.Visibility = Visibility.Collapsed;
            this.StopButton.Visibility = Visibility.Visible;

            this.EditButton.IsEnabled   = false;
            this.DeleteButton.IsEnabled = false;
            this.EnableDisableToggleSwitch.IsEnabled = false;

            CommandBase command = this.GetCommandFromCommandButtons <CommandBase>(this);

            if (command != null)
            {
                UserViewModel currentUser = await ChannelSession.GetCurrentUser();

                Dictionary <string, string> extraSpecialIdentifiers = new Dictionary <string, string>();
                if (command is EventCommand)
                {
                    EventCommand eventCommand = command as EventCommand;
                    switch (eventCommand.EventType)
                    {
                    case Mixer.Base.Clients.ConstellationEventTypeEnum.channel__id__hosted:
                        extraSpecialIdentifiers["hostviewercount"] = "123";
                        break;

                    case Mixer.Base.Clients.ConstellationEventTypeEnum.channel__id__resubscribed:
                        extraSpecialIdentifiers["usersubmonths"] = "5";
                        break;
                    }

                    switch (eventCommand.OtherEventType)
                    {
                    case OtherEventTypeEnum.GameWispSubscribed:
                    case OtherEventTypeEnum.GameWispResubscribed:
                        extraSpecialIdentifiers["subscribemonths"] = "999";
                        extraSpecialIdentifiers["subscribetier"]   = "Test Tier";
                        extraSpecialIdentifiers["subscribeamount"] = "$12.34";
                        break;

                    case OtherEventTypeEnum.StreamlabsDonation:
                    case OtherEventTypeEnum.GawkBoxDonation:
                    case OtherEventTypeEnum.TiltifyDonation:
                    case OtherEventTypeEnum.ExtraLifeDonation:
                    case OtherEventTypeEnum.TipeeeStreamDonation:
                    case OtherEventTypeEnum.TreatStreamDonation:
                    case OtherEventTypeEnum.StreamJarDonation:
                        UserDonationModel donation = new UserDonationModel()
                        {
                            Amount    = 12.34,
                            Message   = "Test donation message",
                            ImageLink = currentUser.AvatarLink
                        };

                        switch (eventCommand.OtherEventType)
                        {
                        case OtherEventTypeEnum.StreamlabsDonation: donation.Source = UserDonationSourceEnum.Streamlabs; break;

                        case OtherEventTypeEnum.GawkBoxDonation: donation.Source = UserDonationSourceEnum.GawkBox; break;

                        case OtherEventTypeEnum.TiltifyDonation: donation.Source = UserDonationSourceEnum.Tiltify; break;

                        case OtherEventTypeEnum.ExtraLifeDonation: donation.Source = UserDonationSourceEnum.ExtraLife; break;

                        case OtherEventTypeEnum.TipeeeStreamDonation: donation.Source = UserDonationSourceEnum.TipeeeStream; break;

                        case OtherEventTypeEnum.TreatStreamDonation: donation.Source = UserDonationSourceEnum.TreatStream; break;

                        case OtherEventTypeEnum.StreamJarDonation: donation.Source = UserDonationSourceEnum.StreamJar; break;
                        }

                        foreach (var kvp in donation.GetSpecialIdentifiers())
                        {
                            extraSpecialIdentifiers[kvp.Key] = kvp.Value;
                        }
                        extraSpecialIdentifiers["donationtype"] = "Pizza";
                        break;

                    case OtherEventTypeEnum.PatreonSubscribed:
                        extraSpecialIdentifiers[SpecialIdentifierStringBuilder.PatreonTierNameSpecialIdentifier]   = "Super Tier";
                        extraSpecialIdentifiers[SpecialIdentifierStringBuilder.PatreonTierAmountSpecialIdentifier] = "12.34";
                        extraSpecialIdentifiers[SpecialIdentifierStringBuilder.PatreonTierImageSpecialIdentifier]  = "https://xforgeassets002.xboxlive.com/xuid-2535473787585366-public/b7a1d715-3a9e-4bdd-a030-32f9e2e0f51e/0013_lots-o-stars_256.png";
                        break;

                    case OtherEventTypeEnum.TwitterStreamTweetRetweet:
                        break;

                    case OtherEventTypeEnum.MixerSkillUsed:
                        extraSpecialIdentifiers["skillname"]     = "Lots of stars";
                        extraSpecialIdentifiers["skilltype"]     = EnumHelper.GetEnumName(SkillTypeEnum.Sticker);
                        extraSpecialIdentifiers["skillcosttype"] = "Embers";
                        extraSpecialIdentifiers["skillcost"]     = "50";
                        extraSpecialIdentifiers["skillimage"]    = "https://xforgeassets002.xboxlive.com/xuid-2535473787585366-public/b7a1d715-3a9e-4bdd-a030-32f9e2e0f51e/0013_lots-o-stars_256.png";
                        extraSpecialIdentifiers["skillissparks"] = false.ToString();
                        extraSpecialIdentifiers["skillisembers"] = true.ToString();
                        extraSpecialIdentifiers["skillmessage"]  = "Hello World!";
                        break;

                    case OtherEventTypeEnum.MixerMilestoneReached:
                        extraSpecialIdentifiers["milestoneamount"]               = "100";
                        extraSpecialIdentifiers["milestoneremainingamount"]      = "100";
                        extraSpecialIdentifiers["milestonereward"]               = "$10.00";
                        extraSpecialIdentifiers["milestonenextamount"]           = "100";
                        extraSpecialIdentifiers["milestonenextremainingamount"]  = "100";
                        extraSpecialIdentifiers["milestonenextreward"]           = "$10.00";
                        extraSpecialIdentifiers["milestonefinalamount"]          = "100";
                        extraSpecialIdentifiers["milestonefinalremainingamount"] = "100";
                        extraSpecialIdentifiers["milestonefinalreward"]          = "$10.00";
                        extraSpecialIdentifiers["milestoneearnedamount"]         = "100";
                        extraSpecialIdentifiers["milestoneearnedreward"]         = "$10.00";
                        break;

                    case OtherEventTypeEnum.MixerSparksUsed:
                        extraSpecialIdentifiers["sparkamount"] = "10";
                        break;

                    case OtherEventTypeEnum.MixerEmbersUsed:
                        extraSpecialIdentifiers["emberamount"] = "10";
                        break;
                    }
                }
                else if (command is InteractiveCommand)
                {
                    InteractiveCommand iCommand = (InteractiveCommand)command;

                    extraSpecialIdentifiers["mixplaycontrolid"]   = iCommand.Name;
                    extraSpecialIdentifiers["mixplaycontrolcost"] = "123";
                }
                else if (command is CustomCommand)
                {
                    if (command.Name.Equals(InventoryWindow.ItemsBoughtCommandName) || command.Name.Equals(InventoryWindow.ItemsSoldCommandName))
                    {
                        extraSpecialIdentifiers["itemtotal"]    = "5";
                        extraSpecialIdentifiers["itemname"]     = "Chocolate Bars";
                        extraSpecialIdentifiers["itemcost"]     = "500";
                        extraSpecialIdentifiers["currencyname"] = "CURRENCY_NAME";
                    }
                }

                await command.PerformAndWait(currentUser, new List <string>() { "@" + currentUser.UserName }, extraSpecialIdentifiers);

                if (command is PermissionsCommandBase)
                {
                    PermissionsCommandBase permissionCommand = (PermissionsCommandBase)command;
                    permissionCommand.ResetCooldown(await ChannelSession.GetCurrentUser());
                }
                this.SwitchToPlay();
            }

            this.RaiseEvent(new RoutedEventArgs(CommandButtonsControl.PlayClickedEvent, this));
        }
        private async void PlayButton_Click(object sender, RoutedEventArgs e)
        {
            this.PlayButton.Visibility = Visibility.Collapsed;
            this.StopButton.Visibility = Visibility.Visible;

            this.EditButton.IsEnabled   = false;
            this.DeleteButton.IsEnabled = false;
            this.EnableDisableToggleSwitch.IsEnabled = false;

            if (this.DataContext != null && this.DataContext is CommandBase)
            {
                CommandBase command = (CommandBase)this.DataContext;
                await command.PerformAndWait(ChannelSession.GetCurrentUser(), new List <string>() { "@" + ChannelSession.GetCurrentUser().UserName });

                this.SwitchToPlay();
            }

            this.RaiseEvent(new RoutedEventArgs(CommandButtonsControl.PlayClickedEvent, this));
        }
示例#28
0
        public override Task LoadTestData()
        {
            ChatMessageViewModel message = new ChatMessageViewModel(Guid.NewGuid().ToString(), StreamingPlatformTypeEnum.All, ChannelSession.GetCurrentUser());

            message.AddStringMessagePart("Test Message");
            this.GlobalEvents_OnChatMessageReceived(this, message);
            return(Task.FromResult(0));
        }
示例#29
0
        public async Task <string> Start(string item)
        {
            if (this.IsRunning)
            {
                return("A giveaway is already underway");
            }

            if (string.IsNullOrEmpty(item))
            {
                return("The name of the giveaway item must be specified");
            }
            this.Item = item;

            if (ChannelSession.Settings.GiveawayTimer <= 0)
            {
                return("The giveaway length must be greater than 0");
            }

            if (ChannelSession.Settings.GiveawayReminderInterval < 0)
            {
                return("The giveaway reminder must be 0 or greater");
            }

            if (ChannelSession.Settings.GiveawayMaximumEntries <= 0)
            {
                return("The maximum entries must be greater than 0");
            }

            if (string.IsNullOrEmpty(ChannelSession.Settings.GiveawayCommand))
            {
                return("Giveaway command must be specified");
            }

            if (ChannelSession.Settings.GiveawayCommand.Any(c => !Char.IsLetterOrDigit(c)))
            {
                return("Giveaway Command can only contain letters and numbers");
            }

            await ChannelSession.SaveSettings();

            this.IsRunning = true;
            this.Winner    = null;

            this.giveawayCommand = new ChatCommandModel("Giveaway Command", new HashSet <string>()
            {
                ChannelSession.Settings.GiveawayCommand
            });
            if (ChannelSession.Settings.GiveawayAllowPastWinners)
            {
                this.pastWinners.Clear();
            }

            this.TimeLeft = ChannelSession.Settings.GiveawayTimer * 60;
            this.enteredUsers.Clear();
            this.previousEnteredUsers.Clear();

            GlobalEvents.GiveawaysChangedOccurred(usersUpdated: true);

            this.backgroundThreadCancellationTokenSource       = new CancellationTokenSource();
            this.backgroundThreadReRollCancellationTokenSource = new CancellationTokenSource();
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            Task.Run(async() => { await this.GiveawayTimerBackground(); }, this.backgroundThreadCancellationTokenSource.Token);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

            await ChannelSession.Settings.GetCommand(ChannelSession.Settings.GiveawayStartedReminderCommandID).Perform(new CommandParametersModel(this.GetSpecialIdentifiers()));

            return(null);
        }
        public NewUserWizardWindowViewModel()
        {
            this.DiscordCommand = this.CreateCommand((parameter) => { ProcessHelper.LaunchLink("https://mixitupapp.com/discord"); return(Task.FromResult(0)); });
            this.TwitterCommand = this.CreateCommand((parameter) => { ProcessHelper.LaunchLink("https://twitter.com/MixItUpApp"); return(Task.FromResult(0)); });
            this.YouTubeCommand = this.CreateCommand((parameter) => { ProcessHelper.LaunchLink("https://www.youtube.com/channel/UCcY0vKI9yqcMTgh8OzSnRSA"); return(Task.FromResult(0)); });
            this.WikiCommand    = this.CreateCommand((parameter) => { ProcessHelper.LaunchLink("https://github.com/SaviorXTanren/mixer-mixitup/wiki"); return(Task.FromResult(0)); });

            this.Twitch.StartLoadingOperationOccurred += (sender, eventArgs) => { this.StartLoadingOperation(); };
            this.Twitch.EndLoadingOperationOccurred   += (sender, eventArgs) => { this.EndLoadingOperation(); };

            this.SetBackupLocationCommand = this.CreateCommand((parameter) =>
            {
                string folderPath = ChannelSession.Services.FileService.ShowOpenFolderDialog();
                if (!string.IsNullOrEmpty(folderPath) && Directory.Exists(folderPath))
                {
                    this.SettingsBackupLocation = folderPath;
                }

                if (this.SelectedSettingsBackupOption == SettingsBackupRateEnum.None)
                {
                    this.SelectedSettingsBackupOption = SettingsBackupRateEnum.Monthly;
                }

                this.NotifyPropertyChanged("IsBackupLocationSet");

                return(Task.FromResult(0));
            });

            this.NextCommand = this.CreateCommand(async(parameter) =>
            {
                this.StatusMessage = string.Empty;

                if (this.IntroPageVisible)
                {
                    this.IntroPageVisible            = false;
                    this.StreamerAccountsPageVisible = true;
                    this.CanBack = true;
                }
                else if (this.StreamerAccountsPageVisible)
                {
                    if (!this.Twitch.IsUserAccountConnected)
                    {
                        this.StatusMessage = "Twitch Streamer account must be signed in.";
                        return;
                    }

                    this.StreamerAccountsPageVisible = false;
                    this.CommandActionsPageVisible   = true;
                }
                else if (this.CommandActionsPageVisible)
                {
                    this.CommandActionsPageVisible = false;
                    this.FinalPageVisible          = true;
                }
                else if (this.FinalPageVisible)
                {
                    if (!await ChannelSession.InitializeSession())
                    {
                        await DialogHelper.ShowMessage(Resources.SessionInitializationFailed);
                        return;
                    }

                    ChannelSession.Settings.ReRunWizard            = false;
                    ChannelSession.Settings.SettingsBackupLocation = this.SettingsBackupLocation;
                    ChannelSession.Settings.SettingsBackupRate     = this.SelectedSettingsBackupOption;

                    this.WizardComplete = true;
                    this.WizardCompleteEvent(this, new EventArgs());
                }

                this.StatusMessage = string.Empty;
            });

            this.BackCommand = this.CreateCommand((parameter) =>
            {
                if (this.StreamerAccountsPageVisible)
                {
                    this.StreamerAccountsPageVisible = false;
                    this.IntroPageVisible            = true;
                    this.CanBack = false;
                }
                else if (this.CommandActionsPageVisible)
                {
                    this.CommandActionsPageVisible   = false;
                    this.StreamerAccountsPageVisible = true;
                }
                else if (this.FinalPageVisible)
                {
                    this.FinalPageVisible          = false;
                    this.CommandActionsPageVisible = true;
                }

                this.StatusMessage = string.Empty;
                return(Task.FromResult(0));
            });
        }