mod_admin_telnet: Add server:memory() command to view details of Prosody's memory...
[prosody.git] / tools / ejabberdsql2prosody.lua
1 #!/usr/bin/env lua
2 -- Prosody IM
3 -- Copyright (C) 2008-2010 Matthew Wild
4 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- 
6 -- This project is MIT/X11 licensed. Please see the
7 -- COPYING file in the source package for more information.
8 --
9
10 prosody = {};
11
12 package.path = package.path ..";../?.lua";
13 local serialize = require "util.serialization".serialize;
14 local st = require "util.stanza";
15 local parse_xml = require "util.xml".parse;
16 package.loaded["util.logger"] = {init = function() return function() end; end}
17 local dm = require "util.datamanager"
18 dm.set_data_path("data");
19
20 function parseFile(filename)
21 ------
22
23 local file = nil;
24 local last = nil;
25 local line = 1;
26 local function read(expected)
27         local ch;
28         if last then
29                 ch = last; last = nil;
30         else
31                 ch = file:read(1);
32                 if ch == "\n" then line = line + 1; end
33         end
34         if expected and ch ~= expected then error("expected: "..expected.."; got: "..(ch or "nil").." on line "..line); end
35         return ch;
36 end
37 local function pushback(ch)
38         if last then error(); end
39         last = ch;
40 end
41 local function peek()
42         if not last then last = read(); end
43         return last;
44 end
45
46 local escapes = {
47         ["\\0"] = "\0";
48         ["\\'"] = "'";
49         ["\\\""] = "\"";
50         ["\\b"] = "\b";
51         ["\\n"] = "\n";
52         ["\\r"] = "\r";
53         ["\\t"] = "\t";
54         ["\\Z"] = "\26";
55         ["\\\\"] = "\\";
56         ["\\%"] = "%";
57         ["\\_"] = "_";
58 }
59 local function unescape(s)
60         return escapes[s] or error("Unknown escape sequence: "..s);
61 end
62 local function readString()
63         read("'");
64         local s = "";
65         while true do
66                 local ch = peek();
67                 if ch == "\\" then
68                         s = s..unescape(read()..read());
69                 elseif ch == "'" then
70                         break;
71                 else
72                         s = s..read();
73                 end
74         end
75         read("'");
76         return s;
77 end
78 local function readNonString()
79         local s = "";
80         while true do
81                 if peek() == "," or peek() == ")" then
82                         break;
83                 else
84                         s = s..read();
85                 end
86         end
87         return tonumber(s);
88 end
89 local function readItem()
90         if peek() == "'" then
91                 return readString();
92         else
93                 return readNonString();
94         end
95 end
96 local function readTuple()
97         local items = {}
98         read("(");
99         while peek() ~= ")" do
100                 table.insert(items, readItem());
101                 if peek() == ")" then break; end
102                 read(",");
103         end
104         read(")");
105         return items;
106 end
107 local function readTuples()
108         if peek() ~= "(" then read("("); end
109         local tuples = {};
110         while true do
111                 table.insert(tuples, readTuple());
112                 if peek() == "," then read() end
113                 if peek() == ";" then break; end
114         end
115         return tuples;
116 end
117 local function readTableName()
118         local tname = "";
119         while peek() ~= "`" do tname = tname..read(); end
120         return tname;
121 end
122 local function readInsert()
123         if peek() == nil then return nil; end
124         for ch in ("INSERT INTO `"):gmatch(".") do -- find line starting with this
125                 if peek() == ch then
126                         read(); -- found
127                 else -- match failed, skip line
128                         while peek() and read() ~= "\n" do end
129                         return nil;
130                 end
131         end
132         local tname = readTableName();
133         read("`"); read(" ") -- expect this
134         if peek() == "(" then -- skip column list
135                 repeat until read() == ")";
136                 read(" ");
137         end
138         for ch in ("VALUES "):gmatch(".") do read(ch); end -- expect this
139         local tuples = readTuples();
140         read(";"); read("\n");
141         return tname, tuples;
142 end
143
144 local function readFile(filename)
145         file = io.open(filename);
146         if not file then error("File not found: "..filename); os.exit(0); end
147         local t = {};
148         while true do
149                 local tname, tuples = readInsert();
150                 if tname then
151                         if t[tname] then
152                                 local t_name = t[tname];
153                                 for i=1,#tuples do
154                                         table.insert(t_name, tuples[i]);
155                                 end
156                         else
157                                 t[tname] = tuples;
158                         end
159                 elseif peek() == nil then
160                         break;
161                 end
162         end
163         return t;
164 end
165
166 return readFile(filename);
167
168 ------
169 end
170
171 local arg, host = ...;
172 local help = "/? -? ? /h -h /help -help --help";
173 if not(arg and host) or help:find(arg, 1, true) then
174         print([[ejabberd SQL DB dump importer for Prosody
175
176   Usage: ejabberdsql2prosody.lua filename.txt hostname
177
178 The file can be generated using mysqldump:
179   mysqldump db_name > filename.txt]]);
180         os.exit(1);
181 end
182 local map = {
183         ["last"] = {"username", "seconds", "state"};
184         ["privacy_default_list"] = {"username", "name"};
185         ["privacy_list"] = {"username", "name", "id"};
186         ["privacy_list_data"] = {"id", "t", "value", "action", "ord", "match_all", "match_iq", "match_message", "match_presence_in", "match_presence_out"};
187         ["private_storage"] = {"username", "namespace", "data"};
188         ["rostergroups"] = {"username", "jid", "grp"};
189         ["rosterusers"] = {"username", "jid", "nick", "subscription", "ask", "askmessage", "server", "subscribe", "type"};
190         ["spool"] = {"username", "xml", "seq"};
191         ["users"] = {"username", "password"};
192         ["vcard"] = {"username", "vcard"};
193         --["vcard_search"] = {};
194 }
195 local NULL = {};
196 local t = parseFile(arg);
197 for name, data in pairs(t) do
198         local m = map[name];
199         if m then
200                 if #data > 0 and #data[1] ~= #m then
201                         print("[warning] expected "..#m.." columns for table `"..name.."`, found "..#data[1]);
202                 end
203                 for i=1,#data do
204                         local row = data[i];
205                         for j=1,#m do
206                                 row[m[j]] = row[j];
207                                 row[j] = nil;
208                         end
209                 end
210         end
211 end
212 --print(serialize(t));
213
214 for i, row in ipairs(t["users"] or NULL) do
215         local node, password = row.username, row.password;
216         local ret, err = dm.store(node, host, "accounts", {password = password});
217         print("["..(err or "success").."] accounts: "..node.."@"..host);
218 end
219
220 function roster(node, host, jid, item)
221         local roster = dm.load(node, host, "roster") or {};
222         roster[jid] = item;
223         local ret, err = dm.store(node, host, "roster", roster);
224         print("["..(err or "success").."] roster: " ..node.."@"..host.." - "..jid);
225 end
226 function roster_pending(node, host, jid)
227         local roster = dm.load(node, host, "roster") or {};
228         roster.pending = roster.pending or {};
229         roster.pending[jid] = true;
230         local ret, err = dm.store(node, host, "roster", roster);
231         print("["..(err or "success").."] roster-pending: " ..node.."@"..host.." - "..jid);
232 end
233 function roster_group(node, host, jid, group)
234         local roster = dm.load(node, host, "roster") or {};
235         local item = roster[jid];
236         if not item then print("Warning: No roster item "..jid.." for user "..node..", can't put in group "..group); return; end
237         item.groups[group] = true;
238         local ret, err = dm.store(node, host, "roster", roster);
239         print("["..(err or "success").."] roster-group: " ..node.."@"..host.." - "..jid.." - "..group);
240 end
241 function private_storage(node, host, xmlns, stanza)
242         local private = dm.load(node, host, "private") or {};
243         private[stanza.name..":"..xmlns] = st.preserialize(stanza);
244         local ret, err = dm.store(node, host, "private", private);
245         print("["..(err or "success").."] private: " ..node.."@"..host.." - "..xmlns);
246 end
247 function offline_msg(node, host, t, stanza)
248         stanza.attr.stamp = os.date("!%Y-%m-%dT%H:%M:%SZ", t);
249         stanza.attr.stamp_legacy = os.date("!%Y%m%dT%H:%M:%S", t);
250         local ret, err = dm.list_append(node, host, "offline", st.preserialize(stanza));
251         print("["..(err or "success").."] offline: " ..node.."@"..host.." - "..os.date("!%Y-%m-%dT%H:%M:%SZ", t));
252 end
253 for i, row in ipairs(t["rosterusers"] or NULL) do
254         local node, contact = row.username, row.jid;
255         local name = row.nick;
256         if name == "" then name = nil; end
257         local subscription = row.subscription;
258         if subscription == "N" then
259                 subscription = "none"
260         elseif subscription == "B" then
261                 subscription = "both"
262         elseif subscription == "F" then
263                 subscription = "from"
264         elseif subscription == "T" then
265                 subscription = "to"
266         else error("Unknown subscription type: "..subscription) end;
267         local ask = row.ask;
268         if ask == "N" then
269                 ask = nil;
270         elseif ask == "O" then
271                 ask = "subscribe";
272         elseif ask == "I" then
273                 roster_pending(node, host, contact);
274                 ask = nil;
275         elseif ask == "B" then
276                 roster_pending(node, host, contact);
277                 ask = "subscribe";
278         else error("Unknown ask type: "..ask); end
279         local item = {name = name, ask = ask, subscription = subscription, groups = {}};
280         roster(node, host, contact, item);
281 end
282 for i, row in ipairs(t["rostergroups"] or NULL) do
283         roster_group(row.username, host, row.jid, row.grp);
284 end
285 for i, row in ipairs(t["vcard"] or NULL) do
286         local ret, err = dm.store(row.username, host, "vcard", st.preserialize(parse_xml(row.vcard)));
287         print("["..(err or "success").."] vCard: "..row.username.."@"..host);
288 end
289 for i, row in ipairs(t["private_storage"] or NULL) do
290         private_storage(row.username, host, row.namespace, parse_xml(row.data));
291 end
292 table.sort(t["spool"] or NULL, function(a,b) return a.seq < b.seq; end); -- sort by sequence number, just in case
293 local time_offset = os.difftime(os.time(os.date("!*t")), os.time(os.date("*t"))) -- to deal with timezones
294 local date_parse = function(s)
295         local year, month, day, hour, min, sec = s:match("(....)-?(..)-?(..)T(..):(..):(..)");
296         return os.time({year=year, month=month, day=day, hour=hour, min=min, sec=sec-time_offset});
297 end
298 for i, row in ipairs(t["spool"] or NULL) do
299         local stanza = parse_xml(row.xml);
300         local last_child = stanza.tags[#stanza.tags];
301         if not last_child or last_child ~= stanza[#stanza] then error("Last child of offline message is not a tag"); end
302         if last_child.name ~= "x" and last_child.attr.xmlns ~= "jabber:x:delay" then error("Last child of offline message is not a timestamp"); end
303         stanza[#stanza], stanza.tags[#stanza.tags] = nil, nil;
304         local t = date_parse(last_child.attr.stamp);
305         offline_msg(row.username, host, t, stanza);
306 end