-function destroy_session(session)
-end
-
-function send_to_session(session, data)
- log("debug", "Sending: %s", tostring(data));
- session.conn.write(tostring(data));
+function destroy_session(session, err)
+ (session.log or log)("info", "Destroying session");
+
+ -- Send unavailable presence
+ if session.presence then
+ local pres = st.presence{ type = "unavailable" };
+ if (not err) or err == "closed" then err = "connection closed"; end
+ pres:tag("status"):text("Disconnected: "..err);
+ session.stanza_dispatch(pres);
+ end
+
+ -- Remove session/resource from user's session list
+ if session.host and session.username then
+ -- FIXME: How can the below ever be nil? (but they sometimes are...)
+ if hosts[session.host] and hosts[session.host].sessions[session.username] then
+ if session.resource then
+ hosts[session.host].sessions[session.username].sessions[session.resource] = nil;
+ end
+
+ if not next(hosts[session.host].sessions[session.username].sessions) then
+ log("debug", "All resources of %s are now offline", session.username);
+ hosts[session.host].sessions[session.username] = nil;
+ end
+ else
+ log("error", "host or session table didn't exist, please report this! Host: %s [%s] Sessions: %s [%s]",
+ tostring(hosts[session.host]), tostring(session.host),
+ tostring(hosts[session.host].sessions[session.username] ), tostring(session.username));
+ end
+ end
+
+ for k in pairs(session) do
+ if k ~= "trace" then
+ session[k] = nil;
+ end
+ end