Processing Ajax...

Title
Close Dialog

Message

Confirm
Close Dialog

Confirm
Close Dialog

Confirm
Close Dialog

Shorten URL with Bit.ly (with auto copy/paste)

Description
This Macro will copy the selected text, generate a shortened link using the Bit.ly API, and then paste it. Note: You need to sign up for Bit.ly and generate an access token. Set the access token on line 11 in this script.
Language
C#.net
Minimum Version
Created By
Keith Lammers (BFS)
Contributors
PabloMartinez
Date Created
Nov 23, 2020
Date Last Modified
Nov 23, 2020

Macro Code

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;
        }
    }
}