+function room_mt:freeze(live)
+ local frozen, state = {
+ _jid = self.jid;
+ _data = self._data;
+ };
+ for user, affiliation in pairs(self._affiliations) do
+ frozen[user] = affiliation;
+ end
+ if live then
+ state = {};
+ for nick, occupant in self:each_occupant() do
+ state[nick] = {
+ bare_jid = occupant.bare_jid;
+ role = occupant.role;
+ jid = occupant.jid;
+ }
+ for jid, presence in occupant:each_session() do
+ state[jid] = st.preserialize(presence);
+ end
+ end
+ local history = self._history;
+ if history then
+ state._last_message = st.preserialize(history[#history].stanza);
+ state._last_message_at = history[#history].timestamp;
+ end
+ end
+ return frozen, state;
+end
+
+function _M.restore_room(frozen, state)
+ -- COMPAT
+ if frozen.jid and frozen._affiliations then
+ local room = _M.new_room(frozen.jid, frozen._data);
+ room._affiliations = frozen._affiliations;
+ return room;
+ end
+
+ local room_jid = frozen._jid;
+ local room = _M.new_room(room_jid, frozen._data);
+
+ if state and state._last_message and state._last_message_at then
+ room._history = {
+ { stanza = st.deserialize(state._last_message),
+ timestamp = state._last_message_at, },
+ };
+ end
+
+ local occupants = {};
+ local occupant_sessions = {};
+ local room_name, room_host = jid_split(room_jid);
+ for jid, data in pairs(frozen) do
+ local node, host, resource = jid_split(jid);
+ if host:sub(1,1) ~= "_" and not resource and type(data) == "string" then
+ -- bare jid: affiliation
+ room._affiliations[jid] = data;
+ end
+ end
+ for jid, data in pairs(state or frozen) do
+ local node, host, resource = jid_split(jid);
+ if node or host:sub(1,1) ~= "_" then
+ if host == room_host and node == room_name and resource and type(data) == "table" then
+ -- full room jid: bare real jid and role
+ local bare_jid = data.bare_jid;
+ local occupant = occupant_lib.new(bare_jid, jid);
+ occupant.jid = data.jid;
+ occupant.role = data.role;
+ occupants[bare_jid] = occupant;
+ local sessions = occupant_sessions[bare_jid];
+ if sessions then
+ for full_jid, presence in pairs(sessions) do
+ occupant:set_session(full_jid, presence);
+ end
+ end
+ occupant_sessions[bare_jid] = nil;
+ elseif type(data) == "table" and data.name then
+ -- full user jid: presence
+ local presence = st.deserialize(data);
+ local bare_jid = jid_bare(jid);
+ local occupant = occupants[bare_jid];
+ local sessions = occupant_sessions[bare_jid];
+ if occupant then
+ occupant:set_session(jid, presence);
+ elseif sessions then
+ sessions[jid] = presence;
+ else
+ occupant_sessions[bare_jid] = {
+ [jid] = presence;
+ };
+ end
+ end
+ end
+ end
+
+ for _, occupant in pairs(occupants) do
+ room:save_occupant(occupant);
+ end
+
+ return room;
+end
+