examples/shortenurl.lua
author Myhailo Danylenko <isbear@ukrpost.net>
Wed, 28 Nov 2012 20:17:53 +0200
changeset 146 04d19c9c1196
parent 141 1e36a08d7734
permissions -rw-r--r--
Fix module loading problem


--  SHORTENURL

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

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 )

		local url  = args[1]
		local post = main.yesno ( main.option ( 'lua_shorten_post_url' ) )
		if not url then -- ugly. need to redesign argument parsing
			if args.s then
				url  = args.s
				post = true
			elseif args.n then
				url  = args.n
				post = false
			end
		end

		if ( not url ) or ( not url: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 = url }, 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 post then
							main.run ( ('say_to -q %s %s'):format ( jid, reply.id ) )
						else
							print ( ('Full:  %s\n           Short: %s'):format ( url, 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, true )

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