cddb.lua 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. local socket = require("socket")
  2. local http = require("socket.http")
  3. if not arg or not arg[1] or not arg[2] then
  4. print("luasocket cddb.lua <category> <disc-id> [<server>]")
  5. os.exit(1)
  6. end
  7. local server = arg[3] or "http://freedb.freedb.org/~cddb/cddb.cgi"
  8. function parse(body)
  9. local lines = string.gfind(body, "(.-)\r\n")
  10. local status = lines()
  11. local code, message = socket.skip(2, 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 = socket.skip(2, 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. local host = socket.dns.gethostname()
  29. local query = "%s?cmd=cddb+read+%s+%s&hello=LuaSocket+%s+LuaSocket+2.0&proto=6"
  30. local url = string.format(query, server, arg[1], arg[2], host)
  31. local body, headers, code = http.request(url)
  32. if code == 200 then
  33. local data, code, error = parse(body)
  34. if not data then
  35. print(error or code)
  36. else
  37. for i,v in pairs(data) do
  38. io.write(i, ': ', v, '\n')
  39. end
  40. end
  41. else print(error) end