examples/shortenurl.lua
author Myhailo Danylenko <isbear@ukrpost.net>
Fri, 12 Oct 2012 21:24:44 +0300
changeset 136 2b04fad2f61a
parent 127 9157566033e8
child 141 1e36a08d7734
permissions -rw-r--r--
[examples] Fix non-table response handling in shortener Reported by Mikael Berthe


--  SHORTENURL

-- uses:
--  * goo.gl (online service)
--  * curl (program)
--  * lua-json (https://github.com/harningt/luajson/)
--  * shell_escape (mcabberrc.lua)
--  * option lua_shorten_post_url
-- TODO:
--  * other backends
--  * detect curl/wget
--  * ensure curl will not mess screen up
--  * -s switch to send url automatically

local json = require 'json'

local encodeoptions = {
	strings = {
		encodeSet = '\\"%z\1-\031', -- do not escape /, google does not understand that
	}
}

local curlcommand = "curl -s https://www.googleapis.com/urlshortener/v1/url%s -H 'Content-type: application/json' -d %s"

main.command ( 'shorten',
	function ( args )

		if ( not args ) or not args:match ( '%w' ) then
			print ( 'shorten: You must specify url' )
			return
		end

		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 ( querystring, shell_escape ( json.encode ( { longUrl = args }, encodeoptions ) ) ),
			function ( data )
				if data then
					replystring = replystring .. data
					return true
				else -- eof
					local reply = json.decode ( replystring )
					if ( type ( reply ) == 'table' ) and reply.id then
						if jid and main.yesno ( main.option ( 'lua_shorten_post_url' ) ) then
							main.run ( ('say_to -q %s %s'):format ( jid, reply.id ) )
						else
							print ( ('Shortened url: %s'):format ( reply.id ) )
						end
					else
						if type ( reply ) == 'table' and ( 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
				end
			end )

	end )

-- vim: se ts=4 sw=4: --