-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
402 lines (333 loc) · 12.4 KB
/
Copy pathscript.js
File metadata and controls
402 lines (333 loc) · 12.4 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
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
// Global variables
let videoStream = null;
let locationWatcher = null;
let isTracking = false;
let photoCount = 0;
// DOM elements
const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const cameraContainer = document.getElementById('camera-container');
const startCameraBtn = document.getElementById('start-camera');
const stopCameraBtn = document.getElementById('stop-camera');
const takePhotoBtn = document.getElementById('take-photo');
const getLocationBtn = document.getElementById('get-location');
const watchLocationBtn = document.getElementById('watch-location');
const stopTrackingBtn = document.getElementById('stop-tracking');
const deviceStatus = document.getElementById('device-status');
const locationInfo = document.getElementById('location-info');
const alertsContainer = document.getElementById('alerts');
const photosContainer = document.getElementById('photos');
// Initialize app
document.addEventListener('DOMContentLoaded', function() {
updateDeviceStatus();
checkPermissions();
// Auto-update device status every 30 seconds
setInterval(updateDeviceStatus, 30000);
});
// Device status management
function updateDeviceStatus() {
const now = new Date();
const status = navigator.onLine ? 'online' : 'offline';
const statusClass = status === 'online' ? 'online' : 'offline';
deviceStatus.textContent = status === 'online' ? 'Online' : 'Offline';
deviceStatus.className = `status ${statusClass}`;
// Log activity
logActivity(`Device status: ${status} at ${now.toLocaleString()}`);
}
// Check and request permissions
async function checkPermissions() {
try {
// Check camera permission
const cameraPermission = await navigator.permissions.query({name: 'camera'});
console.log('Camera permission:', cameraPermission.state);
// Check location permission
const locationPermission = await navigator.permissions.query({name: 'geolocation'});
console.log('Location permission:', locationPermission.state);
if (cameraPermission.state === 'denied' || locationPermission.state === 'denied') {
showAlert('Beberapa izin diperlukan untuk mengakses kamera dan lokasi', 'warning');
}
} catch (error) {
console.log('Permission API not fully supported');
}
}
// Camera functions
async function startCamera() {
try {
showLoading('Mengakses kamera...');
const constraints = {
video: {
width: { ideal: 1280 },
height: { ideal: 720 },
facingMode: 'environment' // Use back camera on mobile
},
audio: false
};
videoStream = await navigator.mediaDevices.getUserMedia(constraints);
video.srcObject = videoStream;
// Show camera container
cameraContainer.classList.remove('hidden');
// Update button states
startCameraBtn.disabled = true;
stopCameraBtn.disabled = false;
takePhotoBtn.disabled = false;
hideLoading();
showAlert('Kamera berhasil diaktifkan', 'success');
// Log activity
logActivity('Camera started');
} catch (error) {
hideLoading();
showAlert('Gagal mengakses kamera: ' + error.message, 'error');
console.error('Camera error:', error);
}
}
function stopCamera() {
if (videoStream) {
videoStream.getTracks().forEach(track => track.stop());
videoStream = null;
video.srcObject = null;
// Hide camera container
cameraContainer.classList.add('hidden');
// Update button states
startCameraBtn.disabled = false;
stopCameraBtn.disabled = true;
takePhotoBtn.disabled = true;
showAlert('Kamera dihentikan', 'success');
logActivity('Camera stopped');
}
}
function takePhoto() {
if (!videoStream) {
showAlert('Kamera belum diaktifkan', 'error');
return;
}
// Set canvas dimensions to match video
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
// Draw video frame to canvas
const context = canvas.getContext('2d');
context.drawImage(video, 0, 0);
// Convert to blob and create download link
canvas.toBlob(function(blob) {
photoCount++;
const timestamp = new Date().toLocaleString();
const filename = `photo_${photoCount}_${Date.now()}.jpg`;
// Create download link
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
// Create photo preview
const photoDiv = document.createElement('div');
photoDiv.className = 'photo-item';
photoDiv.innerHTML = `
<img src="${link.href}" style="max-width: 200px; border-radius: 10px; margin: 10px;">
<p>Foto ${photoCount} - ${timestamp}</p>
<button onclick="this.parentElement.previousElementSibling.click()">Download</button>
`;
photosContainer.appendChild(link);
photosContainer.appendChild(photoDiv);
photosContainer.classList.remove('hidden');
showAlert(`Foto ${photoCount} berhasil diambil`, 'success');
logActivity(`Photo ${photoCount} taken`);
// Auto download
link.click();
}, 'image/jpeg', 0.8);
}
// Location functions
function getLocation() {
if (!navigator.geolocation) {
showAlert('Geolocation tidak didukung oleh browser ini', 'error');
return;
}
showLoading('Mendapatkan lokasi...');
navigator.geolocation.getCurrentPosition(
function(position) {
hideLoading();
displayLocation(position);
showAlert('Lokasi berhasil didapatkan', 'success');
logActivity('Location obtained');
},
function(error) {
hideLoading();
showAlert('Gagal mendapatkan lokasi: ' + getLocationError(error), 'error');
console.error('Location error:', error);
},
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
}
);
}
function watchLocation() {
if (!navigator.geolocation) {
showAlert('Geolocation tidak didukung oleh browser ini', 'error');
return;
}
if (isTracking) {
showAlert('Pelacakan sudah aktif', 'warning');
return;
}
isTracking = true;
watchLocationBtn.disabled = true;
stopTrackingBtn.disabled = false;
showAlert('Pelacakan lokasi dimulai', 'success');
logActivity('Location tracking started');
locationWatcher = navigator.geolocation.watchPosition(
function(position) {
displayLocation(position);
logActivity('Location updated');
},
function(error) {
showAlert('Error saat melacak lokasi: ' + getLocationError(error), 'error');
console.error('Location tracking error:', error);
},
{
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 1000
}
);
}
function stopTracking() {
if (locationWatcher !== null) {
navigator.geolocation.clearWatch(locationWatcher);
locationWatcher = null;
isTracking = false;
watchLocationBtn.disabled = false;
stopTrackingBtn.disabled = true;
showAlert('Pelacakan lokasi dihentikan', 'success');
logActivity('Location tracking stopped');
}
}
function displayLocation(position) {
const { latitude, longitude, accuracy, altitude, heading, speed } = position.coords;
const timestamp = new Date(position.timestamp).toLocaleString();
document.getElementById('coordinates').innerHTML = `
<strong>Koordinat:</strong><br>
<div class="coordinates">
Latitude: ${latitude.toFixed(6)}<br>
Longitude: ${longitude.toFixed(6)}
</div>
`;
document.getElementById('accuracy').innerHTML = `
<strong>Akurasi:</strong> ${accuracy.toFixed(2)} meter
`;
document.getElementById('timestamp').innerHTML = `
<strong>Waktu:</strong> ${timestamp}
`;
locationInfo.classList.remove('hidden');
// Create Google Maps link
const mapsLink = `https://www.google.com/maps?q=${latitude},${longitude}`;
const linkElement = document.createElement('div');
linkElement.innerHTML = `
<strong>Google Maps:</strong>
<a href="${mapsLink}" target="_blank" style="color: #0066cc;">Lihat di Maps</a>
`;
// Add to location info if not already present
if (!document.getElementById('maps-link')) {
linkElement.id = 'maps-link';
locationInfo.appendChild(linkElement);
} else {
document.getElementById('maps-link').innerHTML = linkElement.innerHTML;
}
}
// Utility functions
function getLocationError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
return 'Izin lokasi ditolak oleh pengguna';
case error.POSITION_UNAVAILABLE:
return 'Informasi lokasi tidak tersedia';
case error.TIMEOUT:
return 'Permintaan lokasi timeout';
default:
return 'Error tidak diketahui';
}
}
function showAlert(message, type = 'info') {
const alert = document.createElement('div');
alert.className = `alert ${type}`;
alert.textContent = message;
alertsContainer.appendChild(alert);
// Auto remove after 5 seconds
setTimeout(() => {
if (alert.parentNode) {
alert.parentNode.removeChild(alert);
}
}, 5000);
}
function showLoading(message) {
const loading = document.createElement('div');
loading.id = 'loading';
loading.className = 'loading';
loading.innerHTML = `
<div class="spinner"></div>
<p>${message}</p>
`;
alertsContainer.appendChild(loading);
}
function hideLoading() {
const loading = document.getElementById('loading');
if (loading) {
loading.remove();
}
}
function logActivity(activity) {
const timestamp = new Date().toLocaleString();
console.log(`[${timestamp}] ${activity}`);
// Store in localStorage for persistence
let logs = JSON.parse(localStorage.getItem('phoneTracker_logs') || '[]');
logs.push({ timestamp, activity });
// Keep only last 100 logs
if (logs.length > 100) {
logs = logs.slice(-100);
}
localStorage.setItem('phoneTracker_logs', JSON.stringify(logs));
}
// Network status monitoring
window.addEventListener('online', function() {
updateDeviceStatus();
showAlert('Koneksi internet pulih', 'success');
});
window.addEventListener('offline', function() {
updateDeviceStatus();
showAlert('Koneksi internet terputus', 'warning');
});
// Page visibility for battery optimization
document.addEventListener('visibilitychange', function() {
if (document.hidden) {
logActivity('Page hidden');
} else {
logActivity('Page visible');
updateDeviceStatus();
}
});
// Battery status (if supported)
if ('getBattery' in navigator) {
navigator.getBattery().then(function(battery) {
const batteryLevel = Math.round(battery.level * 100);
const isCharging = battery.charging;
logActivity(`Battery: ${batteryLevel}% ${isCharging ? '(Charging)' : '(Not charging)'}`);
// Monitor battery changes
battery.addEventListener('levelchange', function() {
const level = Math.round(battery.level * 100);
logActivity(`Battery level changed: ${level}%`);
});
battery.addEventListener('chargingchange', function() {
const status = battery.charging ? 'Charging' : 'Not charging';
logActivity(`Battery charging status: ${status}`);
});
});
}
// Device orientation (if supported)
if ('DeviceOrientationEvent' in window) {
window.addEventListener('deviceorientation', function(event) {
const alpha = event.alpha; // Z axis
const beta = event.beta; // X axis
const gamma = event.gamma; // Y axis
// Log orientation changes (throttled)
if (Math.abs(beta) > 45 || Math.abs(gamma) > 45) {
logActivity(`Device orientation: α=${alpha?.toFixed(1)}, β=${beta?.toFixed(1)}, γ=${gamma?.toFixed(1)}`);
}
});
}