Support for goo.gl api key
authorMyhailo Danylenko <isbear@ukrpost.net>
Tue, 07 Aug 2012 20:58:31 +0300
changeset 127 9157566033e8
parent 126 5f0025da31e6
child 128 8692a6fbe415
Support for goo.gl api key * option lua_shorten_googl_key * better error parsing
examples/lua.rc
examples/shortenurl.lua
--- a/examples/lua.rc	Tue Aug 07 02:46:54 2012 +0300
+++ b/examples/lua.rc	Tue Aug 07 20:58:31 2012 +0300
@@ -32,5 +32,9 @@
 # automatically send shortened urls to current user
 set lua_shorten_post_url = 1
 
+# set this to google api key, if you need it
+# see https://developers.google.com/url-shortener/v1/getting_started#APIKey
+#set lua_shorten_googl_key = XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXX
+
 module load lua
 
--- a/examples/shortenurl.lua	Tue Aug 07 02:46:54 2012 +0300
+++ b/examples/shortenurl.lua	Tue Aug 07 20:58:31 2012 +0300
@@ -21,7 +21,7 @@
 	}
 }
 
-local curlcommand = "curl -s https://www.googleapis.com/urlshortener/v1/url -H 'Content-type: application/json' -d %s"
+local curlcommand = "curl -s https://www.googleapis.com/urlshortener/v1/url%s -H 'Content-type: application/json' -d %s"
 
 main.command ( 'shorten',
 	function ( args )
@@ -31,12 +31,22 @@
 			return
 		end
 
-		local jid = main.current_buddy ()
+		local jid         = main.current_buddy ()
+
+		local querystring = ''
+		local key         = main.option ( 'lua_shorten_googl_key' )
+		if key and key:match ( '%w' ) then
+			querystring   = '?key=' .. key
+		end
+
 		local replystring = ''
-		main.bgread ( ( curlcommand ):format ( shell_escape ( json.encode ( { longUrl = args }, encodeoptions ) ) ),
+		
+		main.bgread ( ( curlcommand ):format ( querystring, shell_escape ( json.encode ( { longUrl = args }, encodeoptions ) ) ),
 			function ( data )
-				if not data then
-					-- eof
+				if data then
+					replystring = replystring .. data
+					return true
+				else -- eof
 					local reply = json.decode ( replystring )
 					if reply and reply.id then
 						if jid and main.yesno ( main.option ( 'lua_shorten_post_url' ) ) then
@@ -45,13 +55,13 @@
 							print ( ('Shortened url: %s'):format ( reply.id ) )
 						end
 					else
-						-- XXX extract message from json?
-						print ( ('Failed to shorten url: %s'):format ( replystring ) )
+						if type ( reply.error ) == 'table' then
+							print ( ('Failed to shorten url: %u %s'):format ( reply.error.code, reply.error.message ) )
+						else
+							print ( ('Failed to shorten url: Unknown response:\n%s'):format ( replystring ) )
+						end
 					end
 					return false
-				else
-					replystring = replystring .. data
-					return true
 				end
 			end )