mcbot/cmds/shortenurl.lua
author Mikael Berthe <mikael@lilotux.net>
Tue, 27 Nov 2012 16:26:04 +0100
changeset 66 d9c00a9fe9d5
parent 65 2cefbe9f3ac6
permissions -rw-r--r--
Add notices before public release


--  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>
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or (at
-- your option) any later version.
--
-- Please check the license in the COPYING file at the root of the tree.
--


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: --