Exemple #1
0
        /// <summary>
        /// Gets a Total object containing a list of Follow objects of type User following the specified user
        /// </summary>
        /// <param name="offset">Object offset for pagination. Default is 0.</param>
        /// <param name="limit">How many users to get at one time. Default is 25. Maximum is 100</param>
        /// <param name="direction">Creation date sorting direction. Default is Descending.</param>
        /// <returns>A Total object containing a list of Follow objects of type User</returns>
        public async Task <Total <List <Follow <User> > > > RetrieveFollowers(int offset = 0, int limit = 25,
                                                                              TwitchConstants.Direction direction = TwitchConstants.Direction.Decending)
        {
            Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("channels", name, "follows");

            if (limit <= 100)
            {
                url.SetQueryParam("limit", limit);
            }
            else
            {
                url.SetQueryParam("limit", 100);
            }
            url.SetQueryParams(new
            {
                offset    = offset,
                direction = TwitchConstants.DirectionToString(direction)
            });
            Uri    uri = new Uri(url.ToString());
            string responseString;

            try
            {
                responseString = await Twixel.GetWebData(uri, version);
            }
            catch (TwitchException ex)
            {
                throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex);
            }
            JObject responseObject        = JObject.Parse(responseString);
            List <Follow <User> > follows = HelperMethods.LoadUserFollows(responseObject, version);

            return(HelperMethods.LoadTotal(responseObject, follows, version));
        }
Exemple #2
0
        /// <summary>
        /// Gets the top videos on Twitch
        /// </summary>
        /// <param name="game">The name of the game to get videos for</param>
        /// <param name="period">The time period you want to look in</param>
        /// <param name="offset">Object offset for pagination. Default is 0.</param>
        /// <param name="limit">How many videos to get at one time. Default is 10. Maximum is 100</param>
        /// <param name="version">Twitch API version</param>
        /// <returns>A list of videos</returns>
        public async Task <List <Video> > RetrieveTopVideos(string game = null,
                                                            TwitchConstants.Period period = TwitchConstants.Period.Week,
                                                            int offset         = 0, int limit = 25,
                                                            APIVersion version = APIVersion.None)
        {
            if (version == APIVersion.None)
            {
                version = DefaultVersion;
            }
            Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("videos", "top");

            url.SetQueryParam("game", game);
            if (limit <= 100)
            {
                url.SetQueryParam("limit", limit);
            }
            else
            {
                url.SetQueryParam("limit", 100);
            }
            url.SetQueryParam("period", TwitchConstants.PeriodToString(period));

            Uri    uri = new Uri(url.ToString());
            string responseString;

            try
            {
                responseString = await GetWebData(uri, version);
            }
            catch (TwitchException ex)
            {
                throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex);
            }
            return(HelperMethods.LoadVideos(JObject.Parse(responseString), version));
        }
Exemple #3
0
        /// <summary>
        /// Get a list of users subscribed to this user. Requires user authorization. Requires Twitch partnership.
        /// </summary>
        /// <param name="limit">How many subscriptions to get at one time. Default is 25. Maximum is 100</param>
        /// <param name="direction">Creation date sorting direction</param>
        /// <returns>A list of subscriptions</returns>
        public async Task <List <Subscription> > RetriveSubscribers(int limit, TwitchConstants.Direction direction)
        {
            if (authorized && authorizedScopes.Contains(TwitchConstants.Scope.ChannelSubscriptions))
            {
                Uri    uri;
                string url = "https://api.twitch.tv/kraken/channels/" + name + "/subscriptions";
                if (limit <= 100)
                {
                    url += "?limit=" + limit.ToString();
                }
                else
                {
                    twixel.CreateError("You cannot fetch more than 100 subs at a time");
                    return(null);
                }

                if (direction != TwitchConstants.Direction.None)
                {
                    url += "&direction=" + TwitchConstants.DirectionToString(direction);
                }

                uri = new Uri(url);
                string responseString = await Twixel.GetWebData(uri, accessToken);

                if (responseString != "422")
                {
                    totalSubscribers = (int)JObject.Parse(responseString)["_total"];
                    nextSubs         = new WebUrl((string)JObject.Parse(responseString)["_links"]["next"]);
                    foreach (JObject o in (JArray)JObject.Parse(responseString)["subscriptions"])
                    {
                        if (!ContainsSubscriber((string)o["user"]["name"]))
                        {
                            subscribedUsers.Add(LoadSubscriber(o));
                        }
                    }
                    return(subscribedUsers);
                }
                else
                {
                    twixel.CreateError("You aren't partnered so you cannot have subs");
                    return(null);
                }
            }
            else
            {
                if (!authorized)
                {
                    twixel.CreateError(name + " is not authorized");
                }
                else if (!authorizedScopes.Contains(TwitchConstants.Scope.ChannelSubscriptions))
                {
                    twixel.CreateError(name + " has not given channel_subscriptions permissions");
                }
                return(null);
            }
        }
Exemple #4
0
 /// <summary>
 /// Get a Total object containing a list of Subscription of type User
 /// Requires authorization.
 /// Requires Twitch partnership.
 /// Requires channel_subscriptions.
 /// </summary>
 /// <param name="offset">Object offset for pagination. Default is 0.</param>
 /// <param name="limit">How many subscriptions to get at one time. Default is 25. Maximum is 100</param>
 /// <param name="direction">Creation date sorting direction. Default is Ascending.</param>
 /// <returns>A Total object containing a list of Subscription objects of type User</returns>
 public async Task <Total <List <Subscription <User> > > > RetriveSubscribers(int offset = 0, int limit = 25,
                                                                              TwitchConstants.Direction direction = TwitchConstants.Direction.Ascending)
 {
     TwitchConstants.Scope relevantScope = TwitchConstants.Scope.ChannelSubscriptions;
     if (authorized && authorizedScopes.Contains(relevantScope) && partnered)
     {
         Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("channels", name, "subscriptions");
         if (limit <= 100)
         {
             url.SetQueryParam("limit", limit);
         }
         else
         {
             url.SetQueryParam("limit", 100);
         }
         url.SetQueryParams(new
         {
             offset    = offset,
             direction = TwitchConstants.DirectionToString(direction)
         });
         Uri    uri = new Uri(url.ToString());
         string responseString;
         try
         {
             responseString = await Twixel.GetWebData(uri, accessToken, version);
         }
         catch (TwitchException ex)
         {
             throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex);
         }
         JObject responseObject           = JObject.Parse(responseString);
         List <Subscription <User> > subs = HelperMethods.LoadUserSubscriptions(JObject.Parse(responseString), version);
         return(HelperMethods.LoadTotal(responseObject, subs, version));
     }
     else
     {
         if (!authorized)
         {
             throw new TwixelException(NotAuthedError());
         }
         else if (!authorizedScopes.Contains(relevantScope))
         {
             throw new TwixelException(MissingPermissionError(relevantScope));
         }
         else if (!partnered)
         {
             throw new TwixelException(NotPartneredError());
         }
         else
         {
             throw new TwixelException(TwitchConstants.unknownErrorString);
         }
     }
 }
Exemple #5
0
 /// <summary>
 /// Starts a commercial on this user's live stream.
 /// Requires authorization.
 /// Requires Twitch partnership.
 /// Requires channel_commercial.
 /// </summary>
 /// <param name="length">The length of the commercial</param>
 /// <returns>
 /// Returns true if the request succeeded.
 /// Throws an exception if the user is not partnered.
 /// </returns>
 public async Task <bool> StartCommercial(TwitchConstants.CommercialLength length)
 {
     TwitchConstants.Scope relevantScope = TwitchConstants.Scope.ChannelCommercial;
     if (authorized && authorizedScopes.Contains(relevantScope) && partnered)
     {
         Url    url = new Url(TwitchConstants.baseUrl).AppendPathSegments("channels", name, "commercial");
         Uri    uri = new Uri(url.ToString());
         string responseString;
         try
         {
             responseString = await Twixel.PostWebData(uri, accessToken,
                                                       "length=" + TwitchConstants.LengthToInt(length).ToString(), version);
         }
         catch (TwitchException ex)
         {
             if (ex.Status == 422)
             {
                 throw new TwixelException(ex.Message, ex);
             }
             else
             {
                 throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex);
             }
         }
         if (string.IsNullOrEmpty(responseString))
         {
             return(true);
         }
         else
         {
             throw new TwixelException(TwitchConstants.unknownErrorString);
         }
     }
     else
     {
         if (!authorized)
         {
             throw new TwixelException(NotAuthedError());
         }
         else if (!authorizedScopes.Contains(relevantScope))
         {
             throw new TwixelException(MissingPermissionError(relevantScope));
         }
         else if (!partnered)
         {
             throw new TwixelException(NotPartneredError());
         }
         else
         {
             throw new TwixelException(TwitchConstants.unknownErrorString);
         }
     }
 }
        private async void twitchLoginWebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
        {
            if (twitchLoginWebView.Source.Host == "golf1052.com")
            {
                if (twitchLoginWebView.Source.Query != "?error=access_denied&error_description=The+user+denied+you+access")
                {
                    twitchLoginWebView.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    string[] splitString       = twitchLoginWebView.Source.Fragment.Split('=');
                    string[] secondSplitString = splitString[1].Split('&');
                    string[] scopes            = splitString[2].Split('+');
                    List <TwitchConstants.Scope> authorizedScopes = new List <TwitchConstants.Scope>();
                    foreach (string scope in scopes)
                    {
                        authorizedScopes.Add(TwitchConstants.StringToScope(scope));
                    }
                    User user = null;
                    user = await AppConstants.twixel.RetrieveUserWithAccessToken(secondSplitString[0]);

                    JObject userData = new JObject();
                    userData["active"] = 0;
                    JObject userO = new JObject();
                    userO["name"]         = user.name;
                    userO["access_token"] = user.accessToken;
                    userData["user"]      = userO;
                    StorageFolder roamingFolder = ApplicationData.Current.RoamingFolder;
                    StorageFile   usersFile     = await roamingFolder.CreateFileAsync("usersFile.json", CreationCollisionOption.ReplaceExisting);

                    await FileIO.WriteTextAsync(usersFile, userData.ToString());

                    AppConstants.ActiveUser = user;
                    Frame.Navigate(typeof(HomePage));
                }
                else if (twitchLoginWebView.Source.Query == "?error=access_denied&error_description=The+user+denied+you+access")
                {
                    Frame.Navigate(typeof(HomePage));
                }
            }
        }
Exemple #7
0
        /// <summary>
        /// Gets the status of an access token, if the token is valid this returns an
        /// authorized user object
        /// </summary>
        /// <param name="accessToken">The access token</param>
        /// <param name="version">Twitch API version</param>
        /// <returns>
        /// An authorized user if the request succeeds.
        /// Throws an exception if the token is not valid.</returns>
        public async Task <User> RetrieveUserWithAccessToken(string accessToken,
                                                             APIVersion version = APIVersion.None)
        {
            if (version == APIVersion.None)
            {
                version = DefaultVersion;
            }
            Url    url = new Url(TwitchConstants.baseUrl);
            Uri    uri = new Uri(url.ToString());
            string responseString;

            try
            {
                responseString = await Twixel.GetWebData(uri, accessToken, version);
            }
            catch (TwitchException ex)
            {
                throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex);
            }
            JObject responseObject = JObject.Parse(responseString);
            JObject token          = (JObject)responseObject["token"];

            if ((bool)token["valid"])
            {
                JArray userScopesA = (JArray)token["authorization"]["scopes"];
                List <TwitchConstants.Scope> userScopes = new List <TwitchConstants.Scope>();
                foreach (string scope in userScopesA)
                {
                    userScopes.Add(TwitchConstants.StringToScope(scope));
                }
                return(await RetrieveAuthenticatedUser(accessToken, userScopes, version));
            }
            else
            {
                throw new TwixelException(accessToken + " is not a valid access token",
                                          (JObject)responseObject["_links"]);
            }
        }
Exemple #8
0
        /// <summary>
        /// Creates a URL that can be used to authenticate a user
        /// </summary>
        /// <param name="scopes">The permissions you are requesting. Must contain at least one permission.</param>
        /// <returns>
        /// Returns a URL to be used for authenticating a user.
        /// Throws an exception if the scopes list contained no scopes.
        /// </returns>
        public Uri Login(List <TwitchConstants.Scope> scopes)
        {
            if (scopes == null)
            {
                throw new TwixelException("The list of scopes cannot be null.");
            }

            if (scopes.Count > 0)
            {
                List <TwitchConstants.Scope> cleanScopes = new List <TwitchConstants.Scope>();
                for (int i = 0; i < scopes.Count; i++)
                {
                    if (!cleanScopes.Contains(scopes[i]))
                    {
                        cleanScopes.Add(scopes[i]);
                    }
                    else
                    {
                        scopes.RemoveAt(i);
                        i--;
                    }
                }
                Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("oauth2", "authorize").SetQueryParams(new
                {
                    response_type = "token",
                    client_id     = clientID,
                    redirect_uri  = redirectUrl,
                    scope         = TwitchConstants.ListOfScopesToStringOfScopes(scopes)
                });
                Uri uri = new Uri(url.ToString());
                return(uri);
            }
            else
            {
                throw new TwixelException("You must have at least 1 scope.");
            }
        }
Exemple #9
0
        private async void webView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
        {
            if (webView.Source.Host == "golf1052.com")
            {
                if (webView.Source.Query != "?error=access_denied&error_description=The+user+denied+you+access")
                {
                    webView.Visibility = Visibility.Collapsed;
                    string[] splitString       = webView.Source.Fragment.Split('=');
                    string[] secondSplitString = splitString[1].Split('&');
                    string[] scopes            = splitString[2].Split('+');
                    List <TwitchConstants.Scope> authorizedScopes = new List <TwitchConstants.Scope>();
                    foreach (string scope in scopes)
                    {
                        authorizedScopes.Add(TwitchConstants.StringToScope(scope));
                    }
                    User user = null;
                    try
                    {
                        user = await AppConstants.Twixel.RetrieveUserWithAccessToken(secondSplitString[0]);
                    }
                    catch (TwixelException ex)
                    {
                        if (ex.Message == TwitchConstants.twitchAPIErrorString)
                        {
                            await HelperMethods.ShowMessageDialog("There was a problem trying to authenticate. Here's the error:\n" + ex.Error.Error);
                        }
                        else
                        {
                            await HelperMethods.ShowMessageDialog(ex.Message);
                        }
                    }
                    catch (Exception ex)
                    {
                        await HelperMethods.ShowMessageDialog("There was a general error.\n" + ex.Message);
                    }
                    finally
                    {
                        Frame.Navigate(typeof(HomePage));
                    }

                    ApplicationDataContainer roamingSettings = ApplicationData.Current.RoamingSettings;
                    StorageFolder            roamingFolder   = ApplicationData.Current.RoamingFolder;
                    StorageFile usersFile = await roamingFolder.GetFileAsync("Users.json");

                    string usersDataString = await FileIO.ReadTextAsync(usersFile);

                    JObject userO = new JObject();
                    userO["name"]         = user.name;
                    userO["access_token"] = user.accessToken;

                    if (string.IsNullOrEmpty(usersDataString))
                    {
                        JArray usersA = new JArray();
                        usersA.Add(userO);
                        await FileIO.WriteTextAsync(usersFile, usersA.ToString());
                    }
                    else
                    {
                        JArray usersA    = JArray.Parse(usersDataString);
                        bool   foundUser = false;
                        foreach (JObject fileUser in usersA)
                        {
                            if ((string)fileUser["name"] == user.name)
                            {
                                fileUser["access_token"] = user.accessToken;
                                foundUser = true;
                                break;
                            }
                        }
                        if (!foundUser)
                        {
                            usersA.Add(userO);
                        }
                        await FileIO.WriteTextAsync(usersFile, usersA.ToString());
                    }

                    roamingSettings.Values["activeUser"] = user.name;
                    AppConstants.activeUser = user;
                    Frame.Navigate(typeof(HomePage));
                }
                else
                {
                    Frame.Navigate(typeof(HomePage));
                }
            }
        }
Exemple #10
0
        /// <summary>
        /// Starts a commercial on this user's live stream. Requires user authorization. Requires Twitch partnership
        /// </summary>
        /// <param name="length">The length of the commercial</param>
        /// <returns>If the request succeeded</returns>
        public async Task <bool> StartCommercial(TwitchConstants.Length length)
        {
            if (authorized && authorizedScopes.Contains(TwitchConstants.Scope.ChannelCommercial))
            {
                Uri uri;
                uri = new Uri("https://api.twitch.tv/kraken/channels/test_user1/commercial");
                string responseString = await Twixel.PostWebData(uri, accessToken, "length=" + TwitchConstants.LengthToInt(length).ToString());

                if (responseString == "")
                {
                    return(true);
                }
                else if (responseString == "422")
                {
                    twixel.CreateError("You are not partnered so you cannot run commercials");
                    return(false);
                }
                else
                {
                    twixel.CreateError(responseString);
                    return(false);
                }
            }
            else
            {
                if (!authorized)
                {
                    twixel.CreateError(name + " is not authorized");
                }
                else if (!authorizedScopes.Contains(TwitchConstants.Scope.ChannelCommercial))
                {
                    twixel.CreateError(name + " has not given channel_commercial permissions");
                }
                return(false);
            }
        }
Exemple #11
0
 private string MissingPermissionError(TwitchConstants.Scope scope)
 {
     return(name + " has not given " + TwitchConstants.ScopeToString(scope) + " permissions.");
 }