examples/shortenurl.lua
changeset 125 3e2421384d7a
child 126 5f0025da31e6
equal deleted inserted replaced
124:286a034e4d5f 125:3e2421384d7a
       
     1 
       
     2 --  SHORTENURL
       
     3 
       
     4 -- uses:
       
     5 --  * goo.gl (online service)
       
     6 --  * curl (program)
       
     7 --  * lua-json (https://github.com/harningt/luajson/)
       
     8 --  * shell_escape (mcabberrc.lua)
       
     9 --  * option lua_shorten_post_url
       
    10 -- TODO:
       
    11 --  * other backends
       
    12 --  * detect curl/wget
       
    13 --  * ensure curl will not mess screen up
       
    14 --  * -s switch to send url automatically
       
    15 
       
    16 local json = require 'json'
       
    17 
       
    18 local encodeoptions = {
       
    19 	strings = {
       
    20 		encodeSet = '\\"%z\1-\031', -- do not escape /, google does not understand that
       
    21 	}
       
    22 }
       
    23 
       
    24 local curlcommand = "curl -s https://www.googleapis.com/urlshortener/v1/url -H 'Content-type: application/json' -d %s"
       
    25 
       
    26 main.command ( 'shorten',
       
    27 	function ( args )
       
    28 
       
    29 		if ( not args ) or not args:match ( '%w' ) then
       
    30 			print ( 'shorten: You must specify url' )
       
    31 			return
       
    32 		end
       
    33 
       
    34 		local jid = main.current_buddy ()
       
    35 		local replystring = ''
       
    36 		main.bgread ( ( curlcommand ):format ( shell_escape ( json.encode ( { longUrl = args }, encodeoptions ) ) ),
       
    37 			function ( data )
       
    38 				if not data then
       
    39 					-- eof
       
    40 					print ( 'lua reply: ' .. replystring )
       
    41 					local reply = json.decode ( replystring )
       
    42 					if reply and reply.id then
       
    43 						if jid and main.yesno ( main.option ( 'lua_shorten_post_url' ) ) then
       
    44 							main.run ( ('say_to -q %s %s'):format ( jid, reply.id ) )
       
    45 						else
       
    46 							print ( ('Shortened url: %s'):format ( reply.id ) )
       
    47 						end
       
    48 					else
       
    49 						-- XXX extract message from json?
       
    50 						print ( ('Failed to shorten url: %s'):format ( replystring ) )
       
    51 					end
       
    52 					return false
       
    53 				else
       
    54 					replystring = replystring .. data
       
    55 					return true
       
    56 				end
       
    57 			end )
       
    58 
       
    59 	end )
       
    60 
       
    61 -- vim: se ts=4 sw=4: --