Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

10.6: Create a tri.im URL shortening Service Internet
One of the great new features of Snow Leopard is the ability thru Automator (and by extension, AppleScript) to make your own service. Automator can set-up services to accept specific inputs (ie files, images, or text) to act on. If you have selected the appropriate type of input, the service will show up in your context menu.

To create a service which generates a tr.im shortened URL when control-clicking a link in Safari. First, open Automator, and select Create a New Service. Set the Service to receive selected text in Safari. Find Run AppleScript from the Action library on the left, and drag that over to the right half of the Automator window. In that area, paste in the following:
on run {inText}
    tell application "Safari"
    activate
    set searchTerm to inText
    set xNow to do JavaScript " 
var x,
z,
i;
x = '" & searchTerm & "';
if (x != null) {
     x = x.toLowerCase();
     z = document.links;    
     for (i = 0; i < z.length; ++i) {
            if ((z[i].innerHTML && z[i].innerHTML.toLowerCase().indexOf(x) != -1) || z[i].href.toLowerCase().indexOf(x) != -1) {      
          z[i].style.color = '#2e2e2e !important';
            sndT = 'http://tr.im/marklet?url=' + escape(z[i].href);
            popup_window = window.open(sndT);
            }
     }
}
" in document 1
  end tell
end run
Save your service, then go to Safari and find a link you want tr.im-ed. Control-click on that link, and you should see your new service at the bottom of the contextual menu.

[robg adds: I can't get this one to run properly on my machine, so I'm posting it in hopes that the community can figure out the issue -- it looks like it's working, but nothing actually seems to happen. In theory, this could be a very useful hint.]
    •    
  • Currently 2.23 / 5
  You rated: 3 / 5 (13 votes cast)
 
[10,060 views]  

10.6: Create a tri.im URL shortening Service | 19 comments | Create New Account
Click here to return to the '10.6: Create a tri.im URL shortening Service' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
10.6: Create a tri.im URL shortening Service
Authored by: Imaria on Sep 14, '09 07:46:07AM

There is a " trailing the final 'end run' command that shouldn't be there. Take that out, and it runs just fine.



[ Reply to This | # ]
10.6: Create a tri.im URL shortening Service
Authored by: GoboGobo on Sep 14, '09 11:22:40AM

I've done that, and the service now at least works and shows up when rightclicking a link. But it doesn't work at the tr.im end:

You can only tr.im URLs via the bookmarklet from other websites, while you are visiting them.

[ Reply to This | # ]
10.6: Create a tri.im URL shortening Service
Authored by: BlueSky on Sep 14, '09 02:37:59PM

It seems to get stuck in a loop generating new pages in Safari until I force quit.



[ Reply to This | # ]
10.6: Create a tri.im URL shortening Service
Authored by: BlueSky on Sep 14, '09 02:57:38PM

Further testing found that if I highlight the URL for the current page in the main menu and run the service it will spawn multiple popup windows but if I control click on a link within the page the service works correctly.

It would be nice if this worked when selecting the URL for the current page.



[ Reply to This | # ]
10.6: Create a tri.im URL shortening Service
Authored by: sittered on Sep 14, '09 08:02:26AM

Is it possible to repurpose this for Firefox? I know FF isn't similarly scriptable.



[ Reply to This | # ]
10.6: Create a tri.im URL shortening Service
Authored by: iandol on Sep 15, '09 03:01:52PM

See my post below, which uses Ruby and is thus browser agnostic (as well as much faster)...



[ Reply to This | # ]
10.6: Create a tri.im URL shortening Service
Authored by: Calpa on Sep 14, '09 09:14:33AM

Started experimenting with automator.. but can't seem to figure out how to remove user-created services. At system preferences I can un-check the box, but I'm unable to remove it.. where are they stored?



[ Reply to This | # ]
10.6: Create a tri.im URL shortening Service
Authored by: boxcarl on Sep 15, '09 01:26:53PM
~/Library/Services/

[ Reply to This | # ]
10.6: Create a tri.im URL shortening Service
Authored by: Anonymous on Sep 14, '09 09:35:11AM

a BRILLIANT hint! as the above says, remove the trailing " from the last line and it runs FINE!

in relation to the above poster wondering where services are stored, you'll find them at:

~/Library/Services/

hope that helps! x



[ Reply to This | # ]
10.6: Create a tri.im URL shortening Service
Authored by: DCJ001 on Sep 14, '09 04:12:25PM
This hint is good.

But I thought it easier to just download the tr.im widget at the below URL. It's pretty simple to use:

http://www.apple.com/downloads/dashboard/blogs_forums/trimit.html

[ Reply to This | # ]
10.6: Create a tri.im URL shortening Service
Authored by: iandol on Sep 15, '09 02:59:50PM
The Applescript is such a horrible hack and requires a specific browser to be open. Tr.im has an open API, and a much more elegant solution is to use Run Shell Script in Automator, set the shell to /usr/bin/ruby, then use this more elegant ruby code:

#!/usr/bin/env ruby
require 'uri'
require 'net/http'

uri = STDIN.gets(nil).strip.delete("\n\r")
unless uri.empty?
  begin
    escaped_uri = URI.escape("http://api.bit.ly/shorten?version=2.0.1&longUrl=#{uri}")
    STDOUT << Net::HTTP.get_response(URI.parse(escaped_uri)).body
  rescue URI::InvalidURIError
    # Do nothing.
  end
end
If you want to use tinyurl.com, then replace the escaped_uri line with this:

escaped_uri = URI.escape("http://tinyurl.com/api-create.php?url=#{uri}")


[ Reply to This | # ]
10.6: Create a tri.im URL shortening Service
Authored by: iandol on Sep 15, '09 03:06:12PM
Sorry, the escapred_url line in my main block of code should be:

escaped_uri = URI.escape("http://api.tr.im/v1/trim_simple?url=#{uri}")
The version posted only works with bit.ly which requires an API key to work.
p.s. wish we could edit our comments here...

[ Reply to This | # ]
10.6: Create a tri.im URL shortening Service
Authored by: elldove on Sep 18, '09 04:07:11PM

The ruby script is a simpler and more elegant solution than my hacky applescript, not to mention browser independent.

However, I was going for a service which can work with links, not just urls. The idea being that, for example, you're on the NYTimes front page and see an article you want to tr.im. With the ruby script you have to open the webpage first, then go the location bar, select the URL, right click and use the tr.im service.

With the applescript you can just right click on the link to the article and use the tr.im service.
Can ruby script work with ? That would be ideal...

Admittedly it does this in a hacky way, using javacript to compare every link's URL on in a page's source to every link's title until it finds the match. The real issue here is that Automator's service creation is limited to accepting as input text, urls, addresses, files, etc. But there's no way to input an html link and get the url out of that.

The limitation to Safari is unforunate, but Firefox and Chrome (being written in Carbon) can't work with any services, so the point is mute. I guess Camino users are out of luck. I will update the script to work with both NetNewsWire and Safari and post that.



[ Reply to This | # ]
10.6: Create a tri.im URL shortening Service
Authored by: elspub on Sep 19, '09 01:26:54PM
GrowlTr.imService.zip - 0.08MB

This should work much better. It uses a lot less javascript. It no longer requires Safari. It runs in the background and puts the tr.im on your clipboard, notifying you via Growl (if you have it) or an OS dialog (if you don't).

This will work with URLs (i.e. "http://...") in any cocoa application (services only work with cocoa. Sorry firefoxers). This will work with any link (i.e. 10.6: Create a tri.im URL shortening Service) in Safari and NetNewsWire.

To install you can follow the link at the top to download the necessary script/service.

Or:
open Automator, select create a service. Drag "Run Applescript" from the actions list into the workflow (delete the default text in the applescript box). Paste the code below into the applescript box. Make sure at the top of the workflow, it is set to receive text in any application. Save. Use.

property trmURL : ""
property shrt : ""
property MyApp : ""
property trmr : ""
property grlr : ""
on run {inText}
	tell application "System Events"
		set MyApp to name of the first process whose frontmost is true
		set processnames to name of every process
	end tell
	if "GrowlHelperApp" is in processnames then
		set grlr to "yes"
	end if
	if urlChk(inText) is true then
		if grlr is "yes" then
			set trmURL to "http://api.tr.im/api/trim_simple?url=" & inText
			triggerGrowl(shlScr(trmURL), "Successful Tr.im")
		else
			shlScr(trmURL)
			set trmr to (the clipboard as text)
			activate "kernel_task"
			display dialog "your tr.im:  " & trmr & " has already been set to your clipboard"
		end if
	else
		set intxt to change_case(inText, 0)
		set nCt to count characters of intxt
		if nCt is greater than 20 then
			set schTm to shortenTxt(intxt, nCt)
			set shrt to "yes"
		else
			set schTm to intxt
			set shrt to "no"
		end if
		if MyApp is "Safari" then
			set thisURL to lnkSrch(schTm)
		else if MyApp is "NetNewsWire" then
			set tbchk to "yes"
			tell application "NetNewsWire"
				activate
				if (index of selected tab is 0) then --IT'S A TAB!
					set tbchk to "no"
					set nnwURL to (URL of selectedHeadline)
					--display dialog nnwURL
					open URL in new tab with nnwURL
					repeat
						delay 2
						set rdy to do JavaScript "document.readyState"
						set tst to rdy as string
						if tst is "complete" then
							exit repeat
						end if
					end repeat
				end if
			end tell
			set thisURL to lnkSrch(schTm)
			if tbchk is "no" then
				if thisURL is null then
					tell application "NetNewsWire"
						set urlsList to URLs of tabs
						set ixCurrentTab to index of selected tab
						set thisURL to (item (ixCurrentTab + 1) of urlsList) as string
						--display dialog thisURL as string
						(* in case the headline sent you through a feed proxy we want to make sure that we have the actual URL of the article and not the proxy. *)
					end tell
				end if
				tell application "System Events" to key code 13 using {command down}
			end if
		end if
		if urlChk(thisURL) is true then
			if grlr is "yes" then
				set trmURL to "http://api.tr.im/api/trim_simple?url=" & thisURL
				triggerGrowl(shlScr(trmURL), "Successful Tr.im")
			else
				shlScr(trmURL)
				set trmr to (the clipboard as text)
				activate "kernel_task"
				display dialog "your tr.im:  " & trmr & " has already been set to your clipboard"
			end if
		else if urlChk(thisURL) is false then
			if grlr is "yes" then
				set trmURL to "This link didn't pan out. Sorry."
				triggerGrowl(trmURL, "Fail")
			else
				activate "kernel_task"
				display dialog "Failure. This link didn't pan out. Sorry."
			end if
			
			--display dialog trmURL
		end if
	end if
end run
on shlScr(yrl)
	do shell script "curl '" & yrl & "'  | pbcopy"
	set trmr to (the clipboard as text)
	set trmr to "The trimmed URL:   " & trmr & "  is on your clipboard"
	return trmr
end shlScr
on lnkSrch(searchTerm)
	--display dialog searchTerm
	if MyApp is "Safari" then
		tell application "Safari"
			activate
			set linknum to do JavaScript "document.links.length" in document 1
			set lnum to linknum - 1
			repeat with I from 0 to lnum
				set nextLink to do JavaScript "document.links[" & I & "].href" in document 1
				set nextIH to do JavaScript "decodeURI(document.links[" & I & "].innerHTML.toLowerCase())" in document 1
				set nextTtl to do JavaScript "decodeURI(document.links[" & I & "].title.toLowerCase())" in document 1
				
				if nextIH is equal to searchTerm then
					--display dialog nextIH & " index: " & I & "   " & nextLink & shrt
					set thisLink to nextLink
					exit repeat
				else if nextTtl is equal to searchTerm then
					set thisLink to nextLink
					exit repeat
				else if nextIH contains searchTerm and shrt is "yes" then
					set thisLink to nextLink
					exit repeat
				else if nextTtl contains searchTerm and shrt is "yes" then
					set thisLink to nextLink
					exit repeat
				else
					--display dialog "nopenope"
					set thisLink to null
				end if
			end repeat
		end tell
	else if MyApp is "NetNewsWire" then
		tell application "NetNewsWire"
			set linknum to do JavaScript "document.links.length"
			set lnum to linknum - 1
			--display dialog lnum
			repeat with I from 0 to lnum
				set nextLink to do JavaScript "document.links[" & I & "].href"
				set nextIH to do JavaScript "decodeURI(document.links[" & I & "].innerHTML.toLowerCase())"
				set nextTtl to do JavaScript "decodeURI(document.links[" & I & "].title.toLowerCase())"
				
				if nextIH is equal to searchTerm then
					--display dialog nextIH & " index: " & I & "   " & nextLink & shrt
					set thisLink to nextLink
					exit repeat
				else if nextTtl is equal to searchTerm then
					set thisLink to nextLink
					exit repeat
				else if nextIH contains searchTerm and shrt is "yes" then
					set thisLink to nextLink
					exit repeat
				else if nextTtl contains searchTerm and shrt is "yes" then
					set thisLink to nextLink
					exit repeat
				else
					--	display dialog "nopenope"
					set thisLink to null
					
				end if
			end repeat
		end tell
	end if
	return thisLink
end lnkSrch
on change_case(this_text, this_case)
	if this_case is 0 then
		set the comparison_string to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
		set the source_string to "abcdefghijklmnopqrstuvwxyz"
	else
		set the comparison_string to "abcdefghijklmnopqrstuvwxyz"
		set the source_string to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	end if
	set the new_text to ""
	repeat with this_char in this_text
		set x to the offset of this_char in the comparison_string
		if x is not 0 then
			set the new_text to (the new_text & character x of the source_string) as string
		else
			set the new_text to (the new_text & this_char) as string
		end if
	end repeat
	return the new_text
end change_case
on urlChk(inT)
	--display dialog inT as string
	set stStr to inT as string --I can't always tell when these kinds of methods are necessary in applescript.
	
	set urlc to characters 1 thru 4 of stStr as string
	if urlc is "http" then
		return true
	else
		return false
	end if
end urlChk
on shortenTxt(intxt, tCt)
	set m to 0.75 * tCt as integer
	set useths to characters 1 thru m of intxt as string
	return useths
end shortenTxt
on triggerGrowl(currentTitle, currentStatus)
	set app_title to "Grltr.im"
	tell application "GrowlHelperApp"
		set the allNotificationsList to {"Notification"}
		set the enabledNotificationsList to {"Notification"}
		register as application 
			app_title all notifications allNotificationsList 
			default notifications enabledNotificationsList 
			icon of application MyApp
		try
			notify with name "Notification" title currentStatus description currentTitle application name app_title
		on error the errorMessage
			notify with name "Error" title "Danger, Will Robinson" application name app_title
		end try
	end tell
end triggerGrowl



[ Reply to This | # ]
10.6: Create a tri.im URL shortening Service
Authored by: mvmaastricht on Mar 18, '10 12:38:25AM

It doesn't work for me (Mac OS 10.6.2, Dutch). I get a dialog with: "Where's NetNewsWire?"
After canceling (I don't have NetNewsWire) I there's nothing new in the clip board...



[ Reply to This | # ]
10.6: Create a tri.im URL shortening Service
Authored by: randyharris on Sep 22, '09 03:41:38PM

I tried the Ruby code, created a service with the Run Shell Script option in Automator with the line for using TinyURL, and I saved the service as TinyURL. Also, I have selected the "Replaces selected text" box up at the top of Automator.


It works! Awesome, I've sorely missed the TinyURL service from pre Snow Leopard.

One thing, how can I modify the Shell Script to not just replace the text, but also copy it into the clipboard? I like the replace feature, but also would like to be able to paste it for some applications.

Thanks



[ Reply to This | # ]
10.6: Create a tri.im URL shortening Service
Authored by: elspub on Sep 24, '09 07:29:06PM
Some bug fixes and script simplifying. These services just work. Highlight a URL in any application and select the service and the shortened URL will be put on your clipboard, and you'll be notified via Growl or the OS.
They don't require Safari or NNW, but in either app you can also use links as well as URLs to get shortened URLs.
The service for Tr.im
http://www.zshare.net/download/66083859e78bbba4/
Tr.imIt.zip - 0.11MB

and a version for Adjix
http://www.zshare.net/download/66083838d1f0db40/
adjixIt.zip - 0.08MB

[ Reply to This | # ]
10.6: Create a tri.im URL shortening Service
Authored by: mvmaastricht on Mar 18, '10 12:19:35AM

Those links do not work anymore. Could you please post the services again?

Thanks!



[ Reply to This | # ]
10.6: Create a tri.im URL shortening Service
Authored by: floz on Feb 10, '11 06:03:22AM
My first contribution, yay :-)

Here's the AppleScript need for using this hint with Google's URL Shortener service, goo.gl:

on run {input, parameters}
	set shorturl to do shell script "/usr/bin/curl -s -d'&url=" & input & "' http://goo.gl/api/url | sed -e 's/{\"short_url\":\"//' -e 's/\",\"added_to_history\":false}/\\n/'"
	return shorturl
end run


[ Reply to This | # ]