|
1 |
|
2 -- This module is derivated from isbear's shortenurl function: |
|
3 -- http://hg.lilotux.net/mod-mcabber-lua/file/tip/examples/shortenurl.lua |
|
4 -- |
|
5 -- * Copyright (C) 2012 Myhailo Danylenko <isbear@ukrpost.net> |
|
6 -- * Copyright (C) 2012 Mikael Berthe <mikael@lilotux.net> |
|
7 -- |
|
8 |
|
9 require "libs.shcmd" |
|
10 |
|
11 local json = require 'json' |
|
12 |
|
13 local shortenurl = { ["desc"] = "URL shortener", |
|
14 } |
|
15 |
|
16 local encodeoptions = { |
|
17 strings = { |
|
18 encodeSet = '\\"%z\1-\031', -- do not escape /, google does not understand that |
|
19 } |
|
20 } |
|
21 |
|
22 local shell_escape = function (str) |
|
23 if str then |
|
24 return "'" .. str:gsub("'", "'\\''") .. "'" |
|
25 else |
|
26 return "''" |
|
27 end |
|
28 end |
|
29 |
|
30 local curlcommand = "curl -s https://www.googleapis.com/urlshortener/v1/url -H 'Content-type: application/json' -d %s" |
|
31 |
|
32 function shortenurl.cmd (url) |
|
33 |
|
34 if ( not url ) or ( not url:match ( '%w' ) ) then |
|
35 return nil, 'You must specify an URL' |
|
36 end |
|
37 |
|
38 local replystring = '' |
|
39 |
|
40 local targeturl = json.encode( { longUrl = url }, encodeoptions ) |
|
41 local data = shcmd(curlcommand:format(shell_escape(targeturl))) |
|
42 if data then |
|
43 local reply = json.decode ( data ) |
|
44 if ( type ( reply ) == 'table' ) and reply.id then |
|
45 return ('Full: %s\nShort: %s'):format(url, reply.id) |
|
46 else |
|
47 local errmsg |
|
48 if type ( reply ) == 'table' and ( type ( reply.error ) == 'table' ) then |
|
49 errmsg = ('Failed to shorten url: %u %s'):format(reply.error.code, |
|
50 reply.error.message) |
|
51 else |
|
52 errmsg = ('Failed to shorten url: Unknown response:\n%s'):format(replystring) |
|
53 end |
|
54 return nil, errmsg |
|
55 end |
|
56 return nil, "Got no data :-(" |
|
57 end |
|
58 end |
|
59 |
|
60 mcbot_register_command("shortenurl", shortenurl) |
|
61 |
|
62 -- vim: se ts=4 sw=4: -- |