public static IActionResult Subscribers(RequestHandler <IActionResult> req) { int limit = 100; int total = int.MaxValue; User user = UserManager.GetUserTwitch("gogomic"); JArray subs = new JArray(); HashSet <string> ids = new HashSet <string>(); for (int offset = 0; offset + limit <= total; offset += limit) { UrlParams param = new UrlParams(); param.Add("limit", limit.ToString()); param.Add("offset", offset.ToString()); // TODO: Chain requests if gogomic ever gets over 100 subs. string url = "https://api.twitch.tv/kraken/channels/" + user.TwitchId + "/subscriptions" + param.ToString(); GetRequest getReq = new GetRequest(url); getReq.AddHeader(HttpRequestHeader.Accept, "application/vnd.twitchtv.v5+json"); getReq.AddHeader("Client-ID", Config.TwitchOAuth.ClientId); getReq.AddHeader("Authorization", "OAuth " + user.TwitchToken); JObject resp = getReq.GetResponseJson(); foreach (JToken sub in (JArray)resp["subscriptions"]) { string id = (string)sub["user"]["_id"]; if (ids.Contains(id) || id == user.TwitchId) { continue; } ids.Add(id); subs.Add(sub); } total = (int)resp["_total"]; } req.View.Subs = subs; return(req.Controller.View()); }
public static UrlParams GetUrlParams() { UrlParams urlparam = (UrlParams)WebContext.Current[UrlParams.DATA_TAG]; if (urlparam == null) { urlparam = new UrlParams(); foreach (string key in WebContext.Current.Request.QueryString.Keys) { if (key != null && key != "OrderField" && key != "PageCount" && key != "PageIndex" && key != "PageSize" && key != "RecordCount") { urlparam.Add(key, WebContext.Current.Request.QueryString[key]); } } WebContext.Current[UrlParams.DATA_TAG] = urlparam; } return(urlparam); }
public static IActionResult Index(RequestHandler <IActionResult> req) { UrlParams param = new UrlParams(); param.Add("client_id", Config.TwitchOAuth.ClientId); param.Add("redirect_uri", Config.OAuthRedirect); param.Add("response_type", "code"); param.Add("scope", Config.TwitchScope); param.Add("force_verify", "true"); param.Add("state", TokenGenerator.Generate()); // TODO: Generate token for this. string twitchUrl = "https://api.twitch.tv/kraken/oauth2/authorize" + param.ToString(); req.View.TwitchUrl = twitchUrl; return(req.Controller.View()); }
public static string GetToken(string code, string state) { PostRequest req = new PostRequest( "https://api.twitch.tv/kraken/oauth2/token"); UrlParams param = new UrlParams(); param.Add("client_id", Config.TwitchOAuth.ClientId); param.Add("client_secret", Config.TwitchOAuth.Secret); param.Add("code", code); param.Add("grant_type", "authorization_code"); param.Add("redirect_uri", Config.OAuthRedirect); param.Add("state", state); req.AddHeader(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded"); req.BodyString = param.ToPostString(); JObject resp = req.GetResponseJson(); return((string)resp["access_token"]); }
public HttpResponseMessage GetResponse() { #if DEBUG System.Diagnostics.Debug.WriteLine(FullURL); #endif #region Local Variables WebRequestPostContentType postContentType = PostContentType; String strPostContent = PostContent; HttpClient httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(BaseURL); HttpResponseMessage httpResponse = null; #endregion Local Variables #region Resolve Headers foreach (KeyValuePair <String, String> kvp in Headers) { httpClient.DefaultRequestHeaders.TryAddWithoutValidation(kvp.Key, kvp.Value); } #endregion Resolve Headers #region Resolve URL Path String strParam = URLParamsString; RequestPath = RequestPath.Replace('\\', '/'); String urlPath = string.Format("{0}{1}{2}{3}", RequestPath, RequestPath.EndsWith("/") || strParam == "" ? "" : "/", strParam != "" ? "?" : "", strParam); #endregion Resolve URL Path switch (RequestType) { case WebRequestType.GET_OFFSET: case WebRequestType.GET_PAGE: case WebRequestType.POST_OFFSET: case WebRequestType.POST_PAGE: Int32 limit = 100, offset = 0, page = 0, maxPages = 20, maxChildren = 0; JObject jObjectMerged = new JObject(), jObjectTemp; Dictionary <string, string> dictPostContent = null; //Used for POST_OFFSET and POST_PAGE #region Initialization by Request Type switch (RequestType) { case WebRequestType.GET_OFFSET: if (UrlParams.ContainsKey(LimitField)) { Int32.TryParse(UrlParams[LimitField], out limit); } else { UrlParams.Add(LimitField, limit.ToString()); } if (UrlParams.ContainsKey(OffsetField)) { Int32.TryParse(UrlParams[OffsetField], out offset); } else { UrlParams.Add(OffsetField, offset.ToString()); } break; case WebRequestType.GET_PAGE: if (UrlParams.ContainsKey(LimitField)) { Int32.TryParse(UrlParams[LimitField], out limit); } else { UrlParams.Add(LimitField, limit.ToString()); } if (UrlParams.ContainsKey(PageField)) { Int32.TryParse(UrlParams[PageField], out page); } else { UrlParams.Add(PageField, page.ToString()); } break; case WebRequestType.POST_OFFSET: dictPostContent = new Dictionary <string, string> { { LimitField, Limit.ToString() }, { OffsetField, offset.ToString() } }; break; case WebRequestType.POST_PAGE: dictPostContent = new Dictionary <string, string> { { LimitField, Limit.ToString() }, { PageField, page.ToString() } }; break; } #endregion Initialization by Request Type do { #region Loop Initialization switch (RequestType) { case WebRequestType.GET_OFFSET: UrlParams[OffsetField] = offset.ToString(); break; case WebRequestType.GET_PAGE: UrlParams[PageField] = page.ToString(); break; case WebRequestType.POST_OFFSET: dictPostContent[OffsetField] = offset.ToString(); break; case WebRequestType.POST_PAGE: dictPostContent[PageField] = page.ToString(); break; } #endregion Loop Initialization strParam = URLParamsString; urlPath = string.Format("{0}{1}{2}{3}", RequestPath, RequestPath.EndsWith("/") ? "" : "/", strParam != "" ? "?" : "", strParam); #region Get the Response by Request Type switch (RequestType) { case WebRequestType.GET_OFFSET: case WebRequestType.GET_PAGE: httpResponse = httpClient.GetAsync(urlPath).Result; break; case WebRequestType.POST_OFFSET: case WebRequestType.POST_PAGE: FormUrlEncodedContent postContent = new FormUrlEncodedContent(dictPostContent); httpResponse = httpClient.PostAsync(urlPath, postContent).Result; break; } #endregion Get the Response by Request Type #region Break out if StatusCode is not OK if (httpResponse.StatusCode != HttpStatusCode.OK) { break; } #endregion Break out if StatusCode is not OK String strResponse = httpResponse.Content.ReadAsStringAsync().Result; if (strResponse.StartsWith("[") && strResponse.EndsWith("]")) { strResponse = $"{{\"root\":{strResponse}}}"; } jObjectTemp = JObject.Parse(strResponse); IEnumerable <JToken> allTokens = jObjectTemp.SelectTokens("*"); maxChildren = allTokens.Select(t => t.Count()).Max(); jObjectMerged.Merge(jObjectTemp); page++; offset += limit; } while (maxChildren > 1 && maxChildren >= limit && page <= maxPages); httpResponse.Content = new StringContent(jObjectMerged.ToString(), Encoding.UTF8, "application/json"); break; case WebRequestType.CANCEL: httpClient.CancelPendingRequests(); break; case WebRequestType.DELETE: httpResponse = httpClient.DeleteAsync(urlPath).Result; break; case WebRequestType.GET: default: httpResponse = httpClient.GetAsync(urlPath).Result; break; case WebRequestType.POST: case WebRequestType.PUT: case WebRequestType.SEND: #region Resolve MediaType String mediaType; switch (postContentType) { case WebRequestPostContentType.STRING: case WebRequestPostContentType.FORM_URL_ENCODED: default: mediaType = "text/plain"; break; case WebRequestPostContentType.JSON: mediaType = "application/json"; break; case WebRequestPostContentType.XML: case WebRequestPostContentType.SOAP: case WebRequestPostContentType.SOAP_STRING: mediaType = "text/xml"; break; } #endregion Resolve MediaType #region Resolve Content HttpContent content; switch (postContentType) { case WebRequestPostContentType.XML: case WebRequestPostContentType.JSON: case WebRequestPostContentType.STRING: default: content = new StringContent(strPostContent, Encoding.UTF8, mediaType); break; case WebRequestPostContentType.FORM_URL_ENCODED: Dictionary <String, String> formData = strPostContent.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries) .Select(part => part.Split('=')) .ToDictionary(split => split[0], split => split[1]); content = new FormUrlEncodedContent(formData); break; case WebRequestPostContentType.SOAP: case WebRequestPostContentType.SOAP_STRING: content = new StringContent(String.Format(@"<?xml version=""1.0"" encoding=""utf-8""?> <s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/""> <s:Body> {0} </s:Body> </s:Envelope>", strPostContent), Encoding.UTF8, mediaType); break; } #endregion Resolve Content switch (RequestType) { case WebRequestType.POST: httpResponse = httpClient.PostAsync(urlPath, content).Result; break; case WebRequestType.PUT: httpResponse = httpClient.PutAsync(urlPath, content).Result; break; case WebRequestType.SEND: HttpRequestMessage httpContent = new HttpRequestMessage(HttpMethod.Post, urlPath) { Content = content, Version = HttpVersion.Version11 }; httpResponse = httpClient.SendAsync(httpContent).Result; break; } break; } return(httpResponse); }