private User UpdateUser(UserDataViewModel user, User updatedUserData)
        {
            if (updatedUserData == null || !updatedUserData.ID.Equals(user.ID))
            {
                var resp = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new ObjectContent <Error>(new Error {
                        Message = "Unable to parse update data from POST body."
                    }, new JsonMediaTypeFormatter(), "application/json"),
                    ReasonPhrase = "Invalid POST Body"
                };
                throw new HttpResponseException(resp);
            }

            if (updatedUserData.ViewingMinutes.HasValue)
            {
                user.ViewingMinutes = updatedUserData.ViewingMinutes.Value;
            }

            foreach (CurrencyAmount currencyData in updatedUserData.CurrencyAmounts)
            {
                if (ChannelSession.Settings.Currencies.ContainsKey(currencyData.ID))
                {
                    user.SetCurrencyAmount(ChannelSession.Settings.Currencies[currencyData.ID], currencyData.Amount);
                }
            }

            return(UserFromUserDataViewModel(user));
        }
        private User UpdateUser(UserDataViewModel user, User updatedUserData)
        {
            if (updatedUserData == null || !updatedUserData.ID.Equals(user.ID))
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            if (updatedUserData.ViewingMinutes.HasValue)
            {
                user.ViewingMinutes = updatedUserData.ViewingMinutes.Value;
            }

            foreach (CurrencyAmount currencyData in updatedUserData.CurrencyAmounts)
            {
                if (ChannelSession.Settings.Currencies.ContainsKey(currencyData.ID))
                {
                    user.SetCurrencyAmount(ChannelSession.Settings.Currencies[currencyData.ID], currencyData.Amount);
                }
            }

            return(UserFromUserDataViewModel(user));
        }
Example #3
0
        protected override HttpStatusCode RequestReceived(HttpListenerRequest request, string data, out string result)
        {
            if (!string.IsNullOrEmpty(request.RawUrl) && request.RawUrl.ToLower().StartsWith("/api"))
            {
                List <string> urlSegments = new List <string>(request.RawUrl.ToLower().Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries));
                urlSegments.RemoveAt(0);
                if (urlSegments.Count() == 0)
                {
                    result = "Welcome to the Mix It Up Developer API! More detailed documentation about this service, please visit https://github.com/SaviorXTanren/mixer-mixitup/wiki/Developer-API";
                    return(HttpStatusCode.OK);
                }
                else if (urlSegments[0].Equals("mixer"))
                {
                    if (urlSegments.Count() == 3 && urlSegments[1].Equals("users"))
                    {
                        if (request.HttpMethod.Equals("GET"))
                        {
                            string identifier = urlSegments[2];

                            UserModel user = null;
                            if (uint.TryParse(identifier, out uint userID))
                            {
                                user = ChannelSession.Connection.GetUser(userID).Result;
                            }
                            else
                            {
                                user = ChannelSession.Connection.GetUser(identifier).Result;
                            }

                            if (user != null)
                            {
                                result = SerializerHelper.SerializeToString(user);
                                return(HttpStatusCode.OK);
                            }
                            else
                            {
                                result = "Could not find the user specified";
                                return(HttpStatusCode.NotFound);
                            }
                        }
                    }
                }
                else if (urlSegments[0].Equals("users") && urlSegments.Count >= 2)
                {
                    string identifier = urlSegments[1];

                    UserDataViewModel user = null;
                    if (uint.TryParse(identifier, out uint userID) && ChannelSession.Settings.UserData.ContainsKey(userID))
                    {
                        user = ChannelSession.Settings.UserData[userID];
                    }
                    else
                    {
                        user = ChannelSession.Settings.UserData.Values.FirstOrDefault(u => u.UserName.ToLower().Equals(identifier));
                    }

                    if (request.HttpMethod.Equals("GET"))
                    {
                        if (user != null)
                        {
                            result = SerializerHelper.SerializeToString(new UserDeveloperAPIModel(user));
                            return(HttpStatusCode.OK);
                        }
                        else
                        {
                            result = "Could not find the user specified";
                            return(HttpStatusCode.NotFound);
                        }
                    }
                    else if (request.HttpMethod.Equals("PUT") || request.HttpMethod.Equals("PATCH"))
                    {
                        UserDeveloperAPIModel updatedUserData = SerializerHelper.DeserializeFromString <UserDeveloperAPIModel>(data);
                        if (updatedUserData != null && updatedUserData.ID.Equals(user.ID))
                        {
                            user.ViewingMinutes = updatedUserData.ViewingMinutes;
                            foreach (UserCurrencyDeveloperAPIModel currencyData in updatedUserData.CurrencyAmounts)
                            {
                                if (ChannelSession.Settings.Currencies.ContainsKey(currencyData.ID))
                                {
                                    user.SetCurrencyAmount(ChannelSession.Settings.Currencies[currencyData.ID], currencyData.Amount);
                                }
                            }

                            result = SerializerHelper.SerializeToString(new UserDeveloperAPIModel(user));
                            return(HttpStatusCode.OK);
                        }
                        else
                        {
                            result = "Invalid data/could not find matching user";
                            return(HttpStatusCode.NotFound);
                        }
                    }
                }
                else if (urlSegments[0].Equals("currency") && urlSegments.Count() == 2)
                {
                    if (request.HttpMethod.Equals("GET"))
                    {
                        string identifier = urlSegments[1];
                        if (Guid.TryParse(identifier, out Guid currencyID) && ChannelSession.Settings.Currencies.ContainsKey(currencyID))
                        {
                            result = SerializerHelper.SerializeToString(ChannelSession.Settings.Currencies[currencyID]);
                            return(HttpStatusCode.OK);
                        }
                        else
                        {
                            result = "Could not find the currency specified";
                            return(HttpStatusCode.NotFound);
                        }
                    }
                }
                else if (urlSegments[0].Equals("commands"))
                {
                    List <CommandBase> allCommands = new List <CommandBase>();
                    allCommands.AddRange(ChannelSession.AllChatCommands);
                    allCommands.AddRange(ChannelSession.Settings.InteractiveCommands);
                    allCommands.AddRange(ChannelSession.Settings.EventCommands);
                    allCommands.AddRange(ChannelSession.Settings.TimerCommands);
                    allCommands.AddRange(ChannelSession.Settings.ActionGroupCommands);

                    if (request.HttpMethod.Equals("GET"))
                    {
                        if (urlSegments.Count() == 1)
                        {
                            result = SerializerHelper.SerializeToString(allCommands);
                            return(HttpStatusCode.OK);
                        }
                        else if (urlSegments.Count() == 2 && Guid.TryParse(urlSegments[1], out Guid ID))
                        {
                            CommandBase command = allCommands.FirstOrDefault(c => c.ID.Equals(ID));
                            if (command != null)
                            {
                                result = SerializerHelper.SerializeToString(command);
                                return(HttpStatusCode.OK);
                            }
                            else
                            {
                                result = "Could not find the command specified";
                                return(HttpStatusCode.NotFound);
                            }
                        }
                    }
                    else if (request.HttpMethod.Equals("POST") && urlSegments.Count() == 2 && Guid.TryParse(urlSegments[1], out Guid ID))
                    {
                        CommandBase command = allCommands.FirstOrDefault(c => c.ID.Equals(ID));
                        if (command != null)
                        {
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                            command.Perform();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

                            result = "";
                            return(HttpStatusCode.OK);
                        }
                        else
                        {
                            result = "Could not find the command specified";
                            return(HttpStatusCode.NotFound);
                        }
                    }
                }

                result = "This is not a valid API";
                return(HttpStatusCode.BadRequest);
            }
            else
            {
                result = "This is not a valid API";
                return(HttpStatusCode.BadRequest);
            }
        }
        private async Task AddUserData(IEnumerable <string> dataValues)
        {
            int currentColumn = 1;
            UserDataViewModel importedUserData = new UserDataViewModel();

            foreach (string dataValue in dataValues)
            {
                bool columnMatched = false;
                foreach (ImportDataColumns dataColumn in this.dataColumns)
                {
                    if (dataColumn.GetColumnNumber() == currentColumn)
                    {
                        switch (dataColumn.DataName)
                        {
                        case "User ID":
                            if (uint.TryParse(dataValue, out uint id))
                            {
                                importedUserData.ID = id;
                            }
                            columnMatched = true;
                            break;

                        case "User Name":
                            importedUserData.UserName = dataValue;
                            columnMatched             = true;
                            break;

                        case "Live Viewing Time (Hours)":
                            if (int.TryParse(dataValue, out int liveHours))
                            {
                                importedUserData.ViewingMinutes = liveHours * 60;
                            }
                            columnMatched = true;
                            break;

                        case "Live Viewing Time (Mins)":
                            if (int.TryParse(dataValue, out int liveMins))
                            {
                                importedUserData.ViewingMinutes = liveMins;
                            }
                            columnMatched = true;
                            break;

                        case "Offline Viewing Time (Hours)":
                            if (int.TryParse(dataValue, out int offlineHours))
                            {
                                importedUserData.OfflineViewingMinutes = offlineHours * 60;
                            }
                            columnMatched = true;
                            break;

                        case "Offline Viewing Time (Mins)":
                            if (int.TryParse(dataValue, out int offlineMins))
                            {
                                importedUserData.OfflineViewingMinutes = offlineMins;
                            }
                            columnMatched = true;
                            break;

                        default:
                            foreach (UserCurrencyViewModel currency in ChannelSession.Settings.Currencies.Values)
                            {
                                if (currency.Name.Equals(dataColumn.DataName))
                                {
                                    if (int.TryParse(dataValue, out int currencyAmount))
                                    {
                                        importedUserData.SetCurrencyAmount(currency, currencyAmount);
                                    }
                                    columnMatched = true;
                                    break;
                                }
                            }
                            break;
                        }
                    }

                    if (columnMatched)
                    {
                        break;
                    }
                }
                currentColumn++;
            }

            if (importedUserData.ID == 0)
            {
                UserModel user = await ChannelSession.Connection.GetUser(importedUserData.UserName);

                if (user != null)
                {
                    importedUserData.ID = user.id;
                }
            }
            else if (string.IsNullOrEmpty(importedUserData.UserName))
            {
                UserModel user = await ChannelSession.Connection.GetUser(importedUserData.ID);

                if (user != null)
                {
                    importedUserData.UserName = user.username;
                }
            }

            if (importedUserData.ID > 0 && !string.IsNullOrEmpty(importedUserData.UserName))
            {
                ChannelSession.Settings.UserData[importedUserData.ID] = importedUserData;
                usersImported++;
                this.Dispatcher.Invoke(() => { this.ImportDataButton.Content = string.Format("Imported {0} Users", usersImported); });
            }
        }
Example #5
0
        private async void ConstellationClient_OnSubscribedEventOccurred(object sender, ConstellationLiveEventModel e)
        {
            ChannelModel  channel = null;
            UserViewModel user    = null;

            JToken userToken;

            if (e.payload.TryGetValue("user", out userToken))
            {
                user = new UserViewModel(userToken.ToObject <UserModel>());

                JToken subscribeStartToken;
                if (e.payload.TryGetValue("since", out subscribeStartToken))
                {
                    user.SubscribeDate = subscribeStartToken.ToObject <DateTimeOffset>();
                }
            }
            else if (e.payload.TryGetValue("hoster", out userToken))
            {
                channel = userToken.ToObject <ChannelModel>();
                user    = new UserViewModel(channel.id, channel.token);
            }

            if (user != null)
            {
                UserDataViewModel userData = ChannelSession.Settings.UserData.GetValueIfExists(user.ID, new UserDataViewModel(user));

                if (e.channel.Equals(ConstellationClientWrapper.ChannelFollowEvent.ToString()))
                {
                    foreach (UserCurrencyViewModel currency in ChannelSession.Settings.Currencies.Values)
                    {
                        userData.SetCurrencyAmount(currency, currency.OnFollowBonus);
                    }
                }
                else if (e.channel.Equals(ConstellationClientWrapper.ChannelHostedEvent.ToString()))
                {
                    foreach (UserCurrencyViewModel currency in ChannelSession.Settings.Currencies.Values)
                    {
                        userData.SetCurrencyAmount(currency, currency.OnHostBonus);
                    }
                }
                else if (e.channel.Equals(ConstellationClientWrapper.ChannelSubscribedEvent.ToString()) || e.channel.Equals(ConstellationClientWrapper.ChannelResubscribedEvent.ToString()) ||
                         e.channel.Equals(ConstellationClientWrapper.ChannelResubscribedSharedEvent.ToString()))
                {
                    foreach (UserCurrencyViewModel currency in ChannelSession.Settings.Currencies.Values)
                    {
                        userData.SetCurrencyAmount(currency, currency.OnSubscribeBonus);
                    }
                }

                if (e.channel.Equals(ConstellationClientWrapper.ChannelSubscribedEvent.ToString()))
                {
                    user.SubscribeDate = DateTimeOffset.Now;
                }
            }

            if (e.channel.Equals(ConstellationClientWrapper.ChannelUpdateEvent.ToString()))
            {
                IDictionary <string, JToken> payloadValues = e.payload;
                if (payloadValues.ContainsKey("online") && (bool)payloadValues["online"])
                {
                    UptimeChatCommand.SetUptime(DateTimeOffset.Now);
                }
            }
            else
            {
                foreach (EventCommand command in ChannelSession.Settings.EventCommands)
                {
                    EventCommand foundCommand = null;

                    if (command.MatchesEvent(e))
                    {
                        foundCommand = command;
                    }

                    if (command.EventType == ConstellationEventTypeEnum.channel__id__subscribed && e.channel.Equals(ConstellationClientWrapper.ChannelResubscribeSharedEvent.ToString()))
                    {
                        foundCommand = command;
                    }

                    if (foundCommand != null)
                    {
                        if (command.EventType == ConstellationEventTypeEnum.channel__id__hosted && channel != null)
                        {
                            foundCommand.AddSpecialIdentifier("hostviewercount", channel.viewersCurrent.ToString());
                        }

                        if (user != null)
                        {
                            await foundCommand.Perform(user);
                        }
                        else
                        {
                            await foundCommand.Perform();
                        }

                        return;
                    }
                }
            }

            if (this.OnEventOccurred != null)
            {
                this.OnEventOccurred(this, e);
            }
        }
        private async Task ProcessDeveloperAPIRequest(HttpListenerContext listenerContext, string httpMethod, List <string> urlSegments, string data)
        {
            if (urlSegments[0].Equals("mixer"))
            {
                if (urlSegments.Count() == 3 && urlSegments[1].Equals("users"))
                {
                    if (httpMethod.Equals(GetHttpMethod))
                    {
                        string identifier = urlSegments[2];

                        UserModel user = null;
                        if (uint.TryParse(identifier, out uint userID))
                        {
                            user = ChannelSession.Connection.GetUser(userID).Result;
                        }
                        else
                        {
                            user = ChannelSession.Connection.GetUser(identifier).Result;
                        }

                        if (user != null)
                        {
                            await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(user));

                            return;
                        }
                        else
                        {
                            await this.CloseConnection(listenerContext, HttpStatusCode.NotFound, "Could not find the user specified");

                            return;
                        }
                    }
                }
            }
            else if (urlSegments[0].Equals("users") && urlSegments.Count() >= 2)
            {
                string identifier = urlSegments[1];

                UserDataViewModel user = null;
                if (uint.TryParse(identifier, out uint userID) && ChannelSession.Settings.UserData.ContainsKey(userID))
                {
                    user = ChannelSession.Settings.UserData[userID];
                }
                else
                {
                    user = ChannelSession.Settings.UserData.Values.FirstOrDefault(u => u.UserName.ToLower().Equals(identifier));
                }

                if (httpMethod.Equals(GetHttpMethod))
                {
                    if (user != null)
                    {
                        await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(new UserDeveloperAPIModel(user)));

                        return;
                    }
                    else
                    {
                        await this.CloseConnection(listenerContext, HttpStatusCode.NotFound, "Could not find the user specified");

                        return;
                    }
                }
                else if (httpMethod.Equals(PutHttpMethod) || httpMethod.Equals(PatchHttpMethod))
                {
                    UserDeveloperAPIModel updatedUserData = SerializerHelper.DeserializeFromString <UserDeveloperAPIModel>(data);
                    if (updatedUserData != null && updatedUserData.ID.Equals(user.ID))
                    {
                        user.ViewingMinutes = updatedUserData.ViewingMinutes;
                        foreach (UserCurrencyDeveloperAPIModel currencyData in updatedUserData.CurrencyAmounts)
                        {
                            if (ChannelSession.Settings.Currencies.ContainsKey(currencyData.ID))
                            {
                                user.SetCurrencyAmount(ChannelSession.Settings.Currencies[currencyData.ID], currencyData.Amount);
                            }
                        }

                        await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(new UserDeveloperAPIModel(user)));

                        return;
                    }
                    else
                    {
                        await this.CloseConnection(listenerContext, HttpStatusCode.NotFound, "Invalid data/could not find matching user");

                        return;
                    }
                }
            }
            else if (urlSegments[0].Equals("currency") && urlSegments.Count() == 2)
            {
                if (httpMethod.Equals(GetHttpMethod))
                {
                    string identifier = urlSegments[1];
                    if (Guid.TryParse(identifier, out Guid currencyID) && ChannelSession.Settings.Currencies.ContainsKey(currencyID))
                    {
                        await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(ChannelSession.Settings.Currencies[currencyID]));

                        return;
                    }
                    else
                    {
                        await this.CloseConnection(listenerContext, HttpStatusCode.NotFound, "Could not find the currency specified");

                        return;
                    }
                }
            }
            else if (urlSegments[0].Equals("commands"))
            {
                List <CommandBase> allCommands = new List <CommandBase>();
                allCommands.AddRange(ChannelSession.Settings.ChatCommands);
                allCommands.AddRange(ChannelSession.Settings.InteractiveCommands);
                allCommands.AddRange(ChannelSession.Settings.EventCommands);
                allCommands.AddRange(ChannelSession.Settings.TimerCommands);
                allCommands.AddRange(ChannelSession.Settings.ActionGroupCommands);
                allCommands.AddRange(ChannelSession.Settings.GameCommands);

                if (httpMethod.Equals(GetHttpMethod))
                {
                    if (urlSegments.Count() == 1)
                    {
                        await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(allCommands));

                        return;
                    }
                    else if (urlSegments.Count() == 2 && Guid.TryParse(urlSegments[1], out Guid ID))
                    {
                        CommandBase command = allCommands.FirstOrDefault(c => c.ID.Equals(ID));
                        if (command != null)
                        {
                            await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(command));

                            return;
                        }
                        else
                        {
                            await this.CloseConnection(listenerContext, HttpStatusCode.NotFound, "Could not find the command specified");

                            return;
                        }
                    }
                }
                else if (httpMethod.Equals(PostHttpMethod))
                {
                    if (urlSegments.Count() == 2 && Guid.TryParse(urlSegments[1], out Guid ID))
                    {
                        CommandBase command = allCommands.FirstOrDefault(c => c.ID.Equals(ID));
                        if (command != null)
                        {
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                            command.Perform();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

                            await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(command));

                            return;
                        }
                        else
                        {
                            await this.CloseConnection(listenerContext, HttpStatusCode.NotFound, "Could not find the command specified");

                            return;
                        }
                    }
                }
                else if (httpMethod.Equals(PutHttpMethod) || httpMethod.Equals(PatchHttpMethod))
                {
                    if (urlSegments.Count() == 2 && Guid.TryParse(urlSegments[1], out Guid ID))
                    {
                        CommandBase commandData    = SerializerHelper.DeserializeAbstractFromString <CommandBase>(data);
                        CommandBase matchedCommand = allCommands.FirstOrDefault(c => c.ID.Equals(ID));
                        if (matchedCommand != null)
                        {
                            matchedCommand.IsEnabled = commandData.IsEnabled;

                            await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(matchedCommand));

                            return;
                        }
                        else
                        {
                            await this.CloseConnection(listenerContext, HttpStatusCode.NotFound, "Invalid data/could not find matching command");

                            return;
                        }
                    }
                }
            }
            else if (urlSegments[0].Equals("spotify") && urlSegments.Count() >= 2)
            {
                if (ChannelSession.Services.Spotify != null)
                {
                    if (httpMethod.Equals(GetHttpMethod))
                    {
                        if (urlSegments.Count() == 2)
                        {
                            if (urlSegments[1].Equals("current"))
                            {
                                await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(await ChannelSession.Services.Spotify.GetCurrentlyPlaying()));

                                return;
                            }
                            else if (urlSegments[1].StartsWith("search?query="))
                            {
                                string search = urlSegments[1].Replace("search?query=", "");
                                search = HttpUtility.UrlDecode(search);

                                await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(await ChannelSession.Services.Spotify.SearchSongs(search)));

                                return;
                            }
                        }
                    }
                    else if (httpMethod.Equals(PostHttpMethod))
                    {
                        if (urlSegments.Count() == 2)
                        {
                            if (urlSegments[1].Equals("play"))
                            {
                                if (string.IsNullOrEmpty(data))
                                {
                                    await ChannelSession.Services.Spotify.PlayCurrentlyPlaying();

                                    await this.CloseConnection(listenerContext, HttpStatusCode.OK, string.Empty);

                                    return;
                                }
                                else
                                {
                                    if (await ChannelSession.Services.Spotify.PlaySong(data))
                                    {
                                        await this.CloseConnection(listenerContext, HttpStatusCode.OK, string.Empty);
                                    }
                                    else
                                    {
                                        await this.CloseConnection(listenerContext, HttpStatusCode.BadRequest, "We were unable to play the uri you specified. If your uri is correct, please try again in a moment");
                                    }
                                    return;
                                }
                            }
                            else if (urlSegments[1].Equals("pause"))
                            {
                                await ChannelSession.Services.Spotify.PauseCurrentlyPlaying();

                                await this.CloseConnection(listenerContext, HttpStatusCode.OK, string.Empty);

                                return;
                            }
                            else if (urlSegments[1].Equals("next"))
                            {
                                await ChannelSession.Services.Spotify.NextCurrentlyPlaying();

                                await this.CloseConnection(listenerContext, HttpStatusCode.OK, string.Empty);

                                return;
                            }
                            else if (urlSegments[1].Equals("previous"))
                            {
                                await ChannelSession.Services.Spotify.PreviousCurrentlyPlaying();

                                await this.CloseConnection(listenerContext, HttpStatusCode.OK, string.Empty);

                                return;
                            }
                        }
                    }
                }
                else
                {
                    await this.CloseConnection(listenerContext, HttpStatusCode.ServiceUnavailable, "The Spotify service is not currently connected in Mix It Up");
                }
            }

            await this.CloseConnection(listenerContext, HttpStatusCode.BadRequest, "This is not a valid API");
        }