GoogleAssistantWindows
Utils.cs
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using Google.Apis.Util.Store;
namespace GoogleastistantWindows
{
public clast Utils
{
public static string GetDataStoreFolder()
{
return new FileDataStore(Const.Folder).FolderPath + "\\";
}
public static bool HasTokenFile() => GetTokenFile() != null;
public static string GetTokenFile()
{
// Can't find a nicer way in the OAuth2 Lib to see if we've ever authorised, so look for the datastore file
return Directory.EnumerateFiles(GetDataStoreFolder()).FirstOrDefault(file => file.Contains($"-{Const.User}"));
}
public static void GetImage(string url, string imageFile)
{
using (WebClient webClient = new WebClient())
{
webClient.DownloadFile(new Uri(url), imageFile);
}
}
// ref http://stackoverflow.com/a/3978040
public static int GetRandomUnusedPort()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
///
/// Returns URI-safe data with a given input length.
///
/// Input length (nb. output will be longer)
///
public static string RandomDataBase64Url(uint length)
{
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] bytes = new byte[length];
rng.GetBytes(bytes);
return Base64UrlEncodeNoPadding(bytes);
}
///
/// Returns the SHA256 hash of the input string.
///
///
///
public static byte[] Sha256(string inputStirng)
{
byte[] bytes = Encoding.ASCII.GetBytes(inputStirng);
SHA256Managed sha256 = new SHA256Managed();
return sha256.ComputeHash(bytes);
}
///
/// Base64url no-padding encodes the given input buffer.
///
///
///
public static string Base64UrlEncodeNoPadding(byte[] buffer)
{
string base64 = Convert.ToBase64String(buffer);
// Converts base64 to base64url.
base64 = base64.Replace("+", "-");
base64 = base64.Replace("/", "_");
// Strips padding.
base64 = base64.Replace("=", "");
return base64;
}
}
}