beta-0.89.2
[luatex.git] / source / texk / web2c / luatexdir / luasocket / samples / cddb.lua
blob49a187119f8a8e85b01cc7de7ba5e305a8518c37
1 local socket = require("socket")
2 local http = require("socket.http")
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
9 local server = arg[3] or "http://freedb.freedb.org/~cddb/cddb.cgi"
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
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.request(url)
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