TannieSpace

geekery, drawing and then some

Bit.ly + TextExpander + Applescript = WIN!

I wanted an easy way to shorten my URLs through one of the URL-shorteners out there. I liked bit.ly, because it’s nice and short, has an easy to navigate web-interface (without a mouse) and I can use its magic with my terminal (cURL).

I also very much like TextExpander and after googling a bit, I ofcourse found an Applescript for TextExpander and Bit.ly. That link also shows how to set it up in TextExpander, very handy! The script does not however use your actual bit.ly account so you can keep track of the URLs you shorten. I tweaked it and made adjustments and it took hours and ofcourse, then I find this which is almost exactly what I had, except with URL-encoding (yummy). The only problem with that one was that I couldn’t get it to have the URLs show up in my recent history. The ‘history=1’ didn’t seem to work.

I tweaked some more and came up with something that completely does what I want. I use OmniWeb so I replaced the

set the PageURL to (the clipboard as string)

with

tell application "OmniWeb" set PageURL to address of active tab of browser 1 end tell

If you use safari, use

tell application "Safari" set PageURL to URL of front document end tell

I’ve made this as readable as possible, the ‘¬’ do matter in Applescript.

tell application "OmniWeb" set PageURL to address of active tab of browser 1 end tell

set login to "YOUR LOGIN" set api_key to "YOUR API KEY" set the EncodedURL to urlencode(PageURL) of me

set curlCMD to ¬ "curl --stderr /dev/null \"http://api.bit.ly/v3/shorten?format=txt&longUrl=" ¬ & EncodedURL & "&history=1&login=" & login ¬ & "&apiKey=" & api_key ¬ & "\""

\-- Run the script and get the result: set bitlyURL to (do shell script curlCMD)

return bitlyURL

on urlencode(theText)
set theTextEnc to "" repeat with eachChar in characters of theText
set useChar to eachChar
set eachCharNum to ASCII number of eachChar
if eachCharNum = 32 then
    set useChar to "+" else if (eachCharNum ‚↠42) and (eachCharNum ‚↠95) ¬
    and (eachCharNum < 45 or eachCharNum > 46) ¬
    and (eachCharNum < 48 or eachCharNum > 57) ¬
    and (eachCharNum < 65 or eachCharNum > 90) ¬
    and (eachCharNum < 97 or eachCharNum > 122) then
        set firstDig to round (eachCharNum / 16) rounding down
        set secondDig to eachCharNum mod 16 if firstDig > 9 then
            set aNum to firstDig + 55 set firstDig to ASCII character aNum
end if
if secondDig > 9 then
    set aNum to secondDig + 55
    set secondDig to ASCII character aNum
end if
set numHex to ("%" & (firstDig as string) ¬
 & (secondDig as string)) as string
 set useChar to numHex
end if
set theTextEnc to theTextEnc & useChar as string
end repeat
return theTextEnc
end urlencode

ETA (2010.09.30): bit.ly changed a few things so I changed the script above to reflect that


Comments powered by Disqus