comparison samples/cddb.lua @ 0:4b915342e2a8

LuaSocket 2.0.2 + CMake build description.
author Eric Wing <ewing . public |-at-| gmail . com>
date Tue, 26 Aug 2008 18:40:01 -0700
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4b915342e2a8
1 local socket = require("socket")
2 local http = require("socket.http")
3
4 if not arg or not arg[1] or not arg[2] then
5 print("luasocket cddb.lua <category> <disc-id> [<server>]")
6 os.exit(1)
7 end
8
9 local server = arg[3] or "http://freedb.freedb.org/~cddb/cddb.cgi"
10
11 function parse(body)
12 local lines = string.gfind(body, "(.-)\r\n")
13 local status = lines()
14 local code, message = socket.skip(2, string.find(status, "(%d%d%d) (.*)"))
15 if tonumber(code) ~= 210 then
16 return nil, code, message
17 end
18 local data = {}
19 for l in lines do
20 local c = string.sub(l, 1, 1)
21 if c ~= '#' and c ~= '.' then
22 local key, value = socket.skip(2, string.find(l, "(.-)=(.*)"))
23 value = string.gsub(value, "\\n", "\n")
24 value = string.gsub(value, "\\\\", "\\")
25 value = string.gsub(value, "\\t", "\t")
26 data[key] = value
27 end
28 end
29 return data, code, message
30 end
31
32 local host = socket.dns.gethostname()
33 local query = "%s?cmd=cddb+read+%s+%s&hello=LuaSocket+%s+LuaSocket+2.0&proto=6"
34 local url = string.format(query, server, arg[1], arg[2], host)
35 local body, headers, code = http.get(url)
36
37 if code == 200 then
38 local data, code, error = parse(body)
39 if not data then
40 print(error or code)
41 else
42 for i,v in pairs(data) do
43 io.write(i, ': ', v, '\n')
44 end
45 end
46 else print(error) end