using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
public static class ClipboardFusionHelper
{
// Paste your access token here. You can get it here https://bitly.is/accesstoken
private static readonly string bitlyToken = "";
public static string ProcessText(string text)
{
text = BFS.Clipboard.CopyText();
if (CheckURLValid(text))
{
var shortenUrl = Shorten(text).Result;
return shortenUrl;
}
else
BFS.Dialog.ShowMessageInfo("It's not a url, or url not valid");
return null;
}
public static bool CheckURLValid(string url)
{
Uri uriResult;
return Uri.TryCreate(url, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
}
public static async Task<string> Shorten(string url)
{
var post = "{\"long_url\": \"" + url + "\"}";
var request = (HttpWebRequest) WebRequest.Create("https://api-ssl.bitly.com/v4/shorten");
try
{
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("Cache-Control", "no-cache");
request.Host = "api-ssl.bitly.com";
request.Headers.Add("Authorization", "Bearer " + bitlyToken);
using (var requestStream = request.GetRequestStream())
{
var postBuffer = Encoding.UTF8.GetBytes(post);
requestStream.Write(postBuffer, 0, postBuffer.Length);
}
var response = await request.GetResponseAsync();
using (var responseStream = response.GetResponseStream())
{
var responseReader = new StreamReader(responseStream, Encoding.UTF8);
var json = responseReader.ReadToEnd();
var shortenUrl = Regex.Match(json, @"""link"": ?""(?<link>[^,;]+)""").Groups["link"].Value;
BFS.Clipboard.PasteText(shortenUrl);
return shortenUrl;
}
}
catch (WebException ex)
{
throw;
}
}
}