71 lines
2.9 KiB
C#
71 lines
2.9 KiB
C#
using Newtonsoft.Json;
|
|
using System;
|
|
using System.IO;
|
|
using System.Net;
|
|
using System.Net.Http;
|
|
using System.Text;
|
|
using System.Threading;
|
|
|
|
namespace twitcher
|
|
{
|
|
public class OAuthTokenGetter
|
|
{
|
|
private static readonly AutoResetEvent _signal = new AutoResetEvent(false);
|
|
public static string GetUser(Httpd server, string clientId, string redirectUri)
|
|
{
|
|
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;
|
|
}
|
|
public static OAuthToken GetApplication(HttpClient client, string clientId, string clientSecret, string[] scopes = null)
|
|
{
|
|
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);
|
|
}
|
|
}
|
|
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; }
|
|
}
|
|
} |