import_directory.lua 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. local lxp = require "lxp";
  2. lxp.lom = require "lxp.lom";
  3. local dbi = require "DBI";
  4. local dbh = assert(dbi.Connect("PostgreSQL", "xmppoke", "xmppoke", "xmppoke", "localhost", 5432));
  5. local stm = assert(dbh:prepare("SET TIMEZONE = 'UTC';"));
  6. assert(stm:execute());
  7. stm = assert(dbh:prepare("DELETE FROM public_servers;"));
  8. assert(stm:execute());
  9. for _,file in ipairs(arg) do
  10. local f = io.open(file, "r");
  11. print(file);
  12. local vcard = lxp.lom.parse(f:read("*a"));
  13. assert(vcard["tag"] == "vcard");
  14. local function get_child(t, nm)
  15. for k,v in ipairs(t) do
  16. if v.tag == nm then
  17. return v;
  18. end
  19. end
  20. end
  21. local function get_text(t)
  22. local result = "";
  23. for k,v in ipairs(t) do
  24. if type(v) == "string" then
  25. result = result .. v;
  26. end
  27. end
  28. return result;
  29. end
  30. local function render_attributes(t)
  31. local result = "";
  32. print(type(t), t);
  33. for k,v in ipairs(t.attr) do
  34. result = " " .. v .. "='" .. t.attr[v] .. "'"
  35. end
  36. return result;
  37. end
  38. local function render(t)
  39. if type(t) == "string" then
  40. return t;
  41. end
  42. local result = "<" .. t.tag .. render_attributes(t) .. ">"
  43. for k, v in ipairs(t) do
  44. result = result .. render(v);
  45. end
  46. return result .. "</" .. t.tag .. ">"
  47. end
  48. local fn = get_child(vcard, "fn");
  49. local name = get_child(fn, "text");
  50. local bday = get_child(vcard, "bday");
  51. local date = get_child(bday, "date");
  52. local adr = get_child(vcard, "adr");
  53. local country = get_child(adr, "country");
  54. local url = get_child(vcard, "url");
  55. local uri = get_child(url, "uri");
  56. local note = get_child(vcard, "note");
  57. local text = note and get_child(note, "text");
  58. local impp = get_child(vcard, "impp");
  59. local impp_uri = impp and get_child(impp, "uri");
  60. local vcard_rest = "";
  61. for k, v in ipairs(vcard) do
  62. if not (v.tag == "fn" or v.tag == "bday" or v.tag == "adr" or v.tag == "url" or v.tag == "note" or v.tag == "impp" or v.tag == "name" or v.tag == "ca") then
  63. vcard_rest = vcard_rest .. render(v)
  64. end
  65. end
  66. local stm = assert(dbh:prepare("INSERT INTO public_servers (server_name, founded, country, url, description, admin, vcard_rest) VALUES (?, ?, ?, ?, ?, ?, ?);"));
  67. assert(stm:execute(get_text(name), get_text(date), get_text(country), get_text(uri), text and get_text(text) or nil, impp_uri and get_text(impp_uri), vcard_rest));
  68. end
  69. dbh:commit();
  70. dbh:close();