public TwitchChannelObjectController() { twixel = new Twixel (ClientCredentials.clientId, ClientCredentials.redirect_uri, Twixel.APIVersion.v3); //twixel = new Twixel (ClientCredentials.clientId, ClientCredentials.secretId, // ClientCredentials.redirect_uri, Twixel.APIVersion.v3); }
/// <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)); }
public VodList( DownloadForm parent, Twixel twixel ) { InitializeComponent(); DownloadWindow = parent; TwitchAPI = twixel; comboBoxService.Text = "Twitch (Recordings)"; objectListViewVideos.SecondarySortColumn = objectListViewVideos.GetColumn( "Video ID" ); objectListViewVideos.SecondarySortOrder = SortOrder.Ascending; comboBoxKnownUsers.Items.Add( " == No Preset == " ); comboBoxKnownUsers.Items.AddRange( UserInfoPersister.KnownUsers.ToArray() ); comboBoxKnownUsers.SelectedIndex = 0; buttonClear.Enabled = false; checkBoxAutoDownload.Enabled = false; if ( !Util.ShowDownloadFetched ) { buttonDownloadFetched.Enabled = false; buttonDownloadFetched.Hide(); buttonDownloadAllKnown.Enabled = false; buttonDownloadAllKnown.Hide(); checkBoxAutoDownload.Hide(); } if ( !Util.ShowAnySpecialButton ) { objectListViewVideos.Size = new Size( objectListViewVideos.Size.Width, objectListViewVideos.Size.Height + 29 ); } }
/// <summary> /// Gets the list of users that can edit this user's channel. /// Requires authorization. /// Requires channel_read. /// </summary> /// <returns>A list of users</returns> public async Task <List <User> > RetrieveChannelEditors() { TwitchConstants.Scope relevantScope = TwitchConstants.Scope.ChannelRead; if (authorized && authorizedScopes.Contains(relevantScope)) { Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("channels", name, "editors"); 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); } return(HelperMethods.LoadUsers(JObject.Parse(responseString), version)); } else { if (!authorized) { throw new TwixelException(NotAuthedError()); } else if (!authorizedScopes.Contains(relevantScope)) { throw new TwixelException(MissingPermissionError(relevantScope)); } else { throw new TwixelException(TwitchConstants.unknownErrorString); } } }
/// <summary> /// Blocks a user. Requires user authorization. /// </summary> /// <param name="username">The name of the user to block</param> /// <returns>The current list of blocked users</returns> public async Task <List <User> > BlockUser(string username) { if (authorized && authorizedScopes.Contains(TwitchConstants.Scope.UserBlocksEdit)) { Uri uri; uri = new Uri("https://api.twitch.tv/kraken/users/" + name + "/blocks/" + username); string responseString = await Twixel.PutWebData(uri, accessToken, ""); User temp = twixel.LoadUser((JObject)JObject.Parse(responseString)["user"]); if (!ContainsBlockedUser(temp.name)) { blockedUsers.Add(temp); } return(blockedUsers); } else { if (!authorized) { twixel.CreateError(name + " is not authorized"); } else if (!authorizedScopes.Contains(TwitchConstants.Scope.UserBlocksEdit)) { twixel.CreateError(name + " has not given user_blocks_edit permissions"); } return(null); } }
/// <summary> /// Gets a list of channels this user is following /// </summary> /// <param name="limit">How many channels to get at one time. Default is 25. Maximum is 100</param> /// <returns>A list of channels</returns> public async Task <List <Channel> > RetrieveFollowing(int limit) { Uri uri; if (limit <= 100) { uri = new Uri("https://api.twitch.tv/kraken/users/" + name + "/follows/channels?limit=" + limit.ToString()); } else { twixel.CreateError("You cannot get more than 100 channels at a time"); return(null); } string responseString = await Twixel.GetWebData(uri); if (Twixel.GoodStatusCode(responseString)) { nextFollowing = new WebUrl((string)JObject.Parse(responseString)["_links"]["next"]); List <Channel> followedChannels = new List <Channel>(); foreach (JObject o in (JArray)JObject.Parse(responseString)["follows"]) { followedChannels.Add(twixel.LoadChannel((JObject)o["channel"])); } return(followedChannels); } else { twixel.CreateError(responseString); return(null); } }
/// <summary> /// Gets a list of users that the user has blocked. Requires user authorization. /// </summary> /// <returns>A list of users</returns> public async Task <List <User> > RetrieveBlockedUsers() { if (authorized && authorizedScopes.Contains(TwitchConstants.Scope.UserBlocksRead)) { Uri uri; uri = new Uri("https://api.twitch.tv/kraken/users/" + name + "/blocks"); string responseString = await Twixel.GetWebData(uri, accessToken); foreach (JObject user in JObject.Parse(responseString)["blocks"]) { User temp = twixel.LoadUser((JObject)user["user"]); if (!ContainsBlockedUser(temp.name)) { blockedUsers.Add(temp); } } return(blockedUsers); } else { if (!authorized) { twixel.CreateError(name + " is not authorized"); } else if (!authorizedScopes.Contains(TwitchConstants.Scope.UserBlocksRead)) { twixel.CreateError(name + " has not given user_blocks_read permissions"); } return(null); } }
public DownloadForm() { InitializeComponent(); objectListViewDownloads.CellEditActivation = BrightIdeasSoftware.ObjectListView.CellEditActivateMode.DoubleClick; comboBoxService.SelectedIndex = 0; comboBoxPowerStateWhenDone.SelectedIndex = 0; TwitchAPI = new Twixel( "", "", Twixel.APIVersion.v3 ); JobQueue = new System.Collections.Concurrent.ConcurrentQueue<IVideoJob>(); RunningJobs = 0; if ( !Util.AllowTimedAutoFetch ) { labelStatusBar.Hide(); } objectListViewDownloads.SecondarySortColumn = objectListViewDownloads.GetColumn( "Video ID" ); objectListViewDownloads.SecondarySortOrder = SortOrder.Ascending; columnStatus.GroupKeyGetter = delegate ( object rowObject ) { return ( (IVideoJob)rowObject ).JobStatus; }; columnIndex.GroupKeyGetter = delegate ( object rowObject ) { return 0; }; objectListViewDownloads.FormatRow += ObjectListViewDownloads_FormatRow; LoadJobs(); if ( Util.AllowTimedAutoFetch ) { StartTimedAutoFetch(); } }
/// <summary> /// Updates a channel's status. Requires user authorization. /// </summary> /// <param name="status">The new status</param> /// <param name="game">The new game</param> /// <returns></returns> public async Task <Channel> UpdateChannel(string status, string game) { if (authorized && authorizedScopes.Contains(TwitchConstants.Scope.ChannelEditor)) { Uri uri; uri = new Uri("https://api.twitch.tv/kraken/channels/" + name); JObject content = new JObject(); content["channel"] = new JObject(); content["channel"]["status"] = status; content["channel"]["game"] = game; string responseString = await Twixel.PutWebData(uri, accessToken, content.ToString()); if (Twixel.GoodStatusCode(responseString)) { return(twixel.LoadChannel(JObject.Parse(responseString))); } else { twixel.CreateError(responseString); return(null); } } else { if (!authorized) { twixel.CreateError(name + " is not authorized"); } else if (!authorizedScopes.Contains(TwitchConstants.Scope.ChannelEditor)) { twixel.CreateError(name + " has not given channel_editor permissions"); } return(null); } }
/// <summary> /// Blocks a user. /// Requires authorization. /// Requires user_blocks_edit. /// </summary> /// <param name="username">The name of the user to block</param> /// <returns>The blocked user</returns> public async Task <Block> BlockUser(string username) { TwitchConstants.Scope relevantScope = TwitchConstants.Scope.UserBlocksEdit; if (authorized && authorizedScopes.Contains(relevantScope)) { Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("users", name, "blocks", username); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await Twixel.PutWebData(uri, accessToken, "", version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } return(HelperMethods.LoadBlock(JObject.Parse(responseString), version)); } else { if (!authorized) { throw new TwixelException(NotAuthedError()); } else if (!authorizedScopes.Contains(relevantScope)) { throw new TwixelException(MissingPermissionError(relevantScope)); } else { throw new TwixelException(TwitchConstants.unknownErrorString); } } }
/// <summary> /// Gets the channel object for this user. Requires user authorization. /// </summary> /// <returns>A channel object</returns> public async Task <Channel> RetrieveChannel() { if (authorized && authorizedScopes.Contains(TwitchConstants.Scope.ChannelRead)) { Uri uri; uri = new Uri("https://api.twitch.tv/kraken/channel"); string responseString = await Twixel.GetWebData(uri, accessToken); if (Twixel.GoodStatusCode(responseString)) { streamKey = (string)JObject.Parse(responseString)["stream_key"]; channel = twixel.LoadChannel(JObject.Parse(responseString)); return(channel); } else { twixel.CreateError(responseString); return(null); } } else { if (!authorized) { twixel.CreateError(name + " is not authorized"); } else if (!authorizedScopes.Contains(TwitchConstants.Scope.ChannelRead)) { twixel.CreateError(name + " has not given channel_read permissions"); } return(null); } }
// här hitta om kanalen är registrerad tidigare eller inte // och isåfall hämta kanalen via staticclient och tilldela värden ifrån den till kanalen public static Models.Channel Authed(Guid clientId) { var t = new Twixel(Config.ClientCredentials.clientId, Config.ClientCredentials.redirect_uri); var channel = ChannelMethods.GetChannelByClientId(clientId); var channelName = channel.TwitchChannelName; // TODO: add user ID var twitchChannel = _staticClient.GetChannel(channelName); channel = ChannelSyncService.SyncChannels(twitchChannel, channel); var twitchGame = twitchChannel.Game; ChannelService.CheckGameStatus(twitchGame, channel); // hur hämta subscribers? var f = _clientGeneric.GetChannelFollowers<dynamic>(channelName); var followers = _staticClient.GetChannelFollowers(channelName); ChannelService.CheckForFollowers(followers, channel); ChannelMethods.SaveChannel(channel); return channel; }
/// <summary> /// Team constructor /// </summary> /// <param name="id">ID</param> /// <param name="name">Name</param> /// <param name="info">Info</param> /// <param name="displayName">Display name</param> /// <param name="createdAt">Creation date</param> /// <param name="updatedAt">Last updated</param> /// <param name="logo">Link to logo</param> /// <param name="banner">Link to banner</param> /// <param name="background">Link to background</param> /// <param name="version">Twitch API version</param> /// <param name="baseLinksO">Base links JSON object</param> public Team(long id, string name, string info, string displayName, string createdAt, string updatedAt, string logo, string banner, string background, Twixel.APIVersion version, JObject baseLinksO) : base(baseLinksO) { this.version = version; this.id = id; this.name = name; this.info = info; this.displayName = displayName; this.createdAt = DateTime.Parse(createdAt); this.updatedAt = DateTime.Parse(updatedAt); if (logo != null) { this.logo = new Uri(logo); } if (banner != null) { this.banner = new Uri(banner); } if (background != null) { this.background = new Uri(background); } }
internal User(Twixel twixel, string name, string logo, long id, string displayName, bool?staff, string createdAt, string updatedAt, string bio) { blockedUsers = new List <User>(); subscribedUsers = new List <Subscription>(); channelEditors = new List <User>(); authorized = false; this.name = name; if (logo != null) { this.logo = new WebUrl(logo); } this.id = id; this.displayName = displayName; if (staff != null) { this.staff = staff; } this.createdAt = DateTime.Parse(createdAt); this.updatedAt = DateTime.Parse(updatedAt); if (bio != null) { this.bio = bio; } }
/// <summary> /// Emoticon constructor /// </summary> /// <param name="regex">Regex</param> /// <param name="imagesA">Emoticon images JSON object</param> /// <param name="version">Twitch API version</param> /// <param name="baseLinksO">Base links JSON object</param> public Emoticon(string regex, JArray imagesA, Twixel.APIVersion version, JObject baseLinksO) : base(baseLinksO) { this.version = version; emoticonImages = new List<EmoticonImage>(); this.regex = regex; emoticonImages = LoadEmoticonImages(imagesA); }
/// <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); } }
/// <summary> /// SearchedGame constructor /// </summary> /// <param name="name">Name</param> /// <param name="popularity">Popularity</param> /// <param name="id">ID</param> /// <param name="giantBombId">GiantBomb ID</param> /// <param name="boxO">Box JSON object</param> /// <param name="logoO">Logo JSON object</param> /// <param name="version">Twitch API version</param> /// <param name="baseLinksO">Base links JSON object</param> public SearchedGame(string name, long? popularity, long? id, long? giantBombId, JObject boxO, JObject logoO, Twixel.APIVersion version, JObject baseLinksO) : base(null, null, name, id, giantBombId, boxO, logoO, version, baseLinksO) { this.popularity = popularity; }
/// <summary> /// Block constructor /// </summary> /// <param name="updatedAt">Last updated at as a string</param> /// <param name="id">Block ID</param> /// <param name="userO">User JSON object</param> /// <param name="version">Twitch API version</param> /// <param name="baseLinksO">Base links JSON object</param> public Block(string updatedAt, long id, JObject userO, Twixel.APIVersion version, JObject baseLinksO) : base(baseLinksO) { this.version = version; this.updatedAt = DateTime.Parse(updatedAt); this.id = id; this.user = HelperMethods.LoadUser(userO, version); }
/// <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); } } }
/// <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); } } }
/// <summary> /// Badge constructor /// </summary> /// <param name="name">Badge name</param> /// <param name="linksO">Badge image links</param> /// <param name="version">Twitch API version</param> /// <param name="baseLinksO">Base links JSON object</param> public Badge(string name, JObject linksO, Twixel.APIVersion version, JObject baseLinksO) : base(baseLinksO) { this.version = version; this.name = name; if (linksO != null) { this.links = HelperMethods.LoadLinks(linksO); } }
/// <summary> /// Unfollows a channel. /// Requires authorization. /// Requires user_follows_edit. /// </summary> /// <param name="channel">The name of the channel</param> /// <returns> /// Returns true the request succeeded. /// Throws an exception if the channel was not being followed. /// Throws an exception if the channel could not be unfollowed. /// </returns> public async Task <bool> UnfollowChannel(string channel) { TwitchConstants.Scope relevantScope = TwitchConstants.Scope.UserFollowsEdit; if (authorized && authorizedScopes.Contains(relevantScope)) { Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("users", name, "follows", "channels", channel); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await Twixel.DeleteWebData(uri, accessToken, version); } catch (TwitchException ex) { if (ex.Status == 404) { throw new TwixelException(channel + " was not being followed.", ex); } else if (ex.Status == 422) { throw new TwixelException(channel + " could not be unfollowed. Try again.", 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 { throw new TwixelException(TwitchConstants.unknownErrorString); } } }
/// <summary> /// Updates a channel's status. /// Updates channel object. /// Requires authorization. /// Requires Twitch partnership if setting a delay above 0. /// Requires channel_editor. /// </summary> /// <param name="status">The new status</param> /// <param name="game">The new game</param> /// <param name="delay">Delay, requires Twitch partnership if above 0</param> /// <returns> /// Returns the channel if the request succeeded. /// Throws an exception if the user is not allowed to use delay. /// </returns> public async Task <Channel> UpdateChannel(string status = "", string game = "", int delay = 0) { TwitchConstants.Scope relevantScope = TwitchConstants.Scope.ChannelEditor; if (authorized && authorizedScopes.Contains(relevantScope)) { Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("channels", name); Uri uri = new Uri(url.ToString()); JObject content = new JObject(); content["channel"] = new JObject(); content["channel"]["status"] = status; content["channel"]["game"] = game; if (version == Twixel.APIVersion.v3) { content["channel"]["delay"] = delay; } string responseString; try { responseString = await Twixel.PutWebData(uri, accessToken, content.ToString(), version); } catch (TwitchException ex) { if (ex.Status == 422) { throw new TwixelException(name + " is not allowed to use delay.", ex); } else { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } } channel = HelperMethods.LoadChannel(JObject.Parse(responseString), version); return(channel); } else { if (!authorized) { throw new TwixelException(NotAuthedError()); } else if (!authorizedScopes.Contains(relevantScope)) { throw new TwixelException(MissingPermissionError(relevantScope)); } else { throw new TwixelException(TwitchConstants.unknownErrorString); } } }
/// <summary> /// Ingest constructor /// </summary> /// <param name="name">Name</param> /// <param name="defaultIngest">Default status</param> /// <param name="id">ID</param> /// <param name="urlTemplate">Url template</param> /// <param name="avalibility">Availability</param> /// <param name="version">Twitch API version</param> /// <param name="baseLinksO">Base links JSON object</param> public Ingest(string name, bool defaultIngest, long id, string urlTemplate, double avalibility, Twixel.APIVersion version, JObject baseLinksO) : base(baseLinksO) { this.version = version; this.name = name; this.defaultIngest = defaultIngest; this.id = id; this.urlTemplate = new Uri(urlTemplate); this.avalibility = avalibility; }
internal User(Twixel twixel, string accessToken, List <TwitchConstants.Scope> authorizedScopes, string name, string logo, long id, string displayName, string email, bool?staff, bool?partnered, string createdAt, string updatedAt, string bio) { this.twixel = twixel; blockedUsers = new List <User>(); subscribedUsers = new List <Subscription>(); channelEditors = new List <User>(); authorized = true; this.accessToken = accessToken; this.authorizedScopes = authorizedScopes; this.name = name; if (logo != null) { this.logo = new WebUrl(logo); } this.id = id; this.displayName = displayName; if (email != null) { this.email = email; } if (staff != null) { this.staff = staff; } if (partnered != null) { this.partnered = partnered; } this.createdAt = DateTime.Parse(createdAt); this.updatedAt = DateTime.Parse(updatedAt); if (bio != null) { this.bio = bio; } }
/// <summary> /// Checks to see if a specified user is subscribed to this user. /// Requires authorization. /// Requires Twitch partnership. /// Requires channel_check_subscription. /// </summary> /// <param name="username">The name of the user</param> /// <returns>A Subscription object of type User if the user is subscribed</returns> public async Task <Subscription <User> > RetrieveSubsciber(string username) { TwitchConstants.Scope relevantScope = TwitchConstants.Scope.ChannelCheckSubscription; if (authorized && authorizedScopes.Contains(relevantScope) && partnered) { Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("channels", name, "subcriptions", username); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await Twixel.GetWebData(uri, accessToken, version); } catch (TwitchException ex) { if (ex.Status == 404) { throw new TwixelException(username + " is not subscribed.", ex); } else { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } } return(HelperMethods.LoadUserSubscription(JObject.Parse(responseString), 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); } } }
/// <summary> /// Checks to see if this user is subcribed to a specified channel. /// Requires authorization. /// Requires user_subscriptions. /// </summary> /// <param name="channel">The name of the channel</param> /// <returns> /// A subscription object of type Channel if the request succeeds. /// Throws an exception if the user is not subscribed to the channel. /// Throws an exception if the channel is not partnered.</returns> public async Task <Subscription <Channel> > RetrieveSubscription(string channel) { TwitchConstants.Scope relevantScope = TwitchConstants.Scope.UserSubcriptions; if (authorized && authorizedScopes.Contains(relevantScope)) { Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("users", name, "subscriptions", channel); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await Twixel.GetWebData(uri, accessToken, version); } catch (TwitchException ex) { if (ex.Status == 404) { throw new TwixelException("You are not subscribed to " + channel, ex); } else if (ex.Status == 422) { throw new TwixelException(channel + " has no subscription program", ex); } else { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } } return(HelperMethods.LoadChannelSubscription(JObject.Parse(responseString), version)); } else { if (!authorized) { throw new TwixelException(NotAuthedError()); } else if (!authorizedScopes.Contains(relevantScope)) { throw new TwixelException(MissingPermissionError(relevantScope)); } else { throw new TwixelException(TwitchConstants.unknownErrorString); } } }
/// <summary> /// Resets this user's stream key. /// Updates channel object. /// Requires authorization. /// Requires channel_stream. /// </summary> /// <returns>The new stream key</returns> public async Task <string> ResetStreamKey() { TwitchConstants.Scope relevantScope = TwitchConstants.Scope.ChannelStream; if (authorized && authorizedScopes.Contains(relevantScope)) { Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("channels", name, "stream_key"); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await Twixel.DeleteWebData(uri, accessToken, version); } catch (TwitchException ex) { if (ex.Status == 422) { throw new TwixelException("Error resetting stream key.", ex); } else { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } } JObject responseObject = JObject.Parse(responseString); channel = HelperMethods.LoadChannel(responseObject, version); streamKey = (string)responseObject["stream_key"]; return(streamKey); } else { if (!authorized) { throw new TwixelException(NotAuthedError()); } else if (!authorizedScopes.Contains(relevantScope)) { throw new TwixelException(MissingPermissionError(relevantScope)); } else { throw new TwixelException(TwitchConstants.unknownErrorString); } } }
/// <summary> /// Game constructor /// </summary> /// <param name="viewers">Number of viewers</param> /// <param name="channels">Number of channels</param> /// <param name="name">Name</param> /// <param name="id">ID</param> /// <param name="giantBombId">GiantBomb ID</param> /// <param name="boxO">Box JSON object</param> /// <param name="logoO">Logo JSON object</param> /// <param name="version">Twitch API version</param> /// <param name="baseLinksO">Base links JSON object</param> public Game(long? viewers, long? channels, string name, long? id, long? giantBombId, JObject boxO, JObject logoO, Twixel.APIVersion version, JObject baseLinksO) : base (baseLinksO) { this.version = version; this.viewers = viewers; this.channels = channels; this.name = name; this.id = id; this.giantBombId = giantBombId; this.box = HelperMethods.LoadLinks(boxO); this.logo = HelperMethods.LoadLinks(logoO); }
/// <summary> /// Gets a list of users that the user has blocked. /// Requires authorization. /// Requires user_blocks_read. /// </summary> /// <param name="offset">Object offset for pagination. Default is 0.</param> /// <param name="limit">Maximum number of objects in array. Default is 25. Maximum is 100.</param> /// <returns>A list of blocked users</returns> public async Task <List <Block> > RetrieveBlockedUsers(int offset = 0, int limit = 25) { TwitchConstants.Scope relevantScope = TwitchConstants.Scope.UserBlocksRead; if (authorized && authorizedScopes.Contains(relevantScope)) { Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("users", name, "blocks"); if (limit <= 100) { url.SetQueryParam("limit", limit); } else { url.SetQueryParam("limit", 100); } url.SetQueryParam("offset", offset); 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); } return(HelperMethods.LoadBlocks(JObject.Parse(responseString), version)); } else { if (!authorized) { throw new TwixelException(NotAuthedError()); } else if (!authorizedScopes.Contains(relevantScope)) { throw new TwixelException(MissingPermissionError(relevantScope)); } else { throw new TwixelException(TwitchConstants.unknownErrorString); } } }
/// <summary> /// Unblocks a user. Requires user authorization. /// </summary> /// <param name="username">The name of the user to block</param> /// <returns>The current list of blocked users</returns> public async Task <List <User> > UnblockUser(string username) { if (authorized && authorizedScopes.Contains(TwitchConstants.Scope.UserBlocksEdit)) { Uri uri; uri = new Uri("https://api.twitch.tv/kraken/users/" + name + "/blocks/" + username); string responseString = await Twixel.DeleteWebData(uri, accessToken); if (responseString == "") { blockedUsers.Remove(GetBlockedUser(username)); return(blockedUsers); } else if (responseString == "404") { twixel.CreateError(username + "was never blocked"); return(null); } else if (responseString == "422") { twixel.CreateError(username + " could not be unblocked. Try again."); return(null); } else { twixel.CreateError(responseString); return(null); } } else { if (!authorized) { twixel.CreateError(name + " is not authorized"); } else if (!authorizedScopes.Contains(TwitchConstants.Scope.UserBlocksEdit)) { twixel.CreateError(name + " has not given user_blocks_edit permissions"); } return(null); } }
/// <summary> /// Follows a channel. /// Requires authorization. /// Requires user_follows_edit. /// </summary> /// <param name="channel">The name of the channel</param> /// <param name="notifications"> /// Whether :user should receive email/push notifications /// (depending on their notification settings) when the specified channel goes live. /// Default is false. /// </param> /// <returns> /// A Follow object of type Channel if the request succeeds. /// Throws an exception if the request was not processed. /// </returns> public async Task <Follow <Channel> > FollowChannel(string channel, bool notifications = false) { TwitchConstants.Scope relevantScope = TwitchConstants.Scope.UserFollowsEdit; if (authorized && authorizedScopes.Contains(relevantScope)) { Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("users", name, "follows", "channels", channel).SetQueryParam("notifications", notifications); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await Twixel.PutWebData(uri, accessToken, "", version); } catch (TwitchException ex) { if (ex.Status == 422) { throw new TwixelException("Could not follow " + channel); } else { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } } return(HelperMethods.LoadChannelFollow(JObject.Parse(responseString), version)); } else { if (!authorized) { throw new TwixelException(NotAuthedError()); } else if (!authorizedScopes.Contains(relevantScope)) { throw new TwixelException(MissingPermissionError(relevantScope)); } else { throw new TwixelException(TwitchConstants.unknownErrorString); } } }
/// <summary> /// Get a list of videos from the channels this user follows /// </summary> /// <param name="offset">Object offset for pagination. Default is 0.</param> /// <param name="limit">How many videos to get at once. Default is 25. Maximum is 100.</param> /// <returns>A list of videos.</returns> public async Task <List <Video> > RetrieveFollowedVideos(int offset = 0, int limit = 10) { if (version == Twixel.APIVersion.v3) { TwitchConstants.Scope relevantScope = TwitchConstants.Scope.UserRead; if (authorized && authorizedScopes.Contains(relevantScope)) { Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("videos", "followed"); 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); } return(HelperMethods.LoadVideos(JObject.Parse(responseString), version)); } else { if (!authorized) { throw new TwixelException(NotAuthedError()); } else if (!authorizedScopes.Contains(relevantScope)) { throw new TwixelException(MissingPermissionError(relevantScope)); } else { throw new TwixelException(TwitchConstants.unknownErrorString); } } } else { throw new TwixelException(TwitchConstants.v2UnsupportedErrorString); } }
/// <summary> /// Unfollows a channel. Requires user authorization. /// </summary> /// <param name="channel">The name of the channel</param> /// <returns>If the request succeeded</returns> public async Task <bool> UnfollowChannel(string channel) { if (authorized && authorizedScopes.Contains(TwitchConstants.Scope.UserFollowsEdit)) { Uri uri; uri = new Uri("https://api.twitch.tv/kraken/users/" + name + "/follows/channels/" + channel); string responseString = await Twixel.DeleteWebData(uri, accessToken); if (responseString == "") { return(true); } else if (responseString == "404") { twixel.CreateError(channel + "was not being followed"); return(false); } else if (responseString == "422") { twixel.CreateError(channel + " could not be unfollowed. Try again."); return(false); } else { twixel.CreateError(responseString); return(false); } } else { if (!authorized) { twixel.CreateError(name + " is not authorized"); } else if (!authorizedScopes.Contains(TwitchConstants.Scope.UserFollowsEdit)) { twixel.CreateError(name + " has not given user_follows_edit permissions"); } return(false); } }
/// <summary> /// Checks to see if this user is subcribed to a specified channel. Requires user authorization. /// </summary> /// <param name="channel">The name of the channel</param> /// <returns>A subscription object</returns> public async Task <Subscription> RetrieveSubscription(string channel) { if (authorized && authorizedScopes.Contains(TwitchConstants.Scope.UserSubcriptions)) { Uri uri; uri = new Uri("https://api.twitch.tv/kraken/users/" + name + "/subscriptions/" + channel); string responseString = await Twixel.GetWebData(uri, accessToken); if (responseString != "422" && responseString != "404") { return(LoadSubscription(JObject.Parse(responseString))); } else if (responseString == "404") { twixel.CreateError("You are not subscribed to " + channel); return(null); } else if (responseString == "422") { twixel.CreateError(channel + " has no subscription program"); return(null); } else { twixel.CreateError(responseString); return(null); } } else { if (!authorized) { twixel.CreateError(name + " is not authorized"); } else if (!authorizedScopes.Contains(TwitchConstants.Scope.UserSubcriptions)) { twixel.CreateError(name + " has not given user_subscriptions permissions"); } return(null); } }
/// <summary> /// Checks to see if a specified user is subscribed to this user. Requires user authorization. Requires Twitch partnership. /// </summary> /// <param name="username">The name of the user</param> /// <returns>A subscription object if the user is subscribed</returns> public async Task <Subscription> RetrieveSubsciber(string username) { if (authorized && authorizedScopes.Contains(TwitchConstants.Scope.ChannelCheckSubscription)) { Uri uri; uri = new Uri("https://api.twitch.tv/kraken/channels/" + name + "/subscriptions/" + username); string responseString = await Twixel.GetWebData(uri, accessToken); if (responseString != "422" && responseString != "404") { return(LoadSubscriber(JObject.Parse(responseString))); } else if (responseString == "404") { twixel.CreateError(username + " is not subscribed"); return(null); } else if (responseString == "422") { twixel.CreateError("You aren't partnered so you cannot have subs"); return(null); } else { twixel.CreateError(responseString); return(null); } } else { if (!authorized) { twixel.CreateError(name + " is not authorized"); } else if (!authorizedScopes.Contains(TwitchConstants.Scope.ChannelCheckSubscription)) { twixel.CreateError(name + " has not given channel_check_subscription permissions"); } return(null); } }
/// <summary> /// Gets a list of users subscribed to this user. Requires user authorization. Requires Twitch partnership. /// </summary> /// <param name="getNext">If this method was called before then this will get the next page of subscriptions</param> /// <returns>A list of subscriptions</returns> public async Task <List <Subscription> > RetriveSubscribers(bool getNext) { if (authorized && authorizedScopes.Contains(TwitchConstants.Scope.ChannelSubscriptions)) { Uri uri; uri = new Uri("https://api.twitch.tv/kraken/channels/" + name + "/subscriptions"); 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); } }
/// <summary> /// Checks to see if this user is following a specified channel /// </summary> /// <param name="channel">The name of the channel</param> /// <returns>A channel object</returns> public async Task <Channel> RetrieveFollowing(string channel) { Uri uri; uri = new Uri("https://api.twitch.tv/kraken/users/" + name + "/follows/channels/" + channel); string responseString = await Twixel.GetWebData(uri); if (responseString != "404") { return(twixel.LoadChannel((JObject)JObject.Parse(responseString)["channel"])); } else if (responseString == "404") { twixel.CreateError(name + " is not following " + channel); return(null); } else { twixel.CreateError(responseString); return(null); } }
/// <summary> /// Gets the list of users that can edit this user's channel. Requires user authorization. /// </summary> /// <returns>A list of users</returns> public async Task <List <User> > RetrieveChannelEditors() { if (authorized && authorizedScopes.Contains(TwitchConstants.Scope.ChannelRead)) { Uri uri; uri = new Uri("https://api.twitch.tv/kraken/channels/" + name + "/editors"); string responseString = await Twixel.GetWebData(uri, accessToken); if (Twixel.GoodStatusCode(responseString)) { foreach (JObject o in (JArray)JObject.Parse(responseString)["users"]) { if (!ContainsEditor((string)o["name"])) { channelEditors.Add(twixel.LoadUser(o)); } } return(channelEditors); } else { twixel.CreateError(responseString); return(null); } } else { if (!authorized) { twixel.CreateError(name + " is not authorized"); } else if (!authorizedScopes.Contains(TwitchConstants.Scope.ChannelRead)) { twixel.CreateError(name + " has not given channel_read permissions"); } return(null); } }
/// <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"]); } }
/// <summary> /// Checks to see if this user is following a specified channel /// </summary> /// <param name="channel">The name of the channel</param> /// <returns> /// A Follow object of type Channel if the request succeeded. /// Throws an exception if the user is not following the specified channel. /// </returns> public async Task <Follow <Channel> > RetrieveFollowing(string channel) { Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("users", name, "follows", "channels", channel); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await Twixel.GetWebData(uri, version); } catch (TwitchException ex) { if (ex.Status == 404) { throw new TwixelException(name + " is not following " + channel, ex); } else { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } } return(HelperMethods.LoadChannelFollow(JObject.Parse(responseString), version)); }
public TwitchVideoJob( Twixel api, string id, StatusUpdate.IStatusUpdate statusUpdater = null ) { JobStatus = VideoJobStatus.NotStarted; StatusUpdater = statusUpdater == null ? new StatusUpdate.NullStatusUpdate() : statusUpdater; VideoInfo = new GenericVideoInfo() { Service = StreamService.Twitch, VideoId = id }; TwitchAPI = api; }
public static async Task AutoDownload( UserInfo[] users, Twixel twitchApi, DownloadForm downloadWindow ) { for ( int i = 0; i < users.Length; ++i ) { var userInfo = users[i]; if ( userInfo != null ) { if ( !userInfo.AutoDownload ) { continue; } List<IVideoInfo> videos = new List<IVideoInfo>(); while ( true ) { downloadWindow.SetAutoDownloadStatus( "[" + ( i + 1 ).ToString() + "/" + users.Length.ToString() + "] Fetching " + userInfo.ToString() + "..." ); try { FetchReturnValue fetchReturnValue; do { await Task.Delay( 15000 ); fetchReturnValue = await Fetch( twitchApi, userInfo, videos.Count ); if ( fetchReturnValue.Success ) { videos.AddRange( fetchReturnValue.Videos ); } } while ( fetchReturnValue.Success && fetchReturnValue.HasMore ); break; } catch ( Exception ex ) { // TODO: Better errorhandling? break; } } DownloadFetched( videos, downloadWindow ); } } }
private static async Task<FetchReturnValue> Fetch( Twixel twitchApi, UserInfo userInfo, int offset ) { List<IVideoInfo> videosToAdd = new List<IVideoInfo>(); bool hasMore = true; long maxVideos = -1; switch ( userInfo.Service ) { case ServiceVideoCategoryType.TwitchRecordings: case ServiceVideoCategoryType.TwitchHighlights: Total<List<Video>> broadcasts = await twitchApi.RetrieveVideos( userInfo.Username, offset: offset, limit: 25, broadcasts: userInfo.Service == ServiceVideoCategoryType.TwitchRecordings, hls: false ); if ( broadcasts.total.HasValue ) { hasMore = offset + broadcasts.wrapped.Count < broadcasts.total; maxVideos = (long)broadcasts.total; } else { hasMore = broadcasts.wrapped.Count == 25; } foreach ( var v in broadcasts.wrapped ) { videosToAdd.Add( new TwitchVideoInfo( v ) ); } break; case ServiceVideoCategoryType.HitboxRecordings: List<HitboxVideo> videos = await Hitbox.RetrieveVideos( userInfo.Username, offset: offset, limit: 100 ); hasMore = videos.Count == 100; foreach ( var v in videos ) { videosToAdd.Add( new HitboxVideoInfo( v ) ); } break; default: return new FetchReturnValue { Success = false, HasMore = false, TotalVideos = maxVideos, Videos = videosToAdd }; } if ( videosToAdd.Count <= 0 ) { return new FetchReturnValue { Success = true, HasMore = false, TotalVideos = maxVideos, Videos = videosToAdd }; } if ( UserInfoPersister.KnownUsers.Add( userInfo ) ) { UserInfoPersister.Save(); } return new FetchReturnValue { Success = true, HasMore = hasMore, TotalVideos = maxVideos, Videos = videosToAdd }; }
public TwitchApi(IConfig config) { _twixel = new Twixel(config.TwitchClientID, config.TwitchRedirectUrl); }