/// <summary> /// Updates the specified broadcaster's channel with the specified tags. /// </summary> /// <param name="broadcaster">The broadcaster to get stream tags for.</param> /// <param name="tags">The set of tags to update with</param> /// <returns>An awaitable Task</returns> public async Task UpdateStreamTags(UserModel broadcaster, IEnumerable <TagModel> tags = null) { Validator.ValidateVariable(broadcaster, "broadcaster"); List <string> tagIDs = (tags != null) ? tags.Select(t => t.tag_id).ToList() : new List <string>(); await this.PutAsync("streams/tags?broadcaster_id=" + broadcaster.id, AdvancedHttpClient.CreateContentFromObject(new { tag_ids = tagIDs })); }
public override async Task <Result> Connect() { try { string authorizationCode = await this.ConnectViaOAuthRedirect(string.Format(StreamlabsService.AuthorizationUrl, StreamlabsService.ClientID)); if (!string.IsNullOrEmpty(authorizationCode)) { JObject payload = new JObject(); payload["grant_type"] = "authorization_code"; payload["client_id"] = StreamlabsService.ClientID; payload["client_secret"] = ChannelSession.Services.Secrets.GetSecret("StreamlabsSecret"); payload["code"] = authorizationCode; payload["redirect_uri"] = OAuthExternalServiceBase.DEFAULT_OAUTH_LOCALHOST_URL; this.token = await this.PostAsync <OAuthTokenModel>("token", AdvancedHttpClient.CreateContentFromObject(payload), autoRefreshToken : false); if (this.token != null) { token.authorizationCode = authorizationCode; return(await this.InitializeInternal()); } } } catch (Exception ex) { Logger.Log(ex); return(new Result(ex)); } return(new Result(false)); }
public async Task <DiscordMessage> CreateMessage(DiscordChannel channel, string message, string filePath) { try { DiscordMessage messageObj = new DiscordMessage() { Content = message }; var messageContent = AdvancedHttpClient.CreateContentFromObject(messageObj); var multiPart = new MultipartFormDataContent(); multiPart.Add(messageContent, "\"payload_json\""); if (!string.IsNullOrEmpty(filePath)) { byte[] bytes = await ChannelSession.Services.FileService.ReadFileAsBytes(filePath); if (bytes != null && bytes.Length > 0) { var fileContent = new ByteArrayContent(bytes); string fileName = System.IO.Path.GetFileName(filePath); multiPart.Add(fileContent, "\"file\"", $"\"{fileName}\""); } } return(await this.PostAsync <DiscordMessage>("channels/" + channel.ID + "/messages", multiPart)); } catch (Exception ex) { Logger.Log(ex); } return(null); }
/// <summary> /// Processes the webhook topic request /// </summary> /// <param name="callback">URL where notifications will be delivered.</param> /// <param name="mode"></param> /// <param name="topic">URL for the topic to subscribe to or unsubscribe from. topic maps to a new Twitch API endpoint.</param> /// <param name="lease_seconds">Number of seconds until the subscription expires. Default: 0. Maximum: 864000.</param> /// <param name="secret">Secret used to sign notification payloads. The X-Hub-Signature header is generated by sha256(secret, notification_bytes).</param> /// <returns>True if the request was successfully sent to Twitch, otherise false</returns> private async Task <bool> processWebhookTopicRequest(string callback, string mode, string topic, int lease_seconds, string secret) { var hubObject = new WebhookHubModel() { callback = callback, mode = mode, topic = topic, lease_seconds = lease_seconds.ToString(), secret = secret }; try { var response = await this.PostAsync("webhooks/hub", AdvancedHttpClient.CreateContentFromObject(hubObject)); if (response.IsSuccessStatusCode) { return(true); } else { return(false); } } catch (Exception) { return(false); } }
/// <summary> /// Updates the specified channel. /// </summary> /// <param name="id">The ID of the channel</param> /// <param name="title">The title of the channel</param> /// <param name="categoryID">The ID of the category for the channel</param> /// <param name="langaugeCode">The language code for the channel</param> /// <param name="audience">The viewing audience for the channel</param> /// <returns>Whether the update was successful</returns> public async Task <bool> UpdateChannel(string id, string title = null, string categoryID = null, string langaugeCode = null, ChannelAudienceTypeEnum?audience = null) { Validator.ValidateString(id, "id"); JObject jobj = new JObject(); jobj["channel_id"] = id; if (!string.IsNullOrEmpty(title)) { jobj["live_title"] = title; } if (!string.IsNullOrEmpty(categoryID)) { jobj["category_id"] = categoryID; } if (!string.IsNullOrEmpty(langaugeCode)) { jobj["language_code"] = langaugeCode; } if (audience != null) { jobj["audi_type"] = audience.ToString(); } HttpResponseMessage response = await this.PostAsync("channels/update", AdvancedHttpClient.CreateContentFromObject(jobj)); return(response.IsSuccessStatusCode); }
/// <summary> /// Sets the communities for a channel. /// </summary> /// <param name="channel">The channel to set communities for</param> /// <param name="communities">The communities to set</param> /// <returns>An awaitable Task</returns> public async Task SetChannelCommunities(ChannelModel channel, IEnumerable <CommunityModel> communities) { Validator.ValidateVariable(channel, "channel"); JObject content = new JObject(); content["community_ids"] = new JArray(communities.Select(c => c.id).ToList()); await this.PutAsync("channels/" + channel.id + "/communities", AdvancedHttpClient.CreateContentFromObject(content)); }
/// <summary> /// Sends a message to the currently authenticated channel. /// </summary> /// <param name="message">The message to send</param> /// <returns>An awaitable Task</returns> public async Task SendMessage(string message) { Validator.ValidateString(message, "message"); JObject jobj = new JObject(); jobj["content"] = message; await this.PostAsync("chat/send", AdvancedHttpClient.CreateContentFromObject(jobj)); }
/// <summary> /// Processes the webhook topic request /// </summary> /// <param name="callback">URL where notifications will be delivered.</param> /// <param name="mode">Whether the request is a subscribing or unsubscribing</param> /// <param name="topic">URL for the topic to subscribe to or unsubscribe from. topic maps to a new Twitch API endpoint.</param> /// <param name="lease_seconds">Number of seconds until the subscription expires. Default: 0. Maximum: 864000.</param> /// <param name="secret">Secret used to sign notification payloads. The X-Hub-Signature header is generated by sha256(secret, notification_bytes).</param> /// <returns>An awaitable task</returns> /// <exception cref="HttpRestRequestException">Throw in the event of a failed request</exception> private async Task processWebhookTopicRequest(string callback, string mode, string topic, int lease_seconds, string secret) { HttpResponseMessage response = await this.PostAsync("webhooks/hub", AdvancedHttpClient.CreateContentFromObject(new WebhookSubscriptionRegistrationModel(callback, mode, topic, lease_seconds, secret))); if (!response.IsSuccessStatusCode) { throw new HttpRestRequestException(response); } }
/// <summary> /// Gets the channel matching the specified username. /// </summary> /// <param name="username">The channel username to search for</param> /// <returns>The matching channel</returns> public async Task <ChannelModel> GetChannelByUsername(string username) { Validator.ValidateString(username, "username"); JObject requestParameters = new JObject(); requestParameters["username"] = username; return(await this.PostAsync <ChannelModel>("channels/id", AdvancedHttpClient.CreateContentFromObject(requestParameters))); }
/// <summary> /// Gets the channel matching the specified ID. /// </summary> /// <param name="id">The channel ID to search for</param> /// <returns>The matching channel</returns> public async Task <ChannelModel> GetChannelByID(string id) { Validator.ValidateString(id, "id"); JObject requestParameters = new JObject(); requestParameters["channel_id"] = id; return(await this.PostAsync <ChannelModel>("channels/id", AdvancedHttpClient.CreateContentFromObject(requestParameters))); }
/// <summary> /// Performs a POST REST request using the provided request URI for paged cursor data. /// </summary> /// <param name="requestUri">The request URI to use</param> /// <param name="maxResults">The maximum number of results. Will be either that amount or slightly more</param> /// <param name="maxLimit">The maximum limit of results that can be returned in a single request</param> /// <param name="parameters">Optional parameters to include in the request</param> /// <returns>A type-casted object of the contents of the response</returns> public async Task <IEnumerable <T> > PostPagedTokenAsync <T>(string requestUri, int maxResults = 1, int maxLimit = -1, Dictionary <string, object> parameters = null) where T : PageDataResponseModel { JObject requestParameters = new JObject(); if (maxLimit > 0) { requestParameters["limit"] = maxLimit; } requestParameters["after"] = true; if (parameters != null) { foreach (var kvp in parameters) { requestParameters[kvp.Key] = kvp.Value.ToString(); } } List <T> results = new List <T>(); string token = null; int cursor = -1; int count = 0; do { if (!string.IsNullOrEmpty(token) && cursor > 0) { requestParameters["token"] = token; requestParameters["cursor"] = cursor; } T data = await this.PostAsync <T>(requestUri, AdvancedHttpClient.CreateContentFromObject(requestParameters)); if (data != null) { results.Add(data); count += data.GetItemCount(); if (data.cursor < data.total_page) { token = data.token; cursor = data.cursor; } else { token = null; cursor = -1; } } }while (count < maxResults && !string.IsNullOrEmpty(token)); return(results); }
/// <summary> /// Ends the poll for the specified broadcaster and poll ID. /// </summary> /// <param name="broadcaster">The broadcaster to get the poll for</param> /// <param name="id">The ID of the poll to get</param> /// <returns>The poll</returns> public async Task <PollModel> EndPoll(UserModel broadcaster, string id) { Validator.ValidateVariable(broadcaster, "broadcaster"); Validator.ValidateString(id, "id"); JObject jobj = new JObject(); jobj["broadcaster_id"] = broadcaster.id; jobj["id"] = id; jobj["status"] = "TERMINATED"; return((await this.PostDataResultAsync <PollModel>("polls", AdvancedHttpClient.CreateContentFromObject(jobj)))?.FirstOrDefault()); }
/// <summary> /// Adds the specified "to" user ID to the followers of the specified "from" user ID. /// </summary> /// <param name="from">The user ID to perform the follow</param> /// <param name="to">The user ID to be followed</param> /// <returns>Whether the follow was successful</returns> public async Task <bool> FollowUser(string from, string to) { Validator.ValidateVariable(from, "from"); Validator.ValidateVariable(to, "to"); JObject jobj = new JObject(); jobj["from_id"] = from; jobj["to_id"] = to; HttpResponseMessage response = await this.PostAsync("users/follows", AdvancedHttpClient.CreateContentFromObject(jobj)); return(response.IsSuccessStatusCode); }
protected override async Task RefreshOAuthToken() { if (this.token != null) { JObject payload = new JObject(); payload["grant_type"] = "refresh_token"; payload["client_id"] = StreamlabsService.ClientID; payload["client_secret"] = ChannelSession.Services.Secrets.GetSecret("StreamlabsSecret"); payload["refresh_token"] = this.token.refreshToken; payload["redirect_uri"] = OAuthExternalServiceBase.DEFAULT_OAUTH_LOCALHOST_URL; this.token = await this.PostAsync <OAuthTokenModel>("token", AdvancedHttpClient.CreateContentFromObject(payload), autoRefreshToken : false); } }
public async Task <string> GetSocketToken() { try { JObject payload = new JObject(); payload["client_id"] = TreatStreamService.ClientID; payload["access_token"] = this.token.accessToken; HttpContent content = AdvancedHttpClient.CreateContentFromObject(payload); content.Headers.Clear(); content.Headers.Add("Content-Type", "application/json"); JObject jobj = await this.PostAsync <JObject>("https://treatstream.com/Oauth2/Authorize/socketToken", content); if (jobj != null && jobj.ContainsKey("socket_token")) { return(jobj["socket_token"].ToString()); } } catch (Exception ex) { Logger.Log(ex); } return(null); }
/// <summary> /// Performs an official Trovo command in the specified channel. /// </summary> /// <param name="channelID">The ID of the channel to perform the command in</param> /// <param name="command">The command to perform</param> /// <returns>Null if successful, a status message indicating why the command failed to perform</returns> public async Task <string> PerformChatCommand(string channelID, string command) { Validator.ValidateString(channelID, "channelID"); Validator.ValidateString(command, "command"); JObject jobj = new JObject(); jobj["channel_id"] = channelID; jobj["command"] = command; jobj = await this.PostAsync <JObject>("channels/command", AdvancedHttpClient.CreateContentFromObject(jobj)); if (jobj != null) { JToken success = jobj.SelectToken("is_success"); JToken message = jobj.SelectToken("display_msg"); if (success != null && bool.Equals(false, success)) { return(message.ToString()); } } return(null); }
/// <summary> /// Runs an add for the specified channel. /// </summary> /// <param name="channel">The channel to run the add on</param> /// <param name="length">Desired length of the commercial in seconds. Valid options are 30, 60, 90, 120, 150, 180.</param> /// <returns></returns> public async Task <AdResponseModel> RunAd(UserModel channel, int length) { Validator.ValidateVariable(channel, "channel"); Validator.Validate(length > 0, "length"); JObject body = new JObject(); body["broadcaster_id"] = channel.id; body["length"] = length; JObject result = await this.PostAsync <JObject>("channels/commercial", AdvancedHttpClient.CreateContentFromObject(body)); if (result != null && result.ContainsKey("data")) { JArray array = (JArray)result["data"]; IEnumerable <AdResponseModel> adResult = array.ToTypedArray <AdResponseModel>(); if (adResult != null) { return(adResult.FirstOrDefault()); } } return(null); }
public override async Task <bool> ValidateConnection(RemoteConnectionAuthenticationTokenModel authToken) { return(await this.AsyncWrapper <bool>(async() => { HttpResponseMessage response = await this.PostAsync("authentication/validateconnection", AdvancedHttpClient.CreateContentFromObject(authToken)); return response.IsSuccessStatusCode; })); }
/// <summary> /// Gets the set of users matching the specified usernames. /// </summary> /// <param name="usernames">The usernames to search for</param> /// <returns>The matching users.</returns> public async Task <IEnumerable <UserModel> > GetUsers(IEnumerable <string> usernames) { Validator.ValidateList(usernames, "usernames"); JObject jobj = new JObject(); JArray jarr = new JArray(); foreach (string username in usernames) { jarr.Add(username); } jobj["user"] = jarr; GetUsersResult result = await this.PostAsync <GetUsersResult>("getusers", AdvancedHttpClient.CreateContentFromObject(jobj)); if (result != null) { return(result.users); } return(null); }
private async Task <bool> UpdateChannelInformation(string broadcasterID, string title = null, string gameID = null, string broadcasterLanguage = null) { JObject jobj = new JObject(); if (!string.IsNullOrEmpty(title)) { jobj["title"] = title; } if (!string.IsNullOrEmpty(gameID)) { jobj["game_id"] = gameID; } if (!string.IsNullOrEmpty(broadcasterLanguage)) { jobj["broadcaster_language"] = broadcasterLanguage; } HttpResponseMessage response = await this.PatchAsync("channels?broadcaster_id=" + broadcasterID, AdvancedHttpClient.CreateContentFromObject(jobj)); return(response.IsSuccessStatusCode); }
/// <summary> /// Creates a subscription for the app identified by a Bearer token. Requires App Token. /// </summary> /// <returns>The subscribed webhooks for the app identified by a Bearer token in the Twitch connection</returns> public async Task <EventSubSubscriptionModel> CreateSubscription(EventSubTypesEnum type, string conditionName, string conditionValue, string callback, string secret) { JObject jobj = new JObject(); jobj["type"] = EnumHelper.GetEnumName(type); jobj["version"] = "1"; jobj["condition"] = new JObject(); jobj["condition"][conditionName] = conditionValue; jobj["transport"] = new JObject(); jobj["transport"]["method"] = "webhook"; jobj["transport"]["callback"] = callback; jobj["transport"]["secret"] = secret; // TODO: Consider getting other top level fields // "total": 1, // "total_cost": 1, // "max_total_cost": 10000, // "limit": 10000 var subs = await this.PostDataResultAsync <EventSubSubscriptionModel>("eventsub/subscriptions", AdvancedHttpClient.CreateContentFromObject(jobj)); return(subs?.FirstOrDefault()); }
public async Task <Result> SendMessageToOverlay(string overlayID, PixelChatSendMessageModel message) { try { HttpResponseMessage response = await this.PutAsync($"overlays/{overlayID}/message", AdvancedHttpClient.CreateContentFromObject(message)); if (response.IsSuccessStatusCode) { return(new Result()); } else { return(new Result(await response.Content.ReadAsStringAsync())); } } catch (Exception ex) { Logger.Log(ex); return(new Result(ex)); } }
public async Task <Result> EditSceneComponent(string sceneID, string componentID, bool visible) { try { JObject jobj = new JObject(); jobj["hidden"] = !visible; HttpResponseMessage response = await this.PatchAsync($"scenes/{sceneID}/components/{componentID}", AdvancedHttpClient.CreateContentFromObject(jobj)); if (response.IsSuccessStatusCode) { return(new Result()); } else { return(new Result(await response.Content.ReadAsStringAsync())); } } catch (Exception ex) { Logger.Log(ex); return(new Result(ex)); } }
/// <summary> /// Gets the set of available emotes for the currently authenticated user. /// </summary> /// <param name="channelIDs">The optional list of IDs of the channels to get emotes for</param> /// <returns>The set of available emotes</returns> public async Task <ChatEmotePackageModel> GetEmotes(IEnumerable <string> channelIDs = null) { JObject jobj = new JObject(); jobj["emote_type"] = (channelIDs != null && channelIDs.Count() > 0) ? 0 : 2; jobj["channel_id"] = new JArray(channelIDs); ChatEmotePackageWrapperModel result = await this.PostAsync <ChatEmotePackageWrapperModel>("getemotes", AdvancedHttpClient.CreateContentFromObject(jobj)); if (result != null) { return(result.channels); } return(null); }
/// <summary> /// Updates the channel with the specified metadata. /// </summary> /// <param name="channel">The channel to update</param> /// <param name="update">The metadata to update</param> /// <returns>The updated channel</returns> public async Task <PrivateChannelModel> UpdateChannel(ChannelModel channel, ChannelUpdateModel update) { Validator.ValidateVariable(update, "update"); return(await this.PutAsync <PrivateChannelModel>("channels/" + channel.id, AdvancedHttpClient.CreateContentFromObject(new { channel = update }))); }
public async Task <Result> Connect(string authorizationToken) { try { if (!string.IsNullOrEmpty(authorizationToken)) { JObject payload = new JObject(); payload["grant_type"] = "authorization_code"; payload["client_id"] = TiltifyService.ClientID; payload["client_secret"] = ChannelSession.Services.Secrets.GetSecret("TiltifySecret"); payload["code"] = authorizationToken; payload["redirect_uri"] = TiltifyService.ListeningURL; this.token = await this.PostAsync <OAuthTokenModel>("https://tiltify.com/oauth/token", AdvancedHttpClient.CreateContentFromObject(payload), autoRefreshToken : false); if (this.token != null) { token.authorizationCode = authorizationToken; token.AcquiredDateTime = DateTimeOffset.Now; token.expiresIn = int.MaxValue; return(await this.InitializeInternal()); } } } catch (Exception ex) { Logger.Log(ex); return(new Result(ex)); } return(new Result(false)); }
/// <summary> /// Shows a commercial on the channel. /// </summary> /// <param name="channel">The channel to show a commercial for</param> /// <param name="length">The length of the commercial</param> /// <returns>Information about the commercial</returns> public async Task <ChannelCommercialModel> ShowChannelCommercial(ChannelModel channel, int length) { Validator.ValidateVariable(channel, "channel"); return(await this.PostAsync <ChannelCommercialModel>("channels/" + channel.id + "/commercial", AdvancedHttpClient.CreateContentFromObject(new { length = length }))); }
/// <summary> /// Creates a stream marker for the specified broadcaster. /// </summary> /// <param name="broadcaster">The broadcaster to create the stream marker on</param> /// <param name="description">The description of the stream marker</param> /// <returns>The created stream marker</returns> public async Task <CreatedStreamMarkerModel> CreateStreamMarker(UserModel broadcaster, string description) { Validator.ValidateVariable(broadcaster, "broadcaster"); return(await this.PostAsync <CreatedStreamMarkerModel>("streams/markers", AdvancedHttpClient.CreateContentFromObject(new { user_id = broadcaster.id, description = description }))); }
protected override async Task RefreshOAuthToken() { if (this.token != null) { JObject payload = new JObject(); payload["client_id"] = TreatStreamService.ClientID; payload["client_secret"] = ChannelSession.Services.Secrets.GetSecret("TreatStreamSecret"); payload["refresh_token"] = this.token.refreshToken; payload["grant_type"] = "refresh_token"; this.token = await this.PostAsync <OAuthTokenModel>(TreatStreamService.RefreshTokenURL, AdvancedHttpClient.CreateContentFromObject(payload), autoRefreshToken : false); } }
public override async Task <Result> Connect() { try { this.authorizationToken = await this.ConnectViaOAuthRedirect(string.Format(TreatStreamService.AuthorizationURL, TreatStreamService.ClientID, TreatStreamService.ListeningURL)); if (!string.IsNullOrEmpty(this.authorizationToken)) { JObject payload = new JObject(); payload["grant_type"] = "authorization_code"; payload["client_id"] = TreatStreamService.ClientID; payload["client_secret"] = ChannelSession.Services.Secrets.GetSecret("TreatStreamSecret"); payload["code"] = this.authorizationToken; payload["redirect_uri"] = TreatStreamService.ListeningURL; payload["scope"] = "userinfo"; this.token = await this.PostAsync <OAuthTokenModel>(TreatStreamService.OAuthTokenURL, AdvancedHttpClient.CreateContentFromObject(payload), autoRefreshToken : false); if (this.token != null) { token.authorizationCode = this.authorizationToken; token.AcquiredDateTime = DateTimeOffset.Now; token.expiresIn = int.MaxValue; return(await this.InitializeInternal()); } } } catch (Exception ex) { Logger.Log(ex); return(new Result(ex)); } return(new Result(false)); }