diff options
Diffstat (limited to 'samples')
-rw-r--r-- | samples/cddb.lua | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/samples/cddb.lua b/samples/cddb.lua new file mode 100644 index 0000000..6ade3c0 --- /dev/null +++ b/samples/cddb.lua | |||
@@ -0,0 +1,43 @@ | |||
1 | if not arg or not arg[1] or not arg[2] then | ||
2 | print("luasocket cddb.lua <category> <disc-id> [<server>]") | ||
3 | os.exit(1) | ||
4 | end | ||
5 | |||
6 | local server = arg[3] or "http://freedb.freedb.org/~cddb/cddb.cgi" | ||
7 | |||
8 | function parse(body) | ||
9 | local lines = string.gfind(body, "(.-)\r\n") | ||
10 | local status = lines() | ||
11 | local _, _, code, message = string.find(status, "(%d%d%d) (.*)") | ||
12 | if tonumber(code) ~= 210 then | ||
13 | return nil, code, message | ||
14 | end | ||
15 | local data = {} | ||
16 | for l in lines do | ||
17 | local c = string.sub(l, 1, 1) | ||
18 | if c ~= '#' and c ~= '.' then | ||
19 | local _, _, key, value = string.find(l, "(.-)=(.*)") | ||
20 | value = string.gsub(value, "\\n", "\n") | ||
21 | value = string.gsub(value, "\\\\", "\\") | ||
22 | value = string.gsub(value, "\\t", "\t") | ||
23 | data[key] = value | ||
24 | end | ||
25 | end | ||
26 | return data, code, message | ||
27 | end | ||
28 | |||
29 | local host = socket.dns.gethostname() | ||
30 | local query = "%s?cmd=cddb+read+%s+%s&hello=LuaSocket+%s+LuaSocket+2.0&proto=6" | ||
31 | local url = string.format(query, server, arg[1], arg[2], host) | ||
32 | local body, headers, code, error = socket.http.get(url) | ||
33 | |||
34 | if code == 200 then | ||
35 | local data, code, error = parse(body) | ||
36 | if not data then | ||
37 | print(error or code) | ||
38 | else | ||
39 | for i,v in data do | ||
40 | io.write(i, ': ', v, '\n') | ||
41 | end | ||
42 | end | ||
43 | else print(error) end | ||