/** * Zone editor: canvas-based polygon drawing for camera zones. * - Click the canvas to add points to the polygon currently being drawn. * - Choose a level (warning/restricted/pinch), then Save -> POST /api/zones. * - "Load" fetches existing zones for the camera via GET /api/zones/{camera} * and redraws them; each has a Delete button -> POST /api/zones/{id}/delete. * - If a `?snapshot={uuid}` query param is present, that image (served via * the authenticated /snap/{uuid} proxy) is drawn as the canvas background; * otherwise the canvas keeps its plain dark backdrop. * * XSS-safe: all dynamic text is set via textContent, never innerHTML. */ (function () { 'use strict'; // Mount prefix: '' at the web root, '/move_detect' when the app shares a www/ with another // site. Injected by src/View/layout.php from the server's SCRIPT_NAME. var B = window.APP_BASE || ''; var canvas = document.getElementById('zone-canvas'); if (!canvas) return; var ctx = canvas.getContext('2d'); var deviceInput = document.getElementById('device-id'); var cameraInput = document.getElementById('camera-id'); var levelSelect = document.getElementById('zone-level'); var loadBtn = document.getElementById('zone-load-btn'); var clearBtn = document.getElementById('zone-clear-btn'); var saveBtn = document.getElementById('zone-save-btn'); var listEl = document.getElementById('zone-list'); var statusEl = document.getElementById('zone-status'); var LEVEL_STYLE = { warning: { stroke: '#eab308', label: '경고' }, restricted: { stroke: '#dc2626', label: '제한' }, pinch: { stroke: '#a855f7', label: '협착' } }; var backgroundImage = null; var existingZones = []; // [{zone_id, level, points: [[x,y],...]}] var currentPoints = []; // in-progress polygon being drawn var csrfToken = null; function setStatus(msg) { statusEl.textContent = msg; } function loadCsrfToken() { return fetch(B + '/api/csrf', { headers: { Accept: 'application/json' } }) .then(function (res) { return res.ok ? res.json() : null; }) .then(function (data) { if (data && data.token) csrfToken = data.token; }) .catch(function () { /* save/delete will fail with 403 if the token is missing */ }); } // WIRE CONTRACT: zone polygons are stored NORMALIZED (0..1 of the image), so the edge can // compare them against a foot point normalized by the camera's own resolution regardless of // how big the camera is. On this canvas we draw in canvas pixels, so convert at the two wire // boundaries only: denormalize on load (here), normalize on save (saveZone). function parsePolygon(zone) { try { var pts = JSON.parse(zone.polygon_json || '[]'); if (!Array.isArray(pts)) return []; return pts.map(function (p) { return [p[0] * canvas.width, p[1] * canvas.height]; }); } catch (e) { return []; } } function drawPolygon(points, strokeStyle, label, closed) { if (points.length === 0) return; ctx.strokeStyle = strokeStyle; ctx.fillStyle = strokeStyle; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(points[0][0], points[0][1]); for (var i = 1; i < points.length; i++) ctx.lineTo(points[i][0], points[i][1]); if (closed && points.length > 2) ctx.closePath(); ctx.stroke(); points.forEach(function (p) { ctx.beginPath(); ctx.arc(p[0], p[1], 3, 0, Math.PI * 2); ctx.fill(); }); if (label) { ctx.font = '14px sans-serif'; ctx.fillText(label, points[0][0] + 6, points[0][1] - 6); } } function redraw() { ctx.clearRect(0, 0, canvas.width, canvas.height); if (backgroundImage) { ctx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height); } existingZones.forEach(function (z) { var style = LEVEL_STYLE[z.level] || { stroke: '#9ca3af', label: z.level }; drawPolygon(z.points, style.stroke, style.label, true); }); var current = LEVEL_STYLE[levelSelect.value] || { stroke: '#38bdf8', label: '' }; drawPolygon(currentPoints, current.stroke, currentPoints.length ? '편집중' : '', false); } function renderZoneList() { listEl.textContent = ''; existingZones.forEach(function (z) { var li = document.createElement('li'); var style = LEVEL_STYLE[z.level] || { label: z.level }; var label = document.createElement('span'); label.textContent = style.label + ' (' + z.points.length + '점)'; li.appendChild(label); var del = document.createElement('button'); del.type = 'button'; del.textContent = '삭제'; del.addEventListener('click', function () { deleteZone(z.zone_id); }); li.appendChild(del); listEl.appendChild(li); }); } function loadBackground(uuid) { if (!uuid) { backgroundImage = null; redraw(); return; } var img = new Image(); img.onload = function () { backgroundImage = img; redraw(); }; img.onerror = function () { backgroundImage = null; redraw(); }; img.src = B + '/snap/' + encodeURIComponent(uuid); } function loadZones() { var camera = cameraInput.value.trim(); if (!camera) { setStatus('카메라 ID를 입력하세요.'); return; } setStatus('불러오는 중...'); fetch(B + '/api/zones/' + encodeURIComponent(camera), { headers: { Accept: 'application/json' } }) .then(function (res) { if (res.status === 401) { window.location.href = B + '/login'; return null; } if (!res.ok) throw new Error('load_failed:' + res.status); return res.json(); }) .then(function (data) { if (!data) return; existingZones = (data.zones || []).map(function (z) { return { zone_id: z.zone_id, level: z.level, points: parsePolygon(z) }; }); currentPoints = []; renderZoneList(); redraw(); setStatus('구역 ' + existingZones.length + '개를 불러왔습니다.'); }) .catch(function () { setStatus('불러오기에 실패했습니다.'); }); } function saveZone() { var camera = cameraInput.value.trim(); var device = deviceInput.value.trim(); if (!camera) { setStatus('카메라 ID를 입력하세요.'); return; } if (currentPoints.length < 3) { setStatus('폴리곤 점을 3개 이상 클릭하세요.'); return; } setStatus('저장 중...'); fetch(B + '/api/zones', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Csrf-Token': csrfToken || '' }, body: JSON.stringify({ device_id: device, camera_id: camera, level: levelSelect.value, // Normalize canvas pixels -> 0..1 of the image (the edge un-normalizes with the // camera's own resolution). See the parsePolygon contract note above. polygon: currentPoints.map(function (p) { return [p[0] / canvas.width, p[1] / canvas.height]; }) }) }) .then(function (res) { if (res.status === 401) { window.location.href = B + '/login'; return null; } if (!res.ok) throw new Error('save_failed:' + res.status); return res.json(); }) .then(function (data) { if (!data) return; currentPoints = []; setStatus('저장되었습니다.'); loadZones(); }) .catch(function () { setStatus('저장에 실패했습니다.'); }); } function deleteZone(zoneId) { fetch(B + '/api/zones/' + encodeURIComponent(zoneId) + '/delete', { method: 'POST', headers: { 'X-Csrf-Token': csrfToken || '' } }) .then(function (res) { if (res.status === 401) { window.location.href = B + '/login'; return; } if (!res.ok) throw new Error('delete_failed:' + res.status); loadZones(); }) .catch(function () { setStatus('삭제에 실패했습니다.'); }); } canvas.addEventListener('click', function (evt) { var rect = canvas.getBoundingClientRect(); var scaleX = canvas.width / rect.width; var scaleY = canvas.height / rect.height; var x = Math.round((evt.clientX - rect.left) * scaleX); var y = Math.round((evt.clientY - rect.top) * scaleY); currentPoints.push([x, y]); redraw(); }); levelSelect.addEventListener('change', redraw); loadBtn.addEventListener('click', loadZones); clearBtn.addEventListener('click', function () { currentPoints = []; redraw(); setStatus('현재 폴리곤을 지웠습니다.'); }); saveBtn.addEventListener('click', saveZone); var params = new URLSearchParams(window.location.search); if (params.get('camera')) cameraInput.value = params.get('camera'); if (params.get('device')) deviceInput.value = params.get('device'); loadBackground(params.get('snapshot')); loadCsrfToken(); if (cameraInput.value) loadZones(); })();