?

Log in

No account? Create an account

Peter Rogers's Blog
Artist-in-Residence at Chez Firth

Wednesday (8/18/10) 10:48am - ... wherein Peter adds an AHK script for URL shortening.

Neat -- just made an AutoHotKey script that shortens URLs.  Now I can select a URL, type windows-U, and it automatically replaces the text with an is.gd link.

I was completely ripping off this code from AHK forum user "Petr".

Here's my slightly-adjusted version of his code:


;Win + U shortens URLs
#u::
ClipSaved_SURL := ClipboardAll
Send {Ctrl Down}c{Ctrl Up}
Sleep 100
CleanString := Clipboard
longURL = http://is.gd/api.php?longurl=%Clipboard%
shortURL := UrlDownloadToVar(longURL,0)
AutoTrim, on
shortURL = %shortURL%
;msgbox %shortURL%
RegExMatch(shortURL, "(.*)", Matches)        ; hack to get rid of weird extra linefeeds
SendInput %Matches%
Clipboard := ClipSaved_SURL
return

UrlDownloadToVar(URL, DeleteAmount="", Proxy="", ProxyBypass="")
{
AutoTrim, Off
hModule := DllCall("LoadLibrary", "str", "wininet.dll")

;msgbox %URL%

If (Proxy != "")
AccessType=3
Else
AccessType=1
;INTERNET_OPEN_TYPE_PRECONFIG                    0  // use registry configuration
;INTERNET_OPEN_TYPE_DIRECT                      1  // direct to net
;INTERNET_OPEN_TYPE_PROXY                        3  // via named proxy
;INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY  4  // prevent using java/script/INS

io_hInternet := DllCall("wininet\InternetOpenA"
, "str", "" ;lpszAgent
, "uint", AccessType
, "str", Proxy
, "str", ProxyBypass
, "uint", 0) ;dwFlags

iou := DllCall("wininet\InternetOpenUrlA"
, "uint", io_hInternet
, "str", url
, "str", "" ;lpszHeaders
, "uint", 0 ;dwHeadersLength
, "uint", 0x80000000 ;dwFlags: INTERNET_FLAG_RELOAD = 0x80000000 // retrieve the original item
, "uint", 0) ;dwContext

If (ErrorLevel != 0 or iou = 0)
{
DllCall("FreeLibrary", "uint", hModule)
return 0
}

VarSetCapacity(buffer, 512, 0)
VarSetCapacity(NumberOfBytesRead, 4, 0)
Loop
{
  irf := DllCall("wininet\InternetReadFile", "uint", iou, "uint", &buffer, "uint", 512, "uint", &NumberOfBytesRead)
  NOBR = 0
  Loop 4  ; Build the integer by adding up its bytes. - ExtractInteger
    NOBR += *(&NumberOfBytesRead + A_Index-1) << 8*(A_Index-1)
  IfEqual, NOBR, 0, break
  ;BytesReadTotal += NOBR
  DllCall("lstrcpy", "str", buffer, "uint", &buffer)
  res = %res%%buffer%
}

; The bit I added:
StringTrimRight, res, res, DeleteAmount ;Removes new lines if necessary

DllCall("wininet\InternetCloseHandle",  "uint", iou)
DllCall("wininet\InternetCloseHandle",  "uint", io_hInternet)
DllCall("FreeLibrary", "uint", hModule)
AutoTrim, on
return, res
}

It's not perfect -- not yet, anyway.  For some reason right now, it often adds a zero to the end of the is.gd link. (?)  Still, it's far more convenient than opening up a new browser window/tab and going to the is.gd site, or (on Opera) typing in "is <url name>" as a jerry-rigged address-bar search.

Tags: ,
Mood: [mood icon] happy · Music: none
Previous Entry Share Next Entry