-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathanalytics.js
More file actions
145 lines (122 loc) · 4.84 KB
/
analytics.js
File metadata and controls
145 lines (122 loc) · 4.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
/**
* analytics.js
* Tracks user sessions, page views, and duration.
* Saves data to Firestore collection "analytics".
*/
(function() {
console.log("Analytics: Initializing...");
// Helper to get/create Session ID
function getSessionId() {
let sid = sessionStorage.getItem('analytics_session_id');
if (!sid) {
sid = 'sess_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now();
sessionStorage.setItem('analytics_session_id', sid);
}
return sid;
}
const sessionId = getSessionId();
let db = null;
let auth = null;
let currentUser = 'anonymous';
// Check previous session state to avoid tracking admins on page reload
let isExcluded = sessionStorage.getItem('analytics_is_admin') === 'true';
let isTracking = false;
// Wait for Firebase to be available
function waitForFirebase() {
if (window.firebase && window.firebase.apps.length > 0) {
initAnalytics();
} else {
setTimeout(waitForFirebase, 500);
}
}
function initAnalytics() {
if (isTracking) return;
isTracking = true;
console.log("Analytics: Firebase found. Starting tracking.");
const app = window.firebase.app();
db = app.firestore();
auth = app.auth();
// Track user
auth.onAuthStateChanged(async (user) => {
if (user) {
try {
// Check if Superadmin or Admin
const isSuperAdmin = user.email === '4simpleproblems@gmail.com';
let isAdmin = false;
if (!isSuperAdmin) {
const adminDoc = await db.collection('admins').doc(user.uid).get();
isAdmin = adminDoc.exists;
}
if (isSuperAdmin || isAdmin) {
console.log("Analytics: Admin detected. Tracking disabled.");
isExcluded = true;
sessionStorage.setItem('analytics_is_admin', 'true');
return; // Stop processing
} else {
// User is logged in but not admin
isExcluded = false;
sessionStorage.removeItem('analytics_is_admin');
}
} catch (e) {
console.error("Analytics: Error checking admin status", e);
}
currentUser = user.uid;
} else {
// Logged out
currentUser = 'anonymous';
isExcluded = false;
sessionStorage.removeItem('analytics_is_admin');
}
updateSession();
});
// Initialize Start Time if new session
if (!sessionStorage.getItem('analytics_start_time')) {
sessionStorage.setItem('analytics_start_time', Date.now());
}
// Track Page View
trackPageView();
// Heartbeat to update duration
setInterval(updateSession, 10000);
// Visibility / Unload listeners
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
updateSession();
}
});
window.addEventListener('beforeunload', () => {
updateSession();
});
}
function trackPageView() {
if (isExcluded || !db) return;
const path = window.location.pathname;
const pageName = document.title || path;
const docRef = db.collection('analytics').doc(sessionId);
// Atomically add page visit and increment counter
docRef.set({
sessionId: sessionId,
userAgent: navigator.userAgent,
lastActive: window.firebase.firestore.FieldValue.serverTimestamp(),
visitedPages: window.firebase.firestore.FieldValue.arrayUnion({
path: path,
title: pageName,
timestamp: Date.now()
}),
pageCount: window.firebase.firestore.FieldValue.increment(1)
}, { merge: true }).catch(err => console.error("Analytics Error:", err));
}
function updateSession() {
if (isExcluded || !db) return;
const docRef = db.collection('analytics').doc(sessionId);
let startTime = parseInt(sessionStorage.getItem('analytics_start_time') || Date.now());
const now = Date.now();
const duration = (now - startTime) / 1000; // seconds
docRef.set({
userId: currentUser,
lastActive: window.firebase.firestore.FieldValue.serverTimestamp(),
duration: duration,
startTime: startTime
}, { merge: true });
}
waitForFirebase();
})();