Fetch articles w/ Safari Reader

I use Instapaper and Laterstars to quickly collect links from around the web. They work well for collecting, but their RSS feeds don’t have any content, so I have to open up the URL in a browser to see the full page. I wrote this script to go through my RSS feeds, open the pages in Safari, use the reader function, and clip them to DT. After running it, I have the full contents of every page I’ve saved for later, nicely formatted using Safari Reader.

The script that you see here looks for particular groups, but you could use DT’s current selection instead.

set feeds_database to "feeds"
set feed_groups to {"Instapaper", "Laterstars", "Starred on Google Reader"}
-- set feed_groups to {"unread"}

on load_page(theURL)
	tell application "Safari"
		activate
		make new document at end of documents
		set URL of document 1 to theURL
	end tell
end load_page

on import_using_reader()
	delay 2
	tell application "Safari" to activate
	tell application "System Events"
		keystroke "r" using {command down, shift down}
		delay 2
		keystroke "a" using command down
		delay 2
		keystroke ")" using {command down}
		delay 2
	end tell
	tell application "Safari" to close document 1
end import_using_reader

on page_loaded(timeout_value)
	delay 2
	repeat with i from 1 to the timeout_value
		tell application "Safari"
			if (do JavaScript "document.readyState" in document 1) is "complete" then
				return true
			else if i is the timeout_value then
				return false
			else
				delay 1
			end if
		end tell
	end repeat
	return false
end page_loaded

try
	tell application "DEVONthink Pro"
		set this_selection to {}
		repeat with feed_name in feed_groups
			set current_feed to get record at feed_name in feeds_database
			repeat with feed_item in children of current_feed
				if unread of feed_item then set end of this_selection to feed_item
			end repeat
		end repeat
		-- set this_selection to the selection
		--		if this_selection is {} then error "Please select some contents."
		
	end tell
	
	tell application "DEVONthink Pro"
		repeat with this_record in this_selection
			set theURL to URL of this_record
			my load_page(theURL)
			if my page_loaded(10) then
				set unread of this_record to false
				my import_using_reader()
				delay 1
			end if
		end repeat
	end tell
	
on error error_message number error_number
	if the error_number is not -128 then
		try
			display alert "DEVONthink Pro" message error_message as warning
		on error number error_number
			if error_number is -1708 then display dialog error_message buttons {"OK"} default button 1
		end try
	end if
end try