Files
Final-Year-Project/Backend/public/mobile-sim.html

752 lines
25 KiB
HTML

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Mobile Client Simulator</title>
<style>
:root {
--bg: #0f172a;
--panel: #111827;
--muted: #94a3b8;
--text: #e2e8f0;
--accent: #14b8a6;
--warn: #f59e0b;
--danger: #ef4444;
}
body {
margin: 0;
font-family: "IBM Plex Sans", "Segoe UI", sans-serif;
background: radial-gradient(circle at 15% 15%, #1e293b 0%, var(--bg) 45%);
color: var(--text);
}
.page {
max-width: 1100px;
margin: 0 auto;
padding: 24px;
}
h1 {
margin-top: 0;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
gap: 16px;
}
.panel {
background: rgba(17, 24, 39, 0.82);
border: 1px solid #1f2937;
border-radius: 12px;
padding: 14px;
}
label,
small,
p {
color: var(--muted);
}
input,
select,
button,
textarea {
width: 100%;
border-radius: 8px;
border: 1px solid #334155;
background: #0b1220;
color: var(--text);
padding: 9px;
margin: 6px 0;
box-sizing: border-box;
}
button {
cursor: pointer;
background: #0d9488;
border-color: #0f766e;
font-weight: 700;
}
button.alt {
background: #334155;
border-color: #475569;
}
button.warn {
background: #b45309;
border-color: #92400e;
}
button.danger {
background: #b91c1c;
border-color: #991b1b;
}
.row {
display: flex;
gap: 8px;
}
.row > * {
flex: 1;
}
pre {
background: #020617;
color: #cbd5e1;
border-radius: 8px;
padding: 10px;
max-height: 250px;
overflow: auto;
}
.online {
color: #22c55e;
}
.offline {
color: #ef4444;
}
</style>
</head>
<body>
<div class="page">
<h1>Mobile Client Simulator</h1>
<p>
Use this page like a phone app: register device role, connect socket with bearer device token, and run camera/client
actions. You must already be signed in via Better Auth in this browser session.
</p>
<div class="grid">
<section class="panel">
<h2>Auth</h2>
<label>Name</label>
<input id="authName" placeholder="optional display name" />
<label>Email</label>
<input id="authEmail" placeholder="you@example.com" />
<label>Password</label>
<input id="authPassword" type="password" placeholder="password" />
<div class="row">
<button id="signUpBtn" class="alt">Sign Up</button>
<button id="signInBtn">Sign In</button>
</div>
<div class="row">
<button id="sessionBtn" class="alt">Check Session</button>
<button id="signOutBtn" class="danger">Sign Out</button>
</div>
<pre id="authState"></pre>
</section>
<section class="panel">
<h2>Device Bootstrap</h2>
<label>Device Name</label>
<input id="deviceName" placeholder="e.g. Hallway iPhone" />
<label>Role</label>
<select id="role">
<option value="client">client</option>
<option value="camera">camera</option>
</select>
<label>Push Token (simulated)</label>
<input id="pushToken" placeholder="optional push token for offline delivery" />
<div class="row">
<button id="registerBtn">Register Device</button>
<button id="loadSavedBtn" class="alt">Load Saved</button>
</div>
<div class="row">
<button id="connectBtn">Connect Socket</button>
<button id="disconnectBtn" class="alt">Disconnect</button>
</div>
<small id="connectionState" class="offline">Socket disconnected</small>
<pre id="deviceState"></pre>
</section>
<section class="panel">
<h2>Client Actions</h2>
<label>Target Camera Device ID</label>
<input id="targetCameraId" placeholder="camera uuid" />
<div class="row">
<button id="refreshDevicesBtn" class="alt">Refresh Devices</button>
<button id="linkBtn" class="alt">Link Camera</button>
</div>
<button id="requestStreamBtn">Request On-Demand Stream</button>
<button id="fetchPlaybackBtn" class="alt">Fetch Playback Token (Latest)</button>
<button id="fetchSubscribeBtn" class="alt">Fetch Subscribe Credentials</button>
<button id="listRecordingsBtn" class="alt">List Recordings</button>
<button id="downloadLatestRecordingBtn" class="alt">Download URL (Latest)</button>
<pre id="clientState"></pre>
</section>
<section class="panel">
<h2>Camera Actions</h2>
<button id="startMotionBtn" class="warn">Start Motion Event</button>
<button id="endMotionBtn" class="danger">End Last Motion Event</button>
<button id="fetchPublishBtn" class="alt">Fetch Publish Credentials</button>
<button id="finalizeRecordingBtn" class="alt">Finalize Recording (Latest)</button>
<pre id="cameraState"></pre>
</section>
</div>
<section class="panel" style="margin-top:16px">
<h2>Live Event Log</h2>
<pre id="log"></pre>
</section>
</div>
<script src="/socket.io/socket.io.js"></script>
<script>
const state = {
session: null,
device: null,
deviceToken: null,
socket: null,
lastMotionEventId: null,
lastStreamSessionId: null,
lastRecordingId: null,
latestPushNotificationId: null,
};
const $ = (id) => document.getElementById(id);
const log = (message, payload) => {
const ts = new Date().toISOString();
const line = `[${ts}] ${message}`;
const current = $('log').textContent;
$('log').textContent = `${line}${payload ? `\n${JSON.stringify(payload, null, 2)}` : ''}\n\n${current}`;
};
const saveLocal = () => {
localStorage.setItem('mobileSimDevice', JSON.stringify({ device: state.device, deviceToken: state.deviceToken }));
};
const render = () => {
$('authState').textContent = JSON.stringify({ session: state.session }, null, 2);
$('deviceState').textContent = JSON.stringify({ device: state.device, hasToken: Boolean(state.deviceToken) }, null, 2);
$('clientState').textContent = JSON.stringify({ lastStreamSessionId: state.lastStreamSessionId }, null, 2);
$('cameraState').textContent = JSON.stringify(
{
lastMotionEventId: state.lastMotionEventId,
lastRecordingId: state.lastRecordingId,
latestPushNotificationId: state.latestPushNotificationId,
},
null,
2,
);
};
const getAuthPayload = () => ({
name: $('authName').value.trim() || undefined,
email: $('authEmail').value.trim(),
password: $('authPassword').value,
});
$('signUpBtn').addEventListener('click', async () => {
try {
const authPayload = getAuthPayload();
const payload = await authFetch('/api/auth/sign-up/email', {
method: 'POST',
body: JSON.stringify(authPayload),
});
log('sign up', payload);
$('sessionBtn').click();
} catch (error) {
log('sign up failed', { error: error.message });
}
});
$('signInBtn').addEventListener('click', async () => {
try {
const authPayload = getAuthPayload();
const payload = await authFetch('/api/auth/sign-in/email', {
method: 'POST',
body: JSON.stringify({ email: authPayload.email, password: authPayload.password }),
});
log('sign in', payload);
$('sessionBtn').click();
} catch (error) {
log('sign in failed', { error: error.message });
}
});
$('sessionBtn').addEventListener('click', async () => {
try {
const payload = await authFetch('/api/auth/get-session');
state.session = payload?.session ? payload : null;
render();
log('session check', payload);
} catch (error) {
state.session = null;
render();
log('session check failed', { error: error.message });
}
});
$('signOutBtn').addEventListener('click', async () => {
try {
const payload = await authFetch('/api/auth/sign-out', { method: 'POST', body: JSON.stringify({}) });
state.session = null;
render();
log('sign out', payload);
} catch (error) {
log('sign out failed', { error: error.message });
}
});
const authFetch = async (url, options = {}) => {
const response = await fetch(url, {
credentials: 'include',
...options,
headers: {
'Content-Type': 'application/json',
...(options.headers || {}),
},
});
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(payload.message || response.statusText);
}
return payload;
};
const deviceFetch = async (url, options = {}) => {
if (!state.deviceToken) {
throw new Error('No device token. Register device first.');
}
return authFetch(url, {
...options,
headers: {
Authorization: `Bearer ${state.deviceToken}`,
...(options.headers || {}),
},
});
};
const connectSocket = () => {
if (!state.deviceToken) {
throw new Error('No device token');
}
if (state.socket) {
state.socket.disconnect();
}
state.socket = io({ auth: { token: state.deviceToken } });
state.socket.on('connect', () => {
$('connectionState').textContent = 'Socket connected';
$('connectionState').className = 'online';
log('socket connected');
});
state.socket.on('disconnect', () => {
$('connectionState').textContent = 'Socket disconnected';
$('connectionState').className = 'offline';
log('socket disconnected');
});
state.socket.on('connected', (payload) => log('connected', payload));
state.socket.on('command:status', (payload) => log('command:status', payload));
state.socket.on('stream:requested', (payload) => {
state.lastStreamSessionId = payload.streamSessionId;
render();
log('stream:requested', payload);
});
state.socket.on('stream:started', (payload) => {
state.lastStreamSessionId = payload.streamSessionId;
render();
log('stream:started', payload);
if (state.device?.role === 'client') {
deviceFetch(`/streams/${payload.streamSessionId}/subscribe-credentials`)
.then((credentials) => log('auto subscribe credentials', credentials))
.catch((error) => log('auto subscribe credentials failed', { error: error.message }));
}
});
state.socket.on('stream:ended', (payload) => log('stream:ended', payload));
state.socket.on('motion:detected', (payload) => log('motion:detected', payload));
state.socket.on('motion:ended', (payload) => log('motion:ended', payload));
// Mobile-camera behavior: accept start_stream commands and acknowledge.
state.socket.on('command:received', async (payload) => {
log('command:received', payload);
try {
if (payload.commandType === 'start_stream' && payload.payload?.streamSessionId) {
await deviceFetch(`/streams/${payload.payload.streamSessionId}/accept`, {
method: 'POST',
body: JSON.stringify({}),
});
const publishCredentials = await deviceFetch(
`/streams/${payload.payload.streamSessionId}/publish-credentials`,
);
log('auto publish credentials', publishCredentials);
}
if (payload.commandType === 'stop_stream' && payload.payload?.streamSessionId) {
await deviceFetch(`/streams/${payload.payload.streamSessionId}/end`, {
method: 'POST',
body: JSON.stringify({ reason: 'completed' }),
});
}
state.socket.emit('command:ack', { commandId: payload.commandId, status: 'acknowledged' });
} catch (error) {
state.socket.emit('command:ack', {
commandId: payload.commandId,
status: 'rejected',
error: error.message,
});
}
});
};
$('registerBtn').addEventListener('click', async () => {
try {
if (!state.session) throw new Error('Authenticate first');
const role = $('role').value;
const name = $('deviceName').value.trim();
const payload = await authFetch('/devices/register', {
method: 'POST',
body: JSON.stringify({
role,
name: name || undefined,
platform: 'web',
appVersion: 'sim-1',
pushToken: $('pushToken').value.trim() || undefined,
}),
});
state.device = payload.device;
state.deviceToken = payload.deviceToken;
saveLocal();
render();
log('device registered', payload);
} catch (error) {
log('register failed', { error: error.message });
}
});
$('loadSavedBtn').addEventListener('click', () => {
const raw = localStorage.getItem('mobileSimDevice');
if (!raw) return;
const parsed = JSON.parse(raw);
state.device = parsed.device;
state.deviceToken = parsed.deviceToken;
render();
log('loaded saved device', parsed);
});
const auditPanel = document.createElement('section');
auditPanel.className = 'panel';
auditPanel.style.marginTop = '16px';
auditPanel.innerHTML = `
<h2>Audit Logs</h2>
<button id="fetchAuditBtn" class="alt">Fetch My Device Audit Logs</button>
`;
document.querySelector('.page').appendChild(auditPanel);
$('fetchAuditBtn').addEventListener('click', async () => {
try {
const payload = await deviceFetch('/audit/device');
log('audit logs', payload);
} catch (error) {
log('audit fetch failed', { error: error.message });
}
});
$('loadSavedBtn').addEventListener('click', async () => {
try {
if (!state.device?.id) return;
const token = $('pushToken').value.trim();
if (!token) return;
await authFetch(`/devices/${state.device.id}`, {
method: 'PATCH',
body: JSON.stringify({ pushToken: token }),
});
log('push token updated', { deviceId: state.device.id });
} catch (error) {
log('push token update failed', { error: error.message });
}
});
$('connectBtn').addEventListener('click', () => {
try {
connectSocket();
} catch (error) {
log('connect failed', { error: error.message });
}
});
$('disconnectBtn').addEventListener('click', () => {
state.socket?.disconnect();
});
$('refreshDevicesBtn').addEventListener('click', async () => {
try {
const payload = await authFetch('/devices');
log('devices', payload);
} catch (error) {
log('fetch devices failed', { error: error.message });
}
});
$('linkBtn').addEventListener('click', async () => {
try {
if (!state.device?.id) throw new Error('Register/load a device first');
if (state.device.role !== 'client') throw new Error('This simulator device is not a client role');
const cameraDeviceId = $('targetCameraId').value.trim();
if (!cameraDeviceId) throw new Error('Enter target camera device id');
const payload = await authFetch('/device-links', {
method: 'POST',
body: JSON.stringify({
cameraDeviceId,
clientDeviceId: state.device.id,
}),
});
log('link created', payload);
} catch (error) {
log('link failed', { error: error.message });
}
});
$('requestStreamBtn').addEventListener('click', async () => {
try {
const cameraDeviceId = $('targetCameraId').value.trim();
if (!cameraDeviceId) throw new Error('Enter target camera device id');
const payload = await deviceFetch('/streams/request', {
method: 'POST',
body: JSON.stringify({ cameraDeviceId, reason: 'on_demand' }),
});
state.lastStreamSessionId = payload.streamSession.id;
render();
log('stream requested', payload);
} catch (error) {
log('stream request failed', { error: error.message });
}
});
$('fetchPlaybackBtn').addEventListener('click', async () => {
try {
if (!state.lastStreamSessionId) throw new Error('No known stream session');
const payload = await deviceFetch(`/streams/${state.lastStreamSessionId}/playback-token`);
log('playback token', payload);
} catch (error) {
log('playback token failed', { error: error.message });
}
});
$('listRecordingsBtn').addEventListener('click', async () => {
try {
const payload = await deviceFetch('/recordings/me/list');
if (payload.recordings?.length > 0) {
state.lastRecordingId = payload.recordings[0].id;
render();
}
log('recordings', payload);
} catch (error) {
log('list recordings failed', { error: error.message });
}
});
$('downloadLatestRecordingBtn').addEventListener('click', async () => {
try {
if (!state.lastRecordingId) throw new Error('No recording id available');
const payload = await deviceFetch(`/recordings/${state.lastRecordingId}/download-url`);
log('recording download url', payload);
} catch (error) {
log('recording download failed', { error: error.message });
}
});
$('fetchSubscribeBtn').addEventListener('click', async () => {
try {
if (!state.lastStreamSessionId) throw new Error('No known stream session');
const payload = await deviceFetch(`/streams/${state.lastStreamSessionId}/subscribe-credentials`);
log('subscribe credentials', payload);
} catch (error) {
log('subscribe credentials failed', { error: error.message });
}
});
$('startMotionBtn').addEventListener('click', async () => {
try {
const payload = await deviceFetch('/events/motion/start', {
method: 'POST',
body: JSON.stringify({ title: 'Motion from web simulator', triggeredBy: 'motion' }),
});
state.lastMotionEventId = payload.event.id;
render();
log('motion started', payload);
} catch (error) {
log('motion start failed', { error: error.message });
}
});
$('endMotionBtn').addEventListener('click', async () => {
try {
if (!state.lastMotionEventId) throw new Error('No motion event to end');
const payload = await deviceFetch(`/events/${state.lastMotionEventId}/motion/end`, {
method: 'POST',
body: JSON.stringify({ status: 'completed' }),
});
log('motion ended', payload);
} catch (error) {
log('motion end failed', { error: error.message });
}
});
$('fetchPublishBtn').addEventListener('click', async () => {
try {
if (!state.lastStreamSessionId) throw new Error('No known stream session');
const payload = await deviceFetch(`/streams/${state.lastStreamSessionId}/publish-credentials`);
log('publish credentials', payload);
} catch (error) {
log('publish credentials failed', { error: error.message });
}
});
$('finalizeRecordingBtn').addEventListener('click', async () => {
try {
if (!state.lastStreamSessionId) throw new Error('No stream session yet');
const listPayload = await deviceFetch('/recordings/me/list');
const target = listPayload.recordings?.find((r) => r.streamSessionId === state.lastStreamSessionId) ?? listPayload.recordings?.[0];
if (!target) throw new Error('No recording placeholder exists');
state.lastRecordingId = target.id;
render();
const payload = await deviceFetch(`/recordings/${target.id}/finalize`, {
method: 'POST',
body: JSON.stringify({
objectKey: `recordings/${target.id}.mp4`,
bucket: 'videos',
durationSeconds: 12,
sizeBytes: 1024 * 1024 * 8,
}),
});
log('recording finalized', payload);
} catch (error) {
log('finalize recording failed', { error: error.message });
}
});
const pushPanel = document.createElement('section');
pushPanel.className = 'panel';
pushPanel.style.marginTop = '16px';
pushPanel.innerHTML = `
<h2>Push Inbox (Offline Fallback)</h2>
<div class="row">
<button id="dispatchPushWorkerBtn" class="alt">Dispatch Push Worker</button>
<button id="pollPushInboxBtn" class="alt">Poll Push Inbox</button>
</div>
<button id="markLatestPushReadBtn" class="alt">Mark Latest Push Read</button>
`;
document.querySelector('.page').appendChild(pushPanel);
$('dispatchPushWorkerBtn').addEventListener('click', async () => {
try {
const payload = await deviceFetch('/push-notifications/worker/dispatch', { method: 'POST', body: JSON.stringify({}) });
log('push worker dispatch', payload);
} catch (error) {
log('push worker dispatch failed', { error: error.message });
}
});
$('pollPushInboxBtn').addEventListener('click', async () => {
try {
const payload = await deviceFetch('/push-notifications/me');
const latest = payload.notifications?.[0];
if (latest) {
state.latestPushNotificationId = latest.id;
}
render();
log('push inbox', payload);
} catch (error) {
log('poll push inbox failed', { error: error.message });
}
});
$('markLatestPushReadBtn').addEventListener('click', async () => {
try {
if (!state.latestPushNotificationId) throw new Error('No push notification selected');
const payload = await deviceFetch(`/push-notifications/${state.latestPushNotificationId}/read`, {
method: 'POST',
body: JSON.stringify({}),
});
log('push marked read', payload);
} catch (error) {
log('mark push read failed', { error: error.message });
}
});
const opsPanel = document.createElement('section');
opsPanel.className = 'panel';
opsPanel.style.marginTop = '16px';
opsPanel.innerHTML = `
<h2>Ops Checks</h2>
<div class="row">
<button id="checkLiveBtn" class="alt">GET /ops/live</button>
<button id="checkReadyBtn" class="alt">GET /ops/ready</button>
</div>
<button id="checkMetricsBtn" class="alt">GET /ops/metrics</button>
`;
document.querySelector('.page').appendChild(opsPanel);
$('checkLiveBtn').addEventListener('click', async () => {
try {
const payload = await authFetch('/ops/live');
log('ops live', payload);
} catch (error) {
log('ops live failed', { error: error.message });
}
});
$('checkReadyBtn').addEventListener('click', async () => {
try {
const payload = await authFetch('/ops/ready');
log('ops ready', payload);
} catch (error) {
log('ops ready failed', { error: error.message });
}
});
$('checkMetricsBtn').addEventListener('click', async () => {
try {
const payload = await authFetch('/ops/metrics');
log('ops metrics', payload);
} catch (error) {
log('ops metrics failed', { error: error.message });
}
});
render();
</script>
</body>
</html>