File size: 9,850 Bytes
846829e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Attendance System</title>
    <style>
        /* --- General Resets & Body Styling --- */
        :root {
            --primary-color: #007bff;
            --primary-hover: #0056b3;
            --success-color: #28a745;
            --error-color: #dc3545;
            --light-gray: #f0f2f5;
            --dark-gray: #333;
            --medium-gray: #555;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; background-color: var(--light-gray); padding: 15px; }
        .container { text-align: center; padding: 30px; background-color: white; border-radius: 12px; box-shadow: 0 6px 20px rgba(0,0,0,0.08); width: 100%; max-width: 500px; }
        h1 { color: var(--dark-gray); margin-bottom: 10px; font-size: 1.8rem; }
        p { color: var(--medium-gray); line-height: 1.6; margin-bottom: 20px; }
        button { background-color: var(--primary-color); color: white; border: none; padding: 15px 30px; border-radius: 8px; font-size: 1rem; font-weight: bold; cursor: pointer; transition: all 0.3s; width: 100%; }
        button:hover:not(:disabled) { background-color: var(--primary-hover); box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3); }
        button:disabled { background-color: #6c757d; cursor: not-allowed; }
        #status { margin-top: 25px; font-size: 1.1em; font-weight: bold; line-height: 1.5; min-height: 70px; }
        #status small { display: block; margin-top: 5px; font-weight: normal; color: #6c757d; font-size: 0.85em; }
        .success { color: var(--success-color); }
        .error { color: var(--error-color); }
        .hidden { display: none; }
        #video-container { margin-top: 20px; position: relative; }
        video { width: 100%; max-width: 400px; border-radius: 8px; background-color: #000; }
        canvas { display: none; }
        .spinner { border: 4px solid rgba(0,0,0,0.1); border-left-color: var(--primary-color); border-radius: 50%; width: 30px; height: 30px; animation: spin 1s linear infinite; margin: 20px auto 0; }
        @keyframes spin { to { transform: rotate(30deg); } }
        @media (min-width: 600px) { h1 { font-size: 2.2rem; } .container { padding: 40px; } button { width: auto; } }
    </style>
</head>
<body>
    <div class="container">
        <h1>Smart Attendance</h1>
        
        <!-- Step 1: Location -->
        <div id="location-step">
            <p>Verify your location for class <strong>CS101</strong> to proceed.</p>
            <button id="location-button" onclick="verifyLocation()">Step 1: Verify My Location</button>
        </div>

        <!-- Step 2: Face Recognition -->
        <div id="face-step" class="hidden">
            <p>Location confirmed. Please align your face with the camera.</p>
            <div id="video-container">
                <video id="webcam" autoplay playsinline></video>
                <canvas id="canvas"></canvas>
            </div>
            <button id="face-button" onclick="verifyFace()">Step 2: Capture & Verify Face</button>
        </div>
        
        <!-- Status Area -->
        <div id="status-container">
             <div id="spinner" class="spinner hidden"></div>
             <p id="status"></p>
        </div>
    </div>

    <script>
        // --- API & Config ---
        const LOCATION_API = "/verify-location";
        const FACE_API = "/verify-face";

        // --- Element References ---
        const statusElement = document.getElementById('status');
        const spinner = document.getElementById('spinner');
        const locationButton = document.getElementById('location-button');
        const faceButton = document.getElementById('face-button');
        const locationStepDiv = document.getElementById('location-step');
        const faceStepDiv = document.getElementById('face-step');
        const videoElement = document.getElementById('webcam');
        let stream;

        // --- UI Helper Functions ---
        function showSpinner() { spinner.classList.remove('hidden'); }
        function hideSpinner() { spinner.classList.add('hidden'); }
        function updateStatus(message, type = '') {
            hideSpinner();
            statusElement.innerHTML = message;
            statusElement.className = type;
        }
        function showLoadingStatus(message) {
            showSpinner();
            statusElement.innerHTML = message;
            statusElement.className = '';
        }
        
        // --- STEP 1: Location Logic ---
        async function verifyLocation() {
            if (!navigator.geolocation) {
                updateStatus("Geolocation is not supported by your browser.", "error");
                return;
            }
            locationButton.disabled = true;
            showLoadingStatus("Acquiring your location...");
            try {
                // Call the new, faster location function
                const position = await getFastLocation();
                await sendLocationToServer(position);
            } catch (error) {
                updateStatus(`Error: ${error.message}`, "error");
                locationButton.disabled = false;
            }
        }
        
        /**
         * MODIFIED FUNCTION: Gets location quickly without waiting for accuracy.
         * It asks for the location once and has a timeout if it takes too long.
         */
        function getFastLocation() {
            return new Promise((resolve, reject) => {
                navigator.geolocation.getCurrentPosition(
                    // Success: The browser found the location
                    (position) => {
                        resolve(position);
                    },
                    // Error: The browser failed to get the location
                    (error) => {
                        reject(new Error(error.message));
                    },
                    // Options
                    {
                        enableHighAccuracy: true, // Prefer GPS if available
                        timeout: 5000,           // Maximum time to wait: 5 seconds
                        maximumAge: 0            // Force a fresh location check
                    }
                );
            });
        }

        async function sendLocationToServer(position) {
            const { latitude, longitude, accuracy } = position.coords;
            showLoadingStatus(`Location found (Accuracy: ${accuracy.toFixed(1)}m).<br><small>Verifying coordinates...</small>`);
            try {
                const response = await fetch(LOCATION_API, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ class_id: "CS101", latitude, longitude })
                });
                const result = await response.json();
                if (response.ok && result.status === 'success') {
                    updateStatus(result.message, "success");
                    setTimeout(proceedToFaceStep, 1000);
                } else {
                    updateStatus(result.message || "Failed to verify location.", "error");
                    locationButton.disabled = false;
                }
            } catch (error) {
                updateStatus("Could not connect to the verification server.", "error");
                locationButton.disabled = false;
            }
        }
        
        // --- STEP 2: Face Logic (No changes needed here) ---
        async function proceedToFaceStep() {
            locationStepDiv.classList.add('hidden');
            faceStepDiv.classList.remove('hidden');
            updateStatus("Please look at the camera for face verification.");

            try {
                stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } });
                videoElement.srcObject = stream;
            } catch (error) {
                updateStatus("Could not access the camera. Please grant permission and try again.", "error");
                faceButton.disabled = true;
            }
        }

        async function verifyFace() {
            faceButton.disabled = true;
            const canvas = document.getElementById('canvas');
            canvas.width = videoElement.videoWidth;
            canvas.height = videoElement.videoHeight;
            canvas.getContext('2d').drawImage(videoElement, 0, 0);

            if (stream) { stream.getTracks().forEach(track => track.stop()); }
            
            showLoadingStatus("Image captured. Sending for verification...");
            const imageDataUrl = canvas.toDataURL('image/jpeg');

            try {
                const response = await fetch(FACE_API, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ image: imageDataUrl })
                });
                const result = await response.json();
                if (response.ok && result.status === 'success') {
                    updateStatus("βœ… Attendance Marked Successfully!", "success");
                    faceButton.classList.add('hidden');
                } else {
                    updateStatus(`❌ ${result.message || "Face verification failed."}<br><small>Please refresh to try again.</small>`, "error");
                }
            } catch (error) {
                updateStatus("Connection error during face verification.", "error");
                faceButton.disabled = false;
            }
        }
    </script>

</body>
</html>