mcbot/cmds/shortenurl.lua
changeset 64 62248d5fbb24
child 65 2cefbe9f3ac6
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mcbot/cmds/shortenurl.lua	Sun Nov 25 19:01:31 2012 +0100
@@ -0,0 +1,62 @@
+
+-- 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: --