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); }
/// <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>()); } } }
/// <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> /// Performs a GET REST request using the provided request URI. /// </summary> /// <param name="requestUri">The request URI to use</param> /// <param name="throwExceptionOnFailure">Throws an exception on a failed request</param> /// <returns>A type-casted object of the contents of the response</returns> protected async Task <T> GetAsync <T>(string requestUri, bool throwExceptionOnFailure = true) { using (AdvancedHttpClient client = await this.GetHttpClient()) { try { client.RateLimitUpdateOccurred += Client_RateLimitUpdateOccurred; return(await client.GetAsync <T>(requestUri, throwExceptionOnFailure)); } finally { client.RateLimitUpdateOccurred -= Client_RateLimitUpdateOccurred; } } }
/// <summary> /// Performs a GET REST request using the provided request URI. /// </summary> /// <param name="requestUri">The request URI to use</param> /// <returns>A response message of the request</returns> protected async Task <HttpResponseMessage> GetAsync(string requestUri) { using (AdvancedHttpClient client = await this.GetHttpClient()) { try { client.RateLimitUpdateOccurred += Client_RateLimitUpdateOccurred; return(await client.GetAsync(requestUri)); } finally { client.RateLimitUpdateOccurred -= Client_RateLimitUpdateOccurred; } } }
public static async Task <T> GetAsync <T>(string path) { AdvancedHttpClient client = new AdvancedHttpClient { BaseAddress = new Uri(BaseUri) }; HttpResponseMessage message = await client.GetAsync(path); if (message.IsSuccessStatusCode) { return(JsonConvert.DeserializeObject <T>(await message.Content.ReadAsStringAsync())); } return(default(T)); }
private async Task DownloadBetterTTVEmotes(string twitchID = null) { try { using (AdvancedHttpClient client = new AdvancedHttpClient()) { List <BetterTTVEmoteModel> emotes = new List <BetterTTVEmoteModel>(); HttpResponseMessage response = await client.GetAsync((!string.IsNullOrEmpty(twitchID))? "https://api.betterttv.net/3/cached/users/twitch/" + twitchID : "https://api.betterttv.net/3/cached/emotes/global"); if (response.IsSuccessStatusCode) { if (!string.IsNullOrEmpty(twitchID)) { JObject jobj = await response.ProcessJObjectResponse(); if (jobj != null) { JToken channelEmotes = jobj.SelectToken("channelEmotes"); if (channelEmotes != null) { emotes.AddRange(((JArray)channelEmotes).ToTypedArray <BetterTTVEmoteModel>()); } JToken sharedEmotes = jobj.SelectToken("sharedEmotes"); if (sharedEmotes != null) { emotes.AddRange(((JArray)sharedEmotes).ToTypedArray <BetterTTVEmoteModel>()); } } } else { emotes.AddRange(await response.ProcessResponse <List <BetterTTVEmoteModel> >()); } foreach (BetterTTVEmoteModel emote in emotes) { this.betterTTVEmotes[emote.code] = emote; } } } } catch (Exception ex) { Logger.Log(ex); } }
public static async Task <GameInformation> GetXboxGameInfo(string gameName) { try { gameName = gameName.ToLower(); string cv = Convert.ToBase64String(Guid.NewGuid().ToByteArray(), 0, 12); using (AdvancedHttpClient client = new AdvancedHttpClient("https://displaycatalog.mp.microsoft.com")) { client.DefaultRequestHeaders.UserAgent.ParseAdd("MixItUp"); client.DefaultRequestHeaders.Add("MS-CV", cv); HttpResponseMessage response = await client.GetAsync($"v7.0/productFamilies/Games/products?query={HttpUtility.UrlEncode(gameName)}&$top=1&market=US&languages=en-US&fieldsTemplate=StoreSDK&isAddon=False&isDemo=False&actionFilter=Browse"); if (response.StatusCode == HttpStatusCode.OK) { string result = await response.Content.ReadAsStringAsync(); JObject jobj = JObject.Parse(result); JArray products = jobj["Products"] as JArray; if (products?.FirstOrDefault() is JObject product) { string productId = product["ProductId"]?.Value <string>(); string name = product["LocalizedProperties"]?.First()?["ProductTitle"]?.Value <string>(); double price = product["DisplaySkuAvailabilities"]?.First()?["Availabilities"]?.First()?["OrderManagementData"]?["Price"]?["ListPrice"]?.Value <double>() ?? 0.0; string uri = $"https://www.microsoft.com/store/apps/{productId}"; if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(productId) && name.ToLower().Contains(gameName)) { return(new GameInformation { Name = name, Price = price, Uri = uri }); } } } } } catch (Exception ex) { Logger.Log(ex); } return(null); }
private async Task <T> GetAsync <T>(string endpoint) { try { using (AdvancedHttpClient client = new AdvancedHttpClient(MixItUpAPIEndpoint)) { HttpResponseMessage response = await client.GetAsync(endpoint); if (response.StatusCode == HttpStatusCode.OK) { string content = await response.Content.ReadAsStringAsync(); return(JSONSerializerHelper.DeserializeFromString <T>(content)); } else { await this.ProcessResponseIfError(response); } } } catch (Exception ex) { Logger.Log(ex); } return(default(T)); }
protected override async Task PerformInternal(CommandParametersModel parameters) { if (ChannelSession.Services.FileService.FileExists(this.Url)) { await this.ProcessContents(parameters, await ChannelSession.Services.FileService.ReadFile(this.Url)); } else { using (AdvancedHttpClient httpClient = new AdvancedHttpClient()) { httpClient.DefaultRequestHeaders.Add("User-Agent", $"MixItUp/{Assembly.GetEntryAssembly().GetName().Version.ToString()} (Web call from Mix It Up; https://mixitupapp.com; [email protected])"); httpClient.DefaultRequestHeaders.Add("Twitch-UserID", (ChannelSession.TwitchUserNewAPI != null) ? ChannelSession.TwitchUserNewAPI.id : string.Empty); httpClient.DefaultRequestHeaders.Add("Twitch-UserLogin", (ChannelSession.TwitchUserNewAPI != null) ? ChannelSession.TwitchUserNewAPI.login : string.Empty); using (HttpResponseMessage response = await httpClient.GetAsync(await ReplaceStringWithSpecialModifiers(this.Url, parameters, encode: true))) { if (response.IsSuccessStatusCode) { await this.ProcessContents(parameters, await response.Content.ReadAsStringAsync()); } } } } }
//============================================== // Functionality //============================================== #region Functionality private async void StartCheck() { ToggleMainButton(false); try { string uri = _githubHelper.GetLatestReleaseApiUri(); _log.Info("Retrieving latest version tag..."); using (HttpResponseMessage response = await _httpClient.GetAsync(uri)) { response.EnsureSuccessStatusCode(); string json = await response.Content.ReadAsStringAsync(); dynamic payload = SimpleJson.DeserializeObject(json); string latestVersion = payload["tag_name"]; LatestVersion = latestVersion; _log.Info("Latest version tag '{0}' retrieved.", latestVersion); if (string.Compare(CurrentVersion, latestVersion, true) != 0) { SetCurrentStage(OperationStage.Update); CurrentVersionTextBox.Background = new SolidColorBrush(OutdatedVersionColor); } else { _log.Info("Congratulations, you are on the latest version."); SetCurrentStage(OperationStage.Done); CurrentVersionTextBox.Background = new SolidColorBrush(UpdatedVersionColor); } } } catch (Exception e) { _log.Error("Failed to retrieve latest version: " + e.Message); SetCurrentStage(OperationStage.Check); } }
public static async Task <GameInformation> GetSteamGameInfo(string gameName) { gameName = gameName.ToLower(); if (steamGameList.Count == 0) { using (AdvancedHttpClient client = new AdvancedHttpClient("http://api.steampowered.com/")) { HttpResponseMessage response = await client.GetAsync("ISteamApps/GetAppList/v0002"); if (response.StatusCode == HttpStatusCode.OK) { string result = await response.Content.ReadAsStringAsync(); JObject jobj = JObject.Parse(result); JToken list = jobj["applist"]["apps"]; JArray games = (JArray)list; foreach (JToken game in games) { SteamGameChatCommand.steamGameList[game["name"].ToString().ToLower()] = (int)game["appid"]; } } } } int gameID = -1; if (SteamGameChatCommand.steamGameList.ContainsKey(gameName)) { gameID = SteamGameChatCommand.steamGameList[gameName]; } else { string foundGame = SteamGameChatCommand.steamGameList.Keys.FirstOrDefault(g => g.Contains(gameName)); if (foundGame != null) { gameID = SteamGameChatCommand.steamGameList[foundGame]; } } if (gameID > 0) { using (AdvancedHttpClient client = new AdvancedHttpClient("http://store.steampowered.com/")) { HttpResponseMessage response = await client.GetAsync("api/appdetails?appids=" + gameID); if (response.StatusCode == HttpStatusCode.OK) { string result = await response.Content.ReadAsStringAsync(); JObject jobj = JObject.Parse(result); if (jobj[gameID.ToString()] != null && jobj[gameID.ToString()]["data"] != null) { jobj = (JObject)jobj[gameID.ToString()]["data"]; double price = 0.0; if (jobj["price_overview"] != null && jobj["price_overview"]["final"] != null) { price = (int)jobj["price_overview"]["final"]; price = price / 100.0; } string url = string.Format("http://store.steampowered.com/app/{0}", gameID); return(new GameInformation { Name = jobj["name"].Value <string>(), Price = price, Uri = url }); } } } } return(null); }
protected override async Task PerformInternal(CommandParametersModel parameters) { this.runParameters = parameters; bool useCustomQuestion = (RandomHelper.GenerateProbability() >= 50); if (this.CustomQuestions.Count > 0 && !this.UseRandomOnlineQuestions) { useCustomQuestion = true; } else if (this.CustomQuestions.Count == 0 && this.UseRandomOnlineQuestions) { useCustomQuestion = false; } if (!useCustomQuestion) { using (AdvancedHttpClient client = new AdvancedHttpClient()) { OpenTDBResults openTDBResults = await client.GetAsync <OpenTDBResults>(OpenTDBUrl); if (openTDBResults != null && openTDBResults.results != null && openTDBResults.results.Count > 0) { List <string> answers = new List <string>(); answers.Add(HttpUtility.HtmlDecode(openTDBResults.results[0].correct_answer)); answers.AddRange(openTDBResults.results[0].incorrect_answers.Select(a => HttpUtility.HtmlDecode(a))); this.question = new TriviaGameQuestionModel() { Question = HttpUtility.HtmlDecode(openTDBResults.results[0].question), Answers = answers, }; } } } if (this.CustomQuestions.Count > 0 && (useCustomQuestion || this.question == null)) { this.question = this.CustomQuestions.Random(); } if (this.question == null) { this.question = FallbackQuestion; } int i = 1; foreach (string answer in this.question.Answers.Shuffle()) { this.numbersToAnswers[i] = answer; i++; } int correctAnswerNumber = 0; foreach (var kvp in this.numbersToAnswers) { if (kvp.Value.Equals(this.question.CorrectAnswer)) { correctAnswerNumber = kvp.Key; break; } } this.runParameters.SpecialIdentifiers[TriviaGameCommandModel.GameTriviaQuestionSpecialIdentifier] = this.question.Question; foreach (var kvp in this.numbersToAnswers) { this.runParameters.SpecialIdentifiers[TriviaGameCommandModel.GameTriviaSpecificAnswerHeaderSpecialIdentifier + kvp.Key] = kvp.Value; } this.runParameters.SpecialIdentifiers[TriviaGameCommandModel.GameTriviaAnswersSpecialIdentifier] = string.Join(", ", this.numbersToAnswers.OrderBy(a => a.Key).Select(a => $"{a.Key}) {a.Value}")); this.runParameters.SpecialIdentifiers[TriviaGameCommandModel.GameTriviaCorrectAnswerSpecialIdentifier] = this.question.CorrectAnswer; GlobalEvents.OnChatMessageReceived += GlobalEvents_OnChatMessageReceived; await this.StartedCommand.Perform(this.runParameters); await Task.Delay(this.TimeLimit * 1000); GlobalEvents.OnChatMessageReceived -= GlobalEvents_OnChatMessageReceived; List <CommandParametersModel> winners = new List <CommandParametersModel>(); foreach (var kvp in this.runUserSelections.ToList()) { CommandParametersModel participant = this.runUsers[kvp.Key]; if (kvp.Value == correctAnswerNumber) { winners.Add(participant); this.PerformPrimarySetPayout(participant.User, this.WinAmount); participant.SpecialIdentifiers[GameCommandModelBase.GamePayoutSpecialIdentifier] = this.WinAmount.ToString(); await this.UserSuccessCommand.Perform(participant); } else { await this.UserFailureCommand.Perform(participant); } } this.runParameters.SpecialIdentifiers[GameCommandModelBase.GameWinnersCountSpecialIdentifier] = winners.Count.ToString(); this.runParameters.SpecialIdentifiers[GameCommandModelBase.GameWinnersSpecialIdentifier] = string.Join(", ", winners.Select(u => "@" + u.User.Username)); this.runParameters.SpecialIdentifiers[GameCommandModelBase.GamePayoutSpecialIdentifier] = this.WinAmount.ToString(); this.runParameters.SpecialIdentifiers[GameCommandModelBase.GameAllPayoutSpecialIdentifier] = (this.WinAmount * winners.Count).ToString(); await this.CorrectAnswerCommand.Perform(this.runParameters); await this.PerformCooldown(this.runParameters); this.ClearData(); }
public override async Task CustomRun(CommandParametersModel parameters) { this.runParameters = parameters; bool useCustomQuestion = (RandomHelper.GenerateProbability() >= 50); if (this.CustomQuestions.Count > 0 && !this.UseRandomOnlineQuestions) { useCustomQuestion = true; } else if (this.CustomQuestions.Count == 0 && this.UseRandomOnlineQuestions) { useCustomQuestion = false; } if (!useCustomQuestion) { using (AdvancedHttpClient client = new AdvancedHttpClient()) { OpenTDBResults openTDBResults = await client.GetAsync <OpenTDBResults>(OpenTDBUrl); if (openTDBResults != null && openTDBResults.results != null && openTDBResults.results.Count > 0) { List <string> answers = new List <string>(); answers.Add(HttpUtility.HtmlDecode(openTDBResults.results[0].correct_answer)); answers.AddRange(openTDBResults.results[0].incorrect_answers.Select(a => HttpUtility.HtmlDecode(a))); this.question = new TriviaGameQuestionModel() { Question = HttpUtility.HtmlDecode(openTDBResults.results[0].question), Answers = answers, }; } } } if (this.CustomQuestions.Count > 0 && (useCustomQuestion || this.question == null)) { this.question = this.CustomQuestions.Random(); } if (this.question == null) { this.question = FallbackQuestion; } int i = 1; foreach (string answer in this.question.Answers.Shuffle()) { this.numbersToAnswers[i] = answer; i++; } int correctAnswerNumber = 0; foreach (var kvp in this.numbersToAnswers) { if (kvp.Value.Equals(this.question.CorrectAnswer)) { correctAnswerNumber = kvp.Key; break; } } this.runParameters.SpecialIdentifiers[TriviaGameCommandModel.GameTriviaQuestionSpecialIdentifier] = this.question.Question; foreach (var kvp in this.numbersToAnswers) { this.runParameters.SpecialIdentifiers[TriviaGameCommandModel.GameTriviaSpecificAnswerHeaderSpecialIdentifier + kvp.Key] = kvp.Value; } this.runParameters.SpecialIdentifiers[TriviaGameCommandModel.GameTriviaAnswersSpecialIdentifier] = string.Join(", ", this.numbersToAnswers.OrderBy(a => a.Key).Select(a => $"{a.Key}) {a.Value}")); this.runParameters.SpecialIdentifiers[TriviaGameCommandModel.GameTriviaCorrectAnswerSpecialIdentifier] = this.question.CorrectAnswer; #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(cancellationToken) => { GlobalEvents.OnChatMessageReceived += GlobalEvents_OnChatMessageReceived; await this.DelayNoThrow(this.TimeLimit * 1000, cancellationToken); GlobalEvents.OnChatMessageReceived -= GlobalEvents_OnChatMessageReceived; List <CommandParametersModel> winners = new List <CommandParametersModel>(); foreach (var kvp in this.runUserSelections.ToList()) { CommandParametersModel participant = this.runUsers[kvp.Key]; if (kvp.Value == correctAnswerNumber) { winners.Add(participant); this.PerformPrimarySetPayout(participant.User, this.WinAmount); participant.SpecialIdentifiers[GameCommandModelBase.GamePayoutSpecialIdentifier] = this.WinAmount.ToString(); await this.RunSubCommand(this.UserSuccessCommand, participant); } else { await this.RunSubCommand(this.UserFailureCommand, participant); } } this.SetGameWinners(this.runParameters, winners); this.runParameters.SpecialIdentifiers[GameCommandModelBase.GamePayoutSpecialIdentifier] = this.WinAmount.ToString(); this.runParameters.SpecialIdentifiers[GameCommandModelBase.GameAllPayoutSpecialIdentifier] = (this.WinAmount * winners.Count).ToString(); await this.RunSubCommand(this.CorrectAnswerCommand, this.runParameters); await this.PerformCooldown(this.runParameters); this.ClearData(); }, new CancellationToken()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed await this.RunSubCommand(this.StartedCommand, this.runParameters); }