twitch-agent/OAuthTokenGetter.cs

71 lines
2.9 KiB
C#
Raw Normal View History

using Newtonsoft.Json;
using System;
using System.IO;
2022-01-16 15:10:20 -05:00
using System.Net;
using System.Net.Http;
2022-01-16 15:10:20 -05:00
using System.Text;
using System.Threading;
2022-01-16 15:10:20 -05:00
namespace twitcher
{
2022-01-16 15:10:20 -05:00
public class OAuthTokenGetter
{
2022-01-16 15:10:20 -05:00
private static readonly AutoResetEvent _signal = new AutoResetEvent(false);
public static string GetUser(Httpd server, string clientId, string redirectUri)
{
2022-01-16 15:10:20 -05:00
server.HandleEndpoint("login", (HttpListenerRequest request) =>
{
var toReturn = new Httpd.ResponseSet();
Console.WriteLine($"query string: {request.QueryString}");
Console.WriteLine($"RawUrl: {request.RawUrl}");
toReturn.Text = File.ReadAllText("login.html");
return toReturn;
});
var token = "";
server.HandleEndpoint("token", (HttpListenerRequest request) =>
{
byte[] rawIncomingBytes = new byte[request.ContentLength64];
request.InputStream.Read(rawIncomingBytes, 0, (int)request.ContentLength64);
token = request.ContentEncoding.GetString(rawIncomingBytes);
_signal.Set();
return new Httpd.ResponseSet() {Text = "k" };
});
var sendTo = $"https://id.twitch.tv/oauth2/authorize?client_id={clientId}&redirect_uri={redirectUri}&response_type=token&state=constant_agitation&scope=channel.ban";
Console.WriteLine($"go to {sendTo} plz, I'll wait here");
_signal.WaitOne(new TimeSpan(1, 0, 0));
return token;
}
2022-01-16 15:10:20 -05:00
public static OAuthToken GetApplication(HttpClient client, string clientId, string clientSecret, string[] scopes = null)
{
2022-01-16 15:10:20 -05:00
var scopeString = "";
if (scopes != null && scopes.Length > 0)
{
scopeString = "&scope=" + string.Join(' ', scopes);
}
var postURI = $"https://id.twitch.tv/oauth2/token?client_id={clientId}&client_secret={clientSecret}&grant_type=client_credentials{scopeString}";
//Console.WriteLine(postURI);
var r = client.PostAsync(postURI, null).Result;
var response = "";
using (var streamReader = new StreamReader(r.Content.ReadAsStream()))
{
response = streamReader.ReadToEnd();
}
if (!r.IsSuccessStatusCode)
{
Console.Error.WriteLine(response);
throw new Exception(response);
}
Console.WriteLine(response);
return JsonConvert.DeserializeObject<OAuthToken>(response);
}
}
2022-01-16 15:10:20 -05:00
public class OAuthToken
{
public string access_token { get; set; }
public string refresh_token { get; set; }
public int expires_in { get; set; }
public string[] scope { get; set; }
public string token_type { get; set; }
}
}