/// <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 }));
        }
예제 #2
0
        public override async Task <IEnumerable <StreamingPlatformStatusModel> > GetCurrentIncidents()
        {
            List <StreamingPlatformStatusModel> incidents = new List <StreamingPlatformStatusModel>();

            try
            {
                StatusPageUnresolvedIncidents unresolvedIncidents = null;
                using (AdvancedHttpClient client = new AdvancedHttpClient())
                {
                    unresolvedIncidents = await client.GetAsync <StatusPageUnresolvedIncidents>(this.statusFeedLink);
                }

                if (unresolvedIncidents != null && unresolvedIncidents.incidents != null && unresolvedIncidents.incidents.Count > 0)
                {
                    foreach (StatusPageUnresolvedIncident incident in unresolvedIncidents.incidents)
                    {
                        if (incident.incident_updates != null && incident.incident_updates.Count > 0)
                        {
                            StatusPageUnresolvedIncidentUpdate latestUpdate = incident.incident_updates.OrderByDescending(i => i.updated_at).FirstOrDefault();
                            if (latestUpdate != null)
                            {
                                incidents.Add(new StreamingPlatformStatusModel(this.platform, incident.name, latestUpdate.body, latestUpdate.updated_at, incident.shortlink));
                            }
                        }
                    }
                }
                return(incidents);
            }
            catch (Exception ex) { Logger.Log(ex); }
            return(incidents);
        }
예제 #3
0
        public static void SetBasicClientIDClientSecretAuthorizationHeader(this AdvancedHttpClient client, string clientID, string clientSecret)
        {
            string authorizationValue = string.Format("{0}:{1}", clientID, clientSecret);

            byte[] authorizationBytes = System.Text.Encoding.UTF8.GetBytes(authorizationValue);
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authorizationBytes));
        }
예제 #4
0
        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));
        }
예제 #5
0
        /// <summary>
        /// Sets the configuration data
        /// </summary>
        /// <param name="clientID">The client ID of the extension</param>
        /// <param name="clientSecret">The client secret of the extension</param>
        /// <param name="ownerID">The owner user ID of the extension</param>
        /// <param name="channelID">The channel ID to broadcast to</param>
        /// <param name="segment">The segment type of the configuration</param>
        /// <param name="version">The version for the configuration</param>
        /// <param name="data">The data to set for the configuration</param>
        /// <returns>Whether the broadcast was successful or not. Throws a HttpRestRequestException in the event of failed request</returns>
        public static async Task <bool> SetConfiguration(string clientID, string clientSecret, string ownerID, string channelID, string segment, string version, object data)
        {
            Validator.ValidateString(clientID, "clientID");
            Validator.ValidateString(clientSecret, "clientSecret");
            Validator.ValidateString(ownerID, "ownerID");
            Validator.ValidateString(segment, "segment");
            Validator.ValidateString(version, "version");
            Validator.ValidateVariable(data, "data");

            using (AdvancedHttpClient client = TwitchExtensionService.GetHttpClient(clientID, clientSecret, ownerID, channelID))
            {
                ConfigurationModel configuration = (ConfigurationModel.GlobalConfigurationSegmentValue.Equals(segment)) ?
                                                   new ConfigurationModel(segment, version, JSONSerializerHelper.SerializeToString(data)) :
                                                   new ChannelConfigurationModel(channelID, segment, version, JSONSerializerHelper.SerializeToString(data));

                HttpResponseMessage response = await client.PutAsync($"https://api.twitch.tv/extensions/{clientID}/configurations/",
                                                                     AdvancedHttpClient.CreateContentFromString(JSONSerializerHelper.SerializeToString(configuration)));

                if (response.IsSuccessStatusCode)
                {
                    return(true);
                }
                else
                {
                    throw new HttpRestRequestException(response);
                }
            }
        }
예제 #6
0
        /// <summary>
        /// Gets the global configuration data.
        /// </summary>
        /// <param name="clientID">The client ID of the extension</param>
        /// <param name="clientSecret">The client secret of the extension</param>
        /// <param name="ownerID">The owner user ID of the extension</param>
        /// <returns>The global configuration data for the extension</returns>
        public static async Task <ConfigurationModel> GetGlobalConfiguration(string clientID, string clientSecret, string ownerID)
        {
            Validator.ValidateString(clientID, "clientID");
            Validator.ValidateString(clientSecret, "clientSecret");
            Validator.ValidateString(ownerID, "ownerID");

            using (AdvancedHttpClient client = TwitchExtensionService.GetHttpClient(clientID, clientSecret, ownerID, null))
            {
                HttpResponseMessage response = await client.GetAsync($"https://api.twitch.tv/extensions/{clientID}/configurations/segments/global");

                if (response.IsSuccessStatusCode)
                {
                    JObject jobj = await response.ProcessJObjectResponse();

                    if (jobj != null && jobj.Count > 0)
                    {
                        ConfigurationResultModel result = jobj.Values().First().ToObject <ConfigurationResultModel>();
                        if (result != null)
                        {
                            return(new ConfigurationModel(result));
                        }
                    }
                    return(null);
                }
                else
                {
                    return(null);
                }
            }
        }
        /// <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);
        }
예제 #8
0
        protected override async Task <AdvancedHttpClient> GetHttpClient(bool autoRefreshToken = true)
        {
            AdvancedHttpClient client = await base.GetHttpClient(autoRefreshToken);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bot", this.botToken);
            return(client);
        }
        /// <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);
            }
        }
예제 #10
0
        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);
        }
예제 #11
0
        private async Task DownloadFrankerFaceZEmotes(string channelName = null)
        {
            try
            {
                using (AdvancedHttpClient client = new AdvancedHttpClient())
                {
                    JObject jobj = await client.GetJObjectAsync((!string.IsNullOrEmpty(channelName))? "https://api.frankerfacez.com/v1/room/" + channelName : "https://api.frankerfacez.com/v1/set/global");

                    if (jobj != null && jobj.ContainsKey("sets"))
                    {
                        JObject setsJObj = (JObject)jobj["sets"];
                        foreach (var kvp in setsJObj)
                        {
                            JObject setJObj = (JObject)kvp.Value;
                            if (setJObj != null && setJObj.ContainsKey("emoticons"))
                            {
                                JArray emoticonsJArray = (JArray)setJObj["emoticons"];
                                foreach (FrankerFaceZEmoteModel emote in emoticonsJArray.ToTypedArray <FrankerFaceZEmoteModel>())
                                {
                                    this.frankerFaceZEmotes[emote.name] = emote;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex) { Logger.Log(ex); }
        }
예제 #12
0
        /// <summary>
        /// Gets the configuration data for the specified channel.
        /// </summary>
        /// <param name="clientID">The client ID of the extension</param>
        /// <param name="clientSecret">The client secret of the extension</param>
        /// <param name="ownerID">The owner user ID of the extension</param>
        /// <param name="channelID">The channel ID to broadcast to</param>
        /// <returns>The channel-specific configuration data for the extension</returns>
        public static async Task <IEnumerable <ChannelConfigurationModel> > GetChannelConfiguration(string clientID, string clientSecret, string ownerID, string channelID)
        {
            Validator.ValidateString(clientID, "clientID");
            Validator.ValidateString(clientSecret, "clientSecret");
            Validator.ValidateString(ownerID, "ownerID");
            Validator.ValidateString(channelID, "channelID");

            using (AdvancedHttpClient client = TwitchExtensionService.GetHttpClient(clientID, clientSecret, ownerID, channelID))
            {
                HttpResponseMessage response = await client.GetAsync($"https://api.twitch.tv/extensions/{clientID}/configurations/segments/broadcaster?channel_id={channelID}");

                if (response.IsSuccessStatusCode)
                {
                    List <ChannelConfigurationModel> results = new List <ChannelConfigurationModel>();
                    JObject jobj = await response.ProcessJObjectResponse();

                    if (jobj != null)
                    {
                        foreach (var kvp in jobj)
                        {
                            ConfigurationResultModel result = kvp.Value.ToObject <ConfigurationResultModel>();
                            if (result != null)
                            {
                                results.Add(new ChannelConfigurationModel(result));
                            }
                        }
                    }
                    return(results);
                }
                else
                {
                    return(new List <ChannelConfigurationModel>());
                }
            }
        }
예제 #13
0
        public async Task SendTrigger(string eventName, Dictionary <string, string> values)
        {
            try
            {
                using (AdvancedHttpClient client = new AdvancedHttpClient())
                {
                    JObject jobj = new JObject();
                    foreach (var kvp in values)
                    {
                        jobj[kvp.Key] = kvp.Value;
                    }
                    HttpContent content = new StringContent(JSONSerializerHelper.SerializeToString(jobj), Encoding.UTF8, "application/json");

                    HttpResponseMessage response = await client.PostAsync(string.Format(WebHookURLFormat, eventName, this.token.accessToken), content);

                    if (!response.IsSuccessStatusCode)
                    {
                        Logger.Log(await response.Content.ReadAsStringAsync());
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
        }
        /// <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));
        }
예제 #15
0
        protected override async Task <AdvancedHttpClient> GetHttpClient(bool autoRefreshToken = true)
        {
            AdvancedHttpClient client = await base.GetHttpClient(autoRefreshToken);

            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
            return(client);
        }
예제 #16
0
        protected override Task <AdvancedHttpClient> GetHttpClient(bool autoRefreshToken = true)
        {
            AdvancedHttpClient httpClient = new AdvancedHttpClient(PixelChatService.BaseAddress);

            httpClient.DefaultRequestHeaders.Add("x-api-key", this.token.accessToken);
            httpClient.DefaultRequestHeaders.Add("x-application", "Mix It Up");
            return(Task.FromResult(httpClient));
        }
예제 #17
0
        protected override async Task <AdvancedHttpClient> GetHttpClient(bool autoRefreshToken = true)
        {
            AdvancedHttpClient client = await base.GetHttpClient(autoRefreshToken);

            client.DefaultRequestHeaders.Add("x-app-id", JustGivingService.ClientID);
            client.DefaultRequestHeaders.Add("x-application-key", ChannelSession.Services.Secrets.GetSecret("JustGivingSecret"));
            return(client);
        }
예제 #18
0
        public static async Task DeleteAsync(string path)
        {
            AdvancedHttpClient client = new AdvancedHttpClient
            {
                BaseAddress = new Uri(BaseUri)
            };

            await client.DeleteAsync(path);
        }
        /// <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);
            }
        }
예제 #20
0
        /// <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));
        }
예제 #21
0
        private static AdvancedHttpClient GetHttpClient(string clientID, string clientSecret, string ownerID, string channelID)
        {
            AdvancedHttpClient client = new AdvancedHttpClient();

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("Client-ID", clientID);
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + TwitchExtensionService.CreateAuthenticationToken(clientSecret, ownerID, channelID));
            return(client);
        }
        protected override async Task <AdvancedHttpClient> GetHttpClient(bool autoRefreshToken = true)
        {
            AdvancedHttpClient client = await base.GetHttpClient(autoRefreshToken);

            if (this.token != null)
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", this.token.accessToken);
            }
            return(client);
        }
예제 #23
0
        /// <summary>
        /// Gets the HttpClient using the OAuth for the connection of this service.
        /// </summary>
        /// <param name="autoRefreshToken">Whether to automatically refresh the OAuth token or not if it has to be</param>
        /// <returns>The HttpClient for the connection</returns>
        protected override async Task <AdvancedHttpClient> GetHttpClient(bool autoRefreshToken = true)
        {
            AdvancedHttpClient client = await base.GetHttpClient(autoRefreshToken);

            if (!string.IsNullOrEmpty(this.clientID))
            {
                client.DefaultRequestHeaders.Add("Client-ID", this.clientID);
            }
            return(client);
        }
        /// <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)));
        }
예제 #26
0
 private async Task DeleteAsync(string endpoint)
 {
     try
     {
         using (AdvancedHttpClient client = new AdvancedHttpClient(MixItUpAPIEndpoint))
         {
             await client.DeleteAsync(endpoint);
         }
     }
     catch (Exception ex) { Logger.Log(ex); }
 }
예제 #27
0
        public static async Task PostAsync(string path, object body)
        {
            AdvancedHttpClient client = new AdvancedHttpClient
            {
                BaseAddress = new Uri(BaseUri)
            };

            var         json    = JsonConvert.SerializeObject(body);
            HttpContent content = new StringContent(json, UnicodeEncoding.UTF8, "application/json");
            await client.PostAsync(path, content);
        }
        /// <summary>
        /// Gets the HttpClient using the OAuth for the connection of this service.
        /// </summary>
        /// <param name="autoRefreshToken">Whether to automatically refresh the OAuth token or not if it has to be</param>
        /// <returns>The HttpClient for the connection</returns>
        protected override async Task <AdvancedHttpClient> GetHttpClient(bool autoRefreshToken = true)
        {
            AdvancedHttpClient client = new AdvancedHttpClient(this.GetBaseAddress());
            OAuthTokenModel    token  = await this.GetOAuthToken(autoRefreshToken);

            if (token != null)
            {
                client = new AdvancedHttpClient(this.GetBaseAddress(), "OAuth", token.accessToken);
            }
            client.DefaultRequestHeaders.Add("Client-ID", this.clientID);
            return(client);
        }
        /// <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());
        }