Save to Instapaper from NetNewsWire

February 9th, 2009  |  Published in ruby  |  1 Comment

At some point some applescripts I found for posting from NetNewsWire to Instapaper broke. A few days ago, during one of my rare jaunts to the bottom of the Instapaper homepage I came across a reference to the Read Later API. I wrote it down on my todo list as a thing to deal with over lunch some day.

The API involves nothing more than an HTTP request with a half-dozen parameters, a few of which are optional. I stopped shy of simulating the wonderful Instapaper response popup, settling instead on a system beep:

   #!/usr/bin/env ruby
   require 'rubygems'
   require 'open-uri'
   require 'openssl'
   require 'appscript'
   include Appscript
   require 'osax'
   include OSAX

   username = "USERNAME"
   password = "PASSWORD"
   nnw = app("NetNewsWire")

   OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE

   item = nnw.selectedHeadline.get
   url = URI.encode(item.URL.get).gsub!(/^htt.+?\/\//, "")
   title = item.title.get
   description = item.description.get.gsub!(/<.+?>/, "") 

   selection = description.length > 150 ? description.slice(0,150) + " ..." : description

   base_url = "https://www.instapaper.com/api/add?"
   params = "title=#{title}&url=#{url}&username=#{username}&password=#{password}&selection=#{selection}"
   post_url = "#{base_url}#{params}"


   begin
     response = open(URI.encode(post_url))
     osax.beep
     # or display a dialog:
     # osax.display_dialog("Posted.")
     rescue => ex
       case ex.message.gsub(/\s.*/, "")
         when "400" : message = "Error: Bad Request."
         when "403" : message = "Bad password/username."
         when "500" : message = "Server error."
       end
       osax.display_dialog(message)
   end

© Michael Hall, licensed under a Creative Commons Attribution-ShareAlike 3.0 United States license.