Add shortenurl module, based on isbear's code
This code is derivated from the lua example script shortenurl.lua in
isbear's lua module for mcabber.
-- This module is derivated from isbear's shortenurl function:
-- http://hg.lilotux.net/mod-mcabber-lua/file/tip/examples/shortenurl.lua
--
-- * Copyright (C) 2012 Myhailo Danylenko <isbear@ukrpost.net>
-- * Copyright (C) 2012 Mikael Berthe <mikael@lilotux.net>
--
require "libs.shcmd"
local json = require 'json'
local shortenurl = { ["desc"] = "URL shortener",
}
local encodeoptions = {
strings = {
encodeSet = '\\"%z\1-\031', -- do not escape /, google does not understand that
}
}
local shell_escape = function (str)
if str then
return "'" .. str:gsub("'", "'\\''") .. "'"
else
return "''"
end
end
local curlcommand = "curl -s https://www.googleapis.com/urlshortener/v1/url -H 'Content-type: application/json' -d %s"
function shortenurl.cmd (url)
if ( not url ) or ( not url:match ( '%w' ) ) then
return nil, 'You must specify an URL'
end
local replystring = ''
local targeturl = json.encode( { longUrl = url }, encodeoptions )
local data = shcmd(curlcommand:format(shell_escape(targeturl)))
if data then
local reply = json.decode ( data )
if ( type ( reply ) == 'table' ) and reply.id then
return ('Full: %s\nShort: %s'):format(url, reply.id)
else
local errmsg
if type ( reply ) == 'table' and ( type ( reply.error ) == 'table' ) then
errmsg = ('Failed to shorten url: %u %s'):format(reply.error.code,
reply.error.message)
else
errmsg = ('Failed to shorten url: Unknown response:\n%s'):format(replystring)
end
return nil, errmsg
end
return nil, "Got no data :-("
end
end
mcbot_register_command("shortenurl", shortenurl)
-- vim: se ts=4 sw=4: --