/// <summary> /// Retrieve teams the specified user is a member of. /// </summary> /// <param name="user">The name of the user</param> /// <param name="version">Twitch API version</param> /// <returns>List of teams</returns> public async Task <List <Team> > RetrieveTeams(string user, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } if (version == APIVersion.v3) { Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("channels", user, "teams"); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } return(HelperMethods.LoadTeams(JObject.Parse(responseString), version)); } else { throw new TwixelException(TwitchConstants.v2UnsupportedErrorString); } }
/// <summary> /// Gets the list of teams from Twitch /// </summary> /// <param name="offset">Object offset for pagination. Default is 0.</param> /// <param name="limit">How many teams to get at one time. Default is 25. Maximum is 100.</param> /// <param name="version">Twitch API version</param> /// <returns>A list of teams</returns> public async Task <List <Team> > RetrieveTeams(int offset = 0, int limit = 25, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegment("teams"); if (limit <= 100) { url.SetQueryParam("limit", limit); } else { url.SetQueryParam("limit", 100); } Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } return(HelperMethods.LoadTeams(JObject.Parse(responseString), version)); }
/// <summary> /// Create a new instance of the GraphicsAPI struct. /// </summary> /// <param name="api">The context API to use.</param> /// <param name="profile">The context profile to use.</param> /// <param name="flags">The context flags to use.</param> /// <param name="apiVersion">The API version to use.</param> public GraphicsAPI(ContextAPI api, ContextProfile profile, ContextFlags flags, APIVersion apiVersion) { API = api; Profile = profile; Flags = flags; Version = apiVersion; }
/// <summary> /// Search games on Twitch /// </summary> /// <param name="query">The search query</param> /// <param name="live">If true, only returns games that are live on at least one channel. Default is false.</param> /// <param name="version">Twitch API version</param> /// <returns>Returns a list of searched games</returns> public async Task <List <SearchedGame> > SearchGames(string query, bool live = false, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("search", "games").SetQueryParams(new { query = query, type = "suggest", live = live }); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } return(HelperMethods.LoadSearchedGames(JObject.Parse(responseString), version)); }
public BigCommerceProductsService(BigCommerceConfig config) { Condition.Requires(config, "config").IsNotNull(); this._webRequestServices = new WebRequestServices(config, this.GetMarker()); this._apiVersion = config.GetAPIVersion(); }
/// <summary> /// create a new IEXCloudClient /// </summary> /// <param name="publishableToken">publishable token</param> /// <param name="secretToken">secret token (only used for SCALE and GROW users)</param> /// <param name="signRequest">only SCALE and GROW users should set this to true</param> /// <param name="useSandBox">whether or not to use the sandbox endpoint</param> /// <param name="version">whether to use stable or beta endpoint</param> /// <param name="retryPolicy">which backoff policy to use - applies only REST calls (not SSE)</param> public IEXCloudClient(string publishableToken, string secretToken, bool signRequest, bool useSandBox, APIVersion version = APIVersion.stable, RetryPolicy retryPolicy = RetryPolicy.Exponential) { if (string.IsNullOrWhiteSpace(publishableToken)) { throw new ArgumentException("publishableToken cannot be null"); } this.publishableToken = publishableToken; this.secretToken = secretToken; this.signRequest = signRequest; var baseAddress = useSandBox ? "https://sandbox.iexapis.com/" : "https://cloud.iexapis.com/"; baseAddress += version.ToString() + "/"; baseSSEURL = useSandBox ? "https://sandbox-sse.iexapis.com/" : "https://cloud-sse.iexapis.com/"; baseSSEURL += version.ToString() + "/"; client = new HttpClient { BaseAddress = new Uri(baseAddress) }; client.DefaultRequestHeaders.Add("User-Agent", "VSLee.IEXSharp IEX Cloud .Net"); executor = new ExecutorREST(client, publishableToken, secretToken, signRequest, retryPolicy); executorSSE = new ExecutorSSE(baseSSEURL, publishableToken, secretToken); }
private async Task <User> RetrieveAuthenticatedUser(string accessToken, List <TwitchConstants.Scope> authorizedScopes, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } if (authorizedScopes.Contains(TwitchConstants.Scope.UserRead)) { Url url = new Url(TwitchConstants.baseUrl).AppendPathSegment("user"); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, accessToken, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } return(HelperMethods.LoadAuthedUser(JObject.Parse(responseString), accessToken, authorizedScopes, version)); } else { throw new TwixelException("This user has not given user_read permissions"); } }
/// <summary> /// Gets a live stream. /// If the stream is offline this method will throw an exception. /// </summary> /// <param name="channelName">The channel stream to get.</param> /// <param name="version">Twitch API version</param> /// <returns> /// Returns a stream object. /// If the stream is offline or an error occurs this will throw an exception. /// </returns> public async Task <Stream> RetrieveStream(string channelName, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("streams", channelName); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } JObject stream = JObject.Parse(responseString); if (stream["stream"].ToString() != "") { return(HelperMethods.LoadStream((JObject)stream["stream"], version)); } else { throw new TwixelException(channelName + " is offline", (JObject)stream["_links"]); } }
//Compiler private async Task CheckCompilerBackendAsync() { if (_backend == null) { APIVersion version = await _compilerClient.APIVersionAsync(); string v = version.ApiVersion.Replace(".", ""); if (v.Length == 1) { v += "0"; } if (v.Length == 2) { v += "0"; } int v2 = int.Parse(v); if (v2 > 399) { _backend = "fate"; } else { _backend = "aevm"; } } }
/// <summary> /// Gets the top videos on Twitch /// </summary> /// <param name="game">The name of the game to get videos for</param> /// <param name="period">The time period you want to look in</param> /// <param name="offset">Object offset for pagination. Default is 0.</param> /// <param name="limit">How many videos to get at one time. Default is 10. Maximum is 100</param> /// <param name="version">Twitch API version</param> /// <returns>A list of videos</returns> public async Task <List <Video> > RetrieveTopVideos(string game = null, TwitchConstants.Period period = TwitchConstants.Period.Week, int offset = 0, int limit = 25, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("videos", "top"); url.SetQueryParam("game", game); if (limit <= 100) { url.SetQueryParam("limit", limit); } else { url.SetQueryParam("limit", 100); } url.SetQueryParam("period", TwitchConstants.PeriodToString(period)); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } return(HelperMethods.LoadVideos(JObject.Parse(responseString), version)); }
/// <summary> /// Gets the top live streams on Twitch. /// </summary> /// <param name="game">The game you want streams for.</param> /// <param name="channels">Streams from a list of channels.</param> /// <param name="offset">Object offset for pagination. Default is 0.</param> /// <param name="limit">How many streams to get at one time. Default is 25. Maximum is 100.</param> /// <param name="clientId">Only show stream with this client ID. Version 3 only.</param> /// <param name="version">Twitch API version</param> /// <returns>A Total object containing a list of streams</returns> public async Task <Total <List <Stream> > > RetrieveStreams(string game = null, List <string> channels = null, int offset = 0, int limit = 25, string clientId = null, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegment("streams"); url.SetQueryParam("game", game); if (channels != null && channels.Count > 0) { string channelsString = ""; for (int i = 0; i < channels.Count; i++) { if (i != channels.Count - 1) { channelsString += channels[i] + ","; } else { channelsString += channels[i]; } } url.SetQueryParam("channel", channelsString); } if (limit <= 100) { url.SetQueryParam("limit", limit); } else { url.SetQueryParam("limit", 100); } url.SetQueryParam("offset", offset); if (version == APIVersion.v3) { url.SetQueryParam("client_id", clientId); } Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } JObject responseObject = JObject.Parse(responseString); List <Stream> streams = HelperMethods.LoadStreams(responseObject, version); return(HelperMethods.LoadTotal(responseObject, streams, version)); }
/// <summary> /// Gets a summary of live streams on Twitch /// </summary> /// <param name="game">Only show stats for this game</param> /// <param name="version">Twitch API version</param> /// <returns>A Dictionary with the first key of Viewers and the second key of Channels.</returns> public async Task <Dictionary <string, int> > RetrieveStreamsSummary(string game = null, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("streams", "summary"); if (!string.IsNullOrEmpty(game)) { url.SetQueryParam("game", game); } Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } JObject summary = JObject.Parse(responseString); Dictionary <string, int> summaryDict = new Dictionary <string, int>(); summaryDict.Add("Viewers", (int)summary["viewers"]); summaryDict.Add("Channels", (int)summary["channels"]); return(summaryDict); }
public LoginInfo LoginEx(string username, string password, string clientId, APIVersion required) { LoginInfo retVal = new LoginInfo(); retVal.APIVersion = new APIVersion(APIVersion.CURRENT_VERSION); retVal.ServerVersion = Assembly.GetExecutingAssembly().GetName().Version; if ((required != null) && ((required.Major > retVal.APIVersion.Major) || ((required.Major == retVal.APIVersion.Major) && (required.Minor > retVal.APIVersion.Minor)))) { retVal.ErrorType = "ActionNotSupportedException"; retVal.ErrorMessage = String.Format( "This client uses a modSIC API version ({0}) not supported by this modSIC Server ({1}).", required.ToString(), retVal.APIVersion); //retVal.ErrorMessage = "Client requires API " + required.ToString() + "; Server supports " + retVal.APIVersion; } else { var result = CollectController.Login(username, password, clientId); if (result == null) { retVal.ErrorType = "UnauthorizedAccessException"; retVal.ErrorMessage = "Invalid username or password"; } else { retVal.Token = result; } } return(retVal); }
/// <summary> /// Gets top games on Twitch. /// </summary> /// <param name="offset">Object offset for pagination. Default is 0.</param> /// <param name="limit">How many streams to get at one time. Default is 25. Maximum is 100</param> /// <param name="version">Twitch API version</param> /// <returns>A Total object containing a list of games</returns> public async Task <Total <List <Game> > > RetrieveTopGames(int offset = 0, int limit = 25, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("games", "top"); 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 GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } JObject responseObject = JObject.Parse(responseString); List <Game> games = HelperMethods.LoadGames(responseObject, version); return(HelperMethods.LoadTotal(responseObject, games, version)); }
public ModSicApiTest() { this.FakeApiVersion = new APIVersion("1.0"); this.FakeLoginInfoToReturn = new LoginInfo() { APIVersion = FakeApiVersion, Token = Guid.NewGuid().ToString() }; }
/// <summary> /// This constructor must be use only for unit tests purposes. /// </summary> /// <param name="modSicProxy">An instance of ModSicServiceProxy with mock behavior.</param> /// <param name="username">modSIC user name. It´s optional, because you do not need to pass username in order to call Heartbeat operation.</param> /// <param name="username">modSIC password. Like username parameter.</param> public ModSicConnection(ModSicServiceProxy modSicProxyMock, string username = null, string password = null, string clientId = null, APIVersion apiVersion = null, string fakeCertificatePassword = "******") { this.Username = username; this.Password = password; this.ClientId = clientId; this.RequiredVersion = apiVersion; this.ModSicProxyService = modSicProxyMock; this.CertificatePassword = fakeCertificatePassword; }
/// <summary> /// Constructor for modSIC API. This is the constructor that be used in production code. /// </summary> /// <param name="username">modSIC user name. It´s optional, because you do not need to pass username in order to call Heartbeat operation.</param> /// <param name="username">modSIC password. Like username parameter.</param> public ModSicConnection(string modSicServiceURL, string username = null, string password = null, string clientId = null) { this.Username = username; this.Password = password; this.ClientId = clientId; this.RequiredVersion = new APIVersion(APIVersion.CURRENT_VERSION); this.ModSicProxyService = new ModSicServiceProxy(modSicServiceURL); }
public XBeeSerialPort(uint baudRate, SerialParity parity, SerialStopBitCount stopBitCount, ushort dataBits, APIVersion apiVersion) { this.baudRate = baudRate; this.parity = parity; this.stopBitCount = stopBitCount; this.dataBits = dataBits; this.apiVersion = apiVersion; StartListeningForSerialPortChanges(); }
public string GetRequestBaseUrl(APIVersion version) { if (version == APIVersion.New) { return("https://api.twitch.tv/helix/"); } else if (version == APIVersion.V5) { return("https://api.twitch.tv/kraken/"); } return(null); }
public void OnAuthorization(AuthorizationFilterContext context) { if (context.ActionDescriptor.GetCustomMethodAttribute <AllowAnyAPIVersion>() == null) { if (!context.HttpContext.Request.Headers.TryGetValue(APIVersion.Key, out var requestApiVersion) || !APIVersion.IsCompatible(requestApiVersion)) { throw new IncompatibleAPIVersionException("Server and Client API Major versions do not match." + " This is likley to cause unpredictable behaviour." + $" \nServer API Version: {requestApiVersion}" + $" \nClient API Version: {requestApiVersion}"); } } }
/// <summary> /// Gets a Total object containing a list of videos for a specified channel /// </summary> /// <param name="channel">The name of the channel</param> /// <param name="offset">Object offset for pagination. Default is 0.</param> /// <param name="limit">How many videos to get at one time. Default is 10. Maximum is 100.</param> /// <param name="broadcasts">Returns only broadcasts when true. Otherwise only highlights are returned. Default is false.</param> /// <param name="hls">Returns only HLS VoDs when true. Otherwise only non-HLS VoDs are returned. Default is false.</param> /// <param name="version">Twitch API version</param> /// <returns>A Total object containing list of videos</returns> public async Task <Total <List <Video> > > RetrieveVideos(string channel = null, int offset = 0, int limit = 25, bool broadcasts = false, bool?hls = null, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("channels", channel, "videos"); if (limit <= 100) { url.SetQueryParam("limit", limit); } else { url.SetQueryParam("limit", 100); } url.SetQueryParams(new { broadcasts = broadcasts, offset = offset }); if (version == APIVersion.v3) { if (hls == null) { hls = false; } url.SetQueryParam("hls", hls); } Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } JObject responseObject = JObject.Parse(responseString); List <Video> videos = HelperMethods.LoadVideos(responseObject, version); return(HelperMethods.LoadTotal(responseObject, videos, version)); }
public JObject ToJson(LookupContext ctx, APIVersion v) { var o = new JObject(); o.Add("timestamp", Instant.FromUnixTimeMilliseconds((long)(Message.Mid >> 22) + 1420070400000).ToString()); o.Add("id", Message.Mid.ToString()); o.Add("original", Message.OriginalMid.ToString()); o.Add("sender", Message.Sender.ToString()); o.Add("channel", Message.Channel.ToString()); o.Add("guild", Message.Guild?.ToString()); o.Add("system", System?.ToJson(ctx, v)); o.Add("member", Member?.ToJson(ctx, v: v)); return(o); }
public IDeviceNetwork CreateDeviceNetwork(Dictionary<string, string> configuration) { // get serial port configuration from the configuration dictionary baudRate = UInt32.Parse(configuration["BaudRate"]); parity = (SerialParity)Enum.Parse(typeof(SerialParity), configuration["SerialParity"], true); stopBit = (SerialStopBitCount)Enum.Parse(typeof(SerialStopBitCount), configuration["SerialStopBitCount"], true); dataBits = UInt16.Parse(configuration["DataBits"]); apiVersion = (APIVersion)Enum.Parse(typeof(APIVersion), configuration["APIVersion"], true); // create the serial port IXBeeSerialPort serialPort = CreateSerialPortWithSavedConfigurationParameters(); // now create the device network with this serial port XBeeDeviceNetwork network = new XBeeDeviceNetwork(serialPort); return network; }
/// <summary> /// Search streams on Twitch /// </summary> /// <param name="query">The search query</param> /// <param name="offset">Object offset for pagination. Default is 0.</param> /// <param name="limit">How many streams to get at one time. Default is 25. Maximum is 100.</param> /// <param name="hls">If set to true, only returns streams using HLS. If set to false, only returns streams that are non-HLS.</param> /// <param name="version">Twitch API version</param> /// <returns>A Total object containing a list of streams</returns> public async Task <Total <List <Stream> > > SearchStreams(string query, int offset = 0, int limit = 25, bool?hls = null, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("search", "streams").SetQueryParam("query", query); if (limit <= 100) { url.SetQueryParam("limit", limit); } else { url.SetQueryParam("limit", 100); } url.SetQueryParam("offset", offset); if (version == APIVersion.v3) { if (hls == null) { hls = false; } url.SetQueryParam("hls", hls); } Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } JObject responseObject = JObject.Parse(responseString); List <Stream> streams = HelperMethods.LoadStreams(responseObject, version); return(HelperMethods.LoadTotal(responseObject, streams, version)); }
public static string Decrypt(string value, string clientSecret, APIVersion apiVersion = APIVersion.V2) { try { Payload _payload; try { _payload = JsonConvert.DeserializeObject <Payload>(Encoding.UTF8.GetString(Convert.FromBase64String(value))); } catch { throw new Exception("The payload is invalid."); } if (string.IsNullOrEmpty(_payload.salt)) { throw new Exception("The payload is invalid."); } var base64SaltString = _payload.salt; var saltString = Encoding.UTF8.GetString(Convert.FromBase64String(base64SaltString)); if (saltString.Length < 8) { throw new Exception("The payload is invalid."); } var base64EncryptedString = _payload.encrypted; byte[] cryptBytes = Convert.FromBase64String(base64EncryptedString); byte[] clientSecretBytes = Encoding.UTF8.GetBytes(clientSecret); byte[] saltBytes = Encoding.UTF8.GetBytes(saltString); var computedMac = ComputeMac(clientSecretBytes, Encoding.UTF8.GetBytes(base64SaltString), Encoding.UTF8.GetBytes(base64EncryptedString)); if (!string.Equals(computedMac, _payload.mac)) { throw new Exception("The MAC is invalid."); } return(Encoding.UTF8.GetString(AESDecryptBytes(cryptBytes, clientSecretBytes, saltBytes, apiVersion))); } catch (Exception ex) { throw new AgeIDEncryptionException(ex.Message); } }
/// <summary> /// Gets the list of RTMP ingest points /// </summary> /// <param name="version">Twitch API version</param> /// <returns>A list of ingests</returns> public async Task <List <Ingest> > RetrieveIngests(APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegment("ingests"); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } return(HelperMethods.LoadIngests(JObject.Parse(responseString), version)); }
/// <summary> /// Gets the chat URL's for the specified user /// </summary> /// <param name="user">The name of the user</param> /// <param name="version">Twitch API version</param> /// <returns>A dictionary of links</returns> public async Task <Dictionary <string, Uri> > RetrieveChat(string user, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("chat", user); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } return(HelperMethods.LoadLinks((JObject)JObject.Parse(responseString)["_links"])); }
private Uri BuildCommandQuery(string module, string function, APIVersion _apiVersion, params BatchDomainTools.WebPanelCommons.CommandArgs[] cArg) { UriBuilder ub = new UriBuilder(this.Account.PanelAddr); string args = string.Empty; foreach (string argNow in cArg) { args += "&" + argNow; } ub.Path += "xml-api/cpanel"; ub.Query += string.Format("cpanel_xmlapi_apiversion={0}&cpanel_xmlapi_module={1}", (int)_apiVersion, module); if (!string.IsNullOrEmpty(function)) { ub.Query += "&cpanel_xmlapi_func=" + function; } if (!string.IsNullOrEmpty(args)) { ub.Query += args; } ub.Query = ub.Query.TrimStart('?'); return(ub.Uri); }
/// <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"]); } }
private ServerCheckResult CheckForServer(string checkIp, int timoutMillisecs) { ServerCheckResult result = new ServerCheckResult(); string url = string.Format(m_apiUrl, checkIp); using (var client = new HttpClient()) { client.Timeout = TimeSpan.FromMilliseconds(timoutMillisecs); try { var response = client.GetAsync(url).Result; if (response.IsSuccessStatusCode) { APIVersion version = JsonConvert.DeserializeObject <APIVersion>(response.Content.ReadAsStringAsync().Result); return(new ServerCheckResult { Found = version.HighVersion >= m_minSupportedVersion }); } return(new ServerCheckResult()); } catch (TaskCanceledException) { Debug.WriteLine("Timeout"); return(new ServerCheckResult { TimedOut = true }); } catch (Exception ex) { Debug.WriteLine("Error thrown: " + ex.Message); return(new ServerCheckResult()); } } }
/// <summary> /// Put web data /// </summary> /// <param name="uri">URL</param> /// <param name="accessToken">Access token</param> /// <param name="content">JSON object as a string</param> /// <param name="version">Twitch API version</param> /// <returns>A response string containing a JSON object</returns> public static async Task<string> PutWebData(Uri uri, string accessToken, string content, APIVersion version = APIVersion.None) { return await DoWebData(uri, RequestType.Put, accessToken, content, version); }
/// <summary> /// Get web data with an access token. /// </summary> /// <param name="uri">URL</param> /// <param name="accessToken">Access token</param> /// <param name="version">Twitch API version</param> /// <returns>A response string containing a JSON object</returns> public static async Task<string> GetWebData(Uri uri, string accessToken, APIVersion version = APIVersion.None) { return await DoWebData(uri, RequestType.Get, accessToken, null, version); }
/// <summary> /// Twixel constructor /// </summary> /// <param name="id">Your client ID</param> /// <param name="url">Your redirect URL, should not have / at end</param> /// <param name="defaultVersion">The API version you want to use</param> public Twixel(string id, string url, APIVersion defaultVersion) { clientID = id; redirectUrl = url; this.DefaultVersion = defaultVersion; }
/// <summary> /// Gets a Total object containing a list of videos for a specified channel /// </summary> /// <param name="channel">The name of the channel</param> /// <param name="offset">Object offset for pagination. Default is 0.</param> /// <param name="limit">How many videos to get at one time. Default is 10. Maximum is 100.</param> /// <param name="broadcasts">Returns only broadcasts when true. Otherwise only highlights are returned. Default is false.</param> /// <param name="hls">Returns only HLS VoDs when true. Otherwise only non-HLS VoDs are returned. Default is false.</param> /// <param name="version">Twitch API version</param> /// <returns>A Total object containing list of videos</returns> public async Task<Total<List<Video>>> RetrieveVideos(string channel = null, int offset = 0, int limit = 25, bool broadcasts = false, bool? hls = null, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("channels", channel, "videos"); if (limit <= 100) { url.SetQueryParam("limit", limit); } else { url.SetQueryParam("limit", 100); } url.SetQueryParams(new { broadcasts = broadcasts, offset = offset }); if (version == APIVersion.v3) { if (hls == null) { hls = false; } url.SetQueryParam("hls", hls); } Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } JObject responseObject = JObject.Parse(responseString); List<Video> videos = HelperMethods.LoadVideos(responseObject, version); return HelperMethods.LoadTotal(responseObject, videos, version); }
/// <summary> /// Gets the top videos on Twitch /// </summary> /// <param name="game">The name of the game to get videos for</param> /// <param name="period">The time period you want to look in</param> /// <param name="offset">Object offset for pagination. Default is 0.</param> /// <param name="limit">How many videos to get at one time. Default is 10. Maximum is 100</param> /// <param name="version">Twitch API version</param> /// <returns>A list of videos</returns> public async Task<List<Video>> RetrieveTopVideos(string game = null, TwitchConstants.Period period = TwitchConstants.Period.Week, int offset = 0, int limit = 25, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("videos", "top"); url.SetQueryParam("game", game); if (limit <= 100) { url.SetQueryParam("limit", limit); } else { url.SetQueryParam("limit", 100); } url.SetQueryParam("period", TwitchConstants.PeriodToString(period)); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } return HelperMethods.LoadVideos(JObject.Parse(responseString), version); }
/// <summary> /// Search streams on Twitch /// </summary> /// <param name="query">The search query</param> /// <param name="offset">Object offset for pagination. Default is 0.</param> /// <param name="limit">How many streams to get at one time. Default is 25. Maximum is 100.</param> /// <param name="hls">If set to true, only returns streams using HLS. If set to false, only returns streams that are non-HLS.</param> /// <param name="version">Twitch API version</param> /// <returns>A Total object containing a list of streams</returns> public async Task<Total<List<Stream>>> SearchStreams(string query, int offset = 0, int limit = 25, bool? hls = null, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("search", "streams").SetQueryParam("query", query); if (limit <= 100) { url.SetQueryParam("limit", limit); } else { url.SetQueryParam("limit", 100); } url.SetQueryParam("offset", offset); if (version == APIVersion.v3) { if (hls == null) { hls = false; } url.SetQueryParam("hls", hls); } Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } JObject responseObject = JObject.Parse(responseString); List<Stream> streams = HelperMethods.LoadStreams(responseObject, version); return HelperMethods.LoadTotal(responseObject, streams, version); }
/// <summary> /// Retrieve teams the specified user is a member of. /// </summary> /// <param name="user">The name of the user</param> /// <param name="version">Twitch API version</param> /// <returns>List of teams</returns> public async Task<List<Team>> RetrieveTeams(string user, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } if (version == APIVersion.v3) { Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("channels", user, "teams"); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } return HelperMethods.LoadTeams(JObject.Parse(responseString), version); } else { throw new TwixelException(TwitchConstants.v2UnsupportedErrorString); } }
/// <summary> /// Gets the list of badges that can be used in the specified user's channel /// </summary> /// <param name="user">The name of the user</param> /// <param name="version">Twitch API version</param> /// <returns>List of badges</returns> public async Task<List<Badge>> RetrieveBadges(string user, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("chat", user, "badges"); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } return HelperMethods.LoadBadges(JObject.Parse(responseString), version); }
/// <summary> /// Gets the list of teams from Twitch /// </summary> /// <param name="offset">Object offset for pagination. Default is 0.</param> /// <param name="limit">How many teams to get at one time. Default is 25. Maximum is 100.</param> /// <param name="version">Twitch API version</param> /// <returns>A list of teams</returns> public async Task<List<Team>> RetrieveTeams(int offset = 0, int limit = 25, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegment("teams"); if (limit <= 100) { url.SetQueryParam("limit", limit); } else { url.SetQueryParam("limit", 100); } Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } return HelperMethods.LoadTeams(JObject.Parse(responseString), version); }
/// <summary> /// Gets a summary of live streams on Twitch /// </summary> /// <param name="game">Only show stats for this game</param> /// <param name="version">Twitch API version</param> /// <returns>A Dictionary with the first key of Viewers and the second key of Channels.</returns> public async Task<Dictionary<string, int>> RetrieveStreamsSummary(string game = null, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("streams", "summary"); if (!string.IsNullOrEmpty(game)) { url.SetQueryParam("game", game); } Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } JObject summary = JObject.Parse(responseString); Dictionary<string, int> summaryDict = new Dictionary<string, int>(); summaryDict.Add("Viewers", (int)summary["viewers"]); summaryDict.Add("Channels", (int)summary["channels"]); return summaryDict; }
/// <summary> /// Gets the top live streams on Twitch. /// </summary> /// <param name="game">The game you want streams for.</param> /// <param name="channels">Streams from a list of channels.</param> /// <param name="offset">Object offset for pagination. Default is 0.</param> /// <param name="limit">How many streams to get at one time. Default is 25. Maximum is 100.</param> /// <param name="clientId">Only show stream with this client ID. Version 3 only.</param> /// <param name="version">Twitch API version</param> /// <returns>A Total object containing a list of streams</returns> public async Task<Total<List<Stream>>> RetrieveStreams(string game = null, List<string> channels = null, int offset = 0, int limit = 25, string clientId = null, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegment("streams"); url.SetQueryParam("game", game); if (channels != null && channels.Count > 0) { string channelsString = ""; for (int i = 0; i < channels.Count; i++) { if (i != channels.Count - 1) { channelsString += channels[i] + ","; } else { channelsString += channels[i]; } } url.SetQueryParam("channel", channelsString); } if (limit <= 100) { url.SetQueryParam("limit", limit); } else { url.SetQueryParam("limit", 100); } url.SetQueryParam("offset", offset); if (version == APIVersion.v3) { url.SetQueryParam("client_id", clientId); } Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } JObject responseObject = JObject.Parse(responseString); List<Stream> streams = HelperMethods.LoadStreams(responseObject, version); return HelperMethods.LoadTotal(responseObject, streams, version); }
/// <summary> /// Gets a live stream. /// If the stream is offline this method will throw an exception. /// </summary> /// <param name="channelName">The channel stream to get.</param> /// <param name="version">Twitch API version</param> /// <returns> /// Returns a stream object. /// If the stream is offline or an error occurs this will throw an exception. /// </returns> public async Task<Stream> RetrieveStream(string channelName, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("streams", channelName); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } JObject stream = JObject.Parse(responseString); if (stream["stream"].ToString() != "") { return HelperMethods.LoadStream((JObject)stream["stream"], version); } else { throw new TwixelException(channelName + " is offline", (JObject)stream["_links"]); } }
/// <summary> /// Search games on Twitch /// </summary> /// <param name="query">The search query</param> /// <param name="live">If true, only returns games that are live on at least one channel. Default is false.</param> /// <param name="version">Twitch API version</param> /// <returns>Returns a list of searched games</returns> public async Task<List<SearchedGame>> SearchGames(string query, bool live = false, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("search", "games").SetQueryParams(new { query = query, type = "suggest", live = live }); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } return HelperMethods.LoadSearchedGames(JObject.Parse(responseString), version); }
private static async Task<string> DoWebData(Uri uri, RequestType requestType, string accessToken = null, string content = null, APIVersion version = APIVersion.None) { HttpClient client = new HttpClient(); if (version == APIVersion.None) { version = APIVersion.v3; } if (version == APIVersion.v2) { client.DefaultRequestHeaders.Add("Accept", "application/vnd.twitchtv.v2+json"); } else if (version == APIVersion.v3) { client.DefaultRequestHeaders.Add("Accept", "application/vnd.twitchtv.v3+json"); } client.DefaultRequestHeaders.Add("Client-ID", clientID); if (!string.IsNullOrEmpty(accessToken)) { client.DefaultRequestHeaders.Add("Authorization", "OAuth " + accessToken); } StringContent stringContent = new StringContent("", Encoding.UTF8, "application/json"); if (requestType == RequestType.Put || requestType == RequestType.Post) { stringContent = new StringContent(content, Encoding.UTF8, "application/json"); } HttpResponseMessage response = null; if (requestType == RequestType.Get) { response = await client.GetAsync(uri); } else if (requestType == RequestType.Put) { response = await client.PutAsync(uri, stringContent); } else if (requestType == RequestType.Post) { response = await client.PostAsync(uri, stringContent); } else if (requestType == RequestType.Delete) { response = await client.DeleteAsync(uri); } string responseString; if (response.StatusCode == HttpStatusCode.OK) { responseString = await response.Content.ReadAsStringAsync(); if (responseString.StartsWith("<")) { string[] initialErrorSplit = responseString.Split(' '); string potentialErrorCode = initialErrorSplit[0].Substring(initialErrorSplit[0].Length - 3, 3); int errorCodeNum = -1; try { errorCodeNum = int.Parse(potentialErrorCode); } catch { } throw new TwitchException(responseString, responseString, errorCodeNum); } return responseString; } else if (response.StatusCode == HttpStatusCode.NoContent) { responseString = string.Empty; return responseString; } else { responseString = await response.Content.ReadAsStringAsync(); JObject twitchErrorObject = null; try { twitchErrorObject = JObject.Parse(responseString); throw new TwitchException(twitchErrorObject); } catch { throw new TwitchException(responseString, response.ReasonPhrase, (int)response.StatusCode); } } }
public OpenGLVersionNotSupportedException(APIVersion preferredVersion) : base($"Preferred OpenGL version {preferredVersion.MajorVersion}.{preferredVersion.MinorVersion} is not supported.") => PreferredVersion = preferredVersion;
/// <summary> /// Gets a video by ID /// </summary> /// <param name="id">The video ID</param> /// <param name="version">Twitch API version</param> /// <returns>A video</returns> public async Task<Video> RetrieveVideo(string id, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("videos", id); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } return HelperMethods.LoadVideo(JObject.Parse(responseString), version); }
private async Task<User> RetrieveAuthenticatedUser(string accessToken, List<TwitchConstants.Scope> authorizedScopes, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } if (authorizedScopes.Contains(TwitchConstants.Scope.UserRead)) { Url url = new Url(TwitchConstants.baseUrl).AppendPathSegment("user"); Uri uri = new Uri(url.ToString()); string responseString; try { responseString = await GetWebData(uri, accessToken, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } return HelperMethods.LoadAuthedUser(JObject.Parse(responseString), accessToken, authorizedScopes, version); } else { throw new TwixelException("This user has not given user_read permissions"); } }
/// <summary> /// Gets top games on Twitch. /// </summary> /// <param name="offset">Object offset for pagination. Default is 0.</param> /// <param name="limit">How many streams to get at one time. Default is 25. Maximum is 100</param> /// <param name="version">Twitch API version</param> /// <returns>A Total object containing a list of games</returns> public async Task<Total<List<Game>>> RetrieveTopGames(int offset = 0, int limit = 25, APIVersion version = APIVersion.None) { if (version == APIVersion.None) { version = DefaultVersion; } Url url = new Url(TwitchConstants.baseUrl).AppendPathSegments("games", "top"); 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 GetWebData(uri, version); } catch (TwitchException ex) { throw new TwixelException(TwitchConstants.twitchAPIErrorString, ex); } JObject responseObject = JObject.Parse(responseString); List<Game> games = HelperMethods.LoadGames(responseObject, version); return HelperMethods.LoadTotal(responseObject, games, version); }
public void Init(PluginAttribute plugin) { this.Name = plugin.PluginName; this.Description = plugin.PluginDescription; this.APIVersion = plugin.PluginAPIVersion; }
/// <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"]); } }