Beispiel #1
0
        public override async Task Enable()
        {
            if (this.LeaderboardType == OverlayLeaderboardListItemTypeEnum.Subscribers)
            {
                this.userSubDates.Clear();
                IEnumerable <UserSubscriptionModel> subscribers = await ChannelSession.TwitchUserConnection.GetSubscribersV5(ChannelSession.TwitchChannelV5, int.MaxValue);

                foreach (UserSubscriptionModel subscriber in subscribers)
                {
                    UserViewModel user = await UserViewModel.Create(subscriber.user);

                    DateTimeOffset?subDate = TwitchPlatformService.GetTwitchDateTime(subscriber.created_at);
                    if (subDate.HasValue && this.ShouldIncludeUser(user))
                    {
                        this.userSubDates[user.ID] = subDate.GetValueOrDefault();
                    }
                }

                await this.UpdateSubscribers();

                GlobalEvents.OnSubscribeOccurred          += GlobalEvents_OnSubscribeOccurred;
                GlobalEvents.OnResubscribeOccurred        += GlobalEvents_OnResubscribeOccurred;
                GlobalEvents.OnSubscriptionGiftedOccurred += GlobalEvents_OnSubscriptionGiftedOccurred;
            }
            else if (this.LeaderboardType == OverlayLeaderboardListItemTypeEnum.Donations)
            {
                GlobalEvents.OnDonationOccurred += GlobalEvents_OnDonationOccurred;
            }

            await base.Enable();
        }
Beispiel #2
0
        public async Task <ActionResult> New(string tabId, int parentId)
        {
            var user  = _service.GetUserToAdd();
            var model = UserViewModel.Create(user, tabId, parentId, _service);

            return(await JsonHtml("Properties", model));
        }
Beispiel #3
0
        private async void UserClient_OnChatClearReceived(object sender, ChatClearChatPacketModel chatClear)
        {
            UserViewModel user = ChannelSession.Services.User.GetActiveUserByPlatformID(StreamingPlatformTypeEnum.Twitch, chatClear.UserID);

            if (user == null)
            {
                user = await UserViewModel.Create(chatClear);
            }

            if (chatClear.IsClear)
            {
                await ChannelSession.Services.Alerts.AddAlert(new AlertChatMessageViewModel(StreamingPlatformTypeEnum.Twitch, user, "Chat Cleared", ChannelSession.Settings.AlertModerationColor));
            }
            else if (chatClear.IsTimeout)
            {
                CommandParametersModel parameters = new CommandParametersModel();
                parameters.Arguments.Add("@" + user.Username);
                parameters.TargetUser = user;
                parameters.SpecialIdentifiers["timeoutlength"] = chatClear.BanDuration.ToString();
                await ChannelSession.Services.Events.PerformEvent(EventTypeEnum.ChatUserTimeout, parameters);

                await ChannelSession.Services.Alerts.AddAlert(new AlertChatMessageViewModel(StreamingPlatformTypeEnum.Twitch, user, string.Format("{0} Timed Out for {1} seconds", user.FullDisplayName, chatClear.BanDuration), ChannelSession.Settings.AlertModerationColor));
            }
            else if (chatClear.IsBan)
            {
                CommandParametersModel parameters = new CommandParametersModel();
                parameters.Arguments.Add("@" + user.Username);
                parameters.TargetUser = user;
                await ChannelSession.Services.Events.PerformEvent(EventTypeEnum.ChatUserBan, parameters);

                await ChannelSession.Services.Alerts.AddAlert(new AlertChatMessageViewModel(StreamingPlatformTypeEnum.Twitch, user, string.Format("{0} Banned", user.FullDisplayName), ChannelSession.Settings.AlertModerationColor));

                await ChannelSession.Services.User.RemoveActiveUserByID(user.ID);
            }
        }
Beispiel #4
0
        private async void PubSub_OnSubscribedReceived(object sender, PubSubSubscriptionsEventModel packet)
        {
            UserViewModel user = ChannelSession.Services.User.GetActiveUserByPlatformID(StreamingPlatformTypeEnum.Twitch, packet.user_id);

            if (user == null)
            {
                user = await UserViewModel.Create(packet);
            }

            if (packet.IsSubscription || packet.cumulative_months == 1)
            {
                await this.AddSub(new TwitchSubEventModel(user, packet));
            }
            else
            {
                int    months   = Math.Max(packet.streak_months, packet.cumulative_months);
                string planTier = TwitchEventService.GetSubTierNameFromText(packet.sub_plan);

                CommandParametersModel parameters = new CommandParametersModel(user);
                if (ChannelSession.Services.Events.CanPerformEvent(EventTypeEnum.TwitchChannelResubscribed, parameters))
                {
                    string message = (packet.sub_message.ContainsKey("message") && packet.sub_message["message"] != null) ? packet.sub_message["message"].ToString() : string.Empty;
                    parameters.Arguments = new List <string>(message.Split(new char[] { ' ' }));
                    parameters.SpecialIdentifiers["message"]         = message;
                    parameters.SpecialIdentifiers["usersubmonths"]   = months.ToString();
                    parameters.SpecialIdentifiers["usersubplanname"] = !string.IsNullOrEmpty(packet.sub_plan_name) ? packet.sub_plan_name : TwitchEventService.GetSubTierNameFromText(packet.sub_plan);
                    parameters.SpecialIdentifiers["usersubplan"]     = planTier;
                    parameters.SpecialIdentifiers["usersubstreak"]   = packet.streak_months.ToString();

                    ChannelSession.Settings.LatestSpecialIdentifiersData[SpecialIdentifierStringBuilder.LatestSubscriberUserData]      = user.ID;
                    ChannelSession.Settings.LatestSpecialIdentifiersData[SpecialIdentifierStringBuilder.LatestSubscriberSubMonthsData] = months;

                    user.SubscribeDate             = DateTimeOffset.Now.SubtractMonths(months - 1);
                    user.Data.TwitchSubscriberTier = TwitchEventService.GetSubTierNumberFromText(packet.sub_plan);
                    user.Data.TotalMonthsSubbed++;

                    foreach (CurrencyModel currency in ChannelSession.Settings.Currency.Values)
                    {
                        currency.AddAmount(user.Data, currency.OnSubscribeBonus);
                    }

                    foreach (StreamPassModel streamPass in ChannelSession.Settings.StreamPass.Values)
                    {
                        if (parameters.User.HasPermissionsTo(streamPass.Permission))
                        {
                            streamPass.AddAmount(user.Data, streamPass.SubscribeBonus);
                        }
                    }

                    if (string.IsNullOrEmpty(await ChannelSession.Services.Moderation.ShouldTextBeModerated(user, message)))
                    {
                        await ChannelSession.Services.Events.PerformEvent(EventTypeEnum.TwitchChannelResubscribed, parameters);
                    }
                }

                GlobalEvents.ResubscribeOccurred(new Tuple <UserViewModel, int>(user, months));
                await ChannelSession.Services.Alerts.AddAlert(new AlertChatMessageViewModel(StreamingPlatformTypeEnum.Twitch, user, string.Format("{0} Re-Subscribed For {1} Months at {2}", user.FullDisplayName, months, planTier), ChannelSession.Settings.AlertSubColor));
            }
        }
Beispiel #5
0
        public async Task <ActionResult> Properties(string tabId, int parentId, int id, string successfulActionCode)
        {
            var user  = _service.ReadProperties(id);
            var model = UserViewModel.Create(user, tabId, parentId, _service);

            model.SuccesfulActionCode = successfulActionCode;
            return(await JsonHtml("Properties", model));
        }
        private UserViewModel GetUser(string username)
        {
            UserViewModel user = ChannelSession.Services.User.GetActiveUserByUsername(username);

            if (user == null)
            {
                user = UserViewModel.Create(username);
            }
            return(user);
        }
Beispiel #7
0
 private void UserClient_OnClearMessageReceived(object sender, ChatClearMessagePacketModel packet)
 {
     if (packet != null && !string.IsNullOrEmpty(packet.ID) && !string.IsNullOrEmpty(packet.UserLogin))
     {
         UserViewModel user = ChannelSession.Services.User.GetActiveUserByUsername(packet.UserLogin, StreamingPlatformTypeEnum.Twitch);
         if (user == null)
         {
             user = UserViewModel.Create(packet.UserLogin);
         }
         this.OnMessageDeletedOccurred(this, new TwitchChatMessageViewModel(packet, user));
     }
 }
        private async Task TwitchFollowEvent(string followerId, string followerUsername, string followerDisplayName)
        {
            UserViewModel user = ChannelSession.Services.User.GetActiveUserByPlatformID(StreamingPlatformTypeEnum.Twitch, followerId);

            if (user == null)
            {
                user = await UserViewModel.Create(new TwitchWebhookFollowModel()
                {
                    StreamerID = ChannelSession.TwitchUserNewAPI.id,

                    UserID          = followerId,
                    Username        = followerUsername,
                    UserDisplayName = followerDisplayName
                });
            }

            ChannelSession.Services.Events.TwitchEventService.FollowCache.Add(user.TwitchID);

            if (user.UserRoles.Contains(UserRoleEnum.Banned))
            {
                return;
            }

            CommandParametersModel parameters = new CommandParametersModel(user);

            if (ChannelSession.Services.Events.CanPerformEvent(EventTypeEnum.TwitchChannelFollowed, parameters))
            {
                user.FollowDate = DateTimeOffset.Now;

                ChannelSession.Settings.LatestSpecialIdentifiersData[SpecialIdentifierStringBuilder.LatestFollowerUserData] = user.ID;

                foreach (CurrencyModel currency in ChannelSession.Settings.Currency.Values)
                {
                    currency.AddAmount(user.Data, currency.OnFollowBonus);
                }

                foreach (StreamPassModel streamPass in ChannelSession.Settings.StreamPass.Values)
                {
                    if (user.HasPermissionsTo(streamPass.Permission))
                    {
                        streamPass.AddAmount(user.Data, streamPass.FollowBonus);
                    }
                }

                await ChannelSession.Services.Alerts.AddAlert(new AlertChatMessageViewModel(StreamingPlatformTypeEnum.Twitch, user, string.Format("{0} Followed", user.FullDisplayName), ChannelSession.Settings.AlertFollowColor));

                await ChannelSession.Services.Events.PerformEvent(EventTypeEnum.TwitchChannelFollowed, parameters);

                GlobalEvents.FollowOccurred(user);
            }
        }
Beispiel #9
0
        private async void PubSub_OnBitsV2Received(object sender, PubSubBitsEventV2Model packet)
        {
            UserViewModel user;

            if (packet.is_anonymous)
            {
                user = UserViewModel.Create(MixItUp.Base.Resources.Anonymous);
            }
            else
            {
                user = ChannelSession.Services.User.GetActiveUserByPlatformID(StreamingPlatformTypeEnum.Twitch, packet.user_id);
                if (user == null)
                {
                    user = await UserViewModel.Create(packet);
                }
            }

            TwitchUserBitsCheeredModel bitsCheered = new TwitchUserBitsCheeredModel(user, packet);

            foreach (CurrencyModel bitsCurrency in ChannelSession.Settings.Currency.Values.Where(c => c.SpecialTracking == CurrencySpecialTrackingEnum.Bits))
            {
                bitsCurrency.AddAmount(user.Data, bitsCheered.Amount);
            }

            foreach (StreamPassModel streamPass in ChannelSession.Settings.StreamPass.Values)
            {
                if (user.HasPermissionsTo(streamPass.Permission))
                {
                    streamPass.AddAmount(user.Data, (int)Math.Ceiling(streamPass.BitsBonus * bitsCheered.Amount));
                }
            }

            user.Data.TotalBitsCheered = (uint)packet.total_bits_used;

            ChannelSession.Settings.LatestSpecialIdentifiersData[SpecialIdentifierStringBuilder.LatestBitsCheeredUserData]   = user.ID;
            ChannelSession.Settings.LatestSpecialIdentifiersData[SpecialIdentifierStringBuilder.LatestBitsCheeredAmountData] = bitsCheered.Amount;

            if (string.IsNullOrEmpty(await ChannelSession.Services.Moderation.ShouldTextBeModerated(user, bitsCheered.Message.PlainTextMessage)))
            {
                CommandParametersModel parameters = new CommandParametersModel(user, bitsCheered.Message.ToArguments());
                parameters.SpecialIdentifiers["bitsamount"]          = bitsCheered.Amount.ToString();
                parameters.SpecialIdentifiers["bitslifetimeamount"]  = packet.total_bits_used.ToString();
                parameters.SpecialIdentifiers["messagenocheermotes"] = bitsCheered.Message.PlainTextMessageNoCheermotes;
                parameters.SpecialIdentifiers["message"]             = bitsCheered.Message.PlainTextMessage;
                await ChannelSession.Services.Events.PerformEvent(EventTypeEnum.TwitchChannelBitsCheered, parameters);
            }
            await ChannelSession.Services.Alerts.AddAlert(new AlertChatMessageViewModel(StreamingPlatformTypeEnum.Twitch, user, string.Format("{0} Cheered {1} Bits", user.FullDisplayName, bitsCheered.Amount), ChannelSession.Settings.AlertBitsCheeredColor));

            GlobalEvents.BitsOccurred(bitsCheered);
        }
Beispiel #10
0
        public async Task <ActionResult> Properties(string tabId, int parentId, int id, IFormCollection collection)
        {
            var user  = _service.ReadProperties(id);
            var model = UserViewModel.Create(user, tabId, parentId, _service);

            await TryUpdateModelAsync(model);

            if (ModelState.IsValid)
            {
                model.Data = _service.UpdateProperties(model.Data);
                AppendFormGuidsFromIds("ContentDefaultFilter.ArticleIDs", "ContentDefaultFilter.ArticleUniqueIDs");
                return(Redirect("Properties", new { tabId, parentId, id = model.Data.Id, successfulActionCode = ActionCode.UpdateUser }));
            }

            return(await JsonHtml("Properties", model));
        }
Beispiel #11
0
        public ActionResult New(string tabId, int parentId, FormCollection collection)
        {
            var user  = _service.GetUserToAdd();
            var model = UserViewModel.Create(user, tabId, parentId, _service);

            TryUpdateModel(model);
            model.Validate(ModelState);
            if (ModelState.IsValid)
            {
                model.Data = _service.SaveProperties(model.Data);
                PersistResultId(model.Data.Id);
                AppendFormGuidsFromIds("ContentDefaultFilter.ArticleIDs", "ContentDefaultFilter.ArticleUniqueIDs");
                return(Redirect("Properties", new { tabId, parentId, id = model.Data.Id, successfulActionCode = ActionCode.SaveUser }));
            }

            return(JsonHtml("Properties", model));
        }
        public static UserViewModel GetCurrentUser()
        {
            // TO-DO: Update UserViewModel so that all platform accounts are combined into the same UserViewModel

            UserViewModel user = null;

            if (ChannelSession.TwitchUserNewAPI != null)
            {
                user = ChannelSession.Services.User.GetActiveUserByPlatformID(StreamingPlatformTypeEnum.Twitch, ChannelSession.TwitchUserNewAPI.id);
                if (user == null)
                {
                    user = UserViewModel.Create(ChannelSession.TwitchUserNewAPI).Result;
                    ChannelSession.Services.User.AddOrUpdateActiveUser(user).Wait();
                }
            }

            return(user);
        }
Beispiel #13
0
        private async void PubSub_OnWhisperReceived(object sender, PubSubWhisperEventModel packet)
        {
            if (!string.IsNullOrEmpty(packet.body))
            {
                UserViewModel user = ChannelSession.Services.User.GetActiveUserByPlatformID(StreamingPlatformTypeEnum.Twitch, packet.from_id.ToString());
                if (user == null)
                {
                    user = await UserViewModel.Create(packet);
                }

                UserViewModel recipient = ChannelSession.Services.User.GetActiveUserByPlatformID(StreamingPlatformTypeEnum.Twitch, packet.recipient.id.ToString());
                if (recipient == null)
                {
                    recipient = await UserViewModel.Create(packet.recipient);
                }

                await ChannelSession.Services.Chat.AddMessage(new TwitchChatMessageViewModel(packet, user, recipient));
            }
        }
Beispiel #14
0
        public ActionResult Create(FormCollection UserInfo)
        {
            try
            {
                if (UVM.Create(UserInfo))
                {
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ModelState.AddModelError("password", "El nombre de usuario o contraseña son incorrectos");

                    return(View(user));
                }
            }
            catch
            {
                return(View(user));
            }
        }
Beispiel #15
0
        public IHttpActionResult GetUser(string username)
        {
            var targetUser = this.SocialNetworkData.Users.All()
                             .FirstOrDefault(u => u.UserName == username);

            if (targetUser == null)
            {
                return(this.NotFound());
            }

            var loggedUserId = this.User.Identity.GetUserId();

            if (loggedUserId == null)
            {
                return(this.BadRequest("Invalid session token."));
            }

            var loggedUser = this.SocialNetworkData.Users.GetById(loggedUserId);

            return(this.Ok(UserViewModel.Create(targetUser, loggedUser)));
        }
Beispiel #16
0
        private async void PubSub_OnSubscriptionsGiftedReceived(object sender, PubSubSubscriptionsGiftEventModel packet)
        {
            UserViewModel gifter = packet.IsAnonymousGiftedSubscription ? UserViewModel.Create("An Anonymous Gifter") : ChannelSession.Services.User.GetActiveUserByPlatformID(StreamingPlatformTypeEnum.Twitch, packet.user_id);

            if (gifter == null)
            {
                gifter = await UserViewModel.Create(packet);
            }

            UserViewModel receiver = ChannelSession.Services.User.GetActiveUserByPlatformID(StreamingPlatformTypeEnum.Twitch, packet.recipient_id);

            if (receiver == null)
            {
                receiver = await UserViewModel.Create(new UserModel()
                {
                    id           = packet.recipient_id,
                    login        = packet.recipient_user_name,
                    display_name = packet.recipient_display_name
                });
            }

            TwitchGiftedSubEventModel giftedSubEvent = new TwitchGiftedSubEventModel(gifter, receiver, packet);

            if (ChannelSession.Settings.TwitchMassGiftedSubsFilterAmount > 0)
            {
                lock (this.newGiftedSubTracker)
                {
                    this.newGiftedSubTracker.Add(giftedSubEvent);
                }

                if (giftedSubProcessorTask == null)
                {
                    giftedSubProcessorTask = Task.Run(BackgroundGiftedSubProcessor);
                }
            }
            else
            {
                await ProcessGiftedSub(giftedSubEvent);
            }
        }
Beispiel #17
0
        private async void PubSub_OnChannelPointsRedeemed(object sender, PubSubChannelPointsRedemptionEventModel packet)
        {
            PubSubChannelPointsRedeemedEventModel redemption = packet.redemption;

            UserViewModel user = ChannelSession.Services.User.GetActiveUserByPlatformID(StreamingPlatformTypeEnum.Twitch, redemption.user.id);

            if (user == null)
            {
                user = await UserViewModel.Create(redemption.user);
            }

            List <string> arguments = null;
            Dictionary <string, string> eventCommandSpecialIdentifiers = new Dictionary <string, string>();

            eventCommandSpecialIdentifiers["rewardname"] = redemption.reward.title;
            eventCommandSpecialIdentifiers["rewardcost"] = redemption.reward.cost.ToString();
            if (!string.IsNullOrEmpty(redemption.user_input))
            {
                eventCommandSpecialIdentifiers["message"] = redemption.user_input;
                arguments = new List <string>(redemption.user_input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
            }

            if (string.IsNullOrEmpty(await ChannelSession.Services.Moderation.ShouldTextBeModerated(user, redemption.user_input)))
            {
                await ChannelSession.Services.Events.PerformEvent(EventTypeEnum.TwitchChannelPointsRedeemed, new CommandParametersModel(user, arguments, eventCommandSpecialIdentifiers));

                TwitchChannelPointsCommandModel command = ChannelSession.Services.Command.TwitchChannelPointsCommands.FirstOrDefault(c => string.Equals(c.ChannelPointRewardID.ToString(), redemption.reward.id, StringComparison.CurrentCultureIgnoreCase));
                if (command == null)
                {
                    command = ChannelSession.Services.Command.TwitchChannelPointsCommands.FirstOrDefault(c => string.Equals(c.Name, redemption.reward.title, StringComparison.CurrentCultureIgnoreCase));
                }

                if (command != null)
                {
                    Dictionary <string, string> channelPointSpecialIdentifiers = new Dictionary <string, string>(eventCommandSpecialIdentifiers);
                    await ChannelSession.Services.Command.Queue(command, new CommandParametersModel(user, platform : StreamingPlatformTypeEnum.Twitch, arguments : arguments, specialIdentifiers : channelPointSpecialIdentifiers));
                }
            }
            await ChannelSession.Services.Alerts.AddAlert(new AlertChatMessageViewModel(StreamingPlatformTypeEnum.Twitch, user, string.Format("{0} Redeemed {1}", user.FullDisplayName, redemption.reward.title), ChannelSession.Settings.AlertChannelPointsColor));
        }
Beispiel #18
0
        private async Task BackgroundDonationCheck(CancellationToken token)
        {
            IEnumerable <PatreonCampaignMember> pledges = await this.GetCampaignMembers();

            if (pledges != null && pledges.Count() > 0)
            {
                this.members = pledges.ToList();
                foreach (PatreonCampaignMember member in this.members)
                {
                    if (!this.currentMembersAndTiers.ContainsKey(member.UserID) || !this.currentMembersAndTiers[member.UserID].Equals(member.TierID))
                    {
                        PatreonTier tier = this.Campaign.GetTier(member.TierID);
                        if (tier != null)
                        {
                            CommandParametersModel parameters = new CommandParametersModel();

                            parameters.User = await ChannelSession.Services.User.GetUserFullSearch(member.User.Platform, member.User.PlatformUserID, member.User.PlatformUsername);

                            if (parameters.User != null)
                            {
                                parameters.User.Data.PatreonUserID = member.UserID;
                            }
                            else
                            {
                                parameters.User = UserViewModel.Create(member.User.PlatformUsername);
                            }

                            parameters.SpecialIdentifiers[SpecialIdentifierStringBuilder.PatreonTierNameSpecialIdentifier]   = tier.Title;
                            parameters.SpecialIdentifiers[SpecialIdentifierStringBuilder.PatreonTierAmountSpecialIdentifier] = tier.Amount.ToString();
                            parameters.SpecialIdentifiers[SpecialIdentifierStringBuilder.PatreonTierImageSpecialIdentifier]  = tier.ImageUrl;
                            await ChannelSession.Services.Events.PerformEvent(EventTypeEnum.PatreonSubscribed, parameters);
                        }
                    }
                    this.currentMembersAndTiers[member.UserID] = member.TierID;
                }
            }
        }
Beispiel #19
0
        public async Task <ActionResult <UserViewModel> > Get(string id, CancellationToken cancellationToken)
        {
            var result = await _userRepository.Get(id, cancellationToken);

            return(UserViewModel.Create(result));
        }
Beispiel #20
0
        public async Task <UserViewModel> GetUserFullSearch(StreamingPlatformTypeEnum platform, string userID = null, string username = null)
        {
            UserViewModel user = null;

            if (!string.IsNullOrEmpty(userID))
            {
                if (platform.HasFlag(StreamingPlatformTypeEnum.Twitch) && user == null)
                {
                    user = ChannelSession.Services.User.GetActiveUserByPlatformID(StreamingPlatformTypeEnum.Twitch, userID);
                }

                if (user == null)
                {
                    UserDataModel userData = await ChannelSession.Settings.GetUserDataByPlatformID(StreamingPlatformTypeEnum.Twitch, userID);

                    if (userData != null)
                    {
                        user = new UserViewModel(userData);
                    }
                    else
                    {
                        if (platform.HasFlag(StreamingPlatformTypeEnum.Twitch))
                        {
                            var twitchUser = await ChannelSession.TwitchUserConnection.GetNewAPIUserByID(userID);

                            if (twitchUser != null)
                            {
                                user = await UserViewModel.Create(twitchUser);
                            }
                        }
                    }
                }
            }

            if (user == null && !string.IsNullOrEmpty(username))
            {
                username = this.SanitizeUsername(username);
                user     = ChannelSession.Services.User.GetActiveUserByUsername(username);
                if (user == null)
                {
                    UserDataModel userData = await ChannelSession.Settings.GetUserDataByPlatformUsername(StreamingPlatformTypeEnum.Twitch, username);

                    if (userData != null)
                    {
                        user = new UserViewModel(userData);
                    }
                    else
                    {
                        if (platform.HasFlag(StreamingPlatformTypeEnum.Twitch))
                        {
                            var twitchUser = await ChannelSession.TwitchUserConnection.GetNewAPIUserByLogin(username);

                            if (twitchUser != null)
                            {
                                user = await UserViewModel.Create(twitchUser);
                            }
                        }
                    }

                    if (user == null)
                    {
                        user = UserViewModel.Create(username);
                    }
                }
            }

            return(user);
        }
Beispiel #21
0
        private async void UserClient_OnUserNoticeReceived(object sender, ChatUserNoticePacketModel userNotice)
        {
            try
            {
                if (RaidUserNoticeMessageTypeID.Equals(userNotice.MessageTypeID))
                {
                    UserViewModel user = ChannelSession.Services.User.GetActiveUserByPlatformID(StreamingPlatformTypeEnum.Twitch, userNotice.UserID.ToString());
                    if (user == null)
                    {
                        user = await UserViewModel.Create(userNotice);
                    }
                    user.SetTwitchChatDetails(userNotice);

                    CommandParametersModel parameters = new CommandParametersModel(user);
                    if (ChannelSession.Services.Events.CanPerformEvent(EventTypeEnum.TwitchChannelRaided, parameters))
                    {
                        ChannelSession.Settings.LatestSpecialIdentifiersData[SpecialIdentifierStringBuilder.LatestRaidUserData]        = user.ID;
                        ChannelSession.Settings.LatestSpecialIdentifiersData[SpecialIdentifierStringBuilder.LatestRaidViewerCountData] = userNotice.RaidViewerCount;

                        foreach (CurrencyModel currency in ChannelSession.Settings.Currency.Values.ToList())
                        {
                            currency.AddAmount(user.Data, currency.OnHostBonus);
                        }

                        foreach (StreamPassModel streamPass in ChannelSession.Settings.StreamPass.Values)
                        {
                            if (user.HasPermissionsTo(streamPass.Permission))
                            {
                                streamPass.AddAmount(user.Data, streamPass.HostBonus);
                            }
                        }

                        GlobalEvents.RaidOccurred(user, userNotice.RaidViewerCount);

                        parameters.SpecialIdentifiers["hostviewercount"] = userNotice.RaidViewerCount.ToString();
                        parameters.SpecialIdentifiers["raidviewercount"] = userNotice.RaidViewerCount.ToString();
                        await ChannelSession.Services.Events.PerformEvent(EventTypeEnum.TwitchChannelRaided, parameters);

                        await ChannelSession.Services.Alerts.AddAlert(new AlertChatMessageViewModel(StreamingPlatformTypeEnum.Twitch, user, string.Format("{0} raided with {1} viewers", user.FullDisplayName, userNotice.RaidViewerCount), ChannelSession.Settings.AlertRaidColor));
                    }
                }
                else if (SubMysteryGiftUserNoticeMessageTypeID.Equals(userNotice.MessageTypeID) && userNotice.SubTotalGifted > 0)
                {
                    if (ChannelSession.Services.Events.TwitchEventService != null)
                    {
                        UserViewModel gifter = UserViewModel.Create("An Anonymous Gifter");
                        if (!TwitchMassGiftedSubEventModel.IsAnonymousGifter(userNotice))
                        {
                            gifter = await ChannelSession.Services.User.GetUserFullSearch(StreamingPlatformTypeEnum.Twitch, userNotice.UserID.ToString(), userNotice.Login);

                            gifter.SetTwitchChatDetails(userNotice);
                        }
                        await ChannelSession.Services.Events.TwitchEventService.AddMassGiftedSub(new TwitchMassGiftedSubEventModel(userNotice, gifter));
                    }
                }
                else if (SubGiftPaidUpgradeUserNoticeMessageTypeID.Equals(userNotice.MessageTypeID))
                {
                    if (ChannelSession.Services.Events.TwitchEventService != null)
                    {
                        UserViewModel user = ChannelSession.Services.User.GetActiveUserByPlatformID(StreamingPlatformTypeEnum.Twitch, userNotice.UserID.ToString());
                        if (user == null)
                        {
                            user = await UserViewModel.Create(userNotice);
                        }
                        user.SetTwitchChatDetails(userNotice);

                        await ChannelSession.Services.Events.TwitchEventService.AddSub(new TwitchSubEventModel(user, userNotice));
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.ForceLog(LogLevel.Debug, JSONSerializerHelper.SerializeToString(userNotice));
                Logger.Log(ex);
                throw ex;
            }
        }
Beispiel #22
0
        private async Task BackgroundEventChecks(CancellationToken cancellationToken)
        {
            if (!cancellationToken.IsCancellationRequested)
            {
                if (ChannelSession.Services.WebhookService.IsWebhookHubConnected && ChannelSession.Services.WebhookService.IsWebhookHubAllowed)
                {
                    // We are using the new webhooks
                    return;
                }

                if (streamStartCheckTime != DateTimeOffset.MaxValue)
                {
                    DateTimeOffset startTime = await UptimePreMadeChatCommandModel.GetStartTime();

                    Logger.Log(LogLevel.Debug, "Check for stream start: " + startTime + " - " + streamStartCheckTime);
                    if (startTime > streamStartCheckTime)
                    {
                        Logger.Log(LogLevel.Debug, "Stream start detected");

                        streamStartCheckTime = DateTimeOffset.MaxValue;
                        await ChannelSession.Services.Events.PerformEvent(EventTypeEnum.TwitchChannelStreamStart, new CommandParametersModel());
                    }
                }

                IEnumerable <UserFollowModel> followers = await ChannelSession.TwitchUserConnection.GetNewAPIFollowers(ChannelSession.TwitchUserNewAPI, maxResult : 100);

                if (this.FollowCache.Count() > 0)
                {
                    foreach (UserFollowModel follow in followers)
                    {
                        if (!this.FollowCache.Contains(follow.from_id))
                        {
                            this.FollowCache.Add(follow.from_id);

                            UserViewModel user = ChannelSession.Services.User.GetActiveUserByPlatformID(StreamingPlatformTypeEnum.Twitch, follow.from_id);
                            if (user == null)
                            {
                                user = await UserViewModel.Create(follow);
                            }

                            if (user.UserRoles.Contains(UserRoleEnum.Banned))
                            {
                                return;
                            }

                            CommandParametersModel parameters = new CommandParametersModel(user);
                            if (ChannelSession.Services.Events.CanPerformEvent(EventTypeEnum.TwitchChannelFollowed, parameters))
                            {
                                user.FollowDate = DateTimeOffset.Now;

                                ChannelSession.Settings.LatestSpecialIdentifiersData[SpecialIdentifierStringBuilder.LatestFollowerUserData] = user.ID;

                                foreach (CurrencyModel currency in ChannelSession.Settings.Currency.Values)
                                {
                                    currency.AddAmount(user.Data, currency.OnFollowBonus);
                                }

                                foreach (StreamPassModel streamPass in ChannelSession.Settings.StreamPass.Values)
                                {
                                    if (user.HasPermissionsTo(streamPass.Permission))
                                    {
                                        streamPass.AddAmount(user.Data, streamPass.FollowBonus);
                                    }
                                }

                                await ChannelSession.Services.Events.PerformEvent(EventTypeEnum.TwitchChannelFollowed, parameters);

                                GlobalEvents.FollowOccurred(user);

                                await ChannelSession.Services.Alerts.AddAlert(new AlertChatMessageViewModel(StreamingPlatformTypeEnum.Twitch, user, string.Format("{0} Followed", user.FullDisplayName), ChannelSession.Settings.AlertFollowColor));
                            }
                        }
                    }
                }
                else
                {
                    foreach (UserFollowModel follow in followers)
                    {
                        this.FollowCache.Add(follow.from_id);
                    }
                }
            }
        }
Beispiel #23
0
        public CurrencyWindowViewModel()
        {
            if (ChannelSession.Settings.Currency.All(c => !c.Value.IsPrimary))
            {
                this.IsPrimary = true;
            }

            this.OnlineRate  = CurrencyAcquireRateTypeEnum.Minutes;
            this.OfflineRate = CurrencyAcquireRateTypeEnum.Disabled;

            this.AutomaticResetRate = CurrencyResetRateEnum.Never;

            this.AddRankCommand = this.CreateCommand(async() =>
            {
                if (string.IsNullOrEmpty(this.NewRankName))
                {
                    await DialogHelper.ShowMessage(Resources.RankRequired);
                    return;
                }

                if (this.NewRankAmount < 0)
                {
                    await DialogHelper.ShowMessage(Resources.MinimumAmountRequired);
                    return;
                }

                if (this.Ranks.Any(r => r.Name.Equals(this.NewRankName) || r.Amount == this.NewRankAmount))
                {
                    await DialogHelper.ShowMessage(Resources.UniqueRankNameAndMinimumAmountRequired);
                    return;
                }

                RankModel newRank = new RankModel(this.NewRankName, this.NewRankAmount);
                this.Ranks.Add(newRank);

                var tempRanks = this.Ranks.ToList();

                this.Ranks.ClearAndAddRange(tempRanks.OrderBy(r => r.Amount));

                this.NewRankName   = string.Empty;
                this.NewRankAmount = 0;
            });

            this.ManualResetCommand = this.CreateCommand(async() =>
            {
                if (await DialogHelper.ShowConfirmation(string.Format(Resources.ResetCurrencyRankPointsPrompt, this.CurrencyRankIdentifierString)))
                {
                    if (this.Currency != null)
                    {
                        await this.Currency.Reset();
                    }
                }
            });

            this.RetroactivelyGivePointsCommand = this.CreateCommand(async() =>
            {
                if (await DialogHelper.ShowConfirmation(string.Format(Resources.RetroactivelyGivePointsPrompt1 +
                                                                      Environment.NewLine + Environment.NewLine + Resources.RetroactivelyGivePointsPrompt2 +
                                                                      Environment.NewLine + Environment.NewLine + Resources.RetroactivelyGivePointsPrompt3, this.CurrencyRankIdentifierString)))
                {
                    if (this.Currency != null && this.Currency.AcquireInterval > 0)
                    {
                        if (this.Currency.SpecialTracking != CurrencySpecialTrackingEnum.None)
                        {
                            await DialogHelper.ShowMessage(Resources.RetroactiveUnsupported);
                            return;
                        }

                        await ChannelSession.Settings.LoadAllUserData();

                        await this.Currency.Reset();
                        foreach (MixItUp.Base.Model.User.UserDataModel userData in ChannelSession.Settings.UserData.Values)
                        {
                            int intervalsToGive = userData.ViewingMinutes / this.Currency.AcquireInterval;
                            this.Currency.AddAmount(userData, this.Currency.AcquireAmount * intervalsToGive);
                            if (userData.TwitchUserRoles.Contains(UserRoleEnum.Mod) || userData.TwitchUserRoles.Contains(UserRoleEnum.ChannelEditor))
                            {
                                this.Currency.AddAmount(userData, this.Currency.ModeratorBonus * intervalsToGive);
                            }
                            else if (userData.TwitchUserRoles.Contains(UserRoleEnum.Subscriber))
                            {
                                this.Currency.AddAmount(userData, this.Currency.SubscriberBonus * intervalsToGive);
                            }
                            ChannelSession.Settings.UserData.ManualValueChanged(userData.ID);
                        }
                    }
                }
            });

            this.ImportFromFileCommand = this.CreateCommand(async() =>
            {
                this.userImportData.Clear();
                if (await DialogHelper.ShowConfirmation(string.Format(Resources.ImportPointsPrompt1 +
                                                                      Environment.NewLine + Environment.NewLine + Resources.ImportPointsPrompt2, this.CurrencyRankIdentifierString)))
                {
                    try
                    {
                        string filePath = ChannelSession.Services.FileService.ShowOpenFileDialog();
                        if (!string.IsNullOrEmpty(filePath))
                        {
                            string fileContents = await ChannelSession.Services.FileService.ReadFile(filePath);
                            string[] lines      = fileContents.Split(new string[] { Environment.NewLine, "\n" }, StringSplitOptions.RemoveEmptyEntries);
                            if (lines.Count() > 0)
                            {
                                foreach (string line in lines)
                                {
                                    long id         = 0;
                                    string username = null;
                                    int amount      = 0;

                                    string[] segments = line.Split(new string[] { " ", "\t", "," }, StringSplitOptions.RemoveEmptyEntries);
                                    if (segments.Count() == 2)
                                    {
                                        if (!int.TryParse(segments[1], out amount))
                                        {
                                            throw new InvalidOperationException("File is not in the correct format");
                                        }

                                        if (!long.TryParse(segments[0], out id))
                                        {
                                            username = segments[0];
                                        }
                                    }
                                    else if (segments.Count() == 3)
                                    {
                                        if (!long.TryParse(segments[0], out id))
                                        {
                                            throw new InvalidOperationException("File is not in the correct format");
                                        }

                                        if (!int.TryParse(segments[2], out amount))
                                        {
                                            throw new InvalidOperationException("File is not in the correct format");
                                        }
                                    }
                                    else
                                    {
                                        throw new InvalidOperationException("File is not in the correct format");
                                    }

                                    UserViewModel user = null;
                                    if (amount > 0)
                                    {
                                        if (id > 0)
                                        {
                                            UserDataModel userData = await ChannelSession.Settings.GetUserDataByPlatformID(StreamingPlatformTypeEnum.Twitch, id.ToString());
                                            if (userData != null)
                                            {
                                                user = new UserViewModel(userData);
                                            }
                                            else
                                            {
                                                UserModel twitchUser = await ChannelSession.TwitchUserConnection.GetNewAPIUserByID(id.ToString());
                                                if (twitchUser != null)
                                                {
                                                    user = await UserViewModel.Create(twitchUser);
                                                }
                                            }
                                        }
                                        else if (!string.IsNullOrEmpty(username))
                                        {
                                            UserModel twitchUser = await ChannelSession.TwitchUserConnection.GetNewAPIUserByLogin(username);
                                            if (twitchUser != null)
                                            {
                                                user = await UserViewModel.Create(twitchUser);
                                            }
                                        }
                                    }

                                    if (user != null)
                                    {
                                        if (!this.userImportData.ContainsKey(user.ID))
                                        {
                                            this.userImportData[user.ID] = amount;
                                        }
                                        this.userImportData[user.ID] = Math.Max(this.userImportData[user.ID], amount);
                                        this.ImportFromFileText      = string.Format("{0} {1}...", this.userImportData.Count(), MixItUp.Base.Resources.Imported);
                                    }
                                }

                                await ChannelSession.Settings.LoadAllUserData();

                                foreach (var kvp in this.userImportData)
                                {
                                    if (ChannelSession.Settings.UserData.ContainsKey(kvp.Key))
                                    {
                                        MixItUp.Base.Model.User.UserDataModel userData = ChannelSession.Settings.UserData[kvp.Key];
                                        this.Currency.SetAmount(userData, kvp.Value);
                                    }
                                }

                                this.ImportFromFileText = MixItUp.Base.Resources.ImportFromFile;
                                return;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Log(ex);
                    }

                    await DialogHelper.ShowMessage(Resources.CurrencyImportFailed +
                                                   Environment.NewLine + Environment.NewLine + "<USERNAME> <AMOUNT>" +
                                                   Environment.NewLine + Environment.NewLine + "<USER ID> <AMOUNT>" +
                                                   Environment.NewLine + Environment.NewLine + "<USER ID> <USERNAME> <AMOUNT>");

                    this.ImportFromFileText = MixItUp.Base.Resources.ImportFromFile;
                }
            });

            this.ExportToFileCommand = this.CreateCommand(async() =>
            {
                await ChannelSession.Settings.LoadAllUserData();

                string filePath = ChannelSession.Services.FileService.ShowSaveFileDialog(this.Currency.Name + " Data.txt");
                if (!string.IsNullOrEmpty(filePath))
                {
                    StringBuilder fileContents = new StringBuilder();
                    foreach (MixItUp.Base.Model.User.UserDataModel userData in ChannelSession.Settings.UserData.Values.ToList())
                    {
                        fileContents.AppendLine(string.Format("{0} {1} {2}", userData.TwitchID, userData.Username, this.Currency.GetAmount(userData)));
                    }
                    await ChannelSession.Services.FileService.SaveFile(filePath, fileContents.ToString());
                }
            });

            this.HelpCommand = this.CreateCommand(() =>
            {
                ProcessHelper.LaunchLink("https://github.com/SaviorXTanren/mixer-mixitup/wiki/Currency,-Rank,-&-Inventory");
            });
        }