|
1 local store = module:open_store("lastlog2"); |
|
2 |
|
3 local measure_d1 = module:measure("active_users_1d", "amount"); |
|
4 local measure_d7 = module:measure("active_users_7d", "amount"); |
|
5 local measure_d30 = module:measure("active_users_30d", "amount"); |
|
6 |
|
7 function update_calculations() |
|
8 module:log("debug", "Calculating active users"); |
|
9 local host_user_sessions = prosody.hosts[module.host].sessions; |
|
10 local active_d1, active_d7, active_d30 = 0, 0, 0; |
|
11 local now = os.time(); |
|
12 for username in store:users() do |
|
13 if host_user_sessions[username] then |
|
14 -- Active now |
|
15 active_d1, active_d7, active_d30 = |
|
16 active_d1 + 1, active_d7 + 1, active_d30 + 1; |
|
17 else |
|
18 local lastlog_data = store:get(username); |
|
19 if lastlog_data then |
|
20 -- Due to server restarts/crashes/etc. some events |
|
21 -- may not always get recorded, so we'll just take the |
|
22 -- latest as a sign of last activity |
|
23 local last_active = math.max( |
|
24 lastlog_data.login and lastlog_data.login.timestamp or 0, |
|
25 lastlog_data.logout and lastlog_data.logout.timestamp or 0 |
|
26 ); |
|
27 if now - last_active < 86400 then |
|
28 active_d1 = active_d1 + 1; |
|
29 end |
|
30 if now - last_active < 86400*7 then |
|
31 active_d7 = active_d7 + 1; |
|
32 end |
|
33 if now - last_active < 86400*30 then |
|
34 active_d30 = active_d30 + 1; |
|
35 end |
|
36 end |
|
37 end |
|
38 end |
|
39 module:log("debug", "Active users (took %ds): %d (24h), %d (7d), %d (30d)", os.time()-now, active_d1, active_d7, active_d30); |
|
40 measure_d1(active_d1); |
|
41 measure_d7(active_d7); |
|
42 measure_d30(active_d30); |
|
43 |
|
44 return 3600 + (300*math.random()); |
|
45 end |
|
46 |
|
47 module:add_timer(15, update_calculations); |