[examples] Add shortener -s and -n flags
authorMyhailo Danylenko <isbear@ukrpost.net>
Tue, 23 Oct 2012 13:15:37 +0300
changeset 141 1e36a08d7734
parent 140 89841bd3db8c
child 142 7e8f523b66af
[examples] Add shortener -s and -n flags
examples/shortenurl.lua
--- a/examples/shortenurl.lua	Sun Oct 14 20:13:52 2012 +0300
+++ b/examples/shortenurl.lua	Tue Oct 23 13:15:37 2012 +0300
@@ -7,11 +7,11 @@
 --  * 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
---  * -s switch to send url automatically
 
 local json = require 'json'
 
@@ -26,7 +26,19 @@
 main.command ( 'shorten',
 	function ( args )
 
-		if ( not args ) or not args:match ( '%w' ) then
+		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
@@ -41,7 +53,7 @@
 
 		local replystring = ''
 		
-		main.bgread ( ( curlcommand ):format ( querystring, shell_escape ( json.encode ( { longUrl = args }, encodeoptions ) ) ),
+		main.bgread ( ( curlcommand ):format ( querystring, shell_escape ( json.encode ( { longUrl = url }, encodeoptions ) ) ),
 			function ( data )
 				if data then
 					replystring = replystring .. data
@@ -49,10 +61,10 @@
 				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
+						if jid and post then
 							main.run ( ('say_to -q %s %s'):format ( jid, reply.id ) )
 						else
-							print ( ('Shortened url: %s'):format ( reply.id ) )
+							print ( ('Full:  %s\n           Short: %s'):format ( url, reply.id ) )
 						end
 					else
 						if type ( reply ) == 'table' and ( type ( reply.error ) == 'table' ) then
@@ -65,6 +77,6 @@
 				end
 			end )
 
-	end )
+	end, true )
 
 -- vim: se ts=4 sw=4: --